id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
140,148 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/samples/failures_and_unexpected_passes.py
|
virtue.tests.samples.failures_and_unexpected_passes.Foo
|
class Foo(TestCase):
def test_foo(self):
self.fail("Nope!")
@expectedFailure
def test_bar(self):
pass
@expectedFailure
def test_baz(self):
pass
@expectedFailure
def test_quux(self):
pass
def test_spam(self):
pass
|
class Foo(TestCase):
def test_foo(self):
pass
@expectedFailure
def test_bar(self):
pass
@expectedFailure
def test_baz(self):
pass
@expectedFailure
def test_quux(self):
pass
def test_spam(self):
pass
| 9 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 5 | 0 | 5 | 77 | 18 | 4 | 14 | 9 | 5 | 0 | 11 | 6 | 5 | 1 | 2 | 0 | 5 |
140,149 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/samples/mixin.py
|
virtue.tests.samples.mixin.FooMixin
|
class FooMixin:
def test_foo(self):
self.fail("Nope!")
def test_bar(self):
raise Exception("Boom!")
def test_baz(self):
raise Exception("Whiz!")
def test_quux(self):
raise Exception("Bang!")
def test_spam(self):
raise Exception("Hiss!")
|
class FooMixin:
def test_foo(self):
pass
def test_bar(self):
pass
def test_baz(self):
pass
def test_quux(self):
pass
def test_spam(self):
pass
| 6 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 5 | 0 | 5 | 5 | 15 | 4 | 11 | 6 | 5 | 0 | 11 | 6 | 5 | 1 | 0 | 0 | 5 |
140,150 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/samples/module_for_TestObjectLocator.py
|
virtue.tests.samples.module_for_TestObjectLocator.Bar
|
class Bar:
def stuff(self):
pass
def test_foo(self):
pass
|
class Bar:
def stuff(self):
pass
def test_foo(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 6 | 1 | 5 | 3 | 2 | 0 | 5 | 3 | 2 | 1 | 0 | 0 | 2 |
140,151 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/samples/module_for_TestLoaders.py
|
virtue.tests.samples.module_for_TestLoaders.Baz
|
class Baz(TestCase):
def test_bar(self):
pass
def test_baz(self):
pass
|
class Baz(TestCase):
def test_bar(self):
pass
def test_baz(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 74 | 6 | 1 | 5 | 3 | 2 | 0 | 5 | 3 | 2 | 1 | 2 | 0 | 2 |
140,152 |
Julian/Virtue
|
Julian_Virtue/virtue/reporters.py
|
virtue.reporters.Outputter
|
class Outputter:
"""
An outputter converts test results to renderable strings.
"""
_last_test_class = None
_last_test_module = None
_current_subtests_test = None
FAILED, PASSED = "FAILED", "PASSED"
ERROR, FAIL, OK, SKIPPED = "[ERROR]", "[FAIL]", "[OK]", "[SKIPPED]"
EXPECTED_FAILURE, UNEXPECTED_SUCCESS = "[XFAIL]", "[UNEXPECTED SUCCESS]"
_COLORS = [
("_error", "RED", ERROR),
("_fail", "RED", FAIL),
("_failed", "RED", FAILED),
("_ok", "GREEN", OK),
("_passed", "GREEN", PASSED),
("_skipped", "BLUE", SKIPPED),
("_unexpected_success", "YELLOW", UNEXPECTED_SUCCESS),
("_expected_failure", "BLUE", EXPECTED_FAILURE),
]
def __init__(self, colored=True, indent=" " * 2, line_width=120):
self.indent = indent
self.line_width = line_width
if colored:
from colorama import Fore, Style
for attribute, color, text in self._COLORS:
color = getattr(Fore, color)
message = f"{Style.BRIGHT}{color}{text}{Style.RESET_ALL}"
setattr(self, attribute, message)
else:
for attribute, _, text in self._COLORS:
setattr(self, attribute, text)
self._later = {
status: defaultdict(list)
for status in [
self.SKIPPED,
self.EXPECTED_FAILURE,
self.FAIL,
self.UNEXPECTED_SUCCESS,
self.ERROR,
]
}
def _show_later(self, **kwargs):
message = _DelayedMessage(width=self.line_width, **kwargs)
self._later[message.status][message.body].append(message)
def run_started(self):
"""
Output nothing.
"""
def run_stopped(self, recorder, runtime):
"""
Output all the messages stored for later, as well as a final summary.
"""
for status in self._later.values():
for messages in status.values():
if not messages:
continue
yield "\n"
yield from messages[0].lines()
for message in messages:
yield "\n"
yield message.subject.id()
yield "\n"
yield "-" * self.line_width
count = recorder.testsRun
tests = "tests" if count != 1 else "test"
subcount = recorder.subtests
if subcount:
pluralized = "subtests" if subcount != 1 else "subtest"
subtests = f" with {subcount} {pluralized}"
else:
subtests = ""
yield f"\nRan {count} {tests}{subtests} in {runtime:.3f}s\n\n"
if recorder.wasSuccessful():
yield self._passed
else:
yield self._failed
if recorder.testsRun:
yield " ("
summary = []
for attribute in (
"successes",
"skips",
"failures",
"errors",
"expected_failures",
"unexpected_successes",
"subtest_failures",
"subtest_errors",
):
subcount = len(getattr(recorder, attribute))
if subcount:
summary.append(f"{attribute}={subcount}")
yield ", ".join(summary)
yield ")"
yield "\n"
def test_started(self, test):
"""
Output the test name.
"""
cls = test.__class__
module = cls.__module__
if self._last_test_module != module:
self._last_test_module = module
yield module
yield "\n"
if self._last_test_class != cls:
self._last_test_class = cls
yield self.indent
yield cls.__name__
yield "\n"
def test_stopped(self, test):
"""
Output nothing.
"""
def test_errored(self, test, exc_info):
"""
Output an error.
"""
self._show_later(
status=self.ERROR,
body="".join(format_exception(*exc_info)),
subject=test,
)
return self._format_line(test, self._error)
def test_failed(self, test, exc_info):
"""
Output a failure.
"""
self._show_later(
status=self.FAIL,
body="".join(format_exception(*exc_info)),
subject=test,
)
return self._format_line(test, self._fail)
def test_skipped(self, test, reason):
"""
Output a skip.
"""
self._show_later(status=self.SKIPPED, body=reason, subject=test)
return self._format_line(test, self._skipped)
def test_expectedly_failed(self, test, exc_info):
"""
Output an expected failure.
"""
self._show_later(status=self.EXPECTED_FAILURE, subject=test)
return self._format_line(test, self._expected_failure)
def test_unexpectedly_succeeded(self, test):
"""
Output an unexpected success.
"""
self._show_later(status=self.UNEXPECTED_SUCCESS, subject=test)
return self._format_line(test, self._unexpected_success)
def test_succeeded(self, test):
"""
Output a success.
"""
return self._format_line(test, self._ok)
def subtest_succeeded(self, test, subtest):
"""
Output nothing.
"""
def subtest_failed(self, test, subtest, exc_info):
"""
Output a failed subtest.
"""
self._show_later(
status=self.FAIL,
body="".join(format_exception(*exc_info)),
subject=subtest,
)
return self._format_subtest_result(test, subtest, self._fail)
def subtest_errored(self, test, subtest, exc_info):
"""
Output an errored subtest.
"""
self._show_later(
status=self.ERROR,
body="".join(format_exception(*exc_info)),
subject=subtest,
)
return self._format_subtest_result(test, subtest, self._error)
def _format_line(self, test, result):
before = f"{self.indent}{self.indent}{test._testMethodName} ..."
return self._pad_center(left=before, right=result) + "\n"
def _format_subtest_result(self, test, subtest, result):
if self._current_subtests_test != test.id():
before = f"{self.indent}{self.indent}{test._testMethodName}\n"
else:
before = ""
self._current_subtests_test = test.id()
line = f"{self.indent * 3}{subtest._subDescription()[1:-1]} ..."
return f"{before}{self._pad_center(left=line, right=result)}\n"
def _pad_center(self, left, right):
space = self.line_width - len(left) - len(right)
return left + " " * space + right
|
class Outputter:
'''
An outputter converts test results to renderable strings.
'''
def __init__(self, colored=True, indent=" " * 2, line_width=120):
pass
def _show_later(self, **kwargs):
pass
def run_started(self):
'''
Output nothing.
'''
pass
def run_stopped(self, recorder, runtime):
'''
Output all the messages stored for later, as well as a final summary.
'''
pass
def test_started(self, test):
'''
Output the test name.
'''
pass
def test_stopped(self, test):
'''
Output nothing.
'''
pass
def test_errored(self, test, exc_info):
'''
Output an error.
'''
pass
def test_failed(self, test, exc_info):
'''
Output a failure.
'''
pass
def test_skipped(self, test, reason):
'''
Output a skip.
'''
pass
def test_expectedly_failed(self, test, exc_info):
'''
Output an expected failure.
'''
pass
def test_unexpectedly_succeeded(self, test):
'''
Output an unexpected success.
'''
pass
def test_succeeded(self, test):
'''
Output a success.
'''
pass
def subtest_succeeded(self, test, subtest):
'''
Output nothing.
'''
pass
def subtest_failed(self, test, subtest, exc_info):
'''
Output a failed subtest.
'''
pass
def subtest_errored(self, test, subtest, exc_info):
'''
Output an errored subtest.
'''
pass
def _format_line(self, test, result):
pass
def _format_subtest_result(self, test, subtest, result):
pass
def _pad_center(self, left, right):
pass
| 19 | 14 | 10 | 1 | 8 | 2 | 2 | 0.27 | 0 | 2 | 1 | 0 | 18 | 3 | 18 | 18 | 228 | 32 | 154 | 50 | 134 | 42 | 107 | 50 | 87 | 12 | 0 | 3 | 35 |
140,153 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/samples/module_for_TestObjectLocator.py
|
virtue.tests.samples.module_for_TestObjectLocator.Baz
|
class Baz:
def test_bar(self):
pass
def test_baz(self):
pass
|
class Baz:
def test_bar(self):
pass
def test_baz(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 6 | 1 | 5 | 3 | 2 | 0 | 5 | 3 | 2 | 1 | 0 | 0 | 2 |
140,154 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/samples/module_for_TestObjectLocator.py
|
virtue.tests.samples.module_for_TestObjectLocator.Foo
|
class Foo(TestCase):
def stuff(self):
pass
def test_foo(self):
pass
|
class Foo(TestCase):
def stuff(self):
pass
def test_foo(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 74 | 6 | 1 | 5 | 3 | 2 | 0 | 5 | 3 | 2 | 1 | 2 | 0 | 2 |
140,155 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/samples/one_expected_failure.py
|
virtue.tests.samples.one_expected_failure.Foo
|
class Foo(TestCase):
@expectedFailure
def test_foo(self):
self.fail("I fail!")
|
class Foo(TestCase):
@expectedFailure
def test_foo(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 4 | 0 | 4 | 3 | 1 | 0 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
140,156 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/samples/one_expected_failure_mispassing.py
|
virtue.tests.samples.one_expected_failure_mispassing.Foo
|
class Foo(TestCase):
@expectedFailure
def test_foo(self):
pass
|
class Foo(TestCase):
@expectedFailure
def test_foo(self):
pass
| 3 | 0 | 2 | 0 | 2 | 1 | 1 | 0.25 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 4 | 0 | 4 | 3 | 1 | 1 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
140,157 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/samples/one_successful_test.py
|
virtue.tests.samples.one_successful_test.Foo
|
class Foo(TestCase):
def test_foo(self):
pass
|
class Foo(TestCase):
def test_foo(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
140,158 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/samples/mixin.py
|
virtue.tests.samples.mixin.TestFoo
|
class TestFoo(FooMixin, TestCase):
pass
|
class TestFoo(FooMixin, TestCase):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 77 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 2 | 0 | 0 |
140,159 |
Julian/Virtue
|
Julian_Virtue/virtue/reporters.py
|
virtue.reporters.Counter
|
class Counter:
"""
A counter is a recorder that does not hold references to tests it sees.
"""
errors: int = 0
failures: int = 0
expected_failures: int = 0
unexpected_successes: int = 0
successes: int = 0
subtest_successes: int = 0
subtest_failures: int = 0
subtest_errors: int = 0
shouldStop = False
@property
def count(self):
"""
Return a total count of all tests.
"""
return sum(attrs.astuple(self))
testsRun = count
def startTest(self, test): # noqa: D102
pass
def stopTest(self, test): # noqa: D102
pass
def addError(self, test, exc_info): # noqa: D102
self.errors += 1
def addFailure(self, test, exc_info): # noqa: D102
self.failures += 1
def addExpectedFailure(self, *args, **kwargs): # noqa: D102
self.expected_failures += 1
def addUnexpectedSuccess(self, test): # noqa: D102
self.unexpected_successes += 1
def addSuccess(self, test): # noqa: D102
self.successes += 1
def addDuration(self, test, elapsed): # noqa: D102
pass
def addSubTest(self, test, subtest, outcome): # noqa: D102
if outcome is None:
self.subtest_successes += 1
elif issubclass(outcome[0], test.failureException):
self.subtest_failures += 1
else:
self.subtest_errors += 1
|
class Counter:
'''
A counter is a recorder that does not hold references to tests it sees.
'''
@property
def count(self):
'''
Return a total count of all tests.
'''
pass
def startTest(self, test):
pass
def stopTest(self, test):
pass
def addError(self, test, exc_info):
pass
def addFailure(self, test, exc_info):
pass
def addExpectedFailure(self, *args, **kwargs):
pass
def addUnexpectedSuccess(self, test):
pass
def addSuccess(self, test):
pass
def addDuration(self, test, elapsed):
pass
def addSubTest(self, test, subtest, outcome):
pass
| 12 | 2 | 3 | 0 | 3 | 1 | 1 | 0.41 | 0 | 0 | 0 | 0 | 10 | 0 | 10 | 10 | 57 | 14 | 37 | 22 | 25 | 15 | 34 | 21 | 23 | 3 | 0 | 1 | 12 |
140,160 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/test_runner.py
|
virtue.tests.test_runner.TestRunOutput
|
class TestRunOutput(unittest.TestCase):
def assertOutputIs(self, expected, **kwargs):
reporter = ComponentizedReporter(
outputter=Outputter(colored=False, line_width=40),
stream=StringIO(),
time=lambda: 0,
)
runner.run(reporter=reporter, **kwargs)
got = reporter.stream.getvalue()
dedented = dedent(expected)
dedented = dedented.removeprefix("\n")
# I'm so sorry.
globbed = re.escape(dedented).replace(re.escape("•"), ".*")
if re.search(globbed, got, re.DOTALL) is None:
self.fail(
"\n "
+ "\n ".join(
ndiff(got.splitlines(), dedented.splitlines()),
),
)
def test_unsuccessful_run(self):
self.assertOutputIs(
tests=[
"virtue.tests.samples.one_successful_test",
"virtue.tests.samples.two_unsuccessful_tests",
],
expected="""
virtue.tests.samples.one_successful_test
Foo
test_foo ... [OK]
virtue.tests.samples.two_unsuccessful_tests
Bar
test_bar ... [OK]
test_foo ... [FAIL]
Foo
test_bar ... [FAIL]
test_foo ... [OK]
========================================
[FAIL]
Traceback (most recent call last):•
File "•unittest/case.py•", line •, in •
•
File "•virtue/tests/samples/two_unsuccessful_tests.py•", line 14, in test_foo
self.fail("I fail too.")
•
AssertionError: I fail too.
virtue.tests.samples.two_unsuccessful_tests.Bar.test_foo
========================================
[FAIL]
Traceback (most recent call last):•
File "•unittest/case.py•", line •, in •
•
File "•virtue/tests/samples/two_unsuccessful_tests.py•", line 9, in test_bar
self.fail("I fail.")
•
AssertionError: I fail.
virtue.tests.samples.two_unsuccessful_tests.Foo.test_bar
----------------------------------------
Ran 5 tests in 0.000s
FAILED (successes=3, failures=2)
""", # noqa: E501
)
def test_single_test(self):
self.assertOutputIs(
tests=["virtue.tests.samples.one_successful_test"],
expected="""
virtue.tests.samples.one_successful_test
Foo
test_foo ... [OK]
----------------------------------------
Ran 1 test in 0.000s
PASSED (successes=1)
""",
)
def test_empty_run(self):
self.assertOutputIs(
tests=[],
expected="""
----------------------------------------
Ran 0 tests in 0.000s
PASSED
""",
)
def test_expected_failure(self):
self.assertOutputIs(
tests=["virtue.tests.samples.one_expected_failure"],
expected="""
virtue.tests.samples.one_expected_failure
Foo
test_foo ... [XFAIL]
========================================
[XFAIL]
virtue.tests.samples.one_expected_failure.Foo.test_foo
----------------------------------------
Ran 1 test in 0.000s
PASSED (expected_failures=1)
""",
)
def test_unexpected_success(self):
self.assertOutputIs(
tests=["virtue.tests.samples.failures_and_unexpected_passes"],
expected="""
virtue.tests.samples.failures_and_unexpected_passes
Foo
test_bar ... [UNEXPECTED SUCCESS]
test_baz ... [UNEXPECTED SUCCESS]
test_foo ... [FAIL]
test_quux ... [UNEXPECTED SUCCESS]
test_spam ... [OK]
========================================
[FAIL]
Traceback (most recent call last):
File "•unittest/case.py•", line •, in •
•
File "•/failures_and_unexpected_passes.py•", line •, in test_foo
self.fail("Nope!")
•
AssertionError: Nope!
virtue.tests.samples.failures_and_unexpected_passes.Foo.test_foo
========================================
[UNEXPECTED SUCCESS]
virtue.tests.samples.failures_and_unexpected_passes.Foo.test_bar
virtue.tests.samples.failures_and_unexpected_passes.Foo.test_baz
virtue.tests.samples.failures_and_unexpected_passes.Foo.test_quux
----------------------------------------
Ran 5 tests in 0.000s
FAILED (successes=1, failures=1, unexpected_successes=3)
""",
)
def test_subtests(self):
self.assertOutputIs(
tests=["virtue.tests.samples.subtests"],
expected="""
virtue.tests.samples.subtests
Baz
test_passing_nested_subtest ... [OK]
test_passing_subtest ... [OK]
Foo
test_no_subtests ... [OK]
test_subtests_one_fail_one_error
i=1 ... [FAIL]
i=3 ... [ERROR]
========================================
[FAIL]
Traceback (most recent call last):
File "•unittest/case.py•", line •, in •
•
File "•/subtests.py•", line •, in test_subtests_one_fail_one_error
self.fail("Fail!")
•
AssertionError: Fail!
virtue.tests.samples.subtests.Foo.test_subtests_one_fail_one_error (i=1)
========================================
[ERROR]
Traceback (most recent call last):
File "•unittest/case.py•", line •, in •
•
File "•/subtests.py•", line •, in test_subtests_one_fail_one_error
raise ZeroDivisionError()•
ZeroDivisionError•
virtue.tests.samples.subtests.Foo.test_subtests_one_fail_one_error (i=3)
----------------------------------------
Ran 4 tests with 7 subtests in 0.000s
FAILED (successes=3, subtest_failures=1, subtest_errors=1)
""", # noqa: E501
)
def test_output_is_compressed(self):
"""
Albeit not sorted, so still not terribly reliably :/.
"""
self.assertOutputIs(
tests=["virtue.tests.samples.repeated_similar_output"],
expected="""
virtue.tests.samples.repeated_similar_output
Foo
test_a ... [SKIPPED]
test_b ... [SKIPPED]
test_c ... [SKIPPED]
========================================
[SKIPPED]
Skipped!
virtue.tests.samples.repeated_similar_output.Foo.test_a
========================================
[SKIPPED]
Skipped 2!
virtue.tests.samples.repeated_similar_output.Foo.test_b
virtue.tests.samples.repeated_similar_output.Foo.test_c
----------------------------------------
Ran 3 tests in 0.000s
PASSED (skips=3)
""",
)
|
class TestRunOutput(unittest.TestCase):
def assertOutputIs(self, expected, **kwargs):
pass
def test_unsuccessful_run(self):
pass
def test_single_test(self):
pass
def test_empty_run(self):
pass
def test_expected_failure(self):
pass
def test_unexpected_success(self):
pass
def test_subtests(self):
pass
def test_output_is_compressed(self):
'''
Albeit not sorted, so still not terribly reliably :/.
'''
pass
| 9 | 1 | 27 | 3 | 23 | 1 | 1 | 0.03 | 1 | 2 | 2 | 0 | 8 | 0 | 8 | 80 | 223 | 31 | 188 | 13 | 179 | 6 | 24 | 13 | 15 | 2 | 2 | 1 | 9 |
140,161 |
Julian/Virtue
|
Julian_Virtue/virtue/locators.py
|
virtue.locators.UnableToLoad
|
class UnableToLoad(Exception):
"""
A test couldn't be loaded.
"""
|
class UnableToLoad(Exception):
'''
A test couldn't be loaded.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 3 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 4 | 0 | 1 | 1 | 0 | 3 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,162 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/samples/two_unsuccessful_tests.py
|
virtue.tests.samples.two_unsuccessful_tests.Bar
|
class Bar(TestCase):
def test_foo(self):
self.fail("I fail too.")
def test_bar(self):
pass
|
class Bar(TestCase):
def test_foo(self):
pass
def test_bar(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 74 | 6 | 1 | 5 | 3 | 2 | 0 | 5 | 3 | 2 | 1 | 2 | 0 | 2 |
140,163 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/samples/two_unsuccessful_tests.py
|
virtue.tests.samples.two_unsuccessful_tests.Foo
|
class Foo(TestCase):
def test_foo(self):
pass
def test_bar(self):
self.fail("I fail.")
|
class Foo(TestCase):
def test_foo(self):
pass
def test_bar(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 74 | 6 | 1 | 5 | 3 | 2 | 0 | 5 | 3 | 2 | 1 | 2 | 0 | 2 |
140,164 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/samples/success_and_warning.py
|
virtue.tests.samples.success_and_warning.Foo
|
class Foo(TestCase):
def test_foo(self):
pass
def test_bar(self):
warnings.warn("Oh no! A Warning!")
|
class Foo(TestCase):
def test_foo(self):
pass
def test_bar(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 74 | 6 | 1 | 5 | 3 | 2 | 0 | 5 | 3 | 2 | 1 | 2 | 0 | 2 |
140,165 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/samples/subtests.py
|
virtue.tests.samples.subtests.Foo
|
class Foo(TestCase):
def test_no_subtests(self):
pass
def test_subtests_one_fail_one_error(self):
for i in range(4):
with self.subTest(i=i):
if i == 1:
self.fail("Fail!")
elif i == 3:
raise ZeroDivisionError()
|
class Foo(TestCase):
def test_no_subtests(self):
pass
def test_subtests_one_fail_one_error(self):
pass
| 3 | 0 | 5 | 0 | 5 | 0 | 3 | 0 | 1 | 2 | 0 | 0 | 2 | 0 | 2 | 74 | 11 | 1 | 10 | 4 | 7 | 0 | 9 | 4 | 6 | 4 | 2 | 3 | 5 |
140,166 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/samples/subtests.py
|
virtue.tests.samples.subtests.Baz
|
class Baz(TestCase):
def test_passing_nested_subtest(self):
with self.subTest(quux="hello", spam="eggs"):
with self.subTest(i=3):
pass
def test_passing_subtest(self):
with self.subTest(eggs=3):
pass
|
class Baz(TestCase):
def test_passing_nested_subtest(self):
pass
def test_passing_subtest(self):
pass
| 3 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 74 | 9 | 1 | 8 | 3 | 5 | 0 | 8 | 3 | 5 | 1 | 2 | 2 | 2 |
140,167 |
Julian/Virtue
|
Julian_Virtue/virtue/_cli.py
|
virtue._cli._Reporter
|
class _Reporter(click.ParamType):
name = "reporter"
_BUILT_IN = {
"bwverbose": twisted.trial.reporter.VerboseTextReporter,
"default": ComponentizedReporter,
"subunit": twisted.trial.reporter.SubunitReporter,
"summary": twisted.trial.reporter.MinimalReporter,
"text": twisted.trial.reporter.TextReporter,
"timing": twisted.trial.reporter.TimingTextReporter,
"tree": twisted.trial.reporter.TreeReporter,
"verbose": twisted.trial.reporter.VerboseTextReporter,
}
def convert(self, value, param, ctx):
if not isinstance(value, str):
return value
Reporter = self._BUILT_IN.get(value)
if Reporter is None:
try:
Reporter = resolve_name(value)
except (ValueError, ImportError, AttributeError) as err:
exc = click.BadParameter(f"{value!r} is not a known reporter")
raise exc from err
return Reporter()
|
class _Reporter(click.ParamType):
def convert(self, value, param, ctx):
pass
| 2 | 0 | 13 | 2 | 11 | 0 | 4 | 0 | 1 | 4 | 0 | 0 | 1 | 0 | 1 | 1 | 27 | 4 | 23 | 7 | 21 | 0 | 14 | 6 | 12 | 4 | 1 | 2 | 4 |
140,168 |
Julian/Virtue
|
Julian_Virtue/virtue/loaders.py
|
virtue.loaders.AttributeLoader
|
class AttributeLoader:
"""
I load a test case by instantiating a class with a given attribute name.
This is the typical way that `unittest.TestCase` methods are loaded:
by calling ``TestCase("test_something")`` (and then by calling
:meth:`~unittest.TestCase.run` on the resulting instance to run the
selected test method).
"""
cls: type
attribute: str
def load(self):
"""
Load as a single test.
"""
return [self.cls(self.attribute)]
|
class AttributeLoader:
'''
I load a test case by instantiating a class with a given attribute name.
This is the typical way that `unittest.TestCase` methods are loaded:
by calling ``TestCase("test_something")`` (and then by calling
:meth:`~unittest.TestCase.run` on the resulting instance to run the
selected test method).
'''
def load(self):
'''
Load as a single test.
'''
pass
| 2 | 2 | 5 | 0 | 2 | 3 | 1 | 2 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 18 | 3 | 5 | 2 | 3 | 10 | 5 | 2 | 3 | 1 | 0 | 0 | 1 |
140,169 |
Julian/Virtue
|
Julian_Virtue/virtue/loaders.py
|
virtue.loaders.ModuleLoader
|
class ModuleLoader:
"""
I load a test case by locating tests in the module with the given name.
"""
locator: ObjectLocator = field(repr=False)
module: twisted.python.modules.PythonModule
def load(self):
"""
Load all test cases in the module.
"""
class_loaders = self.locator.locate_in_module(self.module.load())
return itertools.chain.from_iterable(
class_loader.load() for class_loader in class_loaders
)
|
class ModuleLoader:
'''
I load a test case by locating tests in the module with the given name.
'''
def load(self):
'''
Load all test cases in the module.
'''
pass
| 2 | 2 | 8 | 0 | 5 | 3 | 1 | 0.75 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 16 | 2 | 8 | 4 | 6 | 6 | 6 | 4 | 4 | 1 | 0 | 0 | 1 |
140,170 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/test_cli.py
|
virtue.tests.test_cli.TestMain
|
class TestMain(TestCase):
# TODO: these write to stdout
def test_it_exits_successfully_for_successful_runs(self):
with self.assertRaises(SystemExit) as e:
_cli.main(
[
"--reporter",
"summary",
"virtue.tests.samples.one_successful_test",
],
)
self.assertEqual(e.exception.code, os.EX_OK)
def test_it_exits_unsuccessfully_for_unsuccessful_runs(self):
with self.assertRaises(SystemExit) as e:
_cli.main(
[
"--reporter",
"text",
"virtue.tests.samples.one_unsuccessful_test",
],
)
self.assertNotEqual(e.exception.code, os.EX_OK)
def test_it_exits_unsuccessfully_for_unknown_reporters(self):
with self.assertRaises(SystemExit) as e:
_cli.main(
[
"--reporter",
"non-existent reporter",
"virtue.tests.samples.one_unsuccessful_test",
],
)
self.assertNotEqual(e.exception.code, os.EX_OK)
def test_it_exits_unsuccessfully_when_no_tests_ran(self):
with self.assertRaises(SystemExit) as e:
_cli.main(["virtue.tests.samples.no_tests"])
self.assertNotEqual(e.exception.code, os.EX_OK)
|
class TestMain(TestCase):
def test_it_exits_successfully_for_successful_runs(self):
pass
def test_it_exits_unsuccessfully_for_unsuccessful_runs(self):
pass
def test_it_exits_unsuccessfully_for_unknown_reporters(self):
pass
def test_it_exits_unsuccessfully_when_no_tests_ran(self):
pass
| 5 | 0 | 9 | 0 | 9 | 0 | 1 | 0.03 | 1 | 1 | 0 | 0 | 4 | 0 | 4 | 76 | 39 | 3 | 35 | 9 | 30 | 1 | 17 | 5 | 12 | 1 | 2 | 1 | 4 |
140,171 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/test_loaders.py
|
virtue.tests.test_loaders.TestAttributeLoader
|
class TestAttributeLoader(TestCase):
def test_it_loads_attributes(self):
cls, attr = self.__class__, "test_it_loads_attributes"
loader = loaders.AttributeLoader(cls=cls, attribute=attr)
self.assertEqual(list(loader.load()), [cls(attr)])
def test_eq_neq(self):
cls = self.__class__
loader = loaders.AttributeLoader(cls=cls, attribute="test_eq")
self.assertTrue(
loader == loaders.AttributeLoader(cls=cls, attribute="test_eq"),
)
self.assertFalse(
loader != loaders.AttributeLoader(cls=cls, attribute="test_eq"),
)
self.assertFalse(
loader == loaders.AttributeLoader(cls=cls, attribute="test_neq"),
)
self.assertTrue(
loader != loaders.AttributeLoader(cls=cls, attribute="test_neq"),
)
def test_repr(self):
loader = loaders.AttributeLoader(
cls=self.__class__,
attribute="test_repr",
)
self.assertEqual(
repr(loader),
"AttributeLoader(cls=<class 'virtue.tests.test_loaders.TestAttributeLoader'>, attribute='test_repr')", # noqa: E501
)
|
class TestAttributeLoader(TestCase):
def test_it_loads_attributes(self):
pass
def test_eq_neq(self):
pass
def test_repr(self):
pass
| 4 | 0 | 9 | 0 | 9 | 0 | 1 | 0.03 | 1 | 2 | 1 | 0 | 3 | 1 | 3 | 75 | 31 | 2 | 29 | 10 | 25 | 1 | 15 | 9 | 11 | 1 | 2 | 0 | 3 |
140,172 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/test_loaders.py
|
virtue.tests.test_loaders.TestModuleLoader
|
class TestModuleLoader(TestCase):
locator = locators.ObjectLocator()
def test_it_loads_modules(self):
module = get_module("virtue.tests.samples.module_for_TestLoaders")
loader = loaders.ModuleLoader(locator=self.locator, module=module)
cases = module.load()
self.assertEqual(
list(loader.load()),
[
cases.Baz("test_bar"),
cases.Baz("test_baz"),
cases.Foo("test_foo"),
],
)
def test_eq_neq(self):
virtue, os = get_module("virtue"), get_module("os")
loader = loaders.ModuleLoader(locator=self.locator, module=virtue)
self.assertEqual(
loader,
loaders.ModuleLoader(locator=self.locator, module=virtue),
)
self.assertNotEqual(
loader,
loaders.ModuleLoader(locator=self.locator, module=os),
)
def test_repr(self):
virtue = get_module("virtue")
loader = loaders.ModuleLoader(locator=self.locator, module=virtue)
self.assertEqual(
repr(loader),
"ModuleLoader(module=PythonModule<'virtue'>)",
)
|
class TestModuleLoader(TestCase):
def test_it_loads_modules(self):
pass
def test_eq_neq(self):
pass
def test_repr(self):
pass
| 4 | 0 | 10 | 0 | 10 | 0 | 1 | 0 | 1 | 2 | 1 | 0 | 3 | 0 | 3 | 75 | 36 | 4 | 32 | 12 | 28 | 0 | 16 | 12 | 12 | 1 | 2 | 0 | 3 |
140,173 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/test_locators.py
|
virtue.tests.test_locators.TestObjectLocator
|
class TestObjectLocator(TestCase):
def test_it_finds_tests_in_an_object_specified_by_name(self):
locator = locators.ObjectLocator()
self.assertEqual(
list(locator.locate_by_name(fullyQualifiedName(self.__class__))),
list(locator.locate_in(self.__class__)),
)
def test_it_can_locate_methods_directly_by_name(self):
locator = locators.ObjectLocator()
this_name = "test_it_can_locate_methods_directly_by_name"
this_fully_qualified_name = ".".join(
[fullyQualifiedName(self.__class__), this_name],
)
self.assertEqual(
list(locator.locate_by_name(this_fully_qualified_name)),
[AttributeLoader(cls=self.__class__, attribute=this_name)],
)
def test_it_can_locate_aliased_methods_directly_by_name(self):
locator = locators.ObjectLocator()
this_name = "test_it_can_locate_aliased_methods_directly_by_name"
aliased_fully_qualified_name = f"{self.__class__.__module__}.aliased"
self.assertEqual(
list(locator.locate_by_name(aliased_fully_qualified_name)),
[AttributeLoader(cls=self.__class__, attribute=this_name)],
)
def test_it_finds_methods_on_test_cases(self):
locator = locators.ObjectLocator(
is_test_method=locators.prefixed_by("TEST"),
)
class ASampleTestCase(TestCase):
def not_a_test(self):
pass
def TEST1(self):
pass
def TEST_2(self):
pass
cases = locator.locate_in(ASampleTestCase)
self.assertEqual(
sorted(cases, key=attrgetter("attribute")),
[
AttributeLoader(cls=ASampleTestCase, attribute="TEST1"),
AttributeLoader(cls=ASampleTestCase, attribute="TEST_2"),
],
)
def test_by_default_it_looks_for_methods_prefixed_by_test(self):
locator = locators.ObjectLocator()
class ASampleTestCase(TestCase):
def not_a_test(self):
pass
def TEST1(self):
pass
def test_foo(self):
pass
def testBar(self):
pass
cases = locator.locate_in(ASampleTestCase)
self.assertEqual(
sorted(cases, key=attrgetter("attribute")),
[
AttributeLoader(cls=ASampleTestCase, attribute="testBar"),
AttributeLoader(cls=ASampleTestCase, attribute="test_foo"),
],
)
def test_it_ignores_non_callable_test_methods(self):
locator = locators.ObjectLocator()
class ASampleTestCase(TestCase):
test_foo = 12
def test_bar(self):
pass
cases = locator.locate_in(ASampleTestCase)
self.assertEqual(
sorted(cases, key=attrgetter("attribute")),
[
AttributeLoader(cls=ASampleTestCase, attribute="test_bar"),
],
)
def test_it_loads_methods_from_dynamically_created_test_case_classes(self):
locator = locators.ObjectLocator()
from virtue.tests.samples.dynamic_test import TestFoo
name = "virtue.tests.samples.dynamic_test.TestFoo.test_F0"
self.assertEqual(
list(locator.locate_by_name(name)),
[AttributeLoader(cls=TestFoo, attribute="test_F0")],
)
def test_it_loads_methods_from_test_case_classes_with_mixin_methods(self):
locator = locators.ObjectLocator()
from virtue.tests.samples.mixin import TestFoo
name = "virtue.tests.samples.mixin.TestFoo.test_baz"
self.assertEqual(
list(locator.locate_by_name(name)),
[AttributeLoader(cls=TestFoo, attribute="test_baz")],
)
def test_it_finds_test_case_classes_on_modules(self):
locator = locators.ObjectLocator(
is_test_class=(lambda attr, value: attr != "Foo"),
)
from virtue.tests.samples import module_for_TestObjectLocator as module
cases = locator.locate_in(module)
self.assertEqual(
sorted(cases, key=attrgetter("attribute")),
[
AttributeLoader(cls=module.Baz, attribute="test_bar"),
AttributeLoader(cls=module.Baz, attribute="test_baz"),
AttributeLoader(cls=module.Bar, attribute="test_foo"),
],
)
def test_by_default_it_looks_for_classes_inheriting_TestCase(self):
locator = locators.ObjectLocator()
from virtue.tests.samples import module_for_TestObjectLocator as module
cases = locator.locate_in(module)
self.assertEqual(
sorted(cases, key=attrgetter("attribute")),
[
AttributeLoader(cls=module.Foo, attribute="test_foo"),
],
)
def test_it_finds_test_cases_recursively_in_packages(self):
locator = locators.ObjectLocator(
is_test_module=(lambda name: name != "foo"),
)
package = self.create_package_with_tests(locator)
cases = locator.locate_in(package)
self.assertEqual(
sorted(case.module.name for case in cases),
[
"virtue.tests.temp",
"virtue.tests.temp.bar",
"virtue.tests.temp.sub",
"virtue.tests.temp.sub.test_quux",
"virtue.tests.temp.test_baz",
],
)
def test_by_default_it_finds_test_cases_in_modules_named_test_(self):
locator = locators.ObjectLocator()
package = self.create_package_with_tests(locator)
cases = locator.locate_in(package)
self.assertEqual(
sorted(case.module.name for case in cases),
[
"virtue.tests.temp.sub.test_quux",
"virtue.tests.temp.test_baz",
],
)
def test_it_knows_what_it_does_not_know(self):
with self.assertRaises(locators.UnableToLoad):
locators.ObjectLocator().locate_in(object())
def create_package_with_tests(self, locator):
package_path = FilePath(__file__).sibling(b"temp")
package_path.makedirs()
self.addCleanup(shutil.rmtree, package_path.path)
package_path.child(b"__init__.py").setContent(b"")
package_path.child(b"bar.py").setContent(b"")
package_path.child(b"test_baz.py").setContent(b"")
subpackage = package_path.child(b"sub")
subpackage.makedirs()
subpackage.child(b"__init__.py").setContent(b"")
subpackage.child(b"test_quux.py").setContent(b"")
from virtue.tests import temp as package
return package
|
class TestObjectLocator(TestCase):
def test_it_finds_tests_in_an_object_specified_by_name(self):
pass
def test_it_can_locate_methods_directly_by_name(self):
pass
def test_it_can_locate_aliased_methods_directly_by_name(self):
pass
def test_it_finds_methods_on_test_cases(self):
pass
class ASampleTestCase(TestCase):
def not_a_test(self):
pass
def TEST1(self):
pass
def TEST_2(self):
pass
def test_by_default_it_looks_for_methods_prefixed_by_test(self):
pass
class ASampleTestCase(TestCase):
def not_a_test(self):
pass
def TEST1(self):
pass
def test_foo(self):
pass
def testBar(self):
pass
def test_it_ignores_non_callable_test_methods(self):
pass
class ASampleTestCase(TestCase):
def test_bar(self):
pass
def test_it_loads_methods_from_dynamically_created_test_case_classes(self):
pass
def test_it_loads_methods_from_test_case_classes_with_mixin_methods(self):
pass
def test_it_finds_test_case_classes_on_modules(self):
pass
def test_by_default_it_looks_for_classes_inheriting_TestCase(self):
pass
def test_it_finds_test_cases_recursively_in_packages(self):
pass
def test_by_default_it_finds_test_cases_in_modules_named_test_(self):
pass
def test_it_knows_what_it_does_not_know(self):
pass
def create_package_with_tests(self, locator):
pass
| 26 | 0 | 9 | 1 | 8 | 0 | 1 | 0 | 1 | 12 | 10 | 0 | 14 | 1 | 14 | 86 | 192 | 33 | 159 | 62 | 128 | 0 | 92 | 61 | 61 | 1 | 2 | 1 | 22 |
140,174 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/test_reporters.py
|
virtue.tests.test_reporters.TestRecorder
|
class TestRecorder(TestCase):
def setUp(self):
self.recorder = reporters.Recorder()
def test_it_records_errors(self):
error, exc_info = object(), object()
self.recorder.addError(error, exc_info)
self.assertEqual(self.recorder.errors, [(error, exc_info)])
self.assertFalse(self.recorder.wasSuccessful())
def test_it_records_failures(self):
failure, exc_info = object(), object()
self.recorder.addFailure(failure, exc_info)
self.assertEqual(self.recorder.failures, [(failure, exc_info)])
self.assertFalse(self.recorder.wasSuccessful())
def test_it_records_successes(self):
success = object()
self.recorder.addSuccess(success)
self.assertEqual(self.recorder.successes, [success])
self.assertTrue(self.recorder.wasSuccessful())
def test_it_records_unexpected_successes(self):
success = object()
self.recorder.addUnexpectedSuccess(success)
self.assertEqual(self.recorder.unexpected_successes, [success])
self.assertFalse(self.recorder.wasSuccessful())
def test_testsRun(self):
test, exc_info, reason = object(), object(), "Because!"
self.recorder.addError(test=test, exc_info=exc_info)
self.recorder.addFailure(test=test, exc_info=exc_info)
self.recorder.addSkip(test=test, reason=reason)
self.recorder.addSuccess(test=test)
self.recorder.addUnexpectedSuccess(test=test)
self.assertEqual(self.recorder.testsRun, 5)
|
class TestRecorder(TestCase):
def setUp(self):
pass
def test_it_records_errors(self):
pass
def test_it_records_failures(self):
pass
def test_it_records_successes(self):
pass
def test_it_records_unexpected_successes(self):
pass
def test_testsRun(self):
pass
| 7 | 0 | 5 | 0 | 5 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 6 | 1 | 6 | 78 | 36 | 5 | 31 | 13 | 24 | 0 | 31 | 13 | 24 | 1 | 2 | 0 | 6 |
140,175 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/test_runner.py
|
virtue.tests.test_runner.TestRun
|
class TestRun(unittest.TestCase):
def test_it_runs_tests(self):
result = runner.run(tests=["virtue.tests.samples.one_successful_test"])
self.assertEqual(result, Counter(successes=1))
def test_it_runs_unsuccessful_tests(self):
result = runner.run(
tests=["virtue.tests.samples.one_unsuccessful_test"],
)
self.assertEqual(result, Counter(failures=1))
def test_it_runs_expected_failing_tests(self):
result = runner.run(
tests=["virtue.tests.samples.one_expected_failure"],
)
self.assertEqual(result, Counter(expected_failures=1))
def test_it_runs_unexpectedly_passing_expected_failing_tests(self):
result = runner.run(
tests=[
"virtue.tests.samples.one_expected_failure_mispassing",
],
)
self.assertEqual(result, Counter(unexpected_successes=1))
def test_it_runs_subtests(self):
result = runner.run(tests=["virtue.tests.samples.subtests"])
self.assertEqual(
result,
Counter(
subtest_failures=1,
subtest_successes=4,
successes=3,
errors=1,
),
)
def test_it_can_stop_short(self):
"""
Ooo, I stopped short.
"""
result = runner.run(
tests=["virtue.tests.samples.two_unsuccessful_tests"],
stop_after=1,
)
self.assertEqual(
result,
Counter(failures=1, successes=result.successes),
)
def test_it_can_stop_short_combined_with_errors(self):
counter = runner.run(
tests=["virtue.tests.samples.failures_and_errors"],
)
self.assertGreater(counter.failures + counter.errors, 3)
result = runner.run(
tests=["virtue.tests.samples.failures_and_errors"],
stop_after=3,
)
self.assertEqual(result.failures + result.errors, 3)
def test_it_can_stop_short_combined_with_unexpected_passing_tests(self):
"""
RIP Jerry.
"""
counter = runner.run(
tests=["virtue.tests.samples.failures_and_unexpected_passes"],
)
self.assertGreater(counter.failures + counter.unexpected_successes, 2)
result = runner.run(
tests=["virtue.tests.samples.failures_and_unexpected_passes"],
stop_after=2,
)
self.assertEqual(result.failures + result.unexpected_successes, 2)
def test_warnings_become_errors_by_default(self):
result = runner.run(
tests=["virtue.tests.samples.success_and_warning"],
)
self.assertEqual(result, Counter(errors=1, successes=1))
def test_it_runs_tests_by_path_if_you_insist(self):
import virtue.tests.samples
path = os.path.join(
os.path.dirname(virtue.tests.samples.__file__),
"one_unsuccessful_test.py",
)
result = runner.run(tests=[path])
self.assertEqual(result, Counter(failures=1))
def test_it_errors_for_paths_that_do_not_exist(self):
path = os.path.join(
os.path.dirname(__file__),
"this_is_a_path_that_doesnt_exist_yes_it_goes_on_and_on_my_friend",
)
with self.assertRaises(FileNotFoundError):
runner.run(tests=[path])
def test_unittest_TestResult(self):
result = unittest.TestResult()
runner.run(
tests=["virtue.tests.samples.one_successful_test"],
reporter=result,
)
self.assertEqual(result.testsRun, 1)
def test_Recorder(self):
result = Recorder()
runner.run(
tests=["virtue.tests.samples.one_successful_test"],
reporter=result,
)
import virtue.tests.samples.one_successful_test
self.assertEqual(
result,
Recorder(
successes=v(
virtue.tests.samples.one_successful_test.Foo("test_foo"),
),
),
)
|
class TestRun(unittest.TestCase):
def test_it_runs_tests(self):
pass
def test_it_runs_unsuccessful_tests(self):
pass
def test_it_runs_expected_failing_tests(self):
pass
def test_it_runs_unexpectedly_passing_expected_failing_tests(self):
pass
def test_it_runs_subtests(self):
pass
def test_it_can_stop_short(self):
'''
Ooo, I stopped short.
'''
pass
def test_it_can_stop_short_combined_with_errors(self):
pass
def test_it_can_stop_short_combined_with_unexpected_passing_tests(self):
'''
RIP Jerry.
'''
pass
def test_warnings_become_errors_by_default(self):
pass
def test_it_runs_tests_by_path_if_you_insist(self):
pass
def test_it_errors_for_paths_that_do_not_exist(self):
pass
def test_unittest_TestResult(self):
pass
def test_Recorder(self):
pass
| 14 | 2 | 9 | 0 | 8 | 0 | 1 | 0.06 | 1 | 5 | 3 | 0 | 13 | 0 | 13 | 85 | 126 | 17 | 103 | 32 | 87 | 6 | 50 | 32 | 34 | 1 | 2 | 1 | 13 |
140,176 |
Julian/Virtue
|
Julian_Virtue/virtue/locators.py
|
virtue.locators.ObjectLocator
|
class ObjectLocator:
"""
I locate test cases on an object: a package, module or test class.
Arguments:
is_test_method (collections.abc.Callable):
decide whether the provided object is a test method
or not. By default, callable objects whose names
(``__name__``s) start with ``test_`` are considered
test methods.
is_test_class (collections.abc.Callable):
decide whether the provided object is a test
class or not. By default, objects inheriting from
`unittest.TestCase` are considered test cases.
is_test_module (collections.abc.Callable):
decide whether the provided object is a test module
or not. By default, modules whose names start with
``test_`` are considered to be test modules.
"""
#: Whether an object is a test method or not
is_test_method = field(default=prefixed_by("test"), repr=False)
#: Whether an object is a test class or not
is_test_class = field(default=inherits_from_TestCase, repr=False)
#: Whether an object is a test module or not
is_test_module = field(default=prefixed_by("test_"), repr=False)
def __attrs_post_init__(self):
is_cls, self.is_test_class = self.is_test_class, lambda attr, cls: (
inspect.isclass(cls) and is_cls(attr, cls)
)
is_meth, self.is_test_method = self.is_test_method, lambda attr, val: (
callable(val) and is_meth(attr, val)
)
def locate_by_name(self, name):
"""
Locate any tests found in the object referred to by the given name.
The name should be a fully qualified object name. (E.g., the fully
qualified object name of this function is
``virtue.locators.ObjectLocator.locate_by_name``).
A path may also alternatively used, but no `PYTHONPATH`
modification will be done, so the file must be importable
without modification.
"""
try:
obj = resolve_name(name)
except ValueError:
try:
obj = filename_to_module(name)
except ValueError as error:
raise FileNotFoundError(error) from error
try:
return self.locate_in(obj)
except UnableToLoad:
class_name, _, method_name = name.rpartition(".")
try:
cls = resolve_name(class_name)
except ValueError:
class_name, _, method_name = name.rpartition(".")
cls = resolve_name(class_name)
if inspect.isclass(cls):
return [AttributeLoader(cls=cls, attribute=method_name)]
else:
if inspect.isclass(cls):
return [AttributeLoader(cls=cls, attribute=method_name)]
# Aliased attributes
fqon = fully_qualified_name(obj)
class_name, _, method_name = fqon.rpartition(".")
cls = resolve_name(class_name)
if inspect.isclass(cls):
return [AttributeLoader(cls=cls, attribute=method_name)]
raise
def locate_in(self, obj):
"""
Attempt to locate the test cases in the given object (of any kind).
"""
# We don't use inspect.getmembers because its predicate only
# takes the value, not the attr name.
if inspect.ismodule(obj):
is_package = getattr(obj, "__path__", None)
if is_package is not None:
return self.locate_in_package(obj)
return self.locate_in_module(obj)
elif inspect.isclass(obj):
return self.locate_in_class(obj)
else:
raise UnableToLoad(
f"Can't determine the appropriate way to load {obj!r}",
)
def locate_in_package(self, package):
"""
Locate all of the test cases contained in the given package.
"""
for module in get_module(package.__name__).walkModules():
_, _, name = module.name.rpartition(".")
if self.is_test_module(name):
yield ModuleLoader(locator=self, module=module)
def locate_in_module(self, module):
"""
Locate all of the test cases contained in the given module.
"""
for attribute, value in inspect.getmembers(module):
if self.is_test_class(attribute, value):
yield from self.locate_in_class(value)
def locate_in_class(self, cls):
"""
Locate the methods on the given class that are test cases.
"""
for attribute, value in inspect.getmembers(cls):
if self.is_test_method(attribute, value):
yield AttributeLoader(cls=cls, attribute=attribute)
|
class ObjectLocator:
'''
I locate test cases on an object: a package, module or test class.
Arguments:
is_test_method (collections.abc.Callable):
decide whether the provided object is a test method
or not. By default, callable objects whose names
(``__name__``s) start with ``test_`` are considered
test methods.
is_test_class (collections.abc.Callable):
decide whether the provided object is a test
class or not. By default, objects inheriting from
`unittest.TestCase` are considered test cases.
is_test_module (collections.abc.Callable):
decide whether the provided object is a test module
or not. By default, modules whose names start with
``test_`` are considered to be test modules.
'''
def __attrs_post_init__(self):
pass
def locate_by_name(self, name):
'''
Locate any tests found in the object referred to by the given name.
The name should be a fully qualified object name. (E.g., the fully
qualified object name of this function is
``virtue.locators.ObjectLocator.locate_by_name``).
A path may also alternatively used, but no `PYTHONPATH`
modification will be done, so the file must be importable
without modification.
'''
pass
def locate_in(self, obj):
'''
Attempt to locate the test cases in the given object (of any kind).
'''
pass
def locate_in_package(self, package):
'''
Locate all of the test cases contained in the given package.
'''
pass
def locate_in_module(self, module):
'''
Locate all of the test cases contained in the given module.
'''
pass
def locate_in_class(self, cls):
'''
Locate the methods on the given class that are test cases.
'''
pass
| 7 | 6 | 15 | 1 | 10 | 4 | 4 | 0.69 | 0 | 5 | 3 | 0 | 6 | 0 | 6 | 6 | 129 | 21 | 64 | 22 | 57 | 44 | 56 | 21 | 49 | 8 | 0 | 3 | 22 |
140,177 |
Julian/Virtue
|
Julian_Virtue/virtue/reporters.py
|
virtue.reporters.ComponentizedReporter
|
class ComponentizedReporter:
"""
Combine together outputting and recording capabilities.
"""
outputter: Outputter = attrs.field(factory=Outputter)
recorder = attrs.field(factory=Recorder, repr=False)
stream = attrs.field(default=sys.stdout)
_time = attrs.field(default=time.time, repr=False)
failfast = False # FIXME: needed for subtests?
shouldStop = False
@property
def testsRun(self): # noqa: D102
return self.recorder.testsRun
def startTestRun(self): # noqa: D102
self._start_time = self._time()
self.recorder.startTestRun()
self.stream.writelines(self.outputter.run_started() or "")
def stopTestRun(self): # noqa: D102
self.recorder.stopTestRun()
runtime = self._time() - self._start_time
self.stream.writelines(
self.outputter.run_stopped(self.recorder, runtime) or "",
)
def startTest(self, test): # noqa: D102
self.recorder.startTest(test)
self.stream.writelines(self.outputter.test_started(test) or "")
def stopTest(self, test): # noqa: D102
self.recorder.stopTest(test)
self.stream.writelines(self.outputter.test_stopped(test) or "")
def addError(self, test, exc_info): # noqa: D102
self.recorder.addError(test, exc_info)
self.stream.writelines(
self.outputter.test_errored(test, exc_info) or "",
)
def addFailure(self, test, exc_info): # noqa: D102
self.recorder.addFailure(test, exc_info)
self.stream.writelines(
self.outputter.test_failed(test, exc_info) or "",
)
def addSkip(self, test, reason): # noqa: D102
self.recorder.addSkip(test, reason)
self.stream.writelines(self.outputter.test_skipped(test, reason) or "")
def addExpectedFailure(self, test, exc_info): # noqa: D102
self.recorder.addExpectedFailure(test, exc_info)
self.stream.writelines(
self.outputter.test_expectedly_failed(test, exc_info) or "",
)
def addUnexpectedSuccess(self, test): # noqa: D102
self.recorder.addUnexpectedSuccess(test)
self.stream.writelines(
self.outputter.test_unexpectedly_succeeded(test) or "",
)
def addSuccess(self, test): # noqa: D102
self.recorder.addSuccess(test)
self.stream.writelines(self.outputter.test_succeeded(test) or "")
def addDuration(self, test, elapsed): # noqa: D102
self.recorder.addDuration(test, elapsed)
def addSubTest(self, test, subtest, outcome): # noqa: D102
self.recorder.addSubTest(test, subtest, outcome)
if outcome is None:
output = self.outputter.subtest_succeeded(test, subtest)
elif issubclass(outcome[0], test.failureException):
output = self.outputter.subtest_failed(test, subtest, outcome)
else:
output = self.outputter.subtest_errored(test, subtest, outcome)
self.stream.writelines(output or "")
def wasSuccessful(self): # noqa: D102
return self.recorder.wasSuccessful()
|
class ComponentizedReporter:
'''
Combine together outputting and recording capabilities.
'''
@property
def testsRun(self):
pass
def startTestRun(self):
pass
def stopTestRun(self):
pass
def startTestRun(self):
pass
def stopTestRun(self):
pass
def addError(self, test, exc_info):
pass
def addFailure(self, test, exc_info):
pass
def addSkip(self, test, reason):
pass
def addExpectedFailure(self, test, exc_info):
pass
def addUnexpectedSuccess(self, test):
pass
def addSuccess(self, test):
pass
def addDuration(self, test, elapsed):
pass
def addSubTest(self, test, subtest, outcome):
pass
def wasSuccessful(self):
pass
| 16 | 1 | 4 | 0 | 4 | 1 | 1 | 0.28 | 0 | 0 | 0 | 0 | 14 | 1 | 14 | 14 | 84 | 16 | 65 | 25 | 49 | 18 | 52 | 24 | 37 | 3 | 0 | 1 | 16 |
140,178 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/test_cli.py
|
virtue.tests.test_cli.TestParser
|
class TestParser(TestCase):
def parse_args(self, argv):
return _cli.main.make_context("virtue", argv).params
def test_it_parses_out_tests(self):
arguments = self.parse_args(["foo", "bar", "baz"])
self.assertEqual(list(arguments["tests"]), ["foo", "bar", "baz"])
def test_it_retrieves_built_in_reporters_by_name(self):
arguments = self.parse_args(["--reporter", "tree", "foo"])
self.assertIsInstance(arguments["reporter"], TreeReporter)
def test_it_retrieves_other_reporters_by_fully_qualified_name(self):
arguments = self.parse_args(
["--reporter", "virtue.tests.test_cli.DumbReporter", "abc"],
)
self.assertEqual(arguments["reporter"], DumbReporter())
def test_stop_after(self):
arguments = self.parse_args(["-xxx", "bar", "baz"])
self.assertEqual(
(arguments["stop_after"], list(arguments["tests"])),
(3, ["bar", "baz"]),
)
def test_stop_after_default(self):
arguments = self.parse_args(["-x", "bar", "baz"])
self.assertEqual(
(arguments["stop_after"], list(arguments["tests"])),
(1, ["bar", "baz"]),
)
|
class TestParser(TestCase):
def parse_args(self, argv):
pass
def test_it_parses_out_tests(self):
pass
def test_it_retrieves_built_in_reporters_by_name(self):
pass
def test_it_retrieves_other_reporters_by_fully_qualified_name(self):
pass
def test_stop_after(self):
pass
def test_stop_after_default(self):
pass
| 7 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 6 | 0 | 6 | 78 | 31 | 5 | 26 | 12 | 19 | 0 | 18 | 12 | 11 | 1 | 2 | 0 | 6 |
140,179 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/samples/repeated_similar_output.py
|
virtue.tests.samples.repeated_similar_output.Foo
|
class Foo(TestCase):
def test_a(self):
self.skipTest("Skipped!")
def test_b(self):
self.skipTest("Skipped 2!")
def test_c(self):
self.skipTest("Skipped 2!")
|
class Foo(TestCase):
def test_a(self):
pass
def test_b(self):
pass
def test_c(self):
pass
| 4 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 75 | 9 | 2 | 7 | 4 | 3 | 0 | 7 | 4 | 3 | 1 | 2 | 0 | 3 |
140,180 |
Julian/Virtue
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Julian_Virtue/virtue/tests/test_locators.py
|
virtue.tests.test_locators.TestObjectLocator.test_it_ignores_non_callable_test_methods.ASampleTestCase
|
class ASampleTestCase(TestCase):
test_foo = 12
def test_bar(self):
pass
|
class ASampleTestCase(TestCase):
def test_bar(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 5 | 1 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 2 | 0 | 1 |
140,181 |
Julian/Virtue
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Julian_Virtue/virtue/tests/test_locators.py
|
virtue.tests.test_locators.TestObjectLocator.test_it_finds_methods_on_test_cases.ASampleTestCase
|
class ASampleTestCase(TestCase):
def not_a_test(self):
pass
def TEST1(self):
pass
def TEST_2(self):
pass
|
class ASampleTestCase(TestCase):
def not_a_test(self):
pass
def TEST1(self):
pass
def TEST_2(self):
pass
| 4 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 75 | 9 | 2 | 7 | 4 | 3 | 0 | 7 | 4 | 3 | 1 | 2 | 0 | 3 |
140,182 |
Julian/Virtue
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Julian_Virtue/virtue/tests/test_locators.py
|
virtue.tests.test_locators.TestObjectLocator.test_by_default_it_looks_for_methods_prefixed_by_test.ASampleTestCase
|
class ASampleTestCase(TestCase):
def not_a_test(self):
pass
def TEST1(self):
pass
def test_foo(self):
pass
def testBar(self):
pass
|
class ASampleTestCase(TestCase):
def not_a_test(self):
pass
def TEST1(self):
pass
def test_foo(self):
pass
def testBar(self):
pass
| 5 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 4 | 76 | 12 | 3 | 9 | 5 | 4 | 0 | 9 | 5 | 4 | 1 | 2 | 0 | 4 |
140,183 |
Julian/Virtue
|
Julian_Virtue/virtue/tests/samples/one_unsuccessful_test.py
|
virtue.tests.samples.one_unsuccessful_test.Foo
|
class Foo(TestCase):
def test_foo(self):
self.fail("I fail!")
|
class Foo(TestCase):
def test_foo(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
140,184 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.AntiDraft6LeakMixin
|
class AntiDraft6LeakMixin:
"""
Make sure functionality from draft 6 doesn't leak backwards in time.
"""
def test_True_is_not_a_schema(self):
with self.assertRaises(exceptions.SchemaError) as e:
self.Validator.check_schema(True)
self.assertIn("True is not of type", str(e.exception))
def test_False_is_not_a_schema(self):
with self.assertRaises(exceptions.SchemaError) as e:
self.Validator.check_schema(False)
self.assertIn("False is not of type", str(e.exception))
def test_True_is_not_a_schema_even_if_you_forget_to_check(self):
with self.assertRaises(Exception) as e:
self.Validator(True).validate(12)
self.assertNotIsInstance(e.exception, exceptions.ValidationError)
def test_False_is_not_a_schema_even_if_you_forget_to_check(self):
with self.assertRaises(Exception) as e:
self.Validator(False).validate(12)
self.assertNotIsInstance(e.exception, exceptions.ValidationError)
|
class AntiDraft6LeakMixin:
'''
Make sure functionality from draft 6 doesn't leak backwards in time.
'''
def test_True_is_not_a_schema(self):
pass
def test_False_is_not_a_schema(self):
pass
def test_True_is_not_a_schema_even_if_you_forget_to_check(self):
pass
def test_False_is_not_a_schema_even_if_you_forget_to_check(self):
pass
| 5 | 1 | 4 | 0 | 4 | 0 | 1 | 0.18 | 0 | 2 | 0 | 2 | 4 | 0 | 4 | 4 | 24 | 4 | 17 | 9 | 12 | 3 | 17 | 5 | 12 | 1 | 0 | 1 | 4 |
140,185 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.TestRefResolver
|
class TestRefResolver(TestCase):
base_uri = ""
stored_uri = "foo://stored"
stored_schema = {"stored": "schema"}
def setUp(self):
self.referrer = {}
self.store = {self.stored_uri: self.stored_schema}
self.resolver = validators._RefResolver(
self.base_uri, self.referrer, self.store,
)
def test_it_does_not_retrieve_schema_urls_from_the_network(self):
ref = validators.Draft3Validator.META_SCHEMA["id"]
with mock.patch.object(self.resolver, "resolve_remote") as patched: # noqa: SIM117
with self.resolver.resolving(ref) as resolved:
pass
self.assertEqual(resolved, validators.Draft3Validator.META_SCHEMA)
self.assertFalse(patched.called)
def test_it_resolves_local_refs(self):
ref = "#/properties/foo"
self.referrer["properties"] = {"foo": object()}
with self.resolver.resolving(ref) as resolved:
self.assertEqual(resolved, self.referrer["properties"]["foo"])
def test_it_resolves_local_refs_with_id(self):
schema = {"id": "http://bar/schema#", "a": {"foo": "bar"}}
resolver = validators._RefResolver.from_schema(
schema,
id_of=lambda schema: schema.get("id", ""),
)
with resolver.resolving("#/a") as resolved:
self.assertEqual(resolved, schema["a"])
with resolver.resolving("http://bar/schema#/a") as resolved:
self.assertEqual(resolved, schema["a"])
def test_it_retrieves_stored_refs(self):
with self.resolver.resolving(self.stored_uri) as resolved:
self.assertIs(resolved, self.stored_schema)
self.resolver.store["cached_ref"] = {"foo": 12}
with self.resolver.resolving("cached_ref#/foo") as resolved:
self.assertEqual(resolved, 12)
def test_it_retrieves_unstored_refs_via_requests(self):
ref = "http://bar#baz"
schema = {"baz": 12}
if "requests" in sys.modules: # pragma: no cover
self.addCleanup(
sys.modules.__setitem__, "requests", sys.modules["requests"],
)
sys.modules["requests"] = ReallyFakeRequests({"http://bar": schema})
with self.resolver.resolving(ref) as resolved:
self.assertEqual(resolved, 12)
def test_it_retrieves_unstored_refs_via_urlopen(self):
ref = "http://bar#baz"
schema = {"baz": 12}
if "requests" in sys.modules: # pragma: no cover
self.addCleanup(
sys.modules.__setitem__, "requests", sys.modules["requests"],
)
sys.modules["requests"] = None
@contextmanager
def fake_urlopen(url):
self.assertEqual(url, "http://bar")
yield BytesIO(json.dumps(schema).encode("utf8"))
self.addCleanup(setattr, validators, "urlopen", validators.urlopen)
validators.urlopen = fake_urlopen
with self.resolver.resolving(ref) as resolved:
pass
self.assertEqual(resolved, 12)
def test_it_retrieves_local_refs_via_urlopen(self):
with tempfile.NamedTemporaryFile(delete=False, mode="wt") as tempf:
self.addCleanup(os.remove, tempf.name)
json.dump({"foo": "bar"}, tempf)
ref = f"file://{pathname2url(tempf.name)}#foo"
with self.resolver.resolving(ref) as resolved:
self.assertEqual(resolved, "bar")
def test_it_can_construct_a_base_uri_from_a_schema(self):
schema = {"id": "foo"}
resolver = validators._RefResolver.from_schema(
schema,
id_of=lambda schema: schema.get("id", ""),
)
self.assertEqual(resolver.base_uri, "foo")
self.assertEqual(resolver.resolution_scope, "foo")
with resolver.resolving("") as resolved:
self.assertEqual(resolved, schema)
with resolver.resolving("#") as resolved:
self.assertEqual(resolved, schema)
with resolver.resolving("foo") as resolved:
self.assertEqual(resolved, schema)
with resolver.resolving("foo#") as resolved:
self.assertEqual(resolved, schema)
def test_it_can_construct_a_base_uri_from_a_schema_without_id(self):
schema = {}
resolver = validators._RefResolver.from_schema(schema)
self.assertEqual(resolver.base_uri, "")
self.assertEqual(resolver.resolution_scope, "")
with resolver.resolving("") as resolved:
self.assertEqual(resolved, schema)
with resolver.resolving("#") as resolved:
self.assertEqual(resolved, schema)
def test_custom_uri_scheme_handlers(self):
def handler(url):
self.assertEqual(url, ref)
return schema
schema = {"foo": "bar"}
ref = "foo://bar"
resolver = validators._RefResolver("", {}, handlers={"foo": handler})
with resolver.resolving(ref) as resolved:
self.assertEqual(resolved, schema)
def test_cache_remote_on(self):
response = [object()]
def handler(url):
try:
return response.pop()
except IndexError: # pragma: no cover
self.fail("Response must not have been cached!")
ref = "foo://bar"
resolver = validators._RefResolver(
"", {}, cache_remote=True, handlers={"foo": handler},
)
with resolver.resolving(ref):
pass
with resolver.resolving(ref):
pass
def test_cache_remote_off(self):
response = [object()]
def handler(url):
try:
return response.pop()
except IndexError: # pragma: no cover
self.fail("Handler called twice!")
ref = "foo://bar"
resolver = validators._RefResolver(
"", {}, cache_remote=False, handlers={"foo": handler},
)
with resolver.resolving(ref):
pass
def test_if_you_give_it_junk_you_get_a_resolution_error(self):
error = ValueError("Oh no! What's this?")
def handler(url):
raise error
ref = "foo://bar"
resolver = validators._RefResolver("", {}, handlers={"foo": handler})
with self.assertRaises(exceptions._RefResolutionError) as err: # noqa: SIM117
with resolver.resolving(ref):
self.fail("Shouldn't get this far!") # pragma: no cover
self.assertEqual(err.exception, exceptions._RefResolutionError(error))
def test_helpful_error_message_on_failed_pop_scope(self):
resolver = validators._RefResolver("", {})
resolver.pop_scope()
with self.assertRaises(exceptions._RefResolutionError) as exc:
resolver.pop_scope()
self.assertIn("Failed to pop the scope", str(exc.exception))
def test_pointer_within_schema_with_different_id(self):
"""
See #1085.
"""
schema = validators.Draft7Validator.META_SCHEMA
one = validators._RefResolver("", schema)
validator = validators.Draft7Validator(schema, resolver=one)
self.assertFalse(validator.is_valid({"maxLength": "foo"}))
another = {
"allOf": [{"$ref": validators.Draft7Validator.META_SCHEMA["$id"]}],
}
two = validators._RefResolver("", another)
validator = validators.Draft7Validator(another, resolver=two)
self.assertFalse(validator.is_valid({"maxLength": "foo"}))
def test_newly_created_validator_with_ref_resolver(self):
"""
See https://github.com/python-jsonschema/jsonschema/issues/1061#issuecomment-1624266555.
"""
def handle(uri):
self.assertEqual(uri, "http://example.com/foo")
return {"type": "integer"}
resolver = validators._RefResolver("", {}, handlers={"http": handle})
Validator = validators.create(
meta_schema={},
validators=validators.Draft4Validator.VALIDATORS,
)
schema = {"$id": "http://example.com/bar", "$ref": "foo"}
validator = Validator(schema, resolver=resolver)
self.assertEqual(
(validator.is_valid({}), validator.is_valid(37)),
(False, True),
)
def test_refresolver_with_pointer_in_schema_with_no_id(self):
"""
See https://github.com/python-jsonschema/jsonschema/issues/1124#issuecomment-1632574249.
"""
schema = {
"properties": {"x": {"$ref": "#/definitions/x"}},
"definitions": {"x": {"type": "integer"}},
}
validator = validators.Draft202012Validator(
schema,
resolver=validators._RefResolver("", schema),
)
self.assertEqual(
(validator.is_valid({"x": "y"}), validator.is_valid({"x": 37})),
(False, True),
)
|
class TestRefResolver(TestCase):
def setUp(self):
pass
def test_it_does_not_retrieve_schema_urls_from_the_network(self):
pass
def test_it_resolves_local_refs(self):
pass
def test_it_resolves_local_refs_with_id(self):
pass
def test_it_retrieves_stored_refs(self):
pass
def test_it_retrieves_unstored_refs_via_requests(self):
pass
def test_it_retrieves_unstored_refs_via_urlopen(self):
pass
@contextmanager
def fake_urlopen(url):
pass
def test_it_retrieves_local_refs_via_urlopen(self):
pass
def test_it_can_construct_a_base_uri_from_a_schema(self):
pass
def test_it_can_construct_a_base_uri_from_a_schema_without_id(self):
pass
def test_custom_uri_scheme_handlers(self):
pass
def handler(url):
pass
def test_cache_remote_on(self):
pass
def handler(url):
pass
def test_cache_remote_off(self):
pass
def handler(url):
pass
def test_if_you_give_it_junk_you_get_a_resolution_error(self):
pass
def handler(url):
pass
def test_helpful_error_message_on_failed_pop_scope(self):
pass
def test_pointer_within_schema_with_different_id(self):
'''
See #1085.
'''
pass
def test_newly_created_validator_with_ref_resolver(self):
'''
See https://github.com/python-jsonschema/jsonschema/issues/1061#issuecomment-1624266555.
'''
pass
def handler(url):
pass
def test_refresolver_with_pointer_in_schema_with_no_id(self):
'''
See https://github.com/python-jsonschema/jsonschema/issues/1124#issuecomment-1632574249.
'''
pass
| 26 | 3 | 10 | 1 | 9 | 1 | 1 | 0.15 | 1 | 4 | 1 | 0 | 18 | 3 | 18 | 90 | 237 | 39 | 189 | 83 | 163 | 28 | 155 | 68 | 130 | 2 | 2 | 2 | 28 |
140,186 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.TestDraft7Validator
|
class TestDraft7Validator(ValidatorTestMixin, TestCase):
Validator = validators.Draft7Validator
valid: tuple[dict, dict] = ({}, {})
invalid = {"type": "integer"}, "foo"
|
class TestDraft7Validator(ValidatorTestMixin, TestCase):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 97 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
140,187 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.TestDraft6Validator
|
class TestDraft6Validator(ValidatorTestMixin, TestCase):
Validator = validators.Draft6Validator
valid: tuple[dict, dict] = ({}, {})
invalid = {"type": "integer"}, "foo"
|
class TestDraft6Validator(ValidatorTestMixin, TestCase):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 97 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
140,188 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.TestDraft4Validator
|
class TestDraft4Validator(AntiDraft6LeakMixin, ValidatorTestMixin, TestCase):
Validator = validators.Draft4Validator
valid: tuple[dict, dict] = ({}, {})
invalid = {"type": "integer"}, "foo"
|
class TestDraft4Validator(AntiDraft6LeakMixin, ValidatorTestMixin, TestCase):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 101 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
140,189 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/_format.py
|
jsonschema._format.FormatChecker
|
class FormatChecker:
"""
A ``format`` property checker.
JSON Schema does not mandate that the ``format`` property actually do any
validation. If validation is desired however, instances of this class can
be hooked into validators to enable format validation.
`FormatChecker` objects always return ``True`` when asked about
formats that they do not know how to validate.
To add a check for a custom format use the `FormatChecker.checks`
decorator.
Arguments:
formats:
The known formats to validate. This argument can be used to
limit which formats will be used during validation.
"""
checkers: dict[
str,
tuple[_FormatCheckCallable, _RaisesType],
] = {} # noqa: RUF012
def __init__(self, formats: typing.Iterable[str] | None = None):
if formats is None:
formats = self.checkers.keys()
self.checkers = {k: self.checkers[k] for k in formats}
def __repr__(self):
return f"<FormatChecker checkers={sorted(self.checkers)}>"
def checks(
self, format: str, raises: _RaisesType = (),
) -> typing.Callable[[_F], _F]:
"""
Register a decorated function as validating a new format.
Arguments:
format:
The format that the decorated function will check.
raises:
The exception(s) raised by the decorated function when an
invalid instance is found.
The exception object will be accessible as the
`jsonschema.exceptions.ValidationError.cause` attribute of the
resulting validation error.
"""
def _checks(func: _F) -> _F:
self.checkers[format] = (func, raises)
return func
return _checks
@classmethod
def cls_checks(
cls, format: str, raises: _RaisesType = (),
) -> typing.Callable[[_F], _F]:
warnings.warn(
(
"FormatChecker.cls_checks is deprecated. Call "
"FormatChecker.checks on a specific FormatChecker instance "
"instead."
),
DeprecationWarning,
stacklevel=2,
)
return cls._cls_checks(format=format, raises=raises)
@classmethod
def _cls_checks(
cls, format: str, raises: _RaisesType = (),
) -> typing.Callable[[_F], _F]:
def _checks(func: _F) -> _F:
cls.checkers[format] = (func, raises)
return func
return _checks
def check(self, instance: object, format: str) -> None:
"""
Check whether the instance conforms to the given format.
Arguments:
instance (*any primitive type*, i.e. str, number, bool):
The instance to check
format:
The format that instance should conform to
Raises:
FormatError:
if the instance does not conform to ``format``
"""
if format not in self.checkers:
return
func, raises = self.checkers[format]
result, cause = None, None
try:
result = func(instance)
except raises as e:
cause = e
if not result:
raise FormatError(f"{instance!r} is not a {format!r}", cause=cause)
def conforms(self, instance: object, format: str) -> bool:
"""
Check whether the instance conforms to the given format.
Arguments:
instance (*any primitive type*, i.e. str, number, bool):
The instance to check
format:
The format that instance should conform to
Returns:
bool: whether it conformed
"""
try:
self.check(instance, format)
except FormatError:
return False
else:
return True
|
class FormatChecker:
'''
A ``format`` property checker.
JSON Schema does not mandate that the ``format`` property actually do any
validation. If validation is desired however, instances of this class can
be hooked into validators to enable format validation.
`FormatChecker` objects always return ``True`` when asked about
formats that they do not know how to validate.
To add a check for a custom format use the `FormatChecker.checks`
decorator.
Arguments:
formats:
The known formats to validate. This argument can be used to
limit which formats will be used during validation.
'''
def __init__(self, formats: typing.Iterable[str] | None = None):
pass
def __repr__(self):
pass
def checks(
self, format: str, raises: _RaisesType = (),
) -> typing.Callable[[_F], _F]:
'''
Register a decorated function as validating a new format.
Arguments:
format:
The format that the decorated function will check.
raises:
The exception(s) raised by the decorated function when an
invalid instance is found.
The exception object will be accessible as the
`jsonschema.exceptions.ValidationError.cause` attribute of the
resulting validation error.
'''
pass
def _checks(func: _F) -> _F:
pass
@classmethod
def cls_checks(
cls, format: str, raises: _RaisesType = (),
) -> typing.Callable[[_F], _F]:
pass
@classmethod
def _cls_checks(
cls, format: str, raises: _RaisesType = (),
) -> typing.Callable[[_F], _F]:
pass
def _checks(func: _F) -> _F:
pass
def checks(
self, format: str, raises: _RaisesType = (),
) -> typing.Callable[[_F], _F]:
'''
Check whether the instance conforms to the given format.
Arguments:
instance (*any primitive type*, i.e. str, number, bool):
The instance to check
format:
The format that instance should conform to
Raises:
FormatError:
if the instance does not conform to ``format``
'''
pass
def conforms(self, instance: object, format: str) -> bool:
'''
Check whether the instance conforms to the given format.
Arguments:
instance (*any primitive type*, i.e. str, number, bool):
The instance to check
format:
The format that instance should conform to
Returns:
bool: whether it conformed
'''
pass
| 12 | 4 | 13 | 3 | 6 | 4 | 2 | 0.83 | 0 | 5 | 0 | 0 | 5 | 0 | 7 | 7 | 148 | 43 | 58 | 22 | 40 | 48 | 39 | 13 | 29 | 4 | 0 | 1 | 14 |
140,190 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/_typing.py
|
jsonschema._typing.SchemaKeywordValidator
|
class SchemaKeywordValidator(Protocol):
def __call__(
self,
validator: Validator,
value: Any,
instance: Any,
schema: referencing.jsonschema.Schema,
) -> None:
...
|
class SchemaKeywordValidator(Protocol):
def __call__(
self,
validator: Validator,
value: Any,
instance: Any,
schema: referencing.jsonschema.Schema,
) -> None:
pass
| 2 | 0 | 8 | 0 | 8 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 9 | 0 | 9 | 8 | 1 | 0 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
140,191 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.TestReferencing
|
class TestReferencing(TestCase):
def test_registry_with_retrieve(self):
def retrieve(uri):
return DRAFT202012.create_resource({"type": "integer"})
registry = referencing.Registry(retrieve=retrieve)
schema = {"$ref": "https://example.com/"}
validator = validators.Draft202012Validator(schema, registry=registry)
self.assertEqual(
(validator.is_valid(12), validator.is_valid("foo")),
(True, False),
)
def test_custom_registries_do_not_autoretrieve_remote_resources(self):
registry = referencing.Registry()
schema = {"$ref": "https://example.com/"}
validator = validators.Draft202012Validator(schema, registry=registry)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
with self.assertRaises(referencing.exceptions.Unresolvable):
validator.validate(12)
self.assertFalse(w)
|
class TestReferencing(TestCase):
def test_registry_with_retrieve(self):
pass
def retrieve(uri):
pass
def test_custom_registries_do_not_autoretrieve_remote_resources(self):
pass
| 4 | 0 | 8 | 1 | 7 | 0 | 1 | 0 | 1 | 3 | 0 | 0 | 2 | 0 | 2 | 74 | 24 | 4 | 20 | 11 | 16 | 0 | 17 | 10 | 13 | 1 | 2 | 2 | 3 |
140,192 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/_utils.py
|
jsonschema._utils.URIDict
|
class URIDict(MutableMapping):
"""
Dictionary which uses normalized URIs as keys.
"""
def normalize(self, uri):
return urlsplit(uri).geturl()
def __init__(self, *args, **kwargs):
self.store = dict()
self.store.update(*args, **kwargs)
def __getitem__(self, uri):
return self.store[self.normalize(uri)]
def __setitem__(self, uri, value):
self.store[self.normalize(uri)] = value
def __delitem__(self, uri):
del self.store[self.normalize(uri)]
def __iter__(self):
return iter(self.store)
def __len__(self): # pragma: no cover -- untested, but to be removed
return len(self.store)
def __repr__(self): # pragma: no cover -- untested, but to be removed
return repr(self.store)
|
class URIDict(MutableMapping):
'''
Dictionary which uses normalized URIs as keys.
'''
def normalize(self, uri):
pass
def __init__(self, *args, **kwargs):
pass
def __getitem__(self, uri):
pass
def __setitem__(self, uri, value):
pass
def __delitem__(self, uri):
pass
def __iter__(self):
pass
def __len__(self):
pass
def __repr__(self):
pass
| 9 | 1 | 2 | 0 | 2 | 0 | 1 | 0.28 | 1 | 1 | 0 | 0 | 8 | 1 | 8 | 49 | 29 | 8 | 18 | 10 | 9 | 5 | 18 | 10 | 9 | 1 | 7 | 0 | 8 |
140,193 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/_utils.py
|
jsonschema._utils.Unset
|
class Unset:
"""
An as-of-yet unset attribute or unprovided default parameter.
"""
def __repr__(self): # pragma: no cover
return "<unset>"
|
class Unset:
'''
An as-of-yet unset attribute or unprovided default parameter.
'''
def __repr__(self):
pass
| 2 | 1 | 2 | 0 | 2 | 1 | 1 | 1.33 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 7 | 1 | 3 | 2 | 1 | 4 | 3 | 2 | 1 | 1 | 0 | 0 | 1 |
140,194 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/cli.py
|
jsonschema.cli._CannotLoadFile
|
class _CannotLoadFile(Exception):
pass
|
class _CannotLoadFile(Exception):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
140,195 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/cli.py
|
jsonschema.cli._Outputter
|
class _Outputter:
_formatter = field()
_stdout = field()
_stderr = field()
@classmethod
def from_arguments(cls, arguments, stdout, stderr):
if arguments["output"] == "plain":
formatter = _PlainFormatter(arguments["error_format"])
elif arguments["output"] == "pretty":
formatter = _PrettyFormatter()
return cls(formatter=formatter, stdout=stdout, stderr=stderr)
def load(self, path):
try:
file = open(path) # noqa: SIM115, PTH123
except FileNotFoundError as error:
self.filenotfound_error(path=path, exc_info=sys.exc_info())
raise _CannotLoadFile() from error
with file:
try:
return json.load(file)
except JSONDecodeError as error:
self.parsing_error(path=path, exc_info=sys.exc_info())
raise _CannotLoadFile() from error
def filenotfound_error(self, **kwargs):
self._stderr.write(self._formatter.filenotfound_error(**kwargs))
def parsing_error(self, **kwargs):
self._stderr.write(self._formatter.parsing_error(**kwargs))
def validation_error(self, **kwargs):
self._stderr.write(self._formatter.validation_error(**kwargs))
def validation_success(self, **kwargs):
self._stdout.write(self._formatter.validation_success(**kwargs))
|
class _Outputter:
@classmethod
def from_arguments(cls, arguments, stdout, stderr):
pass
def load(self, path):
pass
def filenotfound_error(self, **kwargs):
pass
def parsing_error(self, **kwargs):
pass
def validation_error(self, **kwargs):
pass
def validation_success(self, **kwargs):
pass
| 8 | 0 | 5 | 0 | 4 | 0 | 2 | 0.03 | 0 | 5 | 3 | 0 | 5 | 0 | 6 | 6 | 39 | 8 | 31 | 14 | 23 | 1 | 29 | 12 | 22 | 3 | 0 | 2 | 10 |
140,196 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/_types.py
|
jsonschema._types.TypeChecker
|
class TypeChecker:
"""
A :kw:`type` property checker.
A `TypeChecker` performs type checking for a `Validator`, converting
between the defined JSON Schema types and some associated Python types or
objects.
Modifying the behavior just mentioned by redefining which Python objects
are considered to be of which JSON Schema types can be done using
`TypeChecker.redefine` or `TypeChecker.redefine_many`, and types can be
removed via `TypeChecker.remove`. Each of these return a new `TypeChecker`.
Arguments:
type_checkers:
The initial mapping of types to their checking functions.
"""
_type_checkers: HashTrieMap[
str, Callable[[TypeChecker, Any], bool],
] = field(default=HashTrieMap(), converter=_typed_map_converter)
def __repr__(self):
types = ", ".join(repr(k) for k in sorted(self._type_checkers))
return f"<{self.__class__.__name__} types={{{types}}}>"
def is_type(self, instance, type: str) -> bool:
"""
Check if the instance is of the appropriate type.
Arguments:
instance:
The instance to check
type:
The name of the type that is expected.
Raises:
`jsonschema.exceptions.UndefinedTypeCheck`:
if ``type`` is unknown to this object.
"""
try:
fn = self._type_checkers[type]
except KeyError:
raise UndefinedTypeCheck(type) from None
return fn(self, instance)
def redefine(self, type: str, fn) -> TypeChecker:
"""
Produce a new checker with the given type redefined.
Arguments:
type:
The name of the type to check.
fn (collections.abc.Callable):
A callable taking exactly two parameters - the type
checker calling the function and the instance to check.
The function should return true if instance is of this
type and false otherwise.
"""
return self.redefine_many({type: fn})
def redefine_many(self, definitions=()) -> TypeChecker:
"""
Produce a new checker with the given types redefined.
Arguments:
definitions (dict):
A dictionary mapping types to their checking functions.
"""
type_checkers = self._type_checkers.update(definitions)
return evolve(self, type_checkers=type_checkers)
def remove(self, *types) -> TypeChecker:
"""
Produce a new checker with the given types forgotten.
Arguments:
types:
the names of the types to remove.
Raises:
`jsonschema.exceptions.UndefinedTypeCheck`:
if any given type is unknown to this object
"""
type_checkers = self._type_checkers
for each in types:
try:
type_checkers = type_checkers.remove(each)
except KeyError:
raise UndefinedTypeCheck(each) from None
return evolve(self, type_checkers=type_checkers)
|
class TypeChecker:
'''
A :kw:`type` property checker.
A `TypeChecker` performs type checking for a `Validator`, converting
between the defined JSON Schema types and some associated Python types or
objects.
Modifying the behavior just mentioned by redefining which Python objects
are considered to be of which JSON Schema types can be done using
`TypeChecker.redefine` or `TypeChecker.redefine_many`, and types can be
removed via `TypeChecker.remove`. Each of these return a new `TypeChecker`.
Arguments:
type_checkers:
The initial mapping of types to their checking functions.
'''
def __repr__(self):
pass
def is_type(self, instance, type: str) -> bool:
'''
Check if the instance is of the appropriate type.
Arguments:
instance:
The instance to check
type:
The name of the type that is expected.
Raises:
`jsonschema.exceptions.UndefinedTypeCheck`:
if ``type`` is unknown to this object.
'''
pass
def redefine(self, type: str, fn) -> TypeChecker:
'''
Produce a new checker with the given type redefined.
Arguments:
type:
The name of the type to check.
fn (collections.abc.Callable):
A callable taking exactly two parameters - the type
checker calling the function and the instance to check.
The function should return true if instance is of this
type and false otherwise.
'''
pass
def redefine_many(self, definitions=()) -> TypeChecker:
'''
Produce a new checker with the given types redefined.
Arguments:
definitions (dict):
A dictionary mapping types to their checking functions.
'''
pass
def remove(self, *types) -> TypeChecker:
'''
Produce a new checker with the given types forgotten.
Arguments:
types:
the names of the types to remove.
Raises:
`jsonschema.exceptions.UndefinedTypeCheck`:
if any given type is unknown to this object
'''
pass
| 6 | 5 | 17 | 5 | 4 | 7 | 2 | 1.92 | 0 | 4 | 0 | 0 | 5 | 0 | 5 | 5 | 115 | 39 | 26 | 12 | 20 | 50 | 24 | 12 | 18 | 3 | 0 | 2 | 8 |
140,197 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.TestThreading
|
class TestThreading(TestCase):
"""
Threading-related functionality tests.
jsonschema doesn't promise thread safety, and its validation behavior
across multiple threads may change at any time, but that means it isn't
safe to share *validators* across threads, not that anytime one has
multiple threads that jsonschema won't work (it certainly is intended to).
These tests ensure that this minimal level of functionality continues to
work.
"""
def test_validation_across_a_second_thread(self):
failed = []
def validate():
try:
validators.validate(instance=37, schema=True)
except: # pragma: no cover # noqa: E722
failed.append(sys.exc_info())
validate() # just verify it succeeds
from threading import Thread
thread = Thread(target=validate)
thread.start()
thread.join()
self.assertEqual((thread.is_alive(), failed), (False, []))
|
class TestThreading(TestCase):
'''
Threading-related functionality tests.
jsonschema doesn't promise thread safety, and its validation behavior
across multiple threads may change at any time, but that means it isn't
safe to share *validators* across threads, not that anytime one has
multiple threads that jsonschema won't work (it certainly is intended to).
These tests ensure that this minimal level of functionality continues to
work.
'''
def test_validation_across_a_second_thread(self):
pass
def validate():
pass
| 3 | 1 | 11 | 2 | 9 | 2 | 2 | 0.79 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 73 | 29 | 6 | 14 | 6 | 10 | 11 | 14 | 6 | 10 | 2 | 2 | 1 | 3 |
140,198 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.TestValidationErrorDetails
|
class TestValidationErrorDetails(TestCase):
# TODO: These really need unit tests for each individual keyword, rather
# than just these higher level tests.
def test_anyOf(self):
instance = 5
schema = {
"anyOf": [
{"minimum": 20},
{"type": "string"},
],
}
validator = validators.Draft4Validator(schema)
errors = list(validator.iter_errors(instance))
self.assertEqual(len(errors), 1)
e = errors[0]
self.assertEqual(e.validator, "anyOf")
self.assertEqual(e.validator_value, schema["anyOf"])
self.assertEqual(e.instance, instance)
self.assertEqual(e.schema, schema)
self.assertIsNone(e.parent)
self.assertEqual(e.path, deque([]))
self.assertEqual(e.relative_path, deque([]))
self.assertEqual(e.absolute_path, deque([]))
self.assertEqual(e.json_path, "$")
self.assertEqual(e.schema_path, deque(["anyOf"]))
self.assertEqual(e.relative_schema_path, deque(["anyOf"]))
self.assertEqual(e.absolute_schema_path, deque(["anyOf"]))
self.assertEqual(len(e.context), 2)
e1, e2 = sorted_errors(e.context)
self.assertEqual(e1.validator, "minimum")
self.assertEqual(e1.validator_value, schema["anyOf"][0]["minimum"])
self.assertEqual(e1.instance, instance)
self.assertEqual(e1.schema, schema["anyOf"][0])
self.assertIs(e1.parent, e)
self.assertEqual(e1.path, deque([]))
self.assertEqual(e1.absolute_path, deque([]))
self.assertEqual(e1.relative_path, deque([]))
self.assertEqual(e1.json_path, "$")
self.assertEqual(e1.schema_path, deque([0, "minimum"]))
self.assertEqual(e1.relative_schema_path, deque([0, "minimum"]))
self.assertEqual(
e1.absolute_schema_path, deque(["anyOf", 0, "minimum"]),
)
self.assertFalse(e1.context)
self.assertEqual(e2.validator, "type")
self.assertEqual(e2.validator_value, schema["anyOf"][1]["type"])
self.assertEqual(e2.instance, instance)
self.assertEqual(e2.schema, schema["anyOf"][1])
self.assertIs(e2.parent, e)
self.assertEqual(e2.path, deque([]))
self.assertEqual(e2.relative_path, deque([]))
self.assertEqual(e2.absolute_path, deque([]))
self.assertEqual(e2.json_path, "$")
self.assertEqual(e2.schema_path, deque([1, "type"]))
self.assertEqual(e2.relative_schema_path, deque([1, "type"]))
self.assertEqual(e2.absolute_schema_path, deque(["anyOf", 1, "type"]))
self.assertEqual(len(e2.context), 0)
def test_type(self):
instance = {"foo": 1}
schema = {
"type": [
{"type": "integer"},
{
"type": "object",
"properties": {"foo": {"enum": [2]}},
},
],
}
validator = validators.Draft3Validator(schema)
errors = list(validator.iter_errors(instance))
self.assertEqual(len(errors), 1)
e = errors[0]
self.assertEqual(e.validator, "type")
self.assertEqual(e.validator_value, schema["type"])
self.assertEqual(e.instance, instance)
self.assertEqual(e.schema, schema)
self.assertIsNone(e.parent)
self.assertEqual(e.path, deque([]))
self.assertEqual(e.relative_path, deque([]))
self.assertEqual(e.absolute_path, deque([]))
self.assertEqual(e.json_path, "$")
self.assertEqual(e.schema_path, deque(["type"]))
self.assertEqual(e.relative_schema_path, deque(["type"]))
self.assertEqual(e.absolute_schema_path, deque(["type"]))
self.assertEqual(len(e.context), 2)
e1, e2 = sorted_errors(e.context)
self.assertEqual(e1.validator, "type")
self.assertEqual(e1.validator_value, schema["type"][0]["type"])
self.assertEqual(e1.instance, instance)
self.assertEqual(e1.schema, schema["type"][0])
self.assertIs(e1.parent, e)
self.assertEqual(e1.path, deque([]))
self.assertEqual(e1.relative_path, deque([]))
self.assertEqual(e1.absolute_path, deque([]))
self.assertEqual(e1.json_path, "$")
self.assertEqual(e1.schema_path, deque([0, "type"]))
self.assertEqual(e1.relative_schema_path, deque([0, "type"]))
self.assertEqual(e1.absolute_schema_path, deque(["type", 0, "type"]))
self.assertFalse(e1.context)
self.assertEqual(e2.validator, "enum")
self.assertEqual(e2.validator_value, [2])
self.assertEqual(e2.instance, 1)
self.assertEqual(e2.schema, {"enum": [2]})
self.assertIs(e2.parent, e)
self.assertEqual(e2.path, deque(["foo"]))
self.assertEqual(e2.relative_path, deque(["foo"]))
self.assertEqual(e2.absolute_path, deque(["foo"]))
self.assertEqual(e2.json_path, "$.foo")
self.assertEqual(
e2.schema_path, deque([1, "properties", "foo", "enum"]),
)
self.assertEqual(
e2.relative_schema_path, deque([1, "properties", "foo", "enum"]),
)
self.assertEqual(
e2.absolute_schema_path,
deque(["type", 1, "properties", "foo", "enum"]),
)
self.assertFalse(e2.context)
def test_single_nesting(self):
instance = {"foo": 2, "bar": [1], "baz": 15, "quux": "spam"}
schema = {
"properties": {
"foo": {"type": "string"},
"bar": {"minItems": 2},
"baz": {"maximum": 10, "enum": [2, 4, 6, 8]},
},
}
validator = validators.Draft3Validator(schema)
errors = validator.iter_errors(instance)
e1, e2, e3, e4 = sorted_errors(errors)
self.assertEqual(e1.path, deque(["bar"]))
self.assertEqual(e2.path, deque(["baz"]))
self.assertEqual(e3.path, deque(["baz"]))
self.assertEqual(e4.path, deque(["foo"]))
self.assertEqual(e1.relative_path, deque(["bar"]))
self.assertEqual(e2.relative_path, deque(["baz"]))
self.assertEqual(e3.relative_path, deque(["baz"]))
self.assertEqual(e4.relative_path, deque(["foo"]))
self.assertEqual(e1.absolute_path, deque(["bar"]))
self.assertEqual(e2.absolute_path, deque(["baz"]))
self.assertEqual(e3.absolute_path, deque(["baz"]))
self.assertEqual(e4.absolute_path, deque(["foo"]))
self.assertEqual(e1.json_path, "$.bar")
self.assertEqual(e2.json_path, "$.baz")
self.assertEqual(e3.json_path, "$.baz")
self.assertEqual(e4.json_path, "$.foo")
self.assertEqual(e1.validator, "minItems")
self.assertEqual(e2.validator, "enum")
self.assertEqual(e3.validator, "maximum")
self.assertEqual(e4.validator, "type")
def test_multiple_nesting(self):
instance = [1, {"foo": 2, "bar": {"baz": [1]}}, "quux"]
schema = {
"type": "string",
"items": {
"type": ["string", "object"],
"properties": {
"foo": {"enum": [1, 3]},
"bar": {
"type": "array",
"properties": {
"bar": {"required": True},
"baz": {"minItems": 2},
},
},
},
},
}
validator = validators.Draft3Validator(schema)
errors = validator.iter_errors(instance)
e1, e2, e3, e4, e5, e6 = sorted_errors(errors)
self.assertEqual(e1.path, deque([]))
self.assertEqual(e2.path, deque([0]))
self.assertEqual(e3.path, deque([1, "bar"]))
self.assertEqual(e4.path, deque([1, "bar", "bar"]))
self.assertEqual(e5.path, deque([1, "bar", "baz"]))
self.assertEqual(e6.path, deque([1, "foo"]))
self.assertEqual(e1.json_path, "$")
self.assertEqual(e2.json_path, "$[0]")
self.assertEqual(e3.json_path, "$[1].bar")
self.assertEqual(e4.json_path, "$[1].bar.bar")
self.assertEqual(e5.json_path, "$[1].bar.baz")
self.assertEqual(e6.json_path, "$[1].foo")
self.assertEqual(e1.schema_path, deque(["type"]))
self.assertEqual(e2.schema_path, deque(["items", "type"]))
self.assertEqual(
list(e3.schema_path), ["items", "properties", "bar", "type"],
)
self.assertEqual(
list(e4.schema_path),
["items", "properties", "bar", "properties", "bar", "required"],
)
self.assertEqual(
list(e5.schema_path),
["items", "properties", "bar", "properties", "baz", "minItems"],
)
self.assertEqual(
list(e6.schema_path), ["items", "properties", "foo", "enum"],
)
self.assertEqual(e1.validator, "type")
self.assertEqual(e2.validator, "type")
self.assertEqual(e3.validator, "type")
self.assertEqual(e4.validator, "required")
self.assertEqual(e5.validator, "minItems")
self.assertEqual(e6.validator, "enum")
def test_recursive(self):
schema = {
"definitions": {
"node": {
"anyOf": [{
"type": "object",
"required": ["name", "children"],
"properties": {
"name": {
"type": "string",
},
"children": {
"type": "object",
"patternProperties": {
"^.*$": {
"$ref": "#/definitions/node",
},
},
},
},
}],
},
},
"type": "object",
"required": ["root"],
"properties": {"root": {"$ref": "#/definitions/node"}},
}
instance = {
"root": {
"name": "root",
"children": {
"a": {
"name": "a",
"children": {
"ab": {
"name": "ab",
# missing "children"
},
},
},
},
},
}
validator = validators.Draft4Validator(schema)
e, = validator.iter_errors(instance)
self.assertEqual(e.absolute_path, deque(["root"]))
self.assertEqual(
e.absolute_schema_path, deque(["properties", "root", "anyOf"]),
)
self.assertEqual(e.json_path, "$.root")
e1, = e.context
self.assertEqual(e1.absolute_path, deque(["root", "children", "a"]))
self.assertEqual(
e1.absolute_schema_path, deque(
[
"properties",
"root",
"anyOf",
0,
"properties",
"children",
"patternProperties",
"^.*$",
"anyOf",
],
),
)
self.assertEqual(e1.json_path, "$.root.children.a")
e2, = e1.context
self.assertEqual(
e2.absolute_path, deque(
["root", "children", "a", "children", "ab"],
),
)
self.assertEqual(
e2.absolute_schema_path, deque(
[
"properties",
"root",
"anyOf",
0,
"properties",
"children",
"patternProperties",
"^.*$",
"anyOf",
0,
"properties",
"children",
"patternProperties",
"^.*$",
"anyOf",
],
),
)
self.assertEqual(e2.json_path, "$.root.children.a.children.ab")
def test_additionalProperties(self):
instance = {"bar": "bar", "foo": 2}
schema = {"additionalProperties": {"type": "integer", "minimum": 5}}
validator = validators.Draft3Validator(schema)
errors = validator.iter_errors(instance)
e1, e2 = sorted_errors(errors)
self.assertEqual(e1.path, deque(["bar"]))
self.assertEqual(e2.path, deque(["foo"]))
self.assertEqual(e1.json_path, "$.bar")
self.assertEqual(e2.json_path, "$.foo")
self.assertEqual(e1.validator, "type")
self.assertEqual(e2.validator, "minimum")
def test_patternProperties(self):
instance = {"bar": 1, "foo": 2}
schema = {
"patternProperties": {
"bar": {"type": "string"},
"foo": {"minimum": 5},
},
}
validator = validators.Draft3Validator(schema)
errors = validator.iter_errors(instance)
e1, e2 = sorted_errors(errors)
self.assertEqual(e1.path, deque(["bar"]))
self.assertEqual(e2.path, deque(["foo"]))
self.assertEqual(e1.json_path, "$.bar")
self.assertEqual(e2.json_path, "$.foo")
self.assertEqual(e1.validator, "type")
self.assertEqual(e2.validator, "minimum")
def test_additionalItems(self):
instance = ["foo", 1]
schema = {
"items": [],
"additionalItems": {"type": "integer", "minimum": 5},
}
validator = validators.Draft3Validator(schema)
errors = validator.iter_errors(instance)
e1, e2 = sorted_errors(errors)
self.assertEqual(e1.path, deque([0]))
self.assertEqual(e2.path, deque([1]))
self.assertEqual(e1.json_path, "$[0]")
self.assertEqual(e2.json_path, "$[1]")
self.assertEqual(e1.validator, "type")
self.assertEqual(e2.validator, "minimum")
def test_additionalItems_with_items(self):
instance = ["foo", "bar", 1]
schema = {
"items": [{}],
"additionalItems": {"type": "integer", "minimum": 5},
}
validator = validators.Draft3Validator(schema)
errors = validator.iter_errors(instance)
e1, e2 = sorted_errors(errors)
self.assertEqual(e1.path, deque([1]))
self.assertEqual(e2.path, deque([2]))
self.assertEqual(e1.json_path, "$[1]")
self.assertEqual(e2.json_path, "$[2]")
self.assertEqual(e1.validator, "type")
self.assertEqual(e2.validator, "minimum")
def test_propertyNames(self):
instance = {"foo": 12}
schema = {"propertyNames": {"not": {"const": "foo"}}}
validator = validators.Draft7Validator(schema)
error, = validator.iter_errors(instance)
self.assertEqual(error.validator, "not")
self.assertEqual(
error.message,
"'foo' should not be valid under {'const': 'foo'}",
)
self.assertEqual(error.path, deque([]))
self.assertEqual(error.json_path, "$")
self.assertEqual(error.schema_path, deque(["propertyNames", "not"]))
def test_if_then(self):
schema = {
"if": {"const": 12},
"then": {"const": 13},
}
validator = validators.Draft7Validator(schema)
error, = validator.iter_errors(12)
self.assertEqual(error.validator, "const")
self.assertEqual(error.message, "13 was expected")
self.assertEqual(error.path, deque([]))
self.assertEqual(error.json_path, "$")
self.assertEqual(error.schema_path, deque(["then", "const"]))
def test_if_else(self):
schema = {
"if": {"const": 12},
"else": {"const": 13},
}
validator = validators.Draft7Validator(schema)
error, = validator.iter_errors(15)
self.assertEqual(error.validator, "const")
self.assertEqual(error.message, "13 was expected")
self.assertEqual(error.path, deque([]))
self.assertEqual(error.json_path, "$")
self.assertEqual(error.schema_path, deque(["else", "const"]))
def test_boolean_schema_False(self):
validator = validators.Draft7Validator(False)
error, = validator.iter_errors(12)
self.assertEqual(
(
error.message,
error.validator,
error.validator_value,
error.instance,
error.schema,
error.schema_path,
error.json_path,
),
(
"False schema does not allow 12",
None,
None,
12,
False,
deque([]),
"$",
),
)
def test_ref(self):
ref, schema = "someRef", {"additionalProperties": {"type": "integer"}}
validator = validators.Draft7Validator(
{"$ref": ref},
resolver=validators._RefResolver("", {}, store={ref: schema}),
)
error, = validator.iter_errors({"foo": "notAnInteger"})
self.assertEqual(
(
error.message,
error.validator,
error.validator_value,
error.instance,
error.absolute_path,
error.schema,
error.schema_path,
error.json_path,
),
(
"'notAnInteger' is not of type 'integer'",
"type",
"integer",
"notAnInteger",
deque(["foo"]),
{"type": "integer"},
deque(["additionalProperties", "type"]),
"$.foo",
),
)
def test_prefixItems(self):
schema = {"prefixItems": [{"type": "string"}, {}, {}, {"maximum": 3}]}
validator = validators.Draft202012Validator(schema)
type_error, min_error = validator.iter_errors([1, 2, "foo", 5])
self.assertEqual(
(
type_error.message,
type_error.validator,
type_error.validator_value,
type_error.instance,
type_error.absolute_path,
type_error.schema,
type_error.schema_path,
type_error.json_path,
),
(
"1 is not of type 'string'",
"type",
"string",
1,
deque([0]),
{"type": "string"},
deque(["prefixItems", 0, "type"]),
"$[0]",
),
)
self.assertEqual(
(
min_error.message,
min_error.validator,
min_error.validator_value,
min_error.instance,
min_error.absolute_path,
min_error.schema,
min_error.schema_path,
min_error.json_path,
),
(
"5 is greater than the maximum of 3",
"maximum",
3,
5,
deque([3]),
{"maximum": 3},
deque(["prefixItems", 3, "maximum"]),
"$[3]",
),
)
def test_prefixItems_with_items(self):
schema = {
"items": {"type": "string"},
"prefixItems": [{}],
}
validator = validators.Draft202012Validator(schema)
e1, e2 = validator.iter_errors(["foo", 2, "bar", 4, "baz"])
self.assertEqual(
(
e1.message,
e1.validator,
e1.validator_value,
e1.instance,
e1.absolute_path,
e1.schema,
e1.schema_path,
e1.json_path,
),
(
"2 is not of type 'string'",
"type",
"string",
2,
deque([1]),
{"type": "string"},
deque(["items", "type"]),
"$[1]",
),
)
self.assertEqual(
(
e2.message,
e2.validator,
e2.validator_value,
e2.instance,
e2.absolute_path,
e2.schema,
e2.schema_path,
e2.json_path,
),
(
"4 is not of type 'string'",
"type",
"string",
4,
deque([3]),
{"type": "string"},
deque(["items", "type"]),
"$[3]",
),
)
def test_contains_too_many(self):
"""
`contains` + `maxContains` produces only one error, even if there are
many more incorrectly matching elements.
"""
schema = {"contains": {"type": "string"}, "maxContains": 2}
validator = validators.Draft202012Validator(schema)
error, = validator.iter_errors(["foo", 2, "bar", 4, "baz", "quux"])
self.assertEqual(
(
error.message,
error.validator,
error.validator_value,
error.instance,
error.absolute_path,
error.schema,
error.schema_path,
error.json_path,
),
(
"Too many items match the given schema (expected at most 2)",
"maxContains",
2,
["foo", 2, "bar", 4, "baz", "quux"],
deque([]),
{"contains": {"type": "string"}, "maxContains": 2},
deque(["contains"]),
"$",
),
)
def test_contains_too_few(self):
schema = {"contains": {"type": "string"}, "minContains": 2}
validator = validators.Draft202012Validator(schema)
error, = validator.iter_errors(["foo", 2, 4])
self.assertEqual(
(
error.message,
error.validator,
error.validator_value,
error.instance,
error.absolute_path,
error.schema,
error.schema_path,
error.json_path,
),
(
(
"Too few items match the given schema "
"(expected at least 2 but only 1 matched)"
),
"minContains",
2,
["foo", 2, 4],
deque([]),
{"contains": {"type": "string"}, "minContains": 2},
deque(["contains"]),
"$",
),
)
def test_contains_none(self):
schema = {"contains": {"type": "string"}, "minContains": 2}
validator = validators.Draft202012Validator(schema)
error, = validator.iter_errors([2, 4])
self.assertEqual(
(
error.message,
error.validator,
error.validator_value,
error.instance,
error.absolute_path,
error.schema,
error.schema_path,
error.json_path,
),
(
"[2, 4] does not contain items matching the given schema",
"contains",
{"type": "string"},
[2, 4],
deque([]),
{"contains": {"type": "string"}, "minContains": 2},
deque(["contains"]),
"$",
),
)
def test_ref_sibling(self):
schema = {
"$defs": {"foo": {"required": ["bar"]}},
"properties": {
"aprop": {
"$ref": "#/$defs/foo",
"required": ["baz"],
},
},
}
validator = validators.Draft202012Validator(schema)
e1, e2 = validator.iter_errors({"aprop": {}})
self.assertEqual(
(
e1.message,
e1.validator,
e1.validator_value,
e1.instance,
e1.absolute_path,
e1.schema,
e1.schema_path,
e1.relative_schema_path,
e1.json_path,
),
(
"'bar' is a required property",
"required",
["bar"],
{},
deque(["aprop"]),
{"required": ["bar"]},
deque(["properties", "aprop", "required"]),
deque(["properties", "aprop", "required"]),
"$.aprop",
),
)
self.assertEqual(
(
e2.message,
e2.validator,
e2.validator_value,
e2.instance,
e2.absolute_path,
e2.schema,
e2.schema_path,
e2.relative_schema_path,
e2.json_path,
),
(
"'baz' is a required property",
"required",
["baz"],
{},
deque(["aprop"]),
{"$ref": "#/$defs/foo", "required": ["baz"]},
deque(["properties", "aprop", "required"]),
deque(["properties", "aprop", "required"]),
"$.aprop",
),
)
|
class TestValidationErrorDetails(TestCase):
def test_anyOf(self):
pass
def test_type(self):
pass
def test_single_nesting(self):
pass
def test_multiple_nesting(self):
pass
def test_recursive(self):
pass
def test_additionalProperties(self):
pass
def test_patternProperties(self):
pass
def test_additionalItems(self):
pass
def test_additionalItems_with_items(self):
pass
def test_propertyNames(self):
pass
def test_if_then(self):
pass
def test_if_else(self):
pass
def test_boolean_schema_False(self):
pass
def test_ref(self):
pass
def test_prefixItems(self):
pass
def test_prefixItems_with_items(self):
pass
def test_contains_too_many(self):
'''
`contains` + `maxContains` produces only one error, even if there are
many more incorrectly matching elements.
'''
pass
def test_contains_too_few(self):
pass
def test_contains_none(self):
pass
def test_ref_sibling(self):
pass
| 21 | 1 | 38 | 3 | 34 | 0 | 1 | 0.02 | 1 | 1 | 0 | 0 | 20 | 0 | 20 | 92 | 781 | 87 | 687 | 102 | 666 | 11 | 285 | 102 | 264 | 1 | 2 | 0 | 20 |
140,199 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/cli.py
|
jsonschema.cli._PlainFormatter
|
class _PlainFormatter:
_error_format = field()
def filenotfound_error(self, path, exc_info):
return f"{path!r} does not exist.\n"
def parsing_error(self, path, exc_info):
return "Failed to parse {}: {}\n".format(
"<stdin>" if path == "<stdin>" else repr(path),
exc_info[1],
)
def validation_error(self, instance_path, error):
return self._error_format.format(file_name=instance_path, error=error)
def validation_success(self, instance_path):
return ""
|
class _PlainFormatter:
def filenotfound_error(self, path, exc_info):
pass
def parsing_error(self, path, exc_info):
pass
def validation_error(self, instance_path, error):
pass
def validation_success(self, instance_path):
pass
| 5 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 4 | 0 | 4 | 4 | 18 | 5 | 13 | 6 | 8 | 0 | 10 | 6 | 5 | 2 | 0 | 0 | 5 |
140,200 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.TestValidationErrorMessages
|
class TestValidationErrorMessages(TestCase):
def message_for(self, instance, schema, *args, **kwargs):
cls = kwargs.pop("cls", validators._LATEST_VERSION)
cls.check_schema(schema)
validator = cls(schema, *args, **kwargs)
errors = list(validator.iter_errors(instance))
self.assertTrue(errors, msg=f"No errors were raised for {instance!r}")
self.assertEqual(
len(errors),
1,
msg=f"Expected exactly one error, found {errors!r}",
)
return errors[0].message
def test_single_type_failure(self):
message = self.message_for(instance=1, schema={"type": "string"})
self.assertEqual(message, "1 is not of type 'string'")
def test_single_type_list_failure(self):
message = self.message_for(instance=1, schema={"type": ["string"]})
self.assertEqual(message, "1 is not of type 'string'")
def test_multiple_type_failure(self):
types = "string", "object"
message = self.message_for(instance=1, schema={"type": list(types)})
self.assertEqual(message, "1 is not of type 'string', 'object'")
def test_object_with_named_type_failure(self):
schema = {"type": [{"name": "Foo", "minimum": 3}]}
message = self.message_for(
instance=1,
schema=schema,
cls=validators.Draft3Validator,
)
self.assertEqual(message, "1 is not of type 'Foo'")
def test_minimum(self):
message = self.message_for(instance=1, schema={"minimum": 2})
self.assertEqual(message, "1 is less than the minimum of 2")
def test_maximum(self):
message = self.message_for(instance=1, schema={"maximum": 0})
self.assertEqual(message, "1 is greater than the maximum of 0")
def test_dependencies_single_element(self):
depend, on = "bar", "foo"
schema = {"dependencies": {depend: on}}
message = self.message_for(
instance={"bar": 2},
schema=schema,
cls=validators.Draft3Validator,
)
self.assertEqual(message, "'foo' is a dependency of 'bar'")
def test_object_without_title_type_failure_draft3(self):
type = {"type": [{"minimum": 3}]}
message = self.message_for(
instance=1,
schema={"type": [type]},
cls=validators.Draft3Validator,
)
self.assertEqual(
message,
"1 is not of type {'type': [{'minimum': 3}]}",
)
def test_dependencies_list_draft3(self):
depend, on = "bar", "foo"
schema = {"dependencies": {depend: [on]}}
message = self.message_for(
instance={"bar": 2},
schema=schema,
cls=validators.Draft3Validator,
)
self.assertEqual(message, "'foo' is a dependency of 'bar'")
def test_dependencies_list_draft7(self):
depend, on = "bar", "foo"
schema = {"dependencies": {depend: [on]}}
message = self.message_for(
instance={"bar": 2},
schema=schema,
cls=validators.Draft7Validator,
)
self.assertEqual(message, "'foo' is a dependency of 'bar'")
def test_additionalItems_single_failure(self):
message = self.message_for(
instance=[2],
schema={"items": [], "additionalItems": False},
cls=validators.Draft3Validator,
)
self.assertIn("(2 was unexpected)", message)
def test_additionalItems_multiple_failures(self):
message = self.message_for(
instance=[1, 2, 3],
schema={"items": [], "additionalItems": False},
cls=validators.Draft3Validator,
)
self.assertIn("(1, 2, 3 were unexpected)", message)
def test_additionalProperties_single_failure(self):
additional = "foo"
schema = {"additionalProperties": False}
message = self.message_for(instance={additional: 2}, schema=schema)
self.assertIn("('foo' was unexpected)", message)
def test_additionalProperties_multiple_failures(self):
schema = {"additionalProperties": False}
message = self.message_for(
instance=dict.fromkeys(["foo", "bar"]),
schema=schema,
)
self.assertIn(repr("foo"), message)
self.assertIn(repr("bar"), message)
self.assertIn("were unexpected)", message)
def test_const(self):
schema = {"const": 12}
message = self.message_for(
instance={"foo": "bar"},
schema=schema,
)
self.assertIn("12 was expected", message)
def test_contains_draft_6(self):
schema = {"contains": {"const": 12}}
message = self.message_for(
instance=[2, {}, []],
schema=schema,
cls=validators.Draft6Validator,
)
self.assertEqual(
message,
"None of [2, {}, []] are valid under the given schema",
)
def test_invalid_format_default_message(self):
checker = FormatChecker(formats=())
checker.checks("thing")(lambda value: False)
schema = {"format": "thing"}
message = self.message_for(
instance="bla",
schema=schema,
format_checker=checker,
)
self.assertIn(repr("bla"), message)
self.assertIn(repr("thing"), message)
self.assertIn("is not a", message)
def test_additionalProperties_false_patternProperties(self):
schema = {"type": "object",
"additionalProperties": False,
"patternProperties": {
"^abc$": {"type": "string"},
"^def$": {"type": "string"},
}}
message = self.message_for(
instance={"zebra": 123},
schema=schema,
cls=validators.Draft4Validator,
)
self.assertEqual(
message,
"{} does not match any of the regexes: {}, {}".format(
repr("zebra"), repr("^abc$"), repr("^def$"),
),
)
message = self.message_for(
instance={"zebra": 123, "fish": 456},
schema=schema,
cls=validators.Draft4Validator,
)
self.assertEqual(
message,
"{}, {} do not match any of the regexes: {}, {}".format(
repr("fish"), repr("zebra"), repr("^abc$"), repr("^def$"),
),
)
def test_False_schema(self):
message = self.message_for(
instance="something",
schema=False,
)
self.assertEqual(message, "False schema does not allow 'something'")
def test_multipleOf(self):
message = self.message_for(
instance=3,
schema={"multipleOf": 2},
)
self.assertEqual(message, "3 is not a multiple of 2")
def test_minItems(self):
message = self.message_for(instance=[], schema={"minItems": 2})
self.assertEqual(message, "[] is too short")
def test_maxItems(self):
message = self.message_for(instance=[1, 2, 3], schema={"maxItems": 2})
self.assertEqual(message, "[1, 2, 3] is too long")
def test_minItems_1(self):
message = self.message_for(instance=[], schema={"minItems": 1})
self.assertEqual(message, "[] should be non-empty")
def test_maxItems_0(self):
message = self.message_for(instance=[1, 2, 3], schema={"maxItems": 0})
self.assertEqual(message, "[1, 2, 3] is expected to be empty")
def test_minLength(self):
message = self.message_for(
instance="",
schema={"minLength": 2},
)
self.assertEqual(message, "'' is too short")
def test_maxLength(self):
message = self.message_for(
instance="abc",
schema={"maxLength": 2},
)
self.assertEqual(message, "'abc' is too long")
def test_minLength_1(self):
message = self.message_for(instance="", schema={"minLength": 1})
self.assertEqual(message, "'' should be non-empty")
def test_maxLength_0(self):
message = self.message_for(instance="abc", schema={"maxLength": 0})
self.assertEqual(message, "'abc' is expected to be empty")
def test_minProperties(self):
message = self.message_for(instance={}, schema={"minProperties": 2})
self.assertEqual(message, "{} does not have enough properties")
def test_maxProperties(self):
message = self.message_for(
instance={"a": {}, "b": {}, "c": {}},
schema={"maxProperties": 2},
)
self.assertEqual(
message,
"{'a': {}, 'b': {}, 'c': {}} has too many properties",
)
def test_minProperties_1(self):
message = self.message_for(instance={}, schema={"minProperties": 1})
self.assertEqual(message, "{} should be non-empty")
def test_maxProperties_0(self):
message = self.message_for(
instance={1: 2},
schema={"maxProperties": 0},
)
self.assertEqual(message, "{1: 2} is expected to be empty")
def test_prefixItems_with_items(self):
message = self.message_for(
instance=[1, 2, "foo"],
schema={"items": False, "prefixItems": [{}, {}]},
)
self.assertEqual(
message,
"Expected at most 2 items but found 1 extra: 'foo'",
)
def test_prefixItems_with_multiple_extra_items(self):
message = self.message_for(
instance=[1, 2, "foo", 5],
schema={"items": False, "prefixItems": [{}, {}]},
)
self.assertEqual(
message,
"Expected at most 2 items but found 2 extra: ['foo', 5]",
)
def test_pattern(self):
message = self.message_for(
instance="bbb",
schema={"pattern": "^a*$"},
)
self.assertEqual(message, "'bbb' does not match '^a*$'")
def test_does_not_contain(self):
message = self.message_for(
instance=[],
schema={"contains": {"type": "string"}},
)
self.assertEqual(
message,
"[] does not contain items matching the given schema",
)
def test_contains_too_few(self):
message = self.message_for(
instance=["foo", 1],
schema={"contains": {"type": "string"}, "minContains": 2},
)
self.assertEqual(
message,
"Too few items match the given schema "
"(expected at least 2 but only 1 matched)",
)
def test_contains_too_few_both_constrained(self):
message = self.message_for(
instance=["foo", 1],
schema={
"contains": {"type": "string"},
"minContains": 2,
"maxContains": 4,
},
)
self.assertEqual(
message,
"Too few items match the given schema (expected at least 2 but "
"only 1 matched)",
)
def test_contains_too_many(self):
message = self.message_for(
instance=["foo", "bar", "baz"],
schema={"contains": {"type": "string"}, "maxContains": 2},
)
self.assertEqual(
message,
"Too many items match the given schema (expected at most 2)",
)
def test_contains_too_many_both_constrained(self):
message = self.message_for(
instance=["foo"] * 5,
schema={
"contains": {"type": "string"},
"minContains": 2,
"maxContains": 4,
},
)
self.assertEqual(
message,
"Too many items match the given schema (expected at most 4)",
)
def test_exclusiveMinimum(self):
message = self.message_for(
instance=3,
schema={"exclusiveMinimum": 5},
)
self.assertEqual(
message,
"3 is less than or equal to the minimum of 5",
)
def test_exclusiveMaximum(self):
message = self.message_for(instance=3, schema={"exclusiveMaximum": 2})
self.assertEqual(
message,
"3 is greater than or equal to the maximum of 2",
)
def test_required(self):
message = self.message_for(instance={}, schema={"required": ["foo"]})
self.assertEqual(message, "'foo' is a required property")
def test_dependentRequired(self):
message = self.message_for(
instance={"foo": {}},
schema={"dependentRequired": {"foo": ["bar"]}},
)
self.assertEqual(message, "'bar' is a dependency of 'foo'")
def test_oneOf_matches_none(self):
message = self.message_for(instance={}, schema={"oneOf": [False]})
self.assertEqual(
message,
"{} is not valid under any of the given schemas",
)
def test_oneOf_matches_too_many(self):
message = self.message_for(instance={}, schema={"oneOf": [True, True]})
self.assertEqual(message, "{} is valid under each of True, True")
def test_unevaluated_items(self):
schema = {"type": "array", "unevaluatedItems": False}
message = self.message_for(instance=["foo", "bar"], schema=schema)
self.assertIn(
message,
"Unevaluated items are not allowed ('foo', 'bar' were unexpected)",
)
def test_unevaluated_items_on_invalid_type(self):
schema = {"type": "array", "unevaluatedItems": False}
message = self.message_for(instance="foo", schema=schema)
self.assertEqual(message, "'foo' is not of type 'array'")
def test_unevaluated_properties_invalid_against_subschema(self):
schema = {
"properties": {"foo": {"type": "string"}},
"unevaluatedProperties": {"const": 12},
}
message = self.message_for(
instance={
"foo": "foo",
"bar": "bar",
"baz": 12,
},
schema=schema,
)
self.assertEqual(
message,
"Unevaluated properties are not valid under the given schema "
"('bar' was unevaluated and invalid)",
)
def test_unevaluated_properties_disallowed(self):
schema = {"type": "object", "unevaluatedProperties": False}
message = self.message_for(
instance={
"foo": "foo",
"bar": "bar",
},
schema=schema,
)
self.assertEqual(
message,
"Unevaluated properties are not allowed "
"('bar', 'foo' were unexpected)",
)
def test_unevaluated_properties_on_invalid_type(self):
schema = {"type": "object", "unevaluatedProperties": False}
message = self.message_for(instance="foo", schema=schema)
self.assertEqual(message, "'foo' is not of type 'object'")
def test_single_item(self):
schema = {"prefixItems": [{}], "items": False}
message = self.message_for(
instance=["foo", "bar", "baz"],
schema=schema,
)
self.assertEqual(
message,
"Expected at most 1 item but found 2 extra: ['bar', 'baz']",
)
def test_heterogeneous_additionalItems_with_Items(self):
schema = {"items": [{}], "additionalItems": False}
message = self.message_for(
instance=["foo", "bar", 37],
schema=schema,
cls=validators.Draft7Validator,
)
self.assertEqual(
message,
"Additional items are not allowed ('bar', 37 were unexpected)",
)
def test_heterogeneous_items_prefixItems(self):
schema = {"prefixItems": [{}], "items": False}
message = self.message_for(
instance=["foo", "bar", 37],
schema=schema,
)
self.assertEqual(
message,
"Expected at most 1 item but found 2 extra: ['bar', 37]",
)
def test_heterogeneous_unevaluatedItems_prefixItems(self):
schema = {"prefixItems": [{}], "unevaluatedItems": False}
message = self.message_for(
instance=["foo", "bar", 37],
schema=schema,
)
self.assertEqual(
message,
"Unevaluated items are not allowed ('bar', 37 were unexpected)",
)
def test_heterogeneous_properties_additionalProperties(self):
"""
Not valid deserialized JSON, but this should not blow up.
"""
schema = {"properties": {"foo": {}}, "additionalProperties": False}
message = self.message_for(
instance={"foo": {}, "a": "baz", 37: 12},
schema=schema,
)
self.assertEqual(
message,
"Additional properties are not allowed (37, 'a' were unexpected)",
)
def test_heterogeneous_properties_unevaluatedProperties(self):
"""
Not valid deserialized JSON, but this should not blow up.
"""
schema = {"properties": {"foo": {}}, "unevaluatedProperties": False}
message = self.message_for(
instance={"foo": {}, "a": "baz", 37: 12},
schema=schema,
)
self.assertEqual(
message,
"Unevaluated properties are not allowed (37, 'a' were unexpected)",
)
|
class TestValidationErrorMessages(TestCase):
def message_for(self, instance, schema, *args, **kwargs):
pass
def test_single_type_failure(self):
pass
def test_single_type_list_failure(self):
pass
def test_multiple_type_failure(self):
pass
def test_object_with_named_type_failure(self):
pass
def test_minimum(self):
pass
def test_maximum(self):
pass
def test_dependencies_single_element(self):
pass
def test_object_without_title_type_failure_draft3(self):
pass
def test_dependencies_list_draft3(self):
pass
def test_dependencies_list_draft7(self):
pass
def test_additionalItems_single_failure(self):
pass
def test_additionalItems_multiple_failures(self):
pass
def test_additionalProperties_single_failure(self):
pass
def test_additionalProperties_multiple_failures(self):
pass
def test_const(self):
pass
def test_contains_draft_6(self):
pass
def test_invalid_format_default_message(self):
pass
def test_additionalProperties_false_patternProperties(self):
pass
def test_False_schema(self):
pass
def test_multipleOf(self):
pass
def test_minItems(self):
pass
def test_maxItems(self):
pass
def test_minItems_1(self):
pass
def test_maxItems_0(self):
pass
def test_minLength(self):
pass
def test_maxLength(self):
pass
def test_minLength_1(self):
pass
def test_maxLength_0(self):
pass
def test_minProperties(self):
pass
def test_maxProperties(self):
pass
def test_minProperties_1(self):
pass
def test_maxProperties_0(self):
pass
def test_prefixItems_with_items(self):
pass
def test_prefixItems_with_multiple_extra_items(self):
pass
def test_pattern(self):
pass
def test_does_not_contain(self):
pass
def test_contains_too_few(self):
pass
def test_contains_too_few_both_constrained(self):
pass
def test_contains_too_many(self):
pass
def test_contains_too_many_both_constrained(self):
pass
def test_exclusiveMinimum(self):
pass
def test_exclusiveMaximum(self):
pass
def test_required(self):
pass
def test_dependentRequired(self):
pass
def test_oneOf_matches_none(self):
pass
def test_oneOf_matches_too_many(self):
pass
def test_unevaluated_items(self):
pass
def test_unevaluated_items_on_invalid_type(self):
pass
def test_unevaluated_properties_invalid_against_subschema(self):
pass
def test_unevaluated_properties_disallowed(self):
pass
def test_unevaluated_properties_on_invalid_type(self):
pass
def test_single_item(self):
pass
def test_heterogeneous_additionalItems_with_Items(self):
pass
def test_heterogeneous_items_prefixItems(self):
pass
def test_heterogeneous_unevaluatedItems_prefixItems(self):
pass
def test_heterogeneous_properties_additionalProperties(self):
'''
Not valid deserialized JSON, but this should not blow up.
'''
pass
def test_heterogeneous_properties_unevaluatedProperties(self):
'''
Not valid deserialized JSON, but this should not blow up.
'''
pass
| 59 | 2 | 8 | 0 | 8 | 0 | 1 | 0.01 | 1 | 3 | 0 | 0 | 58 | 0 | 58 | 130 | 511 | 60 | 445 | 147 | 386 | 6 | 215 | 147 | 156 | 1 | 2 | 0 | 58 |
140,201 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.TestValidatorFor
|
class TestValidatorFor(TestCase):
def test_draft_3(self):
schema = {"$schema": "http://json-schema.org/draft-03/schema"}
self.assertIs(
validators.validator_for(schema),
validators.Draft3Validator,
)
schema = {"$schema": "http://json-schema.org/draft-03/schema#"}
self.assertIs(
validators.validator_for(schema),
validators.Draft3Validator,
)
def test_draft_4(self):
schema = {"$schema": "http://json-schema.org/draft-04/schema"}
self.assertIs(
validators.validator_for(schema),
validators.Draft4Validator,
)
schema = {"$schema": "http://json-schema.org/draft-04/schema#"}
self.assertIs(
validators.validator_for(schema),
validators.Draft4Validator,
)
def test_draft_6(self):
schema = {"$schema": "http://json-schema.org/draft-06/schema"}
self.assertIs(
validators.validator_for(schema),
validators.Draft6Validator,
)
schema = {"$schema": "http://json-schema.org/draft-06/schema#"}
self.assertIs(
validators.validator_for(schema),
validators.Draft6Validator,
)
def test_draft_7(self):
schema = {"$schema": "http://json-schema.org/draft-07/schema"}
self.assertIs(
validators.validator_for(schema),
validators.Draft7Validator,
)
schema = {"$schema": "http://json-schema.org/draft-07/schema#"}
self.assertIs(
validators.validator_for(schema),
validators.Draft7Validator,
)
def test_draft_201909(self):
schema = {"$schema": "https://json-schema.org/draft/2019-09/schema"}
self.assertIs(
validators.validator_for(schema),
validators.Draft201909Validator,
)
schema = {"$schema": "https://json-schema.org/draft/2019-09/schema#"}
self.assertIs(
validators.validator_for(schema),
validators.Draft201909Validator,
)
def test_draft_202012(self):
schema = {"$schema": "https://json-schema.org/draft/2020-12/schema"}
self.assertIs(
validators.validator_for(schema),
validators.Draft202012Validator,
)
schema = {"$schema": "https://json-schema.org/draft/2020-12/schema#"}
self.assertIs(
validators.validator_for(schema),
validators.Draft202012Validator,
)
def test_True(self):
self.assertIs(
validators.validator_for(True),
validators._LATEST_VERSION,
)
def test_False(self):
self.assertIs(
validators.validator_for(False),
validators._LATEST_VERSION,
)
def test_custom_validator(self):
Validator = validators.create(
meta_schema={"id": "meta schema id"},
version="12",
id_of=lambda s: s.get("id", ""),
)
schema = {"$schema": "meta schema id"}
self.assertIs(
validators.validator_for(schema),
Validator,
)
def test_custom_validator_draft6(self):
Validator = validators.create(
meta_schema={"$id": "meta schema $id"},
version="13",
)
schema = {"$schema": "meta schema $id"}
self.assertIs(
validators.validator_for(schema),
Validator,
)
def test_validator_for_jsonschema_default(self):
self.assertIs(validators.validator_for({}), validators._LATEST_VERSION)
def test_validator_for_custom_default(self):
self.assertIs(validators.validator_for({}, default=None), None)
def test_warns_if_meta_schema_specified_was_not_found(self):
with self.assertWarns(DeprecationWarning) as cm:
validators.validator_for(schema={"$schema": "unknownSchema"})
self.assertEqual(cm.filename, __file__)
self.assertEqual(
str(cm.warning),
"The metaschema specified by $schema was not found. "
"Using the latest draft to validate, but this will raise "
"an error in the future.",
)
def test_does_not_warn_if_meta_schema_is_unspecified(self):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
validators.validator_for(schema={}, default={})
self.assertFalse(w)
def test_validator_for_custom_default_with_schema(self):
schema, default = {"$schema": "mailto:foo@example.com"}, object()
self.assertIs(validators.validator_for(schema, default), default)
|
class TestValidatorFor(TestCase):
def test_draft_3(self):
pass
def test_draft_4(self):
pass
def test_draft_6(self):
pass
def test_draft_7(self):
pass
def test_draft_201909(self):
pass
def test_draft_202012(self):
pass
def test_True(self):
pass
def test_False(self):
pass
def test_custom_validator(self):
pass
def test_custom_validator_draft6(self):
pass
def test_validator_for_jsonschema_default(self):
pass
def test_validator_for_custom_default(self):
pass
def test_warns_if_meta_schema_specified_was_not_found(self):
pass
def test_does_not_warn_if_meta_schema_is_unspecified(self):
pass
def test_validator_for_custom_default_with_schema(self):
pass
| 16 | 0 | 8 | 0 | 8 | 0 | 1 | 0.05 | 1 | 3 | 0 | 0 | 15 | 0 | 15 | 87 | 141 | 21 | 120 | 29 | 104 | 6 | 60 | 27 | 44 | 1 | 2 | 1 | 15 |
140,202 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators._ReallyFakeJSONResponse
|
class _ReallyFakeJSONResponse:
_response: str
def json(self):
return json.loads(self._response)
|
class _ReallyFakeJSONResponse:
def json(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 6 | 2 | 4 | 2 | 2 | 0 | 4 | 2 | 2 | 1 | 0 | 0 | 1 |
140,203 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/validators.py
|
jsonschema.validators._RefResolver
|
class _RefResolver:
"""
Resolve JSON References.
Arguments:
base_uri (str):
The URI of the referring document
referrer:
The actual referring document
store (dict):
A mapping from URIs to documents to cache
cache_remote (bool):
Whether remote refs should be cached after first resolution
handlers (dict):
A mapping from URI schemes to functions that should be used
to retrieve them
urljoin_cache (:func:`functools.lru_cache`):
A cache that will be used for caching the results of joining
the resolution scope to subscopes.
remote_cache (:func:`functools.lru_cache`):
A cache that will be used for caching the results of
resolved remote URLs.
Attributes:
cache_remote (bool):
Whether remote refs should be cached after first resolution
.. deprecated:: v4.18.0
``RefResolver`` has been deprecated in favor of `referencing`.
"""
_DEPRECATION_MESSAGE = (
"jsonschema.RefResolver is deprecated as of v4.18.0, in favor of the "
"https://github.com/python-jsonschema/referencing library, which "
"provides more compliant referencing behavior as well as more "
"flexible APIs for customization. A future release will remove "
"RefResolver. Please file a feature request (on referencing) if you "
"are missing an API for the kind of customization you need."
)
def __init__(
self,
base_uri,
referrer,
store=HashTrieMap(),
cache_remote=True,
handlers=(),
urljoin_cache=None,
remote_cache=None,
):
if urljoin_cache is None:
urljoin_cache = lru_cache(1024)(urljoin)
if remote_cache is None:
remote_cache = lru_cache(1024)(self.resolve_from_url)
self.referrer = referrer
self.cache_remote = cache_remote
self.handlers = dict(handlers)
self._scopes_stack = [base_uri]
self.store = _utils.URIDict(
(uri, each.contents) for uri, each in SPECIFICATIONS.items()
)
self.store.update(
(id, each.META_SCHEMA) for id, each in _META_SCHEMAS.items()
)
self.store.update(store)
self.store.update(
(schema["$id"], schema)
for schema in store.values()
if isinstance(schema, Mapping) and "$id" in schema
)
self.store[base_uri] = referrer
self._urljoin_cache = urljoin_cache
self._remote_cache = remote_cache
@classmethod
def from_schema( # noqa: D417
cls,
schema,
id_of=referencing.jsonschema.DRAFT202012.id_of,
*args,
**kwargs,
):
"""
Construct a resolver from a JSON schema object.
Arguments:
schema:
the referring schema
Returns:
`_RefResolver`
"""
return cls(base_uri=id_of(schema) or "", referrer=schema, *args, **kwargs) # noqa: B026, E501
def push_scope(self, scope):
"""
Enter a given sub-scope.
Treats further dereferences as being performed underneath the
given scope.
"""
self._scopes_stack.append(
self._urljoin_cache(self.resolution_scope, scope),
)
def pop_scope(self):
"""
Exit the most recent entered scope.
Treats further dereferences as being performed underneath the
original scope.
Don't call this method more times than `push_scope` has been
called.
"""
try:
self._scopes_stack.pop()
except IndexError:
raise exceptions._RefResolutionError(
"Failed to pop the scope from an empty stack. "
"`pop_scope()` should only be called once for every "
"`push_scope()`",
) from None
@property
def resolution_scope(self):
"""
Retrieve the current resolution scope.
"""
return self._scopes_stack[-1]
@property
def base_uri(self):
"""
Retrieve the current base URI, not including any fragment.
"""
uri, _ = urldefrag(self.resolution_scope)
return uri
@contextlib.contextmanager
def in_scope(self, scope):
"""
Temporarily enter the given scope for the duration of the context.
.. deprecated:: v4.0.0
"""
warnings.warn(
"jsonschema.RefResolver.in_scope is deprecated and will be "
"removed in a future release.",
DeprecationWarning,
stacklevel=3,
)
self.push_scope(scope)
try:
yield
finally:
self.pop_scope()
@contextlib.contextmanager
def resolving(self, ref):
"""
Resolve the given ``ref`` and enter its resolution scope.
Exits the scope on exit of this context manager.
Arguments:
ref (str):
The reference to resolve
"""
url, resolved = self.resolve(ref)
self.push_scope(url)
try:
yield resolved
finally:
self.pop_scope()
def _find_in_referrer(self, key):
return self._get_subschemas_cache()[key]
@lru_cache # noqa: B019
def _get_subschemas_cache(self):
cache = {key: [] for key in _SUBSCHEMAS_KEYWORDS}
for keyword, subschema in _search_schema(
self.referrer, _match_subschema_keywords,
):
cache[keyword].append(subschema)
return cache
@lru_cache # noqa: B019
def _find_in_subschemas(self, url):
subschemas = self._get_subschemas_cache()["$id"]
if not subschemas:
return None
uri, fragment = urldefrag(url)
for subschema in subschemas:
id = subschema["$id"]
if not isinstance(id, str):
continue
target_uri = self._urljoin_cache(self.resolution_scope, id)
if target_uri.rstrip("/") == uri.rstrip("/"):
if fragment:
subschema = self.resolve_fragment(subschema, fragment)
self.store[url] = subschema
return url, subschema
return None
def resolve(self, ref):
"""
Resolve the given reference.
"""
url = self._urljoin_cache(self.resolution_scope, ref).rstrip("/")
match = self._find_in_subschemas(url)
if match is not None:
return match
return url, self._remote_cache(url)
def resolve_from_url(self, url):
"""
Resolve the given URL.
"""
url, fragment = urldefrag(url)
if not url:
url = self.base_uri
try:
document = self.store[url]
except KeyError:
try:
document = self.resolve_remote(url)
except Exception as exc:
raise exceptions._RefResolutionError(exc) from exc
return self.resolve_fragment(document, fragment)
def resolve_fragment(self, document, fragment):
"""
Resolve a ``fragment`` within the referenced ``document``.
Arguments:
document:
The referent document
fragment (str):
a URI fragment to resolve within it
"""
fragment = fragment.lstrip("/")
if not fragment:
return document
if document is self.referrer:
find = self._find_in_referrer
else:
def find(key):
yield from _search_schema(document, _match_keyword(key))
for keyword in ["$anchor", "$dynamicAnchor"]:
for subschema in find(keyword):
if fragment == subschema[keyword]:
return subschema
for keyword in ["id", "$id"]:
for subschema in find(keyword):
if "#" + fragment == subschema[keyword]:
return subschema
# Resolve via path
parts = unquote(fragment).split("/") if fragment else []
for part in parts:
part = part.replace("~1", "/").replace("~0", "~")
if isinstance(document, Sequence):
try: # noqa: SIM105
part = int(part)
except ValueError:
pass
try:
document = document[part]
except (TypeError, LookupError) as err:
raise exceptions._RefResolutionError(
f"Unresolvable JSON pointer: {fragment!r}",
) from err
return document
def resolve_remote(self, uri):
"""
Resolve a remote ``uri``.
If called directly, does not check the store first, but after
retrieving the document at the specified URI it will be saved in
the store if :attr:`cache_remote` is True.
.. note::
If the requests_ library is present, ``jsonschema`` will use it to
request the remote ``uri``, so that the correct encoding is
detected and used.
If it isn't, or if the scheme of the ``uri`` is not ``http`` or
``https``, UTF-8 is assumed.
Arguments:
uri (str):
The URI to resolve
Returns:
The retrieved document
.. _requests: https://pypi.org/project/requests/
"""
try:
import requests
except ImportError:
requests = None
scheme = urlsplit(uri).scheme
if scheme in self.handlers:
result = self.handlers[scheme](uri)
elif scheme in ["http", "https"] and requests:
# Requests has support for detecting the correct encoding of
# json over http
result = requests.get(uri).json()
else:
# Otherwise, pass off to urllib and assume utf-8
with urlopen(uri) as url: # noqa: S310
result = json.loads(url.read().decode("utf-8"))
if self.cache_remote:
self.store[uri] = result
return result
|
class _RefResolver:
'''
Resolve JSON References.
Arguments:
base_uri (str):
The URI of the referring document
referrer:
The actual referring document
store (dict):
A mapping from URIs to documents to cache
cache_remote (bool):
Whether remote refs should be cached after first resolution
handlers (dict):
A mapping from URI schemes to functions that should be used
to retrieve them
urljoin_cache (:func:`functools.lru_cache`):
A cache that will be used for caching the results of joining
the resolution scope to subscopes.
remote_cache (:func:`functools.lru_cache`):
A cache that will be used for caching the results of
resolved remote URLs.
Attributes:
cache_remote (bool):
Whether remote refs should be cached after first resolution
.. deprecated:: v4.18.0
``RefResolver`` has been deprecated in favor of `referencing`.
'''
def __init__(
self,
base_uri,
referrer,
store=HashTrieMap(),
cache_remote=True,
handlers=(),
urljoin_cache=None,
remote_cache=None,
):
pass
@classmethod
def from_schema( # noqa: D417
cls,
schema,
id_of=referencing.jsonschema.DRAFT202012.id_of,
*args,
**kwargs,
):
'''
Construct a resolver from a JSON schema object.
Arguments:
schema:
the referring schema
Returns:
`_RefResolver`
'''
pass
def push_scope(self, scope):
'''
Enter a given sub-scope.
Treats further dereferences as being performed underneath the
given scope.
'''
pass
def pop_scope(self):
'''
Exit the most recent entered scope.
Treats further dereferences as being performed underneath the
original scope.
Don't call this method more times than `push_scope` has been
called.
'''
pass
@property
def resolution_scope(self):
'''
Retrieve the current resolution scope.
'''
pass
@property
def base_uri(self):
'''
Retrieve the current base URI, not including any fragment.
'''
pass
@contextlib.contextmanager
def in_scope(self, scope):
'''
Temporarily enter the given scope for the duration of the context.
.. deprecated:: v4.0.0
'''
pass
@contextlib.contextmanager
def resolving(self, ref):
'''
Resolve the given ``ref`` and enter its resolution scope.
Exits the scope on exit of this context manager.
Arguments:
ref (str):
The reference to resolve
'''
pass
def _find_in_referrer(self, key):
pass
@lru_cache
def _get_subschemas_cache(self):
pass
@lru_cache
def _find_in_subschemas(self, url):
pass
def resolve(self, ref):
'''
Resolve the given reference.
'''
pass
def resolve_from_url(self, url):
'''
Resolve the given URL.
'''
pass
def resolve_fragment(self, document, fragment):
'''
Resolve a ``fragment`` within the referenced ``document``.
Arguments:
document:
The referent document
fragment (str):
a URI fragment to resolve within it
'''
pass
def find(key):
pass
def resolve_remote(self, uri):
'''
Resolve a remote ``uri``.
If called directly, does not check the store first, but after
retrieving the document at the specified URI it will be saved in
the store if :attr:`cache_remote` is True.
.. note::
If the requests_ library is present, ``jsonschema`` will use it to
request the remote ``uri``, so that the correct encoding is
detected and used.
If it isn't, or if the scheme of the ``uri`` is not ``http`` or
``https``, UTF-8 is assumed.
Arguments:
uri (str):
The URI to resolve
Returns:
The retrieved document
.. _requests: https://pypi.org/project/requests/
'''
pass
| 24 | 12 | 18 | 3 | 11 | 5 | 3 | 0.57 | 0 | 15 | 0 | 0 | 14 | 7 | 15 | 15 | 371 | 87 | 185 | 70 | 145 | 106 | 128 | 44 | 110 | 14 | 0 | 3 | 46 |
140,204 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.MetaSchemaTestsMixin
|
class MetaSchemaTestsMixin:
# TODO: These all belong upstream
def test_invalid_properties(self):
with self.assertRaises(exceptions.SchemaError):
self.Validator.check_schema({"properties": 12})
def test_minItems_invalid_string(self):
with self.assertRaises(exceptions.SchemaError):
# needs to be an integer
self.Validator.check_schema({"minItems": "1"})
def test_enum_allows_empty_arrays(self):
"""
Technically, all the spec says is they SHOULD have elements, not MUST.
(As of Draft 6. Previous drafts do say MUST).
See #529.
"""
if self.Validator in {
validators.Draft3Validator,
validators.Draft4Validator,
}:
with self.assertRaises(exceptions.SchemaError):
self.Validator.check_schema({"enum": []})
else:
self.Validator.check_schema({"enum": []})
def test_enum_allows_non_unique_items(self):
"""
Technically, all the spec says is they SHOULD be unique, not MUST.
(As of Draft 6. Previous drafts do say MUST).
See #529.
"""
if self.Validator in {
validators.Draft3Validator,
validators.Draft4Validator,
}:
with self.assertRaises(exceptions.SchemaError):
self.Validator.check_schema({"enum": [12, 12]})
else:
self.Validator.check_schema({"enum": [12, 12]})
def test_schema_with_invalid_regex(self):
with self.assertRaises(exceptions.SchemaError):
self.Validator.check_schema({"pattern": "*notaregex"})
def test_schema_with_invalid_regex_with_disabled_format_validation(self):
self.Validator.check_schema(
{"pattern": "*notaregex"},
format_checker=None,
)
|
class MetaSchemaTestsMixin:
def test_invalid_properties(self):
pass
def test_minItems_invalid_string(self):
pass
def test_enum_allows_empty_arrays(self):
'''
Technically, all the spec says is they SHOULD have elements, not MUST.
(As of Draft 6. Previous drafts do say MUST).
See #529.
'''
pass
def test_enum_allows_non_unique_items(self):
'''
Technically, all the spec says is they SHOULD be unique, not MUST.
(As of Draft 6. Previous drafts do say MUST).
See #529.
'''
pass
def test_schema_with_invalid_regex(self):
pass
def test_schema_with_invalid_regex_with_disabled_format_validation(self):
pass
| 7 | 2 | 8 | 1 | 5 | 2 | 1 | 0.36 | 0 | 0 | 0 | 1 | 6 | 1 | 6 | 6 | 54 | 9 | 33 | 8 | 26 | 12 | 22 | 7 | 15 | 2 | 0 | 2 | 8 |
140,205 |
Julian/jsonschema
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Julian_jsonschema/jsonschema/tests/test_cli.py
|
jsonschema.tests.test_cli.fake_validator.FakeValidator
|
class FakeValidator:
def __init__(self, *args, **kwargs):
pass
def iter_errors(self, instance):
if errors:
return errors.pop()
return [] # pragma: no cover
@classmethod
def check_schema(self, schema):
pass
|
class FakeValidator:
def __init__(self, *args, **kwargs):
pass
def iter_errors(self, instance):
pass
@classmethod
def check_schema(self, schema):
pass
| 5 | 0 | 3 | 0 | 3 | 0 | 1 | 0.1 | 0 | 0 | 0 | 0 | 2 | 0 | 3 | 3 | 12 | 2 | 10 | 5 | 5 | 1 | 9 | 4 | 5 | 2 | 0 | 1 | 4 |
140,206 |
Julian/jsonschema
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Julian_jsonschema/jsonschema/tests/test_deprecations.py
|
jsonschema.tests.test_deprecations.TestDeprecations.test_Validator_subclassing.AnotherSubclass
|
class AnotherSubclass(validators.create(meta_schema={})):
pass
|
class AnotherSubclass(validators.create(meta_schema={})):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 1 | 0 | 0 |
140,207 |
Julian/jsonschema
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Julian_jsonschema/jsonschema/tests/test_deprecations.py
|
jsonschema.tests.test_deprecations.TestDeprecations.test_Validator_subclassing.Subclass
|
class Subclass(validators.Draft202012Validator):
pass
|
class Subclass(validators.Draft202012Validator):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 1 | 0 | 0 |
140,208 |
Julian/jsonschema
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Julian_jsonschema/jsonschema/tests/test_exceptions.py
|
jsonschema.tests.test_exceptions.TestErrorInitReprStr.test_str_works_with_instances_having_overriden_eq_operator.DontEQMeBro
|
class DontEQMeBro:
def __eq__(this, other): # pragma: no cover
self.fail("Don't!")
def __ne__(this, other): # pragma: no cover
self.fail("Don't!")
|
class DontEQMeBro:
def __eq__(this, other):
pass
def __ne__(this, other):
pass
| 3 | 0 | 2 | 0 | 2 | 1 | 1 | 0.4 | 0 | 1 | 1 | 0 | 2 | 0 | 2 | 2 | 6 | 1 | 5 | 3 | 2 | 2 | 5 | 3 | 2 | 1 | 0 | 0 | 2 |
140,209 |
Julian/jsonschema
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.ValidatorTestMixin
|
class ValidatorTestMixin(MetaSchemaTestsMixin):
def test_it_implements_the_validator_protocol(self):
self.assertIsInstance(self.Validator({}), protocols.Validator)
def test_valid_instances_are_valid(self):
schema, instance = self.valid
self.assertTrue(self.Validator(schema).is_valid(instance))
def test_invalid_instances_are_not_valid(self):
schema, instance = self.invalid
self.assertFalse(self.Validator(schema).is_valid(instance))
def test_non_existent_properties_are_ignored(self):
self.Validator({object(): object()}).validate(instance=object())
def test_evolve(self):
schema, format_checker = {"type": "integer"}, FormatChecker()
original = self.Validator(
schema,
format_checker=format_checker,
)
new = original.evolve(
schema={"type": "string"},
format_checker=self.Validator.FORMAT_CHECKER,
)
expected = self.Validator(
{"type": "string"},
format_checker=self.Validator.FORMAT_CHECKER,
_resolver=new._resolver,
)
self.assertEqual(new, expected)
self.assertNotEqual(new, original)
def test_evolve_with_subclass(self):
"""
Subclassing validators isn't supported public API, but some users have
done it, because we don't actually error entirely when it's done :/
We need to deprecate doing so first to help as many of these users
ensure they can move to supported APIs, but this test ensures that in
the interim, we haven't broken those users.
"""
with self.assertWarns(DeprecationWarning):
@define
class OhNo(self.Validator):
foo = field(factory=lambda: [1, 2, 3])
_bar = field(default=37)
validator = OhNo({}, bar=12)
self.assertEqual(validator.foo, [1, 2, 3])
new = validator.evolve(schema={"type": "integer"})
self.assertEqual(new.foo, [1, 2, 3])
self.assertEqual(new._bar, 12)
def test_is_type_is_true_for_valid_type(self):
self.assertTrue(self.Validator({}).is_type("foo", "string"))
def test_is_type_is_false_for_invalid_type(self):
self.assertFalse(self.Validator({}).is_type("foo", "array"))
def test_is_type_evades_bool_inheriting_from_int(self):
self.assertFalse(self.Validator({}).is_type(True, "integer"))
self.assertFalse(self.Validator({}).is_type(True, "number"))
def test_it_can_validate_with_decimals(self):
schema = {"items": {"type": "number"}}
Validator = validators.extend(
self.Validator,
type_checker=self.Validator.TYPE_CHECKER.redefine(
"number",
lambda checker, thing: isinstance(
thing, (int, float, Decimal),
) and not isinstance(thing, bool),
),
)
validator = Validator(schema)
validator.validate([1, 1.1, Decimal(1) / Decimal(8)])
invalid = ["foo", {}, [], True, None]
self.assertEqual(
[error.instance for error in validator.iter_errors(invalid)],
invalid,
)
def test_it_returns_true_for_formats_it_does_not_know_about(self):
validator = self.Validator(
{"format": "carrot"}, format_checker=FormatChecker(),
)
validator.validate("bugs")
def test_it_does_not_validate_formats_by_default(self):
validator = self.Validator({})
self.assertIsNone(validator.format_checker)
def test_it_validates_formats_if_a_checker_is_provided(self):
checker = FormatChecker()
bad = ValueError("Bad!")
@checker.checks("foo", raises=ValueError)
def check(value):
if value == "good":
return True
elif value == "bad":
raise bad
else: # pragma: no cover
self.fail(f"What is {value}? [Baby Don't Hurt Me]")
validator = self.Validator(
{"format": "foo"}, format_checker=checker,
)
validator.validate("good")
with self.assertRaises(exceptions.ValidationError) as cm:
validator.validate("bad")
# Make sure original cause is attached
self.assertIs(cm.exception.cause, bad)
def test_non_string_custom_type(self):
non_string_type = object()
schema = {"type": [non_string_type]}
Crazy = validators.extend(
self.Validator,
type_checker=self.Validator.TYPE_CHECKER.redefine(
non_string_type,
lambda checker, thing: isinstance(thing, int),
),
)
Crazy(schema).validate(15)
def test_it_properly_formats_tuples_in_errors(self):
"""
A tuple instance properly formats validation errors for uniqueItems.
See #224
"""
TupleValidator = validators.extend(
self.Validator,
type_checker=self.Validator.TYPE_CHECKER.redefine(
"array",
lambda checker, thing: isinstance(thing, tuple),
),
)
with self.assertRaises(exceptions.ValidationError) as e:
TupleValidator({"uniqueItems": True}).validate((1, 1))
self.assertIn("(1, 1) has non-unique elements", str(e.exception))
def test_check_redefined_sequence(self):
"""
Allow array to validate against another defined sequence type
"""
schema = {"type": "array", "uniqueItems": True}
MyMapping = namedtuple("MyMapping", "a, b")
Validator = validators.extend(
self.Validator,
type_checker=self.Validator.TYPE_CHECKER.redefine_many(
{
"array": lambda checker, thing: isinstance(
thing, (list, deque),
),
"object": lambda checker, thing: isinstance(
thing, (dict, MyMapping),
),
},
),
)
validator = Validator(schema)
valid_instances = [
deque(["a", None, "1", "", True]),
deque([[False], [0]]),
[deque([False]), deque([0])],
[[deque([False])], [deque([0])]],
[[[[[deque([False])]]]], [[[[deque([0])]]]]],
[deque([deque([False])]), deque([deque([0])])],
[MyMapping("a", 0), MyMapping("a", False)],
[
MyMapping("a", [deque([0])]),
MyMapping("a", [deque([False])]),
],
[
MyMapping("a", [MyMapping("a", deque([0]))]),
MyMapping("a", [MyMapping("a", deque([False]))]),
],
[deque(deque(deque([False]))), deque(deque(deque([0])))],
]
for instance in valid_instances:
validator.validate(instance)
invalid_instances = [
deque(["a", "b", "a"]),
deque([[False], [False]]),
[deque([False]), deque([False])],
[[deque([False])], [deque([False])]],
[[[[[deque([False])]]]], [[[[deque([False])]]]]],
[deque([deque([False])]), deque([deque([False])])],
[MyMapping("a", False), MyMapping("a", False)],
[
MyMapping("a", [deque([False])]),
MyMapping("a", [deque([False])]),
],
[
MyMapping("a", [MyMapping("a", deque([False]))]),
MyMapping("a", [MyMapping("a", deque([False]))]),
],
[deque(deque(deque([False]))), deque(deque(deque([False])))],
]
for instance in invalid_instances:
with self.assertRaises(exceptions.ValidationError):
validator.validate(instance)
def test_it_creates_a_ref_resolver_if_not_provided(self):
with self.assertWarns(DeprecationWarning):
resolver = self.Validator({}).resolver
self.assertIsInstance(resolver, validators._RefResolver)
def test_it_upconverts_from_deprecated_RefResolvers(self):
ref, schema = "someCoolRef", {"type": "integer"}
resolver = validators._RefResolver("", {}, store={ref: schema})
validator = self.Validator({"$ref": ref}, resolver=resolver)
with self.assertRaises(exceptions.ValidationError):
validator.validate(None)
def test_it_upconverts_from_yet_older_deprecated_legacy_RefResolvers(self):
"""
Legacy RefResolvers support only the context manager form of
resolution.
"""
class LegacyRefResolver:
@contextmanager
def resolving(this, ref):
self.assertEqual(ref, "the ref")
yield {"type": "integer"}
resolver = LegacyRefResolver()
schema = {"$ref": "the ref"}
with self.assertRaises(exceptions.ValidationError):
self.Validator(schema, resolver=resolver).validate(None)
|
class ValidatorTestMixin(MetaSchemaTestsMixin):
def test_it_implements_the_validator_protocol(self):
pass
def test_valid_instances_are_valid(self):
pass
def test_invalid_instances_are_not_valid(self):
pass
def test_non_existent_properties_are_ignored(self):
pass
def test_evolve(self):
pass
def test_evolve_with_subclass(self):
'''
Subclassing validators isn't supported public API, but some users have
done it, because we don't actually error entirely when it's done :/
We need to deprecate doing so first to help as many of these users
ensure they can move to supported APIs, but this test ensures that in
the interim, we haven't broken those users.
'''
pass
@define
class OhNo(self.Validator):
def test_is_type_is_true_for_valid_type(self):
pass
def test_is_type_is_false_for_invalid_type(self):
pass
def test_is_type_evades_bool_inheriting_from_int(self):
pass
def test_it_can_validate_with_decimals(self):
pass
def test_it_returns_true_for_formats_it_does_not_know_about(self):
pass
def test_it_does_not_validate_formats_by_default(self):
pass
def test_it_validates_formats_if_a_checker_is_provided(self):
pass
@checker.checks("foo", raises=ValueError)
def check(value):
pass
def test_non_string_custom_type(self):
pass
def test_it_properly_formats_tuples_in_errors(self):
'''
A tuple instance properly formats validation errors for uniqueItems.
See #224
'''
pass
def test_check_redefined_sequence(self):
'''
Allow array to validate against another defined sequence type
'''
pass
def test_it_creates_a_ref_resolver_if_not_provided(self):
pass
def test_it_upconverts_from_deprecated_RefResolvers(self):
pass
def test_it_upconverts_from_yet_older_deprecated_legacy_RefResolvers(self):
'''
Legacy RefResolvers support only the context manager form of
resolution.
'''
pass
class LegacyRefResolver:
@contextmanager
def resolving(this, ref):
pass
| 27 | 4 | 11 | 1 | 9 | 1 | 1 | 0.11 | 1 | 14 | 2 | 6 | 19 | 1 | 19 | 25 | 248 | 39 | 190 | 66 | 163 | 20 | 102 | 60 | 78 | 3 | 1 | 2 | 25 |
140,210 |
Julian/jsonschema
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.ValidatorTestMixin.test_evolve_with_subclass.OhNo
|
class OhNo(self.Validator):
foo = field(factory=lambda: [1, 2, 3])
_bar = field(default=37)
|
class OhNo(self.Validator):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
140,211 |
Julian/jsonschema
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.ValidatorTestMixin.test_it_upconverts_from_yet_older_deprecated_legacy_RefResolvers.LegacyRefResolver
|
class LegacyRefResolver:
@contextmanager
def resolving(this, ref):
self.assertEqual(ref, "the ref")
yield {"type": "integer"}
|
class LegacyRefResolver:
@contextmanager
def resolving(this, ref):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 5 | 0 | 5 | 3 | 2 | 0 | 4 | 2 | 2 | 1 | 0 | 0 | 1 |
140,212 |
Julian/jsonschema
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Julian_jsonschema/jsonschema/validators.py
|
jsonschema.validators.create.Validator
|
class Validator:
VALIDATORS = dict(validators) # noqa: RUF012
META_SCHEMA = dict(meta_schema) # noqa: RUF012
TYPE_CHECKER = type_checker
FORMAT_CHECKER = format_checker_arg
ID_OF = staticmethod(id_of)
_APPLICABLE_VALIDATORS = applicable_validators
_validators = field(init=False, repr=False, eq=False)
schema: referencing.jsonschema.Schema = field(repr=reprlib.repr)
_ref_resolver = field(default=None, repr=False, alias="resolver")
format_checker: _format.FormatChecker | None = field(default=None)
# TODO: include new meta-schemas added at runtime
_registry: referencing.jsonschema.SchemaRegistry = field(
default=_REMOTE_WARNING_REGISTRY,
kw_only=True,
repr=False,
)
_resolver = field(
alias="_resolver",
default=None,
kw_only=True,
repr=False,
)
def __init_subclass__(cls):
warnings.warn(
(
"Subclassing validator classes is not intended to "
"be part of their public API. A future version "
"will make doing so an error, as the behavior of "
"subclasses isn't guaranteed to stay the same "
"between releases of jsonschema. Instead, prefer "
"composition of validators, wrapping them in an object "
"owned entirely by the downstream library."
),
DeprecationWarning,
stacklevel=2,
)
def evolve(self, **changes):
cls = self.__class__
schema = changes.setdefault("schema", self.schema)
NewValidator = validator_for(schema, default=cls)
for field in fields(cls): # noqa: F402
if not field.init:
continue
attr_name = field.name
init_name = field.alias
if init_name not in changes:
changes[init_name] = getattr(self, attr_name)
return NewValidator(**changes)
cls.evolve = evolve
def __attrs_post_init__(self):
if self._resolver is None:
registry = self._registry
if registry is not _REMOTE_WARNING_REGISTRY:
registry = SPECIFICATIONS.combine(registry)
resource = specification.create_resource(self.schema)
self._resolver = registry.resolver_with_root(resource)
if self.schema is True or self.schema is False:
self._validators = []
else:
self._validators = [
(self.VALIDATORS[k], k, v)
for k, v in applicable_validators(self.schema)
if k in self.VALIDATORS
]
# REMOVEME: Legacy ref resolution state management.
push_scope = getattr(self._ref_resolver, "push_scope", None)
if push_scope is not None:
id = id_of(self.schema)
if id is not None:
push_scope(id)
@classmethod
def check_schema(cls, schema, format_checker=_UNSET):
Validator = validator_for(cls.META_SCHEMA, default=cls)
if format_checker is _UNSET:
format_checker = Validator.FORMAT_CHECKER
validator = Validator(
schema=cls.META_SCHEMA,
format_checker=format_checker,
)
for error in validator.iter_errors(schema):
raise exceptions.SchemaError.create_from(error)
@property
def resolver(self):
warnings.warn(
(
f"Accessing {self.__class__.__name__}.resolver is "
"deprecated as of v4.18.0, in favor of the "
"https://github.com/python-jsonschema/referencing "
"library, which provides more compliant referencing "
"behavior as well as more flexible APIs for "
"customization."
),
DeprecationWarning,
stacklevel=2,
)
if self._ref_resolver is None:
self._ref_resolver = _RefResolver.from_schema(
self.schema,
id_of=id_of,
)
return self._ref_resolver
def evolve(self, **changes):
schema = changes.setdefault("schema", self.schema)
NewValidator = validator_for(schema, default=self.__class__)
for (attr_name, init_name) in evolve_fields:
if init_name not in changes:
changes[init_name] = getattr(self, attr_name)
return NewValidator(**changes)
def iter_errors(self, instance, _schema=None):
if _schema is not None:
warnings.warn(
(
"Passing a schema to Validator.iter_errors "
"is deprecated and will be removed in a future "
"release. Call validator.evolve(schema=new_schema)."
"iter_errors(...) instead."
),
DeprecationWarning,
stacklevel=2,
)
validators = [
(self.VALIDATORS[k], k, v)
for k, v in applicable_validators(_schema)
if k in self.VALIDATORS
]
else:
_schema, validators = self.schema, self._validators
if _schema is True:
return
elif _schema is False:
yield exceptions.ValidationError(
f"False schema does not allow {instance!r}",
validator=None,
validator_value=None,
instance=instance,
schema=_schema,
)
return
for validator, k, v in validators:
errors = validator(self, v, instance, _schema) or ()
for error in errors:
# set details if not already set by the called fn
error._set(
validator=k,
validator_value=v,
instance=instance,
schema=_schema,
type_checker=self.TYPE_CHECKER,
)
if k not in {"if", "$ref"}:
error.schema_path.appendleft(k)
yield error
def descend(
self,
instance,
schema,
path=None,
schema_path=None,
resolver=None,
):
if schema is True:
return
elif schema is False:
yield exceptions.ValidationError(
f"False schema does not allow {instance!r}",
validator=None,
validator_value=None,
instance=instance,
schema=schema,
)
return
if self._ref_resolver is not None:
evolved = self.evolve(schema=schema)
else:
if resolver is None:
resolver = self._resolver.in_subresource(
specification.create_resource(schema),
)
evolved = self.evolve(schema=schema, _resolver=resolver)
for k, v in applicable_validators(schema):
validator = evolved.VALIDATORS.get(k)
if validator is None:
continue
errors = validator(evolved, v, instance, schema) or ()
for error in errors:
# set details if not already set by the called fn
error._set(
validator=k,
validator_value=v,
instance=instance,
schema=schema,
type_checker=evolved.TYPE_CHECKER,
)
if k not in {"if", "$ref"}:
error.schema_path.appendleft(k)
if path is not None:
error.path.appendleft(path)
if schema_path is not None:
error.schema_path.appendleft(schema_path)
yield error
def validate(self, *args, **kwargs):
for error in self.iter_errors(*args, **kwargs):
raise error
def is_type(self, instance, type):
try:
return self.TYPE_CHECKER.is_type(instance, type)
except exceptions.UndefinedTypeCheck:
exc = exceptions.UnknownType(type, instance, self.schema)
raise exc from None
def _validate_reference(self, ref, instance):
if self._ref_resolver is None:
try:
resolved = self._resolver.lookup(ref)
except referencing.exceptions.Unresolvable as err:
raise exceptions._WrappedReferencingError(err) from err
return self.descend(
instance,
resolved.contents,
resolver=resolved.resolver,
)
else:
resolve = getattr(self._ref_resolver, "resolve", None)
if resolve is None:
with self._ref_resolver.resolving(ref) as resolved:
return self.descend(instance, resolved)
else:
scope, resolved = resolve(ref)
self._ref_resolver.push_scope(scope)
try:
return list(self.descend(instance, resolved))
finally:
self._ref_resolver.pop_scope()
def is_valid(self, instance, _schema=None):
if _schema is not None:
warnings.warn(
(
"Passing a schema to Validator.is_valid is deprecated "
"and will be removed in a future release. Call "
"validator.evolve(schema=new_schema).is_valid(...) "
"instead."
),
DeprecationWarning,
stacklevel=2,
)
self = self.evolve(schema=_schema)
error = next(self.iter_errors(instance), None)
return error is None
|
class Validator:
def __init_subclass__(cls):
pass
def evolve(self, **changes):
pass
def __attrs_post_init__(self):
pass
@classmethod
def check_schema(cls, schema, format_checker=_UNSET):
pass
@property
def resolver(self):
pass
def evolve(self, **changes):
pass
def iter_errors(self, instance, _schema=None):
pass
def descend(
self,
instance,
schema,
path=None,
schema_path=None,
resolver=None,
):
pass
def validate(self, *args, **kwargs):
pass
def is_type(self, instance, type):
pass
def _validate_reference(self, ref, instance):
pass
def is_valid(self, instance, _schema=None):
pass
| 15 | 0 | 21 | 2 | 19 | 0 | 4 | 0.03 | 0 | 9 | 1 | 0 | 10 | 0 | 11 | 11 | 278 | 30 | 244 | 65 | 222 | 7 | 133 | 55 | 120 | 11 | 0 | 3 | 47 |
140,213 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.TestValidate
|
class TestValidate(TestCase):
def assertUses(self, schema, Validator):
result = []
with mock.patch.object(Validator, "check_schema", result.append):
validators.validate({}, schema)
self.assertEqual(result, [schema])
def test_draft3_validator_is_chosen(self):
self.assertUses(
schema={"$schema": "http://json-schema.org/draft-03/schema#"},
Validator=validators.Draft3Validator,
)
# Make sure it works without the empty fragment
self.assertUses(
schema={"$schema": "http://json-schema.org/draft-03/schema"},
Validator=validators.Draft3Validator,
)
def test_draft4_validator_is_chosen(self):
self.assertUses(
schema={"$schema": "http://json-schema.org/draft-04/schema#"},
Validator=validators.Draft4Validator,
)
# Make sure it works without the empty fragment
self.assertUses(
schema={"$schema": "http://json-schema.org/draft-04/schema"},
Validator=validators.Draft4Validator,
)
def test_draft6_validator_is_chosen(self):
self.assertUses(
schema={"$schema": "http://json-schema.org/draft-06/schema#"},
Validator=validators.Draft6Validator,
)
# Make sure it works without the empty fragment
self.assertUses(
schema={"$schema": "http://json-schema.org/draft-06/schema"},
Validator=validators.Draft6Validator,
)
def test_draft7_validator_is_chosen(self):
self.assertUses(
schema={"$schema": "http://json-schema.org/draft-07/schema#"},
Validator=validators.Draft7Validator,
)
# Make sure it works without the empty fragment
self.assertUses(
schema={"$schema": "http://json-schema.org/draft-07/schema"},
Validator=validators.Draft7Validator,
)
def test_draft202012_validator_is_chosen(self):
self.assertUses(
schema={
"$schema": "https://json-schema.org/draft/2020-12/schema#",
},
Validator=validators.Draft202012Validator,
)
# Make sure it works without the empty fragment
self.assertUses(
schema={
"$schema": "https://json-schema.org/draft/2020-12/schema",
},
Validator=validators.Draft202012Validator,
)
def test_draft202012_validator_is_the_default(self):
self.assertUses(schema={}, Validator=validators.Draft202012Validator)
def test_validation_error_message(self):
with self.assertRaises(exceptions.ValidationError) as e:
validators.validate(12, {"type": "string"})
self.assertRegex(
str(e.exception),
"(?s)Failed validating '.*' in schema.*On instance",
)
def test_schema_error_message(self):
with self.assertRaises(exceptions.SchemaError) as e:
validators.validate(12, {"type": 12})
self.assertRegex(
str(e.exception),
"(?s)Failed validating '.*' in metaschema.*On schema",
)
def test_it_uses_best_match(self):
schema = {
"oneOf": [
{"type": "number", "minimum": 20},
{"type": "array"},
],
}
with self.assertRaises(exceptions.ValidationError) as e:
validators.validate(12, schema)
self.assertIn("12 is less than the minimum of 20", str(e.exception))
|
class TestValidate(TestCase):
def assertUses(self, schema, Validator):
pass
def test_draft3_validator_is_chosen(self):
pass
def test_draft4_validator_is_chosen(self):
pass
def test_draft6_validator_is_chosen(self):
pass
def test_draft7_validator_is_chosen(self):
pass
def test_draft202012_validator_is_chosen(self):
pass
def test_draft202012_validator_is_the_default(self):
pass
def test_validation_error_message(self):
pass
def test_schema_error_message(self):
pass
def test_it_uses_best_match(self):
pass
| 11 | 0 | 9 | 0 | 8 | 1 | 1 | 0.12 | 1 | 1 | 0 | 0 | 10 | 0 | 10 | 82 | 95 | 9 | 81 | 16 | 70 | 10 | 36 | 13 | 25 | 1 | 2 | 1 | 10 |
140,214 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/cli.py
|
jsonschema.cli._PrettyFormatter
|
class _PrettyFormatter:
_ERROR_MSG = dedent(
"""\
===[{type}]===({path})===
{body}
-----------------------------
""",
)
_SUCCESS_MSG = "===[SUCCESS]===({path})===\n"
def filenotfound_error(self, path, exc_info):
return self._ERROR_MSG.format(
path=path,
type="FileNotFoundError",
body=f"{path!r} does not exist.",
)
def parsing_error(self, path, exc_info):
exc_type, exc_value, exc_traceback = exc_info
exc_lines = "".join(
traceback.format_exception(exc_type, exc_value, exc_traceback),
)
return self._ERROR_MSG.format(
path=path,
type=exc_type.__name__,
body=exc_lines,
)
def validation_error(self, instance_path, error):
return self._ERROR_MSG.format(
path=instance_path,
type=error.__class__.__name__,
body=error,
)
def validation_success(self, instance_path):
return self._SUCCESS_MSG.format(path=instance_path)
|
class _PrettyFormatter:
def filenotfound_error(self, path, exc_info):
pass
def parsing_error(self, path, exc_info):
pass
def validation_error(self, instance_path, error):
pass
def validation_success(self, instance_path):
pass
| 5 | 0 | 6 | 0 | 6 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 4 | 0 | 4 | 4 | 39 | 6 | 33 | 9 | 28 | 0 | 13 | 9 | 8 | 1 | 0 | 0 | 4 |
140,215 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.TestLatestValidator
|
class TestLatestValidator(TestCase):
"""
These really apply to multiple versions but are easiest to test on one.
"""
def test_ref_resolvers_may_have_boolean_schemas_stored(self):
ref = "someCoolRef"
schema = {"$ref": ref}
resolver = validators._RefResolver("", {}, store={ref: False})
validator = validators._LATEST_VERSION(schema, resolver=resolver)
with self.assertRaises(exceptions.ValidationError):
validator.validate(None)
|
class TestLatestValidator(TestCase):
'''
These really apply to multiple versions but are easiest to test on one.
'''
def test_ref_resolvers_may_have_boolean_schemas_stored(self):
pass
| 2 | 1 | 8 | 1 | 7 | 0 | 1 | 0.38 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 13 | 2 | 8 | 6 | 6 | 3 | 8 | 6 | 6 | 1 | 2 | 1 | 1 |
140,216 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/exceptions.py
|
jsonschema.exceptions.ErrorTree
|
class ErrorTree:
"""
ErrorTrees make it easier to check which validations failed.
"""
_instance = _unset
def __init__(self, errors: Iterable[ValidationError] = ()):
self.errors: MutableMapping[str, ValidationError] = {}
self._contents: Mapping[str, ErrorTree] = defaultdict(self.__class__)
for error in errors:
container = self
for element in error.path:
container = container[element]
container.errors[error.validator] = error
container._instance = error.instance
def __contains__(self, index: str | int):
"""
Check whether ``instance[index]`` has any errors.
"""
return index in self._contents
def __getitem__(self, index):
"""
Retrieve the child tree one level down at the given ``index``.
If the index is not in the instance that this tree corresponds
to and is not known by this tree, whatever error would be raised
by ``instance.__getitem__`` will be propagated (usually this is
some subclass of `LookupError`.
"""
if self._instance is not _unset and index not in self:
self._instance[index]
return self._contents[index]
def __setitem__(self, index: str | int, value: ErrorTree):
"""
Add an error to the tree at the given ``index``.
.. deprecated:: v4.20.0
Setting items on an `ErrorTree` is deprecated without replacement.
To populate a tree, provide all of its sub-errors when you
construct the tree.
"""
warnings.warn(
"ErrorTree.__setitem__ is deprecated without replacement.",
DeprecationWarning,
stacklevel=2,
)
self._contents[index] = value # type: ignore[index]
def __iter__(self):
"""
Iterate (non-recursively) over the indices in the instance with errors.
"""
return iter(self._contents)
def __len__(self):
"""
Return the `total_errors`.
"""
return self.total_errors
def __repr__(self):
total = len(self)
errors = "error" if total == 1 else "errors"
return f"<{self.__class__.__name__} ({total} total {errors})>"
@property
def total_errors(self):
"""
The total number of errors in the entire tree, including children.
"""
child_errors = sum(len(tree) for _, tree in self._contents.items())
return len(self.errors) + child_errors
|
class ErrorTree:
'''
ErrorTrees make it easier to check which validations failed.
'''
def __init__(self, errors: Iterable[ValidationError] = ()):
pass
def __contains__(self, index: str | int):
'''
Check whether ``instance[index]`` has any errors.
'''
pass
def __getitem__(self, index):
'''
Retrieve the child tree one level down at the given ``index``.
If the index is not in the instance that this tree corresponds
to and is not known by this tree, whatever error would be raised
by ``instance.__getitem__`` will be propagated (usually this is
some subclass of `LookupError`.
'''
pass
def __setitem__(self, index: str | int, value: ErrorTree):
'''
Add an error to the tree at the given ``index``.
.. deprecated:: v4.20.0
Setting items on an `ErrorTree` is deprecated without replacement.
To populate a tree, provide all of its sub-errors when you
construct the tree.
'''
pass
def __iter__(self):
'''
Iterate (non-recursively) over the indices in the instance with errors.
'''
pass
def __len__(self):
'''
Return the `total_errors`.
'''
pass
def __repr__(self):
pass
@property
def total_errors(self):
'''
The total number of errors in the entire tree, including children.
'''
pass
| 10 | 7 | 8 | 1 | 4 | 3 | 2 | 0.83 | 0 | 7 | 1 | 0 | 8 | 2 | 8 | 8 | 79 | 14 | 36 | 19 | 26 | 30 | 31 | 18 | 22 | 3 | 0 | 2 | 12 |
140,217 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_cli.py
|
jsonschema.tests.test_cli.TestCLI
|
class TestCLI(TestCase):
def run_cli(
self, argv, files=None, stdin=StringIO(), exit_code=0, **override,
):
arguments = cli.parse_args(argv)
arguments.update(override)
self.assertFalse(hasattr(cli, "open"))
cli.open = fake_open(files or {})
try:
stdout, stderr = StringIO(), StringIO()
actual_exit_code = cli.run(
arguments,
stdin=stdin,
stdout=stdout,
stderr=stderr,
)
finally:
del cli.open
self.assertEqual(
actual_exit_code, exit_code, msg=dedent(
f"""
Expected an exit code of {exit_code} != {actual_exit_code}.
stdout: {stdout.getvalue()}
stderr: {stderr.getvalue()}
""",
),
)
return stdout.getvalue(), stderr.getvalue()
def assertOutputs(self, stdout="", stderr="", **kwargs):
self.assertEqual(
self.run_cli(**kwargs),
(dedent(stdout), dedent(stderr)),
)
def test_invalid_instance(self):
error = ValidationError("I am an error!", instance=12)
self.assertOutputs(
files=dict(
some_schema='{"does not": "matter since it is stubbed"}',
some_instance=json.dumps(error.instance),
),
validator=fake_validator([error]),
argv=["-i", "some_instance", "some_schema"],
exit_code=1,
stderr="12: I am an error!\n",
)
def test_invalid_instance_pretty_output(self):
error = ValidationError("I am an error!", instance=12)
self.assertOutputs(
files=dict(
some_schema='{"does not": "matter since it is stubbed"}',
some_instance=json.dumps(error.instance),
),
validator=fake_validator([error]),
argv=["-i", "some_instance", "--output", "pretty", "some_schema"],
exit_code=1,
stderr="""\
===[ValidationError]===(some_instance)===
I am an error!
-----------------------------
""",
)
def test_invalid_instance_explicit_plain_output(self):
error = ValidationError("I am an error!", instance=12)
self.assertOutputs(
files=dict(
some_schema='{"does not": "matter since it is stubbed"}',
some_instance=json.dumps(error.instance),
),
validator=fake_validator([error]),
argv=["--output", "plain", "-i", "some_instance", "some_schema"],
exit_code=1,
stderr="12: I am an error!\n",
)
def test_invalid_instance_multiple_errors(self):
instance = 12
first = ValidationError("First error", instance=instance)
second = ValidationError("Second error", instance=instance)
self.assertOutputs(
files=dict(
some_schema='{"does not": "matter since it is stubbed"}',
some_instance=json.dumps(instance),
),
validator=fake_validator([first, second]),
argv=["-i", "some_instance", "some_schema"],
exit_code=1,
stderr="""\
12: First error
12: Second error
""",
)
def test_invalid_instance_multiple_errors_pretty_output(self):
instance = 12
first = ValidationError("First error", instance=instance)
second = ValidationError("Second error", instance=instance)
self.assertOutputs(
files=dict(
some_schema='{"does not": "matter since it is stubbed"}',
some_instance=json.dumps(instance),
),
validator=fake_validator([first, second]),
argv=["-i", "some_instance", "--output", "pretty", "some_schema"],
exit_code=1,
stderr="""\
===[ValidationError]===(some_instance)===
First error
-----------------------------
===[ValidationError]===(some_instance)===
Second error
-----------------------------
""",
)
def test_multiple_invalid_instances(self):
first_instance = 12
first_errors = [
ValidationError("An error", instance=first_instance),
ValidationError("Another error", instance=first_instance),
]
second_instance = "foo"
second_errors = [ValidationError("BOOM", instance=second_instance)]
self.assertOutputs(
files=dict(
some_schema='{"does not": "matter since it is stubbed"}',
some_first_instance=json.dumps(first_instance),
some_second_instance=json.dumps(second_instance),
),
validator=fake_validator(first_errors, second_errors),
argv=[
"-i", "some_first_instance",
"-i", "some_second_instance",
"some_schema",
],
exit_code=1,
stderr="""\
12: An error
12: Another error
foo: BOOM
""",
)
def test_multiple_invalid_instances_pretty_output(self):
first_instance = 12
first_errors = [
ValidationError("An error", instance=first_instance),
ValidationError("Another error", instance=first_instance),
]
second_instance = "foo"
second_errors = [ValidationError("BOOM", instance=second_instance)]
self.assertOutputs(
files=dict(
some_schema='{"does not": "matter since it is stubbed"}',
some_first_instance=json.dumps(first_instance),
some_second_instance=json.dumps(second_instance),
),
validator=fake_validator(first_errors, second_errors),
argv=[
"--output", "pretty",
"-i", "some_first_instance",
"-i", "some_second_instance",
"some_schema",
],
exit_code=1,
stderr="""\
===[ValidationError]===(some_first_instance)===
An error
-----------------------------
===[ValidationError]===(some_first_instance)===
Another error
-----------------------------
===[ValidationError]===(some_second_instance)===
BOOM
-----------------------------
""",
)
def test_custom_error_format(self):
first_instance = 12
first_errors = [
ValidationError("An error", instance=first_instance),
ValidationError("Another error", instance=first_instance),
]
second_instance = "foo"
second_errors = [ValidationError("BOOM", instance=second_instance)]
self.assertOutputs(
files=dict(
some_schema='{"does not": "matter since it is stubbed"}',
some_first_instance=json.dumps(first_instance),
some_second_instance=json.dumps(second_instance),
),
validator=fake_validator(first_errors, second_errors),
argv=[
"--error-format", ":{error.message}._-_.{error.instance}:",
"-i", "some_first_instance",
"-i", "some_second_instance",
"some_schema",
],
exit_code=1,
stderr=":An error._-_.12::Another error._-_.12::BOOM._-_.foo:",
)
def test_invalid_schema(self):
self.assertOutputs(
files=dict(some_schema='{"type": 12}'),
argv=["some_schema"],
exit_code=1,
stderr="""\
12: 12 is not valid under any of the given schemas
""",
)
def test_invalid_schema_pretty_output(self):
schema = {"type": 12}
with self.assertRaises(SchemaError) as e:
validate(schema=schema, instance="")
error = str(e.exception)
self.assertOutputs(
files=dict(some_schema=json.dumps(schema)),
argv=["--output", "pretty", "some_schema"],
exit_code=1,
stderr=(
"===[SchemaError]===(some_schema)===\n\n"
+ str(error)
+ "\n-----------------------------\n"
),
)
def test_invalid_schema_multiple_errors(self):
self.assertOutputs(
files=dict(some_schema='{"type": 12, "items": 57}'),
argv=["some_schema"],
exit_code=1,
stderr="""\
57: 57 is not of type 'object', 'boolean'
""",
)
def test_invalid_schema_multiple_errors_pretty_output(self):
schema = {"type": 12, "items": 57}
with self.assertRaises(SchemaError) as e:
validate(schema=schema, instance="")
error = str(e.exception)
self.assertOutputs(
files=dict(some_schema=json.dumps(schema)),
argv=["--output", "pretty", "some_schema"],
exit_code=1,
stderr=(
"===[SchemaError]===(some_schema)===\n\n"
+ str(error)
+ "\n-----------------------------\n"
),
)
def test_invalid_schema_with_invalid_instance(self):
"""
"Validating" an instance that's invalid under an invalid schema
just shows the schema error.
"""
self.assertOutputs(
files=dict(
some_schema='{"type": 12, "minimum": 30}',
some_instance="13",
),
argv=["-i", "some_instance", "some_schema"],
exit_code=1,
stderr="""\
12: 12 is not valid under any of the given schemas
""",
)
def test_invalid_schema_with_invalid_instance_pretty_output(self):
instance, schema = 13, {"type": 12, "minimum": 30}
with self.assertRaises(SchemaError) as e:
validate(schema=schema, instance=instance)
error = str(e.exception)
self.assertOutputs(
files=dict(
some_schema=json.dumps(schema),
some_instance=json.dumps(instance),
),
argv=["--output", "pretty", "-i", "some_instance", "some_schema"],
exit_code=1,
stderr=(
"===[SchemaError]===(some_schema)===\n\n"
+ str(error)
+ "\n-----------------------------\n"
),
)
def test_invalid_instance_continues_with_the_rest(self):
self.assertOutputs(
files=dict(
some_schema='{"minimum": 30}',
first_instance="not valid JSON!",
second_instance="12",
),
argv=[
"-i", "first_instance",
"-i", "second_instance",
"some_schema",
],
exit_code=1,
stderr="""\
Failed to parse 'first_instance': {}
12: 12 is less than the minimum of 30
""".format(_message_for("not valid JSON!")),
)
def test_custom_error_format_applies_to_schema_errors(self):
instance, schema = 13, {"type": 12, "minimum": 30}
with self.assertRaises(SchemaError):
validate(schema=schema, instance=instance)
self.assertOutputs(
files=dict(some_schema=json.dumps(schema)),
argv=[
"--error-format", ":{error.message}._-_.{error.instance}:",
"some_schema",
],
exit_code=1,
stderr=":12 is not valid under any of the given schemas._-_.12:",
)
def test_instance_is_invalid_JSON(self):
instance = "not valid JSON!"
self.assertOutputs(
files=dict(some_schema="{}", some_instance=instance),
argv=["-i", "some_instance", "some_schema"],
exit_code=1,
stderr=f"""\
Failed to parse 'some_instance': {_message_for(instance)}
""",
)
def test_instance_is_invalid_JSON_pretty_output(self):
stdout, stderr = self.run_cli(
files=dict(
some_schema="{}",
some_instance="not valid JSON!",
),
argv=["--output", "pretty", "-i", "some_instance", "some_schema"],
exit_code=1,
)
self.assertFalse(stdout)
self.assertIn(
"(some_instance)===\n\nTraceback (most recent call last):\n",
stderr,
)
self.assertNotIn("some_schema", stderr)
def test_instance_is_invalid_JSON_on_stdin(self):
instance = "not valid JSON!"
self.assertOutputs(
files=dict(some_schema="{}"),
stdin=StringIO(instance),
argv=["some_schema"],
exit_code=1,
stderr=f"""\
Failed to parse <stdin>: {_message_for(instance)}
""",
)
def test_instance_is_invalid_JSON_on_stdin_pretty_output(self):
stdout, stderr = self.run_cli(
files=dict(some_schema="{}"),
stdin=StringIO("not valid JSON!"),
argv=["--output", "pretty", "some_schema"],
exit_code=1,
)
self.assertFalse(stdout)
self.assertIn(
"(<stdin>)===\n\nTraceback (most recent call last):\n",
stderr,
)
self.assertNotIn("some_schema", stderr)
def test_schema_is_invalid_JSON(self):
schema = "not valid JSON!"
self.assertOutputs(
files=dict(some_schema=schema),
argv=["some_schema"],
exit_code=1,
stderr=f"""\
Failed to parse 'some_schema': {_message_for(schema)}
""",
)
def test_schema_is_invalid_JSON_pretty_output(self):
stdout, stderr = self.run_cli(
files=dict(some_schema="not valid JSON!"),
argv=["--output", "pretty", "some_schema"],
exit_code=1,
)
self.assertFalse(stdout)
self.assertIn(
"(some_schema)===\n\nTraceback (most recent call last):\n",
stderr,
)
def test_schema_and_instance_are_both_invalid_JSON(self):
"""
Only the schema error is reported, as we abort immediately.
"""
schema, instance = "not valid JSON!", "also not valid JSON!"
self.assertOutputs(
files=dict(some_schema=schema, some_instance=instance),
argv=["some_schema"],
exit_code=1,
stderr=f"""\
Failed to parse 'some_schema': {_message_for(schema)}
""",
)
def test_schema_and_instance_are_both_invalid_JSON_pretty_output(self):
"""
Only the schema error is reported, as we abort immediately.
"""
stdout, stderr = self.run_cli(
files=dict(
some_schema="not valid JSON!",
some_instance="also not valid JSON!",
),
argv=["--output", "pretty", "-i", "some_instance", "some_schema"],
exit_code=1,
)
self.assertFalse(stdout)
self.assertIn(
"(some_schema)===\n\nTraceback (most recent call last):\n",
stderr,
)
self.assertNotIn("some_instance", stderr)
def test_instance_does_not_exist(self):
self.assertOutputs(
files=dict(some_schema="{}"),
argv=["-i", "nonexisting_instance", "some_schema"],
exit_code=1,
stderr="""\
'nonexisting_instance' does not exist.
""",
)
def test_instance_does_not_exist_pretty_output(self):
self.assertOutputs(
files=dict(some_schema="{}"),
argv=[
"--output", "pretty",
"-i", "nonexisting_instance",
"some_schema",
],
exit_code=1,
stderr="""\
===[FileNotFoundError]===(nonexisting_instance)===
'nonexisting_instance' does not exist.
-----------------------------
""",
)
def test_schema_does_not_exist(self):
self.assertOutputs(
argv=["nonexisting_schema"],
exit_code=1,
stderr="'nonexisting_schema' does not exist.\n",
)
def test_schema_does_not_exist_pretty_output(self):
self.assertOutputs(
argv=["--output", "pretty", "nonexisting_schema"],
exit_code=1,
stderr="""\
===[FileNotFoundError]===(nonexisting_schema)===
'nonexisting_schema' does not exist.
-----------------------------
""",
)
def test_neither_instance_nor_schema_exist(self):
self.assertOutputs(
argv=["-i", "nonexisting_instance", "nonexisting_schema"],
exit_code=1,
stderr="'nonexisting_schema' does not exist.\n",
)
def test_neither_instance_nor_schema_exist_pretty_output(self):
self.assertOutputs(
argv=[
"--output", "pretty",
"-i", "nonexisting_instance",
"nonexisting_schema",
],
exit_code=1,
stderr="""\
===[FileNotFoundError]===(nonexisting_schema)===
'nonexisting_schema' does not exist.
-----------------------------
""",
)
def test_successful_validation(self):
self.assertOutputs(
files=dict(some_schema="{}", some_instance="{}"),
argv=["-i", "some_instance", "some_schema"],
stdout="",
stderr="",
)
def test_successful_validation_pretty_output(self):
self.assertOutputs(
files=dict(some_schema="{}", some_instance="{}"),
argv=["--output", "pretty", "-i", "some_instance", "some_schema"],
stdout="===[SUCCESS]===(some_instance)===\n",
stderr="",
)
def test_successful_validation_of_stdin(self):
self.assertOutputs(
files=dict(some_schema="{}"),
stdin=StringIO("{}"),
argv=["some_schema"],
stdout="",
stderr="",
)
def test_successful_validation_of_stdin_pretty_output(self):
self.assertOutputs(
files=dict(some_schema="{}"),
stdin=StringIO("{}"),
argv=["--output", "pretty", "some_schema"],
stdout="===[SUCCESS]===(<stdin>)===\n",
stderr="",
)
def test_successful_validation_of_just_the_schema(self):
self.assertOutputs(
files=dict(some_schema="{}", some_instance="{}"),
argv=["-i", "some_instance", "some_schema"],
stdout="",
stderr="",
)
def test_successful_validation_of_just_the_schema_pretty_output(self):
self.assertOutputs(
files=dict(some_schema="{}", some_instance="{}"),
argv=["--output", "pretty", "-i", "some_instance", "some_schema"],
stdout="===[SUCCESS]===(some_instance)===\n",
stderr="",
)
def test_successful_validation_via_explicit_base_uri(self):
ref_schema_file = tempfile.NamedTemporaryFile(delete=False) # noqa: SIM115
ref_schema_file.close()
self.addCleanup(os.remove, ref_schema_file.name)
ref_path = Path(ref_schema_file.name)
ref_path.write_text('{"definitions": {"num": {"type": "integer"}}}')
schema = f'{{"$ref": "{ref_path.name}#/definitions/num"}}'
self.assertOutputs(
files=dict(some_schema=schema, some_instance="1"),
argv=[
"-i", "some_instance",
"--base-uri", ref_path.parent.as_uri() + "/",
"some_schema",
],
stdout="",
stderr="",
)
def test_unsuccessful_validation_via_explicit_base_uri(self):
ref_schema_file = tempfile.NamedTemporaryFile(delete=False) # noqa: SIM115
ref_schema_file.close()
self.addCleanup(os.remove, ref_schema_file.name)
ref_path = Path(ref_schema_file.name)
ref_path.write_text('{"definitions": {"num": {"type": "integer"}}}')
schema = f'{{"$ref": "{ref_path.name}#/definitions/num"}}'
self.assertOutputs(
files=dict(some_schema=schema, some_instance='"1"'),
argv=[
"-i", "some_instance",
"--base-uri", ref_path.parent.as_uri() + "/",
"some_schema",
],
exit_code=1,
stdout="",
stderr="1: '1' is not of type 'integer'\n",
)
def test_nonexistent_file_with_explicit_base_uri(self):
schema = '{"$ref": "someNonexistentFile.json#definitions/num"}'
instance = "1"
with self.assertRaises(_RefResolutionError) as e:
self.assertOutputs(
files=dict(
some_schema=schema,
some_instance=instance,
),
argv=[
"-i", "some_instance",
"--base-uri", Path.cwd().as_uri(),
"some_schema",
],
)
error = str(e.exception)
self.assertIn(f"{os.sep}someNonexistentFile.json'", error)
def test_invalid_explicit_base_uri(self):
schema = '{"$ref": "foo.json#definitions/num"}'
instance = "1"
with self.assertRaises(_RefResolutionError) as e:
self.assertOutputs(
files=dict(
some_schema=schema,
some_instance=instance,
),
argv=[
"-i", "some_instance",
"--base-uri", "not@UR1",
"some_schema",
],
)
error = str(e.exception)
self.assertEqual(
error, "unknown url type: 'foo.json'",
)
def test_it_validates_using_the_latest_validator_when_unspecified(self):
# There isn't a better way now I can think of to ensure that the
# latest version was used, given that the call to validator_for
# is hidden inside the CLI, so guard that that's the case, and
# this test will have to be updated when versions change until
# we can think of a better way to ensure this behavior.
self.assertIs(Draft202012Validator, _LATEST_VERSION)
self.assertOutputs(
files=dict(some_schema='{"const": "check"}', some_instance='"a"'),
argv=["-i", "some_instance", "some_schema"],
exit_code=1,
stdout="",
stderr="a: 'check' was expected\n",
)
def test_it_validates_using_draft7_when_specified(self):
"""
Specifically, `const` validation applies for Draft 7.
"""
schema = """
{
"$schema": "http://json-schema.org/draft-07/schema#",
"const": "check"
}
"""
instance = '"foo"'
self.assertOutputs(
files=dict(some_schema=schema, some_instance=instance),
argv=["-i", "some_instance", "some_schema"],
exit_code=1,
stdout="",
stderr="foo: 'check' was expected\n",
)
def test_it_validates_using_draft4_when_specified(self):
"""
Specifically, `const` validation *does not* apply for Draft 4.
"""
schema = """
{
"$schema": "http://json-schema.org/draft-04/schema#",
"const": "check"
}
"""
instance = '"foo"'
self.assertOutputs(
files=dict(some_schema=schema, some_instance=instance),
argv=["-i", "some_instance", "some_schema"],
stdout="",
stderr="",
)
|
class TestCLI(TestCase):
def run_cli(
self, argv, files=None, stdin=StringIO(), exit_code=0, **override,
):
pass
def assertOutputs(self, stdout="", stderr="", **kwargs):
pass
def test_invalid_instance(self):
pass
def test_invalid_instance_pretty_output(self):
pass
def test_invalid_instance_explicit_plain_output(self):
pass
def test_invalid_instance_multiple_errors(self):
pass
def test_invalid_instance_multiple_errors_pretty_output(self):
pass
def test_multiple_invalid_instances(self):
pass
def test_multiple_invalid_instances_pretty_output(self):
pass
def test_custom_error_format(self):
pass
def test_invalid_schema(self):
pass
def test_invalid_schema_pretty_output(self):
pass
def test_invalid_schema_multiple_errors(self):
pass
def test_invalid_schema_multiple_errors_pretty_output(self):
pass
def test_invalid_schema_with_invalid_instance(self):
'''
"Validating" an instance that's invalid under an invalid schema
just shows the schema error.
'''
pass
def test_invalid_schema_with_invalid_instance_pretty_output(self):
pass
def test_invalid_instance_continues_with_the_rest(self):
pass
def test_custom_error_format_applies_to_schema_errors(self):
pass
def test_instance_is_invalid_JSON(self):
pass
def test_instance_is_invalid_JSON_pretty_output(self):
pass
def test_instance_is_invalid_JSON_on_stdin(self):
pass
def test_instance_is_invalid_JSON_on_stdin_pretty_output(self):
pass
def test_schema_is_invalid_JSON(self):
pass
def test_schema_is_invalid_JSON_pretty_output(self):
pass
def test_schema_and_instance_are_both_invalid_JSON(self):
'''
Only the schema error is reported, as we abort immediately.
'''
pass
def test_schema_and_instance_are_both_invalid_JSON_pretty_output(self):
'''
Only the schema error is reported, as we abort immediately.
'''
pass
def test_instance_does_not_exist(self):
pass
def test_instance_does_not_exist_pretty_output(self):
pass
def test_schema_does_not_exist(self):
pass
def test_schema_does_not_exist_pretty_output(self):
pass
def test_neither_instance_nor_schema_exist(self):
pass
def test_neither_instance_nor_schema_exist_pretty_output(self):
pass
def test_successful_validation(self):
pass
def test_successful_validation_pretty_output(self):
pass
def test_successful_validation_of_stdin(self):
pass
def test_successful_validation_of_stdin_pretty_output(self):
pass
def test_successful_validation_of_just_the_schema(self):
pass
def test_successful_validation_of_just_the_schema_pretty_output(self):
pass
def test_successful_validation_via_explicit_base_uri(self):
pass
def test_unsuccessful_validation_via_explicit_base_uri(self):
pass
def test_nonexistent_file_with_explicit_base_uri(self):
pass
def test_invalid_explicit_base_uri(self):
pass
def test_it_validates_using_the_latest_validator_when_unspecified(self):
pass
def test_it_validates_using_draft7_when_specified(self):
'''
Specifically, `const` validation applies for Draft 7.
'''
pass
def test_it_validates_using_draft4_when_specified(self):
'''
Specifically, `const` validation *does not* apply for Draft 4.
'''
pass
| 46 | 5 | 16 | 2 | 14 | 1 | 1 | 0.05 | 1 | 6 | 0 | 0 | 45 | 0 | 45 | 117 | 762 | 128 | 613 | 108 | 565 | 29 | 178 | 101 | 132 | 1 | 2 | 1 | 45 |
140,218 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_cli.py
|
jsonschema.tests.test_cli.TestCLIIntegration
|
class TestCLIIntegration(TestCase):
def test_license(self):
our_metadata = metadata.metadata("jsonschema")
self.assertEqual(our_metadata.get("License-Expression"), "MIT")
def test_version(self):
version = subprocess.check_output(
[sys.executable, "-W", "ignore", "-m", "jsonschema", "--version"],
stderr=subprocess.STDOUT,
)
version = version.decode("utf-8").strip()
self.assertEqual(version, metadata.version("jsonschema"))
def test_no_arguments_shows_usage_notes(self):
output = subprocess.check_output(
[sys.executable, "-m", "jsonschema"],
stderr=subprocess.STDOUT,
)
output_for_help = subprocess.check_output(
[sys.executable, "-m", "jsonschema", "--help"],
stderr=subprocess.STDOUT,
)
self.assertEqual(output, output_for_help)
|
class TestCLIIntegration(TestCase):
def test_license(self):
pass
def test_version(self):
pass
def test_no_arguments_shows_usage_notes(self):
pass
| 4 | 0 | 7 | 0 | 7 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 75 | 23 | 2 | 21 | 8 | 17 | 0 | 12 | 8 | 8 | 1 | 2 | 0 | 3 |
140,219 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_cli.py
|
jsonschema.tests.test_cli.TestParser
|
class TestParser(TestCase):
FakeValidator = fake_validator()
def test_find_validator_by_fully_qualified_object_name(self):
arguments = cli.parse_args(
[
"--validator",
"jsonschema.tests.test_cli.TestParser.FakeValidator",
"--instance", "mem://some/instance",
"mem://some/schema",
],
)
self.assertIs(arguments["validator"], self.FakeValidator)
def test_find_validator_in_jsonschema(self):
arguments = cli.parse_args(
[
"--validator", "Draft4Validator",
"--instance", "mem://some/instance",
"mem://some/schema",
],
)
self.assertIs(arguments["validator"], Draft4Validator)
def cli_output_for(self, *argv):
stdout, stderr = StringIO(), StringIO()
with redirect_stdout(stdout), redirect_stderr(stderr): # noqa: SIM117
with self.assertRaises(SystemExit):
cli.parse_args(argv)
return stdout.getvalue(), stderr.getvalue()
def test_unknown_output(self):
stdout, stderr = self.cli_output_for(
"--output", "foo",
"mem://some/schema",
)
self.assertIn("invalid choice: 'foo'", stderr)
self.assertFalse(stdout)
def test_useless_error_format(self):
stdout, stderr = self.cli_output_for(
"--output", "pretty",
"--error-format", "foo",
"mem://some/schema",
)
self.assertIn(
"--error-format can only be used with --output plain",
stderr,
)
self.assertFalse(stdout)
|
class TestParser(TestCase):
def test_find_validator_by_fully_qualified_object_name(self):
pass
def test_find_validator_in_jsonschema(self):
pass
def cli_output_for(self, *argv):
pass
def test_unknown_output(self):
pass
def test_useless_error_format(self):
pass
| 6 | 0 | 9 | 0 | 9 | 0 | 1 | 0.02 | 1 | 3 | 0 | 0 | 5 | 0 | 5 | 77 | 51 | 6 | 45 | 12 | 39 | 1 | 22 | 12 | 16 | 1 | 2 | 2 | 5 |
140,220 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_exceptions.py
|
jsonschema.tests.test_exceptions.TestBestMatch
|
class TestBestMatch(TestCase):
def best_match_of(self, instance, schema):
errors = list(_LATEST_VERSION(schema).iter_errors(instance))
msg = f"No errors found for {instance} under {schema!r}!"
self.assertTrue(errors, msg=msg)
best = exceptions.best_match(iter(errors))
reversed_best = exceptions.best_match(reversed(errors))
self.assertEqual(
best._contents(),
reversed_best._contents(),
f"No consistent best match!\nGot: {best}\n\nThen: {reversed_best}",
)
return best
def test_shallower_errors_are_better_matches(self):
schema = {
"properties": {
"foo": {
"minProperties": 2,
"properties": {"bar": {"type": "object"}},
},
},
}
best = self.best_match_of(instance={"foo": {"bar": []}}, schema=schema)
self.assertEqual(best.validator, "minProperties")
def test_oneOf_and_anyOf_are_weak_matches(self):
"""
A property you *must* match is probably better than one you have to
match a part of.
"""
schema = {
"minProperties": 2,
"anyOf": [{"type": "string"}, {"type": "number"}],
"oneOf": [{"type": "string"}, {"type": "number"}],
}
best = self.best_match_of(instance={}, schema=schema)
self.assertEqual(best.validator, "minProperties")
def test_if_the_most_relevant_error_is_anyOf_it_is_traversed(self):
"""
If the most relevant error is an anyOf, then we traverse its context
and select the otherwise *least* relevant error, since in this case
that means the most specific, deep, error inside the instance.
I.e. since only one of the schemas must match, we look for the most
relevant one.
"""
schema = {
"properties": {
"foo": {
"anyOf": [
{"type": "string"},
{"properties": {"bar": {"type": "array"}}},
],
},
},
}
best = self.best_match_of(instance={"foo": {"bar": 12}}, schema=schema)
self.assertEqual(best.validator_value, "array")
def test_no_anyOf_traversal_for_equally_relevant_errors(self):
"""
We don't traverse into an anyOf (as above) if all of its context errors
seem to be equally "wrong" against the instance.
"""
schema = {
"anyOf": [
{"type": "string"},
{"type": "integer"},
{"type": "object"},
],
}
best = self.best_match_of(instance=[], schema=schema)
self.assertEqual(best.validator, "anyOf")
def test_anyOf_traversal_for_single_equally_relevant_error(self):
"""
We *do* traverse anyOf with a single nested error, even though it is
vacuously equally relevant to itself.
"""
schema = {
"anyOf": [
{"type": "string"},
],
}
best = self.best_match_of(instance=[], schema=schema)
self.assertEqual(best.validator, "type")
def test_anyOf_traversal_for_single_sibling_errors(self):
"""
We *do* traverse anyOf with a single subschema that fails multiple
times (e.g. on multiple items).
"""
schema = {
"anyOf": [
{"items": {"const": 37}},
],
}
best = self.best_match_of(instance=[12, 12], schema=schema)
self.assertEqual(best.validator, "const")
def test_anyOf_traversal_for_non_type_matching_sibling_errors(self):
"""
We *do* traverse anyOf with multiple subschemas when one does not type
match.
"""
schema = {
"anyOf": [
{"type": "object"},
{"items": {"const": 37}},
],
}
best = self.best_match_of(instance=[12, 12], schema=schema)
self.assertEqual(best.validator, "const")
def test_if_the_most_relevant_error_is_oneOf_it_is_traversed(self):
"""
If the most relevant error is an oneOf, then we traverse its context
and select the otherwise *least* relevant error, since in this case
that means the most specific, deep, error inside the instance.
I.e. since only one of the schemas must match, we look for the most
relevant one.
"""
schema = {
"properties": {
"foo": {
"oneOf": [
{"type": "string"},
{"properties": {"bar": {"type": "array"}}},
],
},
},
}
best = self.best_match_of(instance={"foo": {"bar": 12}}, schema=schema)
self.assertEqual(best.validator_value, "array")
def test_no_oneOf_traversal_for_equally_relevant_errors(self):
"""
We don't traverse into an oneOf (as above) if all of its context errors
seem to be equally "wrong" against the instance.
"""
schema = {
"oneOf": [
{"type": "string"},
{"type": "integer"},
{"type": "object"},
],
}
best = self.best_match_of(instance=[], schema=schema)
self.assertEqual(best.validator, "oneOf")
def test_oneOf_traversal_for_single_equally_relevant_error(self):
"""
We *do* traverse oneOf with a single nested error, even though it is
vacuously equally relevant to itself.
"""
schema = {
"oneOf": [
{"type": "string"},
],
}
best = self.best_match_of(instance=[], schema=schema)
self.assertEqual(best.validator, "type")
def test_oneOf_traversal_for_single_sibling_errors(self):
"""
We *do* traverse oneOf with a single subschema that fails multiple
times (e.g. on multiple items).
"""
schema = {
"oneOf": [
{"items": {"const": 37}},
],
}
best = self.best_match_of(instance=[12, 12], schema=schema)
self.assertEqual(best.validator, "const")
def test_oneOf_traversal_for_non_type_matching_sibling_errors(self):
"""
We *do* traverse oneOf with multiple subschemas when one does not type
match.
"""
schema = {
"oneOf": [
{"type": "object"},
{"items": {"const": 37}},
],
}
best = self.best_match_of(instance=[12, 12], schema=schema)
self.assertEqual(best.validator, "const")
def test_if_the_most_relevant_error_is_allOf_it_is_traversed(self):
"""
Now, if the error is allOf, we traverse but select the *most* relevant
error from the context, because all schemas here must match anyways.
"""
schema = {
"properties": {
"foo": {
"allOf": [
{"type": "string"},
{"properties": {"bar": {"type": "array"}}},
],
},
},
}
best = self.best_match_of(instance={"foo": {"bar": 12}}, schema=schema)
self.assertEqual(best.validator_value, "string")
def test_nested_context_for_oneOf(self):
"""
We traverse into nested contexts (a oneOf containing an error in a
nested oneOf here).
"""
schema = {
"properties": {
"foo": {
"oneOf": [
{"type": "string"},
{
"oneOf": [
{"type": "string"},
{
"properties": {
"bar": {"type": "array"},
},
},
],
},
],
},
},
}
best = self.best_match_of(instance={"foo": {"bar": 12}}, schema=schema)
self.assertEqual(best.validator_value, "array")
def test_it_prioritizes_matching_types(self):
schema = {
"properties": {
"foo": {
"anyOf": [
{"type": "array", "minItems": 2},
{"type": "string", "minLength": 10},
],
},
},
}
best = self.best_match_of(instance={"foo": "bar"}, schema=schema)
self.assertEqual(best.validator, "minLength")
reordered = {
"properties": {
"foo": {
"anyOf": [
{"type": "string", "minLength": 10},
{"type": "array", "minItems": 2},
],
},
},
}
best = self.best_match_of(instance={"foo": "bar"}, schema=reordered)
self.assertEqual(best.validator, "minLength")
def test_it_prioritizes_matching_union_types(self):
schema = {
"properties": {
"foo": {
"anyOf": [
{"type": ["array", "object"], "minItems": 2},
{"type": ["integer", "string"], "minLength": 10},
],
},
},
}
best = self.best_match_of(instance={"foo": "bar"}, schema=schema)
self.assertEqual(best.validator, "minLength")
reordered = {
"properties": {
"foo": {
"anyOf": [
{"type": "string", "minLength": 10},
{"type": "array", "minItems": 2},
],
},
},
}
best = self.best_match_of(instance={"foo": "bar"}, schema=reordered)
self.assertEqual(best.validator, "minLength")
def test_boolean_schemas(self):
schema = {"properties": {"foo": False}}
best = self.best_match_of(instance={"foo": "bar"}, schema=schema)
self.assertIsNone(best.validator)
def test_one_error(self):
validator = _LATEST_VERSION({"minProperties": 2})
error, = validator.iter_errors({})
self.assertEqual(
exceptions.best_match(validator.iter_errors({})).validator,
"minProperties",
)
def test_no_errors(self):
validator = _LATEST_VERSION({})
self.assertIsNone(exceptions.best_match(validator.iter_errors({})))
|
class TestBestMatch(TestCase):
def best_match_of(self, instance, schema):
pass
def test_shallower_errors_are_better_matches(self):
pass
def test_oneOf_and_anyOf_are_weak_matches(self):
'''
A property you *must* match is probably better than one you have to
match a part of.
'''
pass
def test_if_the_most_relevant_error_is_anyOf_it_is_traversed(self):
'''
If the most relevant error is an anyOf, then we traverse its context
and select the otherwise *least* relevant error, since in this case
that means the most specific, deep, error inside the instance.
I.e. since only one of the schemas must match, we look for the most
relevant one.
'''
pass
def test_no_anyOf_traversal_for_equally_relevant_errors(self):
'''
We don't traverse into an anyOf (as above) if all of its context errors
seem to be equally "wrong" against the instance.
'''
pass
def test_anyOf_traversal_for_single_equally_relevant_error(self):
'''
We *do* traverse anyOf with a single nested error, even though it is
vacuously equally relevant to itself.
'''
pass
def test_anyOf_traversal_for_single_sibling_errors(self):
'''
We *do* traverse anyOf with a single subschema that fails multiple
times (e.g. on multiple items).
'''
pass
def test_anyOf_traversal_for_non_type_matching_sibling_errors(self):
'''
We *do* traverse anyOf with multiple subschemas when one does not type
match.
'''
pass
def test_if_the_most_relevant_error_is_oneOf_it_is_traversed(self):
'''
If the most relevant error is an oneOf, then we traverse its context
and select the otherwise *least* relevant error, since in this case
that means the most specific, deep, error inside the instance.
I.e. since only one of the schemas must match, we look for the most
relevant one.
'''
pass
def test_no_oneOf_traversal_for_equally_relevant_errors(self):
'''
We don't traverse into an oneOf (as above) if all of its context errors
seem to be equally "wrong" against the instance.
'''
pass
def test_oneOf_traversal_for_single_equally_relevant_error(self):
'''
We *do* traverse oneOf with a single nested error, even though it is
vacuously equally relevant to itself.
'''
pass
def test_oneOf_traversal_for_single_sibling_errors(self):
'''
We *do* traverse oneOf with a single subschema that fails multiple
times (e.g. on multiple items).
'''
pass
def test_oneOf_traversal_for_non_type_matching_sibling_errors(self):
'''
We *do* traverse oneOf with multiple subschemas when one does not type
match.
'''
pass
def test_if_the_most_relevant_error_is_allOf_it_is_traversed(self):
'''
Now, if the error is allOf, we traverse but select the *most* relevant
error from the context, because all schemas here must match anyways.
'''
pass
def test_nested_context_for_oneOf(self):
'''
We traverse into nested contexts (a oneOf containing an error in a
nested oneOf here).
'''
pass
def test_it_prioritizes_matching_types(self):
pass
def test_it_prioritizes_matching_union_types(self):
pass
def test_boolean_schemas(self):
pass
def test_one_error(self):
pass
def test_no_errors(self):
pass
| 21 | 13 | 15 | 1 | 11 | 3 | 1 | 0.26 | 1 | 2 | 0 | 0 | 20 | 0 | 20 | 92 | 323 | 38 | 227 | 64 | 206 | 58 | 90 | 64 | 69 | 1 | 2 | 0 | 20 |
140,221 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_exceptions.py
|
jsonschema.tests.test_exceptions.TestByRelevance
|
class TestByRelevance(TestCase):
def test_short_paths_are_better_matches(self):
shallow = exceptions.ValidationError("Oh no!", path=["baz"])
deep = exceptions.ValidationError("Oh yes!", path=["foo", "bar"])
match = max([shallow, deep], key=exceptions.relevance)
self.assertIs(match, shallow)
match = max([deep, shallow], key=exceptions.relevance)
self.assertIs(match, shallow)
def test_global_errors_are_even_better_matches(self):
shallow = exceptions.ValidationError("Oh no!", path=[])
deep = exceptions.ValidationError("Oh yes!", path=["foo"])
errors = sorted([shallow, deep], key=exceptions.relevance)
self.assertEqual(
[list(error.path) for error in errors],
[["foo"], []],
)
errors = sorted([deep, shallow], key=exceptions.relevance)
self.assertEqual(
[list(error.path) for error in errors],
[["foo"], []],
)
def test_weak_keywords_are_lower_priority(self):
weak = exceptions.ValidationError("Oh no!", path=[], validator="a")
normal = exceptions.ValidationError("Oh yes!", path=[], validator="b")
best_match = exceptions.by_relevance(weak="a")
match = max([weak, normal], key=best_match)
self.assertIs(match, normal)
match = max([normal, weak], key=best_match)
self.assertIs(match, normal)
def test_strong_keywords_are_higher_priority(self):
weak = exceptions.ValidationError("Oh no!", path=[], validator="a")
normal = exceptions.ValidationError("Oh yes!", path=[], validator="b")
strong = exceptions.ValidationError("Oh fine!", path=[], validator="c")
best_match = exceptions.by_relevance(weak="a", strong="c")
match = max([weak, normal, strong], key=best_match)
self.assertIs(match, strong)
match = max([strong, normal, weak], key=best_match)
self.assertIs(match, strong)
|
class TestByRelevance(TestCase):
def test_short_paths_are_better_matches(self):
pass
def test_global_errors_are_even_better_matches(self):
pass
def test_weak_keywords_are_lower_priority(self):
pass
def test_strong_keywords_are_higher_priority(self):
pass
| 5 | 0 | 12 | 2 | 9 | 0 | 1 | 0 | 1 | 2 | 0 | 0 | 4 | 0 | 4 | 76 | 50 | 12 | 38 | 20 | 33 | 0 | 32 | 20 | 27 | 1 | 2 | 0 | 4 |
140,222 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_exceptions.py
|
jsonschema.tests.test_exceptions.TestErrorInitReprStr
|
class TestErrorInitReprStr(TestCase):
def make_error(self, **kwargs):
defaults = dict(
message="hello",
validator="type",
validator_value="string",
instance=5,
schema={"type": "string"},
)
defaults.update(kwargs)
return exceptions.ValidationError(**defaults)
def assertShows(self, expected, **kwargs):
expected = textwrap.dedent(expected).rstrip("\n")
error = self.make_error(**kwargs)
message_line, _, rest = str(error).partition("\n")
self.assertEqual(message_line, error.message)
self.assertEqual(rest, expected)
def test_it_calls_super_and_sets_args(self):
error = self.make_error()
self.assertGreater(len(error.args), 1)
def test_repr(self):
self.assertEqual(
repr(exceptions.ValidationError(message="Hello!")),
"<ValidationError: 'Hello!'>",
)
def test_unset_error(self):
error = exceptions.ValidationError("message")
self.assertEqual(str(error), "message")
kwargs = {
"validator": "type",
"validator_value": "string",
"instance": 5,
"schema": {"type": "string"},
}
# Just the message should show if any of the attributes are unset
for attr in kwargs:
k = dict(kwargs)
del k[attr]
error = exceptions.ValidationError("message", **k)
self.assertEqual(str(error), "message")
def test_empty_paths(self):
self.assertShows(
"""
Failed validating 'type' in schema:
{'type': 'string'}
On instance:
5
""",
path=[],
schema_path=[],
)
def test_one_item_paths(self):
self.assertShows(
"""
Failed validating 'type' in schema:
{'type': 'string'}
On instance[0]:
5
""",
path=[0],
schema_path=["items"],
)
def test_multiple_item_paths(self):
self.assertShows(
"""
Failed validating 'type' in schema['items'][0]:
{'type': 'string'}
On instance[0]['a']:
5
""",
path=[0, "a"],
schema_path=["items", 0, 1],
)
def test_uses_pprint(self):
self.assertShows(
"""
Failed validating 'maxLength' in schema:
{0: 0,
1: 1,
2: 2,
3: 3,
4: 4,
5: 5,
6: 6,
7: 7,
8: 8,
9: 9,
10: 10,
11: 11,
12: 12,
13: 13,
14: 14,
15: 15,
16: 16,
17: 17,
18: 18,
19: 19}
On instance:
[0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24]
""",
instance=list(range(25)),
schema=dict(zip(range(20), range(20))),
validator="maxLength",
)
def test_does_not_reorder_dicts(self):
self.assertShows(
"""
Failed validating 'type' in schema:
{'do': 3, 'not': 7, 'sort': 37, 'me': 73}
On instance:
{'here': 73, 'too': 37, 'no': 7, 'sorting': 3}
""",
schema={
"do": 3,
"not": 7,
"sort": 37,
"me": 73,
},
instance={
"here": 73,
"too": 37,
"no": 7,
"sorting": 3,
},
)
def test_str_works_with_instances_having_overriden_eq_operator(self):
"""
Check for #164 which rendered exceptions unusable when a
`ValidationError` involved instances with an `__eq__` method
that returned truthy values.
"""
class DontEQMeBro:
def __eq__(this, other): # pragma: no cover
self.fail("Don't!")
def __ne__(this, other): # pragma: no cover
self.fail("Don't!")
instance = DontEQMeBro()
error = exceptions.ValidationError(
"a message",
validator="foo",
instance=instance,
validator_value="some",
schema="schema",
)
self.assertIn(repr(instance), str(error))
|
class TestErrorInitReprStr(TestCase):
def make_error(self, **kwargs):
pass
def assertShows(self, expected, **kwargs):
pass
def test_it_calls_super_and_sets_args(self):
pass
def test_repr(self):
pass
def test_unset_error(self):
pass
def test_empty_paths(self):
pass
def test_one_item_paths(self):
pass
def test_multiple_item_paths(self):
pass
def test_uses_pprint(self):
pass
def test_does_not_reorder_dicts(self):
pass
def test_str_works_with_instances_having_overriden_eq_operator(self):
'''
Check for #164 which rendered exceptions unusable when a
`ValidationError` involved instances with an `__eq__` method
that returned truthy values.
'''
pass
class DontEQMeBro:
def __eq__(this, other):
pass
def __ne__(this, other):
pass
| 15 | 1 | 14 | 1 | 13 | 1 | 1 | 0.05 | 1 | 7 | 1 | 0 | 11 | 0 | 11 | 83 | 189 | 20 | 163 | 25 | 148 | 8 | 44 | 25 | 29 | 2 | 2 | 1 | 14 |
140,223 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/_suite.py
|
jsonschema.tests._suite._Test
|
class _Test:
version: Version
subject: str
case_description: str
description: str
data: Any
schema: Mapping[str, Any] | bool
valid: bool
_remotes: referencing.jsonschema.SchemaRegistry
comment: str | None = None
def __repr__(self): # pragma: no cover
return f"<Test {self.fully_qualified_name}>"
@property
def fully_qualified_name(self): # pragma: no cover
return " > ".join( # noqa: FLY002
[
self.version.name,
self.subject,
self.case_description,
self.description,
],
)
def to_unittest_method(self, skip=lambda test: None, **kwargs):
if self.valid:
def fn(this):
self.validate(**kwargs)
else:
def fn(this):
with this.assertRaises(jsonschema.ValidationError):
self.validate(**kwargs)
fn.__name__ = "_".join(
[
"test",
_DELIMITERS.sub("_", self.subject),
_DELIMITERS.sub("_", self.case_description),
_DELIMITERS.sub("_", self.description),
],
)
reason = skip(self)
if reason is None or os.environ.get("JSON_SCHEMA_DEBUG", "0") != "0":
return fn
elif os.environ.get("JSON_SCHEMA_EXPECTED_FAILURES", "0") != "0": # pragma: no cover # noqa: E501
return unittest.expectedFailure(fn)
else:
return unittest.skip(reason)(fn)
def validate(self, Validator, **kwargs):
Validator.check_schema(self.schema)
validator = Validator(
schema=self.schema,
registry=self._remotes,
**kwargs,
)
if os.environ.get("JSON_SCHEMA_DEBUG", "0") != "0": # pragma: no cover
breakpoint() # noqa: T100
validator.validate(instance=self.data)
def validate_ignoring_errors(self, Validator): # pragma: no cover
with suppress(jsonschema.ValidationError):
self.validate(Validator=Validator)
|
class _Test:
def __repr__(self):
pass
@property
def fully_qualified_name(self):
pass
def to_unittest_method(self, skip=lambda test: None, **kwargs):
pass
def fn(this):
pass
def fn(this):
pass
def validate(self, Validator, **kwargs):
pass
def validate_ignoring_errors(self, Validator):
pass
| 9 | 0 | 8 | 0 | 7 | 1 | 2 | 0.12 | 0 | 2 | 0 | 0 | 5 | 0 | 5 | 5 | 70 | 12 | 58 | 12 | 49 | 7 | 36 | 11 | 28 | 4 | 0 | 1 | 11 |
140,224 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_exceptions.py
|
jsonschema.tests.test_exceptions.TestErrorTree
|
class TestErrorTree(TestCase):
def test_it_knows_how_many_total_errors_it_contains(self):
# FIXME: #442
errors = [
exceptions.ValidationError("Something", validator=i)
for i in range(8)
]
tree = exceptions.ErrorTree(errors)
self.assertEqual(tree.total_errors, 8)
def test_it_contains_an_item_if_the_item_had_an_error(self):
errors = [exceptions.ValidationError("a message", path=["bar"])]
tree = exceptions.ErrorTree(errors)
self.assertIn("bar", tree)
def test_it_does_not_contain_an_item_if_the_item_had_no_error(self):
errors = [exceptions.ValidationError("a message", path=["bar"])]
tree = exceptions.ErrorTree(errors)
self.assertNotIn("foo", tree)
def test_keywords_that_failed_appear_in_errors_dict(self):
error = exceptions.ValidationError("a message", validator="foo")
tree = exceptions.ErrorTree([error])
self.assertEqual(tree.errors, {"foo": error})
def test_it_creates_a_child_tree_for_each_nested_path(self):
errors = [
exceptions.ValidationError("a bar message", path=["bar"]),
exceptions.ValidationError("a bar -> 0 message", path=["bar", 0]),
]
tree = exceptions.ErrorTree(errors)
self.assertIn(0, tree["bar"])
self.assertNotIn(1, tree["bar"])
def test_children_have_their_errors_dicts_built(self):
e1, e2 = (
exceptions.ValidationError("1", validator="foo", path=["bar", 0]),
exceptions.ValidationError("2", validator="quux", path=["bar", 0]),
)
tree = exceptions.ErrorTree([e1, e2])
self.assertEqual(tree["bar"][0].errors, {"foo": e1, "quux": e2})
def test_multiple_errors_with_instance(self):
e1, e2 = (
exceptions.ValidationError(
"1",
validator="foo",
path=["bar", "bar2"],
instance="i1"),
exceptions.ValidationError(
"2",
validator="quux",
path=["foobar", 2],
instance="i2"),
)
exceptions.ErrorTree([e1, e2])
def test_it_does_not_contain_subtrees_that_are_not_in_the_instance(self):
error = exceptions.ValidationError("123", validator="foo", instance=[])
tree = exceptions.ErrorTree([error])
with self.assertRaises(IndexError):
tree[0]
def test_if_its_in_the_tree_anyhow_it_does_not_raise_an_error(self):
"""
If a keyword refers to a path that isn't in the instance, the
tree still properly returns a subtree for that path.
"""
error = exceptions.ValidationError(
"a message", validator="foo", instance={}, path=["foo"],
)
tree = exceptions.ErrorTree([error])
self.assertIsInstance(tree["foo"], exceptions.ErrorTree)
def test_iter(self):
e1, e2 = (
exceptions.ValidationError(
"1",
validator="foo",
path=["bar", "bar2"],
instance="i1"),
exceptions.ValidationError(
"2",
validator="quux",
path=["foobar", 2],
instance="i2"),
)
tree = exceptions.ErrorTree([e1, e2])
self.assertEqual(set(tree), {"bar", "foobar"})
def test_repr_single(self):
error = exceptions.ValidationError(
"1",
validator="foo",
path=["bar", "bar2"],
instance="i1",
)
tree = exceptions.ErrorTree([error])
self.assertEqual(repr(tree), "<ErrorTree (1 total error)>")
def test_repr_multiple(self):
e1, e2 = (
exceptions.ValidationError(
"1",
validator="foo",
path=["bar", "bar2"],
instance="i1"),
exceptions.ValidationError(
"2",
validator="quux",
path=["foobar", 2],
instance="i2"),
)
tree = exceptions.ErrorTree([e1, e2])
self.assertEqual(repr(tree), "<ErrorTree (2 total errors)>")
def test_repr_empty(self):
tree = exceptions.ErrorTree([])
self.assertEqual(repr(tree), "<ErrorTree (0 total errors)>")
|
class TestErrorTree(TestCase):
def test_it_knows_how_many_total_errors_it_contains(self):
pass
def test_it_contains_an_item_if_the_item_had_an_error(self):
pass
def test_it_does_not_contain_an_item_if_the_item_had_no_error(self):
pass
def test_keywords_that_failed_appear_in_errors_dict(self):
pass
def test_it_creates_a_child_tree_for_each_nested_path(self):
pass
def test_children_have_their_errors_dicts_built(self):
pass
def test_multiple_errors_with_instance(self):
pass
def test_it_does_not_contain_subtrees_that_are_not_in_the_instance(self):
pass
def test_if_its_in_the_tree_anyhow_it_does_not_raise_an_error(self):
'''
If a keyword refers to a path that isn't in the instance, the
tree still properly returns a subtree for that path.
'''
pass
def test_iter(self):
pass
def test_repr_single(self):
pass
def test_repr_multiple(self):
pass
def test_repr_empty(self):
pass
| 14 | 1 | 8 | 0 | 8 | 0 | 1 | 0.05 | 1 | 5 | 0 | 0 | 13 | 0 | 13 | 85 | 121 | 14 | 102 | 38 | 88 | 5 | 53 | 38 | 39 | 1 | 2 | 1 | 13 |
140,225 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_format.py
|
jsonschema.tests.test_format.TestFormatChecker
|
class TestFormatChecker(TestCase):
def test_it_can_validate_no_formats(self):
checker = FormatChecker(formats=())
self.assertFalse(checker.checkers)
def test_it_raises_a_key_error_for_unknown_formats(self):
with self.assertRaises(KeyError):
FormatChecker(formats=["o noes"])
def test_it_can_register_cls_checkers(self):
original = dict(FormatChecker.checkers)
self.addCleanup(FormatChecker.checkers.pop, "boom")
with self.assertWarns(DeprecationWarning):
FormatChecker.cls_checks("boom")(boom)
self.assertEqual(
FormatChecker.checkers,
dict(original, boom=(boom, ())),
)
def test_it_can_register_checkers(self):
checker = FormatChecker()
checker.checks("boom")(boom)
self.assertEqual(
checker.checkers,
dict(FormatChecker.checkers, boom=(boom, ())),
)
def test_it_catches_registered_errors(self):
checker = FormatChecker()
checker.checks("boom", raises=type(BOOM))(boom)
with self.assertRaises(FormatError) as cm:
checker.check(instance=12, format="boom")
self.assertIs(cm.exception.cause, BOOM)
self.assertIs(cm.exception.__cause__, BOOM)
self.assertEqual(str(cm.exception), "12 is not a 'boom'")
# Unregistered errors should not be caught
with self.assertRaises(type(BANG)):
checker.check(instance="bang", format="boom")
def test_format_error_causes_become_validation_error_causes(self):
checker = FormatChecker()
checker.checks("boom", raises=ValueError)(boom)
validator = Draft4Validator({"format": "boom"}, format_checker=checker)
with self.assertRaises(ValidationError) as cm:
validator.validate("BOOM")
self.assertIs(cm.exception.cause, BOOM)
self.assertIs(cm.exception.__cause__, BOOM)
def test_format_checkers_come_with_defaults(self):
# This is bad :/ but relied upon.
# The docs for quite awhile recommended people do things like
# validate(..., format_checker=FormatChecker())
# We should change that, but we can't without deprecation...
checker = FormatChecker()
with self.assertRaises(FormatError):
checker.check(instance="not-an-ipv4", format="ipv4")
def test_repr(self):
checker = FormatChecker(formats=())
checker.checks("foo")(lambda thing: True) # pragma: no cover
checker.checks("bar")(lambda thing: True) # pragma: no cover
checker.checks("baz")(lambda thing: True) # pragma: no cover
self.assertEqual(
repr(checker),
"<FormatChecker checkers=['bar', 'baz', 'foo']>",
)
|
class TestFormatChecker(TestCase):
def test_it_can_validate_no_formats(self):
pass
def test_it_raises_a_key_error_for_unknown_formats(self):
pass
def test_it_can_register_cls_checkers(self):
pass
def test_it_can_register_checkers(self):
pass
def test_it_catches_registered_errors(self):
pass
def test_format_error_causes_become_validation_error_causes(self):
pass
def test_format_checkers_come_with_defaults(self):
pass
def test_repr(self):
pass
| 9 | 0 | 8 | 1 | 7 | 1 | 1 | 0.15 | 1 | 9 | 0 | 0 | 8 | 0 | 8 | 80 | 71 | 12 | 54 | 19 | 45 | 8 | 45 | 17 | 36 | 1 | 2 | 1 | 8 |
140,226 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_types.py
|
jsonschema.tests.test_types.TestCustomTypes
|
class TestCustomTypes(TestCase):
def test_simple_type_can_be_extended(self):
def int_or_str_int(checker, instance):
if not isinstance(instance, (int, str)):
return False
try:
int(instance)
except ValueError:
return False
return True
CustomValidator = extend(
Draft202012Validator,
type_checker=Draft202012Validator.TYPE_CHECKER.redefine(
"integer", int_or_str_int,
),
)
validator = CustomValidator({"type": "integer"})
validator.validate(4)
validator.validate("4")
with self.assertRaises(ValidationError):
validator.validate(4.4)
with self.assertRaises(ValidationError):
validator.validate("foo")
def test_object_can_be_extended(self):
schema = {"type": "object"}
Point = namedtuple("Point", ["x", "y"])
type_checker = Draft202012Validator.TYPE_CHECKER.redefine(
"object", is_object_or_named_tuple,
)
CustomValidator = extend(
Draft202012Validator,
type_checker=type_checker,
)
validator = CustomValidator(schema)
validator.validate(Point(x=4, y=5))
def test_object_extensions_require_custom_validators(self):
schema = {"type": "object", "required": ["x"]}
type_checker = Draft202012Validator.TYPE_CHECKER.redefine(
"object", is_object_or_named_tuple,
)
CustomValidator = extend(
Draft202012Validator,
type_checker=type_checker,
)
validator = CustomValidator(schema)
Point = namedtuple("Point", ["x", "y"])
# Cannot handle required
with self.assertRaises(ValidationError):
validator.validate(Point(x=4, y=5))
def test_object_extensions_can_handle_custom_validators(self):
schema = {
"type": "object",
"required": ["x"],
"properties": {"x": {"type": "integer"}},
}
type_checker = Draft202012Validator.TYPE_CHECKER.redefine(
"object", is_object_or_named_tuple,
)
def coerce_named_tuple(fn):
def coerced(validator, value, instance, schema):
if is_namedtuple(instance):
instance = instance._asdict()
return fn(validator, value, instance, schema)
return coerced
required = coerce_named_tuple(_keywords.required)
properties = coerce_named_tuple(_keywords.properties)
CustomValidator = extend(
Draft202012Validator,
type_checker=type_checker,
validators={"required": required, "properties": properties},
)
validator = CustomValidator(schema)
Point = namedtuple("Point", ["x", "y"])
# Can now process required and properties
validator.validate(Point(x=4, y=5))
with self.assertRaises(ValidationError):
validator.validate(Point(x="not an integer", y=5))
# As well as still handle objects.
validator.validate({"x": 4, "y": 5})
with self.assertRaises(ValidationError):
validator.validate({"x": "not an integer", "y": 5})
def test_unknown_type(self):
with self.assertRaises(UnknownType) as e:
Draft202012Validator({}).is_type(12, "some unknown type")
self.assertIn("'some unknown type'", str(e.exception))
|
class TestCustomTypes(TestCase):
def test_simple_type_can_be_extended(self):
pass
def int_or_str_int(checker, instance):
pass
def test_object_can_be_extended(self):
pass
def test_object_extensions_require_custom_validators(self):
pass
def test_object_extensions_can_handle_custom_validators(self):
pass
def coerce_named_tuple(fn):
pass
def coerced(validator, value, instance, schema):
pass
def test_unknown_type(self):
pass
| 9 | 0 | 15 | 3 | 12 | 0 | 1 | 0.04 | 1 | 5 | 0 | 0 | 5 | 0 | 5 | 77 | 109 | 24 | 82 | 29 | 73 | 3 | 57 | 28 | 48 | 3 | 2 | 1 | 11 |
140,227 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_types.py
|
jsonschema.tests.test_types.TestTypeChecker
|
class TestTypeChecker(TestCase):
def test_is_type(self):
checker = TypeChecker({"two": equals_2})
self.assertEqual(
(
checker.is_type(instance=2, type="two"),
checker.is_type(instance="bar", type="two"),
),
(True, False),
)
def test_is_unknown_type(self):
with self.assertRaises(UndefinedTypeCheck) as e:
TypeChecker().is_type(4, "foobar")
self.assertIn(
"'foobar' is unknown to this type checker",
str(e.exception),
)
self.assertTrue(
e.exception.__suppress_context__,
msg="Expected the internal KeyError to be hidden.",
)
def test_checks_can_be_added_at_init(self):
checker = TypeChecker({"two": equals_2})
self.assertEqual(checker, TypeChecker().redefine("two", equals_2))
def test_redefine_existing_type(self):
self.assertEqual(
TypeChecker().redefine("two", object()).redefine("two", equals_2),
TypeChecker().redefine("two", equals_2),
)
def test_remove(self):
self.assertEqual(
TypeChecker({"two": equals_2}).remove("two"),
TypeChecker(),
)
def test_remove_unknown_type(self):
with self.assertRaises(UndefinedTypeCheck) as context:
TypeChecker().remove("foobar")
self.assertIn("foobar", str(context.exception))
def test_redefine_many(self):
self.assertEqual(
TypeChecker().redefine_many({"foo": int, "bar": str}),
TypeChecker().redefine("foo", int).redefine("bar", str),
)
def test_remove_multiple(self):
self.assertEqual(
TypeChecker({"foo": int, "bar": str}).remove("foo", "bar"),
TypeChecker(),
)
def test_type_check_can_raise_key_error(self):
"""
Make sure no one writes:
try:
self._type_checkers[type](...)
except KeyError:
ignoring the fact that the function itself can raise that.
"""
error = KeyError("Stuff")
def raises_keyerror(checker, instance):
raise error
with self.assertRaises(KeyError) as context:
TypeChecker({"foo": raises_keyerror}).is_type(4, "foo")
self.assertIs(context.exception, error)
def test_repr(self):
checker = TypeChecker({"foo": is_namedtuple, "bar": is_namedtuple})
self.assertEqual(repr(checker), "<TypeChecker types={'bar', 'foo'}>")
|
class TestTypeChecker(TestCase):
def test_is_type(self):
pass
def test_is_unknown_type(self):
pass
def test_checks_can_be_added_at_init(self):
pass
def test_redefine_existing_type(self):
pass
def test_remove(self):
pass
def test_remove_unknown_type(self):
pass
def test_redefine_many(self):
pass
def test_remove_multiple(self):
pass
def test_type_check_can_raise_key_error(self):
'''
Make sure no one writes:
try:
self._type_checkers[type](...)
except KeyError:
ignoring the fact that the function itself can raise that.
'''
pass
def raises_keyerror(checker, instance):
pass
def test_repr(self):
pass
| 12 | 1 | 7 | 1 | 5 | 1 | 1 | 0.12 | 1 | 5 | 0 | 0 | 10 | 0 | 10 | 82 | 80 | 15 | 58 | 19 | 46 | 7 | 34 | 16 | 22 | 1 | 2 | 1 | 11 |
140,228 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_utils.py
|
jsonschema.tests.test_utils.TestDictEqual
|
class TestDictEqual(TestCase):
def test_equal_dictionaries(self):
dict_1 = {"a": "b", "c": "d"}
dict_2 = {"c": "d", "a": "b"}
self.assertTrue(equal(dict_1, dict_2))
def test_equal_dictionaries_with_nan(self):
dict_1 = {"a": nan, "c": "d"}
dict_2 = {"c": "d", "a": nan}
self.assertTrue(equal(dict_1, dict_2))
def test_missing_key(self):
dict_1 = {"a": "b", "c": "d"}
dict_2 = {"c": "d", "x": "b"}
self.assertFalse(equal(dict_1, dict_2))
def test_additional_key(self):
dict_1 = {"a": "b", "c": "d"}
dict_2 = {"c": "d", "a": "b", "x": "x"}
self.assertFalse(equal(dict_1, dict_2))
def test_missing_value(self):
dict_1 = {"a": "b", "c": "d"}
dict_2 = {"c": "d", "a": "x"}
self.assertFalse(equal(dict_1, dict_2))
def test_empty_dictionaries(self):
dict_1 = {}
dict_2 = {}
self.assertTrue(equal(dict_1, dict_2))
def test_one_none(self):
dict_1 = None
dict_2 = {"a": "b", "c": "d"}
self.assertFalse(equal(dict_1, dict_2))
def test_same_item(self):
dict_1 = {"a": "b", "c": "d"}
self.assertTrue(equal(dict_1, dict_1))
def test_nested_equal(self):
dict_1 = {"a": {"a": "b", "c": "d"}, "c": "d"}
dict_2 = {"c": "d", "a": {"a": "b", "c": "d"}}
self.assertTrue(equal(dict_1, dict_2))
def test_nested_dict_unequal(self):
dict_1 = {"a": {"a": "b", "c": "d"}, "c": "d"}
dict_2 = {"c": "d", "a": {"a": "b", "c": "x"}}
self.assertFalse(equal(dict_1, dict_2))
def test_mixed_nested_equal(self):
dict_1 = {"a": ["a", "b", "c", "d"], "c": "d"}
dict_2 = {"c": "d", "a": ["a", "b", "c", "d"]}
self.assertTrue(equal(dict_1, dict_2))
def test_nested_list_unequal(self):
dict_1 = {"a": ["a", "b", "c", "d"], "c": "d"}
dict_2 = {"c": "d", "a": ["b", "c", "d", "a"]}
self.assertFalse(equal(dict_1, dict_2))
|
class TestDictEqual(TestCase):
def test_equal_dictionaries(self):
pass
def test_equal_dictionaries_with_nan(self):
pass
def test_missing_key(self):
pass
def test_additional_key(self):
pass
def test_missing_value(self):
pass
def test_empty_dictionaries(self):
pass
def test_one_none(self):
pass
def test_same_item(self):
pass
def test_nested_equal(self):
pass
def test_nested_dict_unequal(self):
pass
def test_mixed_nested_equal(self):
pass
def test_nested_list_unequal(self):
pass
| 13 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 12 | 0 | 12 | 84 | 59 | 11 | 48 | 36 | 35 | 0 | 48 | 36 | 35 | 1 | 2 | 0 | 12 |
140,229 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_utils.py
|
jsonschema.tests.test_utils.TestEqual
|
class TestEqual(TestCase):
def test_none(self):
self.assertTrue(equal(None, None))
def test_nan(self):
self.assertTrue(equal(nan, nan))
|
class TestEqual(TestCase):
def test_none(self):
pass
def test_nan(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 74 | 6 | 1 | 5 | 3 | 2 | 0 | 5 | 3 | 2 | 1 | 2 | 0 | 2 |
140,230 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_utils.py
|
jsonschema.tests.test_utils.TestListEqual
|
class TestListEqual(TestCase):
def test_equal_lists(self):
list_1 = ["a", "b", "c"]
list_2 = ["a", "b", "c"]
self.assertTrue(equal(list_1, list_2))
def test_equal_lists_with_nan(self):
list_1 = ["a", nan, "c"]
list_2 = ["a", nan, "c"]
self.assertTrue(equal(list_1, list_2))
def test_unsorted_lists(self):
list_1 = ["a", "b", "c"]
list_2 = ["b", "b", "a"]
self.assertFalse(equal(list_1, list_2))
def test_first_list_larger(self):
list_1 = ["a", "b", "c"]
list_2 = ["a", "b"]
self.assertFalse(equal(list_1, list_2))
def test_second_list_larger(self):
list_1 = ["a", "b"]
list_2 = ["a", "b", "c"]
self.assertFalse(equal(list_1, list_2))
def test_list_with_none_unequal(self):
list_1 = ["a", "b", None]
list_2 = ["a", "b", "c"]
self.assertFalse(equal(list_1, list_2))
list_1 = ["a", "b", None]
list_2 = [None, "b", "c"]
self.assertFalse(equal(list_1, list_2))
def test_list_with_none_equal(self):
list_1 = ["a", None, "c"]
list_2 = ["a", None, "c"]
self.assertTrue(equal(list_1, list_2))
def test_empty_list(self):
list_1 = []
list_2 = []
self.assertTrue(equal(list_1, list_2))
def test_one_none(self):
list_1 = None
list_2 = []
self.assertFalse(equal(list_1, list_2))
def test_same_list(self):
list_1 = ["a", "b", "c"]
self.assertTrue(equal(list_1, list_1))
def test_equal_nested_lists(self):
list_1 = ["a", ["b", "c"], "d"]
list_2 = ["a", ["b", "c"], "d"]
self.assertTrue(equal(list_1, list_2))
def test_unequal_nested_lists(self):
list_1 = ["a", ["b", "c"], "d"]
list_2 = ["a", [], "c"]
self.assertFalse(equal(list_1, list_2))
|
class TestListEqual(TestCase):
def test_equal_lists(self):
pass
def test_equal_lists_with_nan(self):
pass
def test_unsorted_lists(self):
pass
def test_first_list_larger(self):
pass
def test_second_list_larger(self):
pass
def test_list_with_none_unequal(self):
pass
def test_list_with_none_equal(self):
pass
def test_empty_list(self):
pass
def test_one_none(self):
pass
def test_same_list(self):
pass
def test_equal_nested_lists(self):
pass
def test_unequal_nested_lists(self):
pass
| 13 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 12 | 0 | 12 | 84 | 63 | 12 | 51 | 36 | 38 | 0 | 51 | 36 | 38 | 1 | 2 | 0 | 12 |
140,231 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_exceptions.py
|
jsonschema.tests.test_exceptions.TestHashable
|
class TestHashable(TestCase):
def test_hashable(self):
{exceptions.ValidationError("")}
{exceptions.SchemaError("")}
|
class TestHashable(TestCase):
def test_hashable(self):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 2 | 0 | 0 | 1 | 0 | 1 | 73 | 4 | 0 | 4 | 2 | 2 | 0 | 4 | 2 | 2 | 1 | 2 | 0 | 1 |
140,232 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/_suite.py
|
jsonschema.tests._suite._Case
|
class _Case:
version: Version
subject: str
description: str
schema: Mapping[str, Any] | bool
tests: list[_Test]
comment: str | None = None
specification: Sequence[dict[str, str]] = ()
@classmethod
def from_dict(cls, data, remotes, **kwargs):
data.update(kwargs)
tests = [
_Test(
version=data["version"],
subject=data["subject"],
case_description=data["description"],
schema=data["schema"],
remotes=remotes,
**test,
) for test in data.pop("tests")
]
return cls(tests=tests, **data)
def benchmark(self, runner: pyperf.Runner, **kwargs): # pragma: no cover
for test in self.tests:
runner.bench_func(
test.fully_qualified_name,
partial(test.validate_ignoring_errors, **kwargs),
)
|
class _Case:
@classmethod
def from_dict(cls, data, remotes, **kwargs):
pass
def benchmark(self, runner: pyperf.Runner, **kwargs):
pass
| 4 | 0 | 10 | 0 | 10 | 1 | 2 | 0.04 | 0 | 2 | 1 | 0 | 1 | 0 | 2 | 2 | 32 | 4 | 28 | 8 | 24 | 1 | 15 | 7 | 12 | 2 | 0 | 1 | 3 |
140,233 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_deprecations.py
|
jsonschema.tests.test_deprecations.TestDeprecations
|
class TestDeprecations(TestCase):
def test_version(self):
"""
As of v4.0.0, __version__ is deprecated in favor of importlib.metadata.
"""
message = "Accessing jsonschema.__version__ is deprecated"
with self.assertWarnsRegex(DeprecationWarning, message) as w:
from jsonschema import __version__
self.assertEqual(__version__, importlib.metadata.version("jsonschema"))
self.assertEqual(w.filename, __file__)
def test_validators_ErrorTree(self):
"""
As of v4.0.0, importing ErrorTree from jsonschema.validators is
deprecated in favor of doing so from jsonschema.exceptions.
"""
message = "Importing ErrorTree from jsonschema.validators is "
with self.assertWarnsRegex(DeprecationWarning, message) as w:
from jsonschema.validators import ErrorTree
self.assertEqual(ErrorTree, exceptions.ErrorTree)
self.assertEqual(w.filename, __file__)
def test_import_ErrorTree(self):
"""
As of v4.18.0, importing ErrorTree from the package root is
deprecated in favor of doing so from jsonschema.exceptions.
"""
message = "Importing ErrorTree directly from the jsonschema package "
with self.assertWarnsRegex(DeprecationWarning, message) as w:
from jsonschema import ErrorTree
self.assertEqual(ErrorTree, exceptions.ErrorTree)
self.assertEqual(w.filename, __file__)
def test_ErrorTree_setitem(self):
"""
As of v4.20.0, setting items on an ErrorTree is deprecated.
"""
e = exceptions.ValidationError("some error", path=["foo"])
tree = exceptions.ErrorTree()
subtree = exceptions.ErrorTree(errors=[e])
message = "ErrorTree.__setitem__ is "
with self.assertWarnsRegex(DeprecationWarning, message) as w:
tree["foo"] = subtree
self.assertEqual(tree["foo"], subtree)
self.assertEqual(w.filename, __file__)
def test_import_FormatError(self):
"""
As of v4.18.0, importing FormatError from the package root is
deprecated in favor of doing so from jsonschema.exceptions.
"""
message = "Importing FormatError directly from the jsonschema package "
with self.assertWarnsRegex(DeprecationWarning, message) as w:
from jsonschema import FormatError
self.assertEqual(FormatError, exceptions.FormatError)
self.assertEqual(w.filename, __file__)
def test_import_Validator(self):
"""
As of v4.19.0, importing Validator from the package root is
deprecated in favor of doing so from jsonschema.protocols.
"""
message = "Importing Validator directly from the jsonschema package "
with self.assertWarnsRegex(DeprecationWarning, message) as w:
from jsonschema import Validator
self.assertEqual(Validator, protocols.Validator)
self.assertEqual(w.filename, __file__)
def test_validators_validators(self):
"""
As of v4.0.0, accessing jsonschema.validators.validators is
deprecated.
"""
message = "Accessing jsonschema.validators.validators is deprecated"
with self.assertWarnsRegex(DeprecationWarning, message) as w:
value = validators.validators
self.assertEqual(value, validators._VALIDATORS)
self.assertEqual(w.filename, __file__)
def test_validators_meta_schemas(self):
"""
As of v4.0.0, accessing jsonschema.validators.meta_schemas is
deprecated.
"""
message = "Accessing jsonschema.validators.meta_schemas is deprecated"
with self.assertWarnsRegex(DeprecationWarning, message) as w:
value = validators.meta_schemas
self.assertEqual(value, validators._META_SCHEMAS)
self.assertEqual(w.filename, __file__)
def test_RefResolver_in_scope(self):
"""
As of v4.0.0, RefResolver.in_scope is deprecated.
"""
resolver = validators._RefResolver.from_schema({})
message = "jsonschema.RefResolver.in_scope is deprecated "
with self.assertWarnsRegex(DeprecationWarning, message) as w: # noqa: SIM117
with resolver.in_scope("foo"):
pass
self.assertEqual(w.filename, __file__)
def test_Validator_is_valid_two_arguments(self):
"""
As of v4.0.0, calling is_valid with two arguments (to provide a
different schema) is deprecated.
"""
validator = validators.Draft7Validator({})
message = "Passing a schema to Validator.is_valid is deprecated "
with self.assertWarnsRegex(DeprecationWarning, message) as w:
result = validator.is_valid("foo", {"type": "number"})
self.assertFalse(result)
self.assertEqual(w.filename, __file__)
def test_Validator_iter_errors_two_arguments(self):
"""
As of v4.0.0, calling iter_errors with two arguments (to provide a
different schema) is deprecated.
"""
validator = validators.Draft7Validator({})
message = "Passing a schema to Validator.iter_errors is deprecated "
with self.assertWarnsRegex(DeprecationWarning, message) as w:
error, = validator.iter_errors("foo", {"type": "number"})
self.assertEqual(error.validator, "type")
self.assertEqual(w.filename, __file__)
def test_Validator_resolver(self):
"""
As of v4.18.0, accessing Validator.resolver is deprecated.
"""
validator = validators.Draft7Validator({})
message = "Accessing Draft7Validator.resolver is "
with self.assertWarnsRegex(DeprecationWarning, message) as w:
self.assertIsInstance(validator.resolver, validators._RefResolver)
self.assertEqual(w.filename, __file__)
def test_RefResolver(self):
"""
As of v4.18.0, RefResolver is fully deprecated.
"""
message = "jsonschema.RefResolver is deprecated"
with self.assertWarnsRegex(DeprecationWarning, message) as w:
from jsonschema import RefResolver
self.assertEqual(w.filename, __file__)
with self.assertWarnsRegex(DeprecationWarning, message) as w:
from jsonschema.validators import RefResolver # noqa: F401
self.assertEqual(w.filename, __file__)
def test_RefResolutionError(self):
"""
As of v4.18.0, RefResolutionError is deprecated in favor of directly
catching errors from the referencing library.
"""
message = "jsonschema.exceptions.RefResolutionError is deprecated"
with self.assertWarnsRegex(DeprecationWarning, message) as w:
from jsonschema import RefResolutionError
self.assertEqual(RefResolutionError, exceptions._RefResolutionError)
self.assertEqual(w.filename, __file__)
with self.assertWarnsRegex(DeprecationWarning, message) as w:
from jsonschema.exceptions import RefResolutionError
self.assertEqual(RefResolutionError, exceptions._RefResolutionError)
self.assertEqual(w.filename, __file__)
def test_catching_Unresolvable_directly(self):
"""
This behavior is the intended behavior (i.e. it's not deprecated), but
given we do "tricksy" things in the iterim to wrap exceptions in a
multiple inheritance subclass, we need to be extra sure it works and
stays working.
"""
validator = validators.Draft202012Validator({"$ref": "urn:nothing"})
with self.assertRaises(referencing.exceptions.Unresolvable) as e:
validator.validate(12)
expected = referencing.exceptions.Unresolvable(ref="urn:nothing")
self.assertEqual(
(e.exception, str(e.exception)),
(expected, "Unresolvable: urn:nothing"),
)
def test_catching_Unresolvable_via_RefResolutionError(self):
"""
Until RefResolutionError is removed, it is still possible to catch
exceptions from reference resolution using it, even though they may
have been raised by referencing.
"""
with self.assertWarns(DeprecationWarning):
from jsonschema import RefResolutionError
validator = validators.Draft202012Validator({"$ref": "urn:nothing"})
with self.assertRaises(referencing.exceptions.Unresolvable) as u:
validator.validate(12)
with self.assertRaises(RefResolutionError) as e:
validator.validate(12)
self.assertEqual(
(e.exception, str(e.exception)),
(u.exception, "Unresolvable: urn:nothing"),
)
def test_WrappedReferencingError_hashability(self):
"""
Ensure the wrapped referencing errors are hashable when possible.
"""
with self.assertWarns(DeprecationWarning):
from jsonschema import RefResolutionError
validator = validators.Draft202012Validator({"$ref": "urn:nothing"})
with self.assertRaises(referencing.exceptions.Unresolvable) as u:
validator.validate(12)
with self.assertRaises(RefResolutionError) as e:
validator.validate(12)
self.assertIn(e.exception, {u.exception})
self.assertIn(u.exception, {e.exception})
def test_Validator_subclassing(self):
"""
As of v4.12.0, subclassing a validator class produces an explicit
deprecation warning.
This was never intended to be public API (and some comments over the
years in issues said so, but obviously that's not a great way to make
sure it's followed).
A future version will explicitly raise an error.
"""
message = "Subclassing validator classes is "
with self.assertWarnsRegex(DeprecationWarning, message) as w:
class Subclass(validators.Draft202012Validator):
pass
self.assertEqual(w.filename, __file__)
with self.assertWarnsRegex(DeprecationWarning, message) as w:
class AnotherSubclass(validators.create(meta_schema={})):
pass
def test_FormatChecker_cls_checks(self):
"""
As of v4.14.0, FormatChecker.cls_checks is deprecated without
replacement.
"""
self.addCleanup(FormatChecker.checkers.pop, "boom", None)
message = "FormatChecker.cls_checks "
with self.assertWarnsRegex(DeprecationWarning, message) as w:
FormatChecker.cls_checks("boom")
self.assertEqual(w.filename, __file__)
def test_draftN_format_checker(self):
"""
As of v4.16.0, accessing jsonschema.draftn_format_checker is deprecated
in favor of Validator.FORMAT_CHECKER.
"""
message = "Accessing jsonschema.draft202012_format_checker is "
with self.assertWarnsRegex(DeprecationWarning, message) as w:
from jsonschema import draft202012_format_checker
self.assertIs(
draft202012_format_checker,
validators.Draft202012Validator.FORMAT_CHECKER,
)
self.assertEqual(w.filename, __file__)
message = "Accessing jsonschema.draft201909_format_checker is "
with self.assertWarnsRegex(DeprecationWarning, message) as w:
from jsonschema import draft201909_format_checker
self.assertIs(
draft201909_format_checker,
validators.Draft201909Validator.FORMAT_CHECKER,
)
self.assertEqual(w.filename, __file__)
message = "Accessing jsonschema.draft7_format_checker is "
with self.assertWarnsRegex(DeprecationWarning, message) as w:
from jsonschema import draft7_format_checker
self.assertIs(
draft7_format_checker,
validators.Draft7Validator.FORMAT_CHECKER,
)
self.assertEqual(w.filename, __file__)
message = "Accessing jsonschema.draft6_format_checker is "
with self.assertWarnsRegex(DeprecationWarning, message) as w:
from jsonschema import draft6_format_checker
self.assertIs(
draft6_format_checker,
validators.Draft6Validator.FORMAT_CHECKER,
)
self.assertEqual(w.filename, __file__)
message = "Accessing jsonschema.draft4_format_checker is "
with self.assertWarnsRegex(DeprecationWarning, message) as w:
from jsonschema import draft4_format_checker
self.assertIs(
draft4_format_checker,
validators.Draft4Validator.FORMAT_CHECKER,
)
self.assertEqual(w.filename, __file__)
message = "Accessing jsonschema.draft3_format_checker is "
with self.assertWarnsRegex(DeprecationWarning, message) as w:
from jsonschema import draft3_format_checker
self.assertIs(
draft3_format_checker,
validators.Draft3Validator.FORMAT_CHECKER,
)
self.assertEqual(w.filename, __file__)
with self.assertRaises(ImportError):
from jsonschema import draft1234_format_checker # noqa: F401
def test_import_cli(self):
"""
As of v4.17.0, importing jsonschema.cli is deprecated.
"""
message = "The jsonschema CLI is deprecated and will be removed "
with self.assertWarnsRegex(DeprecationWarning, message) as w:
import jsonschema.cli
importlib.reload(jsonschema.cli)
self.assertEqual(w.filename, importlib.__file__)
def test_cli(self):
"""
As of v4.17.0, the jsonschema CLI is deprecated.
"""
process = subprocess.run(
[sys.executable, "-m", "jsonschema"],
capture_output=True,
check=True,
)
self.assertIn(b"The jsonschema CLI is deprecated ", process.stderr)
def test_automatic_remote_retrieval(self):
"""
Automatic retrieval of remote references is deprecated as of v4.18.0.
"""
ref = "http://bar#/$defs/baz"
schema = {"$defs": {"baz": {"type": "integer"}}}
if "requests" in sys.modules: # pragma: no cover
self.addCleanup(
sys.modules.__setitem__, "requests", sys.modules["requests"],
)
sys.modules["requests"] = None
@contextmanager
def fake_urlopen(request):
self.assertIsInstance(request, urllib.request.Request)
self.assertEqual(request.full_url, "http://bar")
# Ha ha urllib.request.Request "normalizes" header names and
# Request.get_header does not also normalize them...
(header, value), = request.header_items()
self.assertEqual(header.lower(), "user-agent")
self.assertEqual(
value, "python-jsonschema (deprecated $ref resolution)",
)
yield BytesIO(json.dumps(schema).encode("utf8"))
validator = validators.Draft202012Validator({"$ref": ref})
message = "Automatically retrieving remote references "
patch = mock.patch.object(urllib.request, "urlopen", new=fake_urlopen)
with patch, self.assertWarnsRegex(DeprecationWarning, message):
self.assertEqual(
(validator.is_valid({}), validator.is_valid(37)),
(False, True),
)
|
class TestDeprecations(TestCase):
def test_version(self):
'''
As of v4.0.0, __version__ is deprecated in favor of importlib.metadata.
'''
pass
def test_validators_ErrorTree(self):
'''
As of v4.0.0, importing ErrorTree from jsonschema.validators is
deprecated in favor of doing so from jsonschema.exceptions.
'''
pass
def test_import_ErrorTree(self):
'''
As of v4.18.0, importing ErrorTree from the package root is
deprecated in favor of doing so from jsonschema.exceptions.
'''
pass
def test_ErrorTree_setitem(self):
'''
As of v4.20.0, setting items on an ErrorTree is deprecated.
'''
pass
def test_import_FormatError(self):
'''
As of v4.18.0, importing FormatError from the package root is
deprecated in favor of doing so from jsonschema.exceptions.
'''
pass
def test_import_Validator(self):
'''
As of v4.19.0, importing Validator from the package root is
deprecated in favor of doing so from jsonschema.protocols.
'''
pass
def test_validators_validators(self):
'''
As of v4.0.0, accessing jsonschema.validators.validators is
deprecated.
'''
pass
def test_validators_meta_schemas(self):
'''
As of v4.0.0, accessing jsonschema.validators.meta_schemas is
deprecated.
'''
pass
def test_RefResolver_in_scope(self):
'''
As of v4.0.0, RefResolver.in_scope is deprecated.
'''
pass
def test_Validator_is_valid_two_arguments(self):
'''
As of v4.0.0, calling is_valid with two arguments (to provide a
different schema) is deprecated.
'''
pass
def test_Validator_iter_errors_two_arguments(self):
'''
As of v4.0.0, calling iter_errors with two arguments (to provide a
different schema) is deprecated.
'''
pass
def test_Validator_resolver(self):
'''
As of v4.18.0, accessing Validator.resolver is deprecated.
'''
pass
def test_RefResolver_in_scope(self):
'''
As of v4.18.0, RefResolver is fully deprecated.
'''
pass
def test_RefResolutionError(self):
'''
As of v4.18.0, RefResolutionError is deprecated in favor of directly
catching errors from the referencing library.
'''
pass
def test_catching_Unresolvable_directly(self):
'''
This behavior is the intended behavior (i.e. it's not deprecated), but
given we do "tricksy" things in the iterim to wrap exceptions in a
multiple inheritance subclass, we need to be extra sure it works and
stays working.
'''
pass
def test_catching_Unresolvable_via_RefResolutionError(self):
'''
Until RefResolutionError is removed, it is still possible to catch
exceptions from reference resolution using it, even though they may
have been raised by referencing.
'''
pass
def test_WrappedReferencingError_hashability(self):
'''
Ensure the wrapped referencing errors are hashable when possible.
'''
pass
def test_Validator_subclassing(self):
'''
As of v4.12.0, subclassing a validator class produces an explicit
deprecation warning.
This was never intended to be public API (and some comments over the
years in issues said so, but obviously that's not a great way to make
sure it's followed).
A future version will explicitly raise an error.
'''
pass
class Subclass(validators.Draft202012Validator):
class AnotherSubclass(validators.create(meta_schema={})):
def test_FormatChecker_cls_checks(self):
'''
As of v4.14.0, FormatChecker.cls_checks is deprecated without
replacement.
'''
pass
def test_draftN_format_checker(self):
'''
As of v4.16.0, accessing jsonschema.draftn_format_checker is deprecated
in favor of Validator.FORMAT_CHECKER.
'''
pass
def test_import_cli(self):
'''
As of v4.17.0, importing jsonschema.cli is deprecated.
'''
pass
def test_cli(self):
'''
As of v4.17.0, the jsonschema CLI is deprecated.
'''
pass
def test_automatic_remote_retrieval(self):
'''
Automatic retrieval of remote references is deprecated as of v4.18.0.
'''
pass
@contextmanager
def fake_urlopen(request):
pass
| 28 | 23 | 17 | 3 | 10 | 4 | 1 | 0.42 | 1 | 6 | 0 | 0 | 23 | 0 | 23 | 95 | 418 | 93 | 233 | 110 | 186 | 97 | 197 | 86 | 151 | 2 | 2 | 2 | 25 |
140,234 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.TestDraft3Validator
|
class TestDraft3Validator(AntiDraft6LeakMixin, ValidatorTestMixin, TestCase):
Validator = validators.Draft3Validator
valid: tuple[dict, dict] = ({}, {})
invalid = {"type": "integer"}, "foo"
def test_any_type_is_valid_for_type_any(self):
validator = self.Validator({"type": "any"})
validator.validate(object())
def test_any_type_is_redefinable(self):
"""
Sigh, because why not.
"""
Crazy = validators.extend(
self.Validator,
type_checker=self.Validator.TYPE_CHECKER.redefine(
"any", lambda checker, thing: isinstance(thing, int),
),
)
validator = Crazy({"type": "any"})
validator.validate(12)
with self.assertRaises(exceptions.ValidationError):
validator.validate("foo")
def test_is_type_is_true_for_any_type(self):
self.assertTrue(self.Validator({"type": "any"}).is_valid(object()))
def test_is_type_does_not_evade_bool_if_it_is_being_tested(self):
self.assertTrue(self.Validator({}).is_type(True, "boolean"))
self.assertTrue(self.Validator({"type": "any"}).is_valid(True))
|
class TestDraft3Validator(AntiDraft6LeakMixin, ValidatorTestMixin, TestCase):
def test_any_type_is_valid_for_type_any(self):
pass
def test_any_type_is_redefinable(self):
'''
Sigh, because why not.
'''
pass
def test_is_type_is_true_for_any_type(self):
pass
def test_is_type_does_not_evade_bool_if_it_is_being_tested(self):
pass
| 5 | 1 | 6 | 0 | 5 | 1 | 1 | 0.13 | 3 | 1 | 0 | 0 | 4 | 0 | 4 | 105 | 30 | 4 | 23 | 11 | 18 | 3 | 18 | 11 | 13 | 1 | 2 | 1 | 4 |
140,235 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.ReallyFakeRequests
|
class ReallyFakeRequests:
_responses: dict[str, Any]
def get(self, url):
response = self._responses.get(url)
if url is None: # pragma: no cover
raise ValueError("Unknown URL: " + repr(url))
return _ReallyFakeJSONResponse(json.dumps(response))
|
class ReallyFakeRequests:
def get(self, url):
pass
| 2 | 0 | 5 | 0 | 5 | 1 | 2 | 0.14 | 0 | 2 | 1 | 0 | 1 | 0 | 1 | 1 | 9 | 2 | 7 | 3 | 5 | 1 | 7 | 3 | 5 | 2 | 0 | 1 | 2 |
140,236 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.TestCreateAndExtend
|
class TestCreateAndExtend(TestCase):
def setUp(self):
self.addCleanup(
self.assertEqual,
validators._META_SCHEMAS,
dict(validators._META_SCHEMAS),
)
self.addCleanup(
self.assertEqual,
validators._VALIDATORS,
dict(validators._VALIDATORS),
)
self.meta_schema = {"$id": "some://meta/schema"}
self.validators = {"fail": fail}
self.type_checker = TypeChecker()
self.Validator = validators.create(
meta_schema=self.meta_schema,
validators=self.validators,
type_checker=self.type_checker,
)
def test_attrs(self):
self.assertEqual(
(
self.Validator.VALIDATORS,
self.Validator.META_SCHEMA,
self.Validator.TYPE_CHECKER,
), (
self.validators,
self.meta_schema,
self.type_checker,
),
)
def test_init(self):
schema = {"fail": []}
self.assertEqual(self.Validator(schema).schema, schema)
def test_iter_errors_successful(self):
schema = {"fail": []}
validator = self.Validator(schema)
errors = list(validator.iter_errors("hello"))
self.assertEqual(errors, [])
def test_iter_errors_one_error(self):
schema = {"fail": [{"message": "Whoops!"}]}
validator = self.Validator(schema)
expected_error = exceptions.ValidationError(
"Whoops!",
instance="goodbye",
schema=schema,
validator="fail",
validator_value=[{"message": "Whoops!"}],
schema_path=deque(["fail"]),
)
errors = list(validator.iter_errors("goodbye"))
self.assertEqual(len(errors), 1)
self.assertEqual(errors[0]._contents(), expected_error._contents())
def test_iter_errors_multiple_errors(self):
schema = {
"fail": [
{"message": "First"},
{"message": "Second!", "validator": "asdf"},
{"message": "Third"},
],
}
validator = self.Validator(schema)
errors = list(validator.iter_errors("goodbye"))
self.assertEqual(len(errors), 3)
def test_if_a_version_is_provided_it_is_registered(self):
Validator = validators.create(
meta_schema={"$id": "something"},
version="my version",
)
self.addCleanup(validators._META_SCHEMAS.pop, "something")
self.addCleanup(validators._VALIDATORS.pop, "my version")
self.assertEqual(Validator.__name__, "MyVersionValidator")
self.assertEqual(Validator.__qualname__, "MyVersionValidator")
def test_repr(self):
Validator = validators.create(
meta_schema={"$id": "something"},
version="my version",
)
self.addCleanup(validators._META_SCHEMAS.pop, "something")
self.addCleanup(validators._VALIDATORS.pop, "my version")
self.assertEqual(
repr(Validator({})),
"MyVersionValidator(schema={}, format_checker=None)",
)
def test_long_repr(self):
Validator = validators.create(
meta_schema={"$id": "something"},
version="my version",
)
self.addCleanup(validators._META_SCHEMAS.pop, "something")
self.addCleanup(validators._VALIDATORS.pop, "my version")
self.assertEqual(
repr(Validator({"a": list(range(1000))})), (
"MyVersionValidator(schema={'a': [0, 1, 2, 3, 4, 5, ...]}, "
"format_checker=None)"
),
)
def test_repr_no_version(self):
Validator = validators.create(meta_schema={})
self.assertEqual(
repr(Validator({})),
"Validator(schema={}, format_checker=None)",
)
def test_dashes_are_stripped_from_validator_names(self):
Validator = validators.create(
meta_schema={"$id": "something"},
version="foo-bar",
)
self.addCleanup(validators._META_SCHEMAS.pop, "something")
self.addCleanup(validators._VALIDATORS.pop, "foo-bar")
self.assertEqual(Validator.__qualname__, "FooBarValidator")
def test_if_a_version_is_not_provided_it_is_not_registered(self):
original = dict(validators._META_SCHEMAS)
validators.create(meta_schema={"id": "id"})
self.assertEqual(validators._META_SCHEMAS, original)
def test_validates_registers_meta_schema_id(self):
meta_schema_key = "meta schema id"
my_meta_schema = {"id": meta_schema_key}
validators.create(
meta_schema=my_meta_schema,
version="my version",
id_of=lambda s: s.get("id", ""),
)
self.addCleanup(validators._META_SCHEMAS.pop, meta_schema_key)
self.addCleanup(validators._VALIDATORS.pop, "my version")
self.assertIn(meta_schema_key, validators._META_SCHEMAS)
def test_validates_registers_meta_schema_draft6_id(self):
meta_schema_key = "meta schema $id"
my_meta_schema = {"$id": meta_schema_key}
validators.create(
meta_schema=my_meta_schema,
version="my version",
)
self.addCleanup(validators._META_SCHEMAS.pop, meta_schema_key)
self.addCleanup(validators._VALIDATORS.pop, "my version")
self.assertIn(meta_schema_key, validators._META_SCHEMAS)
def test_create_default_types(self):
Validator = validators.create(meta_schema={}, validators=())
self.assertTrue(
all(
Validator({}).is_type(instance=instance, type=type)
for type, instance in [
("array", []),
("boolean", True),
("integer", 12),
("null", None),
("number", 12.0),
("object", {}),
("string", "foo"),
]
),
)
def test_check_schema_with_different_metaschema(self):
"""
One can create a validator class whose metaschema uses a different
dialect than itself.
"""
NoEmptySchemasValidator = validators.create(
meta_schema={
"$schema": validators.Draft202012Validator.META_SCHEMA["$id"],
"not": {"const": {}},
},
)
NoEmptySchemasValidator.check_schema({"foo": "bar"})
with self.assertRaises(exceptions.SchemaError):
NoEmptySchemasValidator.check_schema({})
NoEmptySchemasValidator({"foo": "bar"}).validate("foo")
def test_check_schema_with_different_metaschema_defaults_to_self(self):
"""
A validator whose metaschema doesn't declare $schema defaults to its
own validation behavior, not the latest "normal" specification.
"""
NoEmptySchemasValidator = validators.create(
meta_schema={"fail": [{"message": "Meta schema whoops!"}]},
validators={"fail": fail},
)
with self.assertRaises(exceptions.SchemaError):
NoEmptySchemasValidator.check_schema({})
def test_extend(self):
original = dict(self.Validator.VALIDATORS)
new = object()
Extended = validators.extend(
self.Validator,
validators={"new": new},
)
self.assertEqual(
(
Extended.VALIDATORS,
Extended.META_SCHEMA,
Extended.TYPE_CHECKER,
self.Validator.VALIDATORS,
), (
dict(original, new=new),
self.Validator.META_SCHEMA,
self.Validator.TYPE_CHECKER,
original,
),
)
def test_extend_idof(self):
"""
Extending a validator preserves its notion of schema IDs.
"""
def id_of(schema):
return schema.get("__test__", self.Validator.ID_OF(schema))
correct_id = "the://correct/id/"
meta_schema = {
"$id": "the://wrong/id/",
"__test__": correct_id,
}
Original = validators.create(
meta_schema=meta_schema,
validators=self.validators,
type_checker=self.type_checker,
id_of=id_of,
)
self.assertEqual(Original.ID_OF(Original.META_SCHEMA), correct_id)
Derived = validators.extend(Original)
self.assertEqual(Derived.ID_OF(Derived.META_SCHEMA), correct_id)
def test_extend_applicable_validators(self):
"""
Extending a validator preserves its notion of applicable validators.
"""
schema = {
"$defs": {"test": {"type": "number"}},
"$ref": "#/$defs/test",
"maximum": 1,
}
draft4 = validators.Draft4Validator(schema)
self.assertTrue(draft4.is_valid(37)) # as $ref ignores siblings
Derived = validators.extend(validators.Draft4Validator)
self.assertTrue(Derived(schema).is_valid(37))
|
class TestCreateAndExtend(TestCase):
def setUp(self):
pass
def test_attrs(self):
pass
def test_init(self):
pass
def test_iter_errors_successful(self):
pass
def test_iter_errors_one_error(self):
pass
def test_iter_errors_multiple_errors(self):
pass
def test_if_a_version_is_provided_it_is_registered(self):
pass
def test_repr(self):
pass
def test_long_repr(self):
pass
def test_repr_no_version(self):
pass
def test_dashes_are_stripped_from_validator_names(self):
pass
def test_if_a_version_is_not_provided_it_is_not_registered(self):
pass
def test_validates_registers_meta_schema_id(self):
pass
def test_validates_registers_meta_schema_draft6_id(self):
pass
def test_create_default_types(self):
pass
def test_check_schema_with_different_metaschema(self):
'''
One can create a validator class whose metaschema uses a different
dialect than itself.
'''
pass
def test_check_schema_with_different_metaschema_defaults_to_self(self):
'''
A validator whose metaschema doesn't declare $schema defaults to its
own validation behavior, not the latest "normal" specification.
'''
pass
def test_extend(self):
pass
def test_extend_idof(self):
'''
Extending a validator preserves its notion of schema IDs.
'''
pass
def id_of(schema):
pass
def test_extend_applicable_validators(self):
'''
Extending a validator preserves its notion of applicable validators.
'''
pass
| 22 | 4 | 12 | 1 | 10 | 1 | 1 | 0.07 | 1 | 5 | 0 | 0 | 20 | 4 | 20 | 92 | 269 | 37 | 218 | 61 | 196 | 16 | 105 | 60 | 83 | 1 | 2 | 1 | 21 |
140,237 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.TestDraft201909Validator
|
class TestDraft201909Validator(ValidatorTestMixin, TestCase):
Validator = validators.Draft201909Validator
valid: tuple[dict, dict] = ({}, {})
invalid = {"type": "integer"}, "foo"
|
class TestDraft201909Validator(ValidatorTestMixin, TestCase):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 97 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
140,238 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/test_validators.py
|
jsonschema.tests.test_validators.TestDraft202012Validator
|
class TestDraft202012Validator(ValidatorTestMixin, TestCase):
Validator = validators.Draft202012Validator
valid: tuple[dict, dict] = ({}, {})
invalid = {"type": "integer"}, "foo"
|
class TestDraft202012Validator(ValidatorTestMixin, TestCase):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 97 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
140,239 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/exceptions.py
|
jsonschema.exceptions.UnknownType
|
class UnknownType(Exception):
"""
A validator was asked to validate an instance against an unknown type.
"""
def __init__(self, type, instance, schema):
self.type = type
self.instance = instance
self.schema = schema
def __str__(self):
prefix = 16 * " "
return dedent(
f"""\
Unknown type {self.type!r} for validator with schema:
{_pretty(self.schema, prefix=prefix)}
While checking instance:
{_pretty(self.instance, prefix=prefix)}
""".rstrip(),
)
|
class UnknownType(Exception):
'''
A validator was asked to validate an instance against an unknown type.
'''
def __init__(self, type, instance, schema):
pass
def __str__(self):
pass
| 3 | 1 | 8 | 1 | 7 | 0 | 1 | 0.2 | 1 | 0 | 0 | 0 | 2 | 3 | 2 | 12 | 22 | 4 | 15 | 7 | 12 | 3 | 8 | 7 | 5 | 1 | 3 | 0 | 2 |
140,240 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/exceptions.py
|
jsonschema.exceptions.ValidationError
|
class ValidationError(_Error):
"""
An instance was invalid under a provided schema.
"""
_word_for_schema_in_error_message = "schema"
_word_for_instance_in_error_message = "instance"
|
class ValidationError(_Error):
'''
An instance was invalid under a provided schema.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 20 | 7 | 1 | 3 | 3 | 2 | 3 | 3 | 3 | 2 | 0 | 4 | 0 | 0 |
140,241 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/exceptions.py
|
jsonschema.exceptions.UndefinedTypeCheck
|
class UndefinedTypeCheck(Exception):
"""
A type checker was asked to check a type it did not have registered.
"""
def __init__(self, type: str) -> None:
self.type = type
def __str__(self) -> str:
return f"Type {self.type!r} is unknown to this type checker"
|
class UndefinedTypeCheck(Exception):
'''
A type checker was asked to check a type it did not have registered.
'''
def __init__(self, type: str) -> None:
pass
def __str__(self) -> str:
pass
| 3 | 1 | 2 | 0 | 2 | 0 | 1 | 0.6 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 12 | 10 | 2 | 5 | 4 | 2 | 3 | 5 | 4 | 2 | 1 | 3 | 0 | 2 |
140,242 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/exceptions.py
|
jsonschema.exceptions._WrappedReferencingError
|
class _WrappedReferencingError(_RefResolutionError, _Unresolvable): # pragma: no cover -- partially uncovered but to be removed # noqa: E501
def __init__(self, cause: _Unresolvable):
object.__setattr__(self, "_wrapped", cause)
def __eq__(self, other):
if other.__class__ is self.__class__:
return self._wrapped == other._wrapped
elif other.__class__ is self._wrapped.__class__:
return self._wrapped == other
return NotImplemented
def __getattr__(self, attr):
return getattr(self._wrapped, attr)
def __hash__(self):
return hash(self._wrapped)
def __repr__(self):
return f"<WrappedReferencingError {self._wrapped!r}>"
def __str__(self):
return f"{self._wrapped.__class__.__name__}: {self._wrapped}"
|
class _WrappedReferencingError(_RefResolutionError, _Unresolvable):
def __init__(self, cause: _Unresolvable):
pass
def __eq__(self, other):
pass
def __getattr__(self, attr):
pass
def __hash__(self):
pass
def __repr__(self):
pass
def __str__(self):
pass
| 7 | 0 | 3 | 0 | 3 | 0 | 1 | 0.06 | 2 | 0 | 0 | 0 | 6 | 0 | 6 | 20 | 22 | 5 | 17 | 7 | 10 | 1 | 16 | 7 | 9 | 3 | 4 | 1 | 8 |
140,243 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/protocols.py
|
jsonschema.protocols.Validator
|
class Validator(Protocol):
"""
The protocol to which all validator classes adhere.
Arguments:
schema:
The schema that the validator object will validate with.
It is assumed to be valid, and providing
an invalid schema can lead to undefined behavior. See
`Validator.check_schema` to validate a schema first.
registry:
a schema registry that will be used for looking up JSON references
resolver:
a resolver that will be used to resolve :kw:`$ref`
properties (JSON references). If unprovided, one will be created.
.. deprecated:: v4.18.0
`RefResolver <_RefResolver>` has been deprecated in favor of
`referencing`, and with it, this argument.
format_checker:
if provided, a checker which will be used to assert about
:kw:`format` properties present in the schema. If unprovided,
*no* format validation is done, and the presence of format
within schemas is strictly informational. Certain formats
require additional packages to be installed in order to assert
against instances. Ensure you've installed `jsonschema` with
its `extra (optional) dependencies <index:extras>` when
invoking ``pip``.
.. deprecated:: v4.12.0
Subclassing validator classes now explicitly warns this is not part of
their public API.
"""
#: An object representing the validator's meta schema (the schema that
#: describes valid schemas in the given version).
META_SCHEMA: ClassVar[Mapping]
#: A mapping of validation keywords (`str`\s) to functions that
#: validate the keyword with that name. For more information see
#: `creating-validators`.
VALIDATORS: ClassVar[Mapping]
#: A `jsonschema.TypeChecker` that will be used when validating
#: :kw:`type` keywords in JSON schemas.
TYPE_CHECKER: ClassVar[jsonschema.TypeChecker]
#: A `jsonschema.FormatChecker` that will be used when validating
#: :kw:`format` keywords in JSON schemas.
FORMAT_CHECKER: ClassVar[jsonschema.FormatChecker]
#: A function which given a schema returns its ID.
ID_OF: _typing.id_of
#: The schema that will be used to validate instances
schema: Mapping | bool
def __init__(
self,
schema: Mapping | bool,
registry: referencing.jsonschema.SchemaRegistry,
format_checker: jsonschema.FormatChecker | None = None,
) -> None:
...
@classmethod
def check_schema(cls, schema: Mapping | bool) -> None:
"""
Validate the given schema against the validator's `META_SCHEMA`.
Raises:
`jsonschema.exceptions.SchemaError`:
if the schema is invalid
"""
def is_type(self, instance: Any, type: str) -> bool:
"""
Check if the instance is of the given (JSON Schema) type.
Arguments:
instance:
the value to check
type:
the name of a known (JSON Schema) type
Returns:
whether the instance is of the given type
Raises:
`jsonschema.exceptions.UnknownType`:
if ``type`` is not a known type
"""
def is_valid(self, instance: Any) -> bool:
"""
Check if the instance is valid under the current `schema`.
Returns:
whether the instance is valid or not
>>> schema = {"maxItems" : 2}
>>> Draft202012Validator(schema).is_valid([2, 3, 4])
False
"""
def iter_errors(self, instance: Any) -> Iterable[ValidationError]:
r"""
Lazily yield each of the validation errors in the given instance.
>>> schema = {
... "type" : "array",
... "items" : {"enum" : [1, 2, 3]},
... "maxItems" : 2,
... }
>>> v = Draft202012Validator(schema)
>>> for error in sorted(v.iter_errors([2, 3, 4]), key=str):
... print(error.message)
4 is not one of [1, 2, 3]
[2, 3, 4] is too long
.. deprecated:: v4.0.0
Calling this function with a second schema argument is deprecated.
Use `Validator.evolve` instead.
"""
def validate(self, instance: Any) -> None:
"""
Check if the instance is valid under the current `schema`.
Raises:
`jsonschema.exceptions.ValidationError`:
if the instance is invalid
>>> schema = {"maxItems" : 2}
>>> Draft202012Validator(schema).validate([2, 3, 4])
Traceback (most recent call last):
...
ValidationError: [2, 3, 4] is too long
"""
def evolve(self, **kwargs) -> Validator:
"""
Create a new validator like this one, but with given changes.
Preserves all other attributes, so can be used to e.g. create a
validator with a different schema but with the same :kw:`$ref`
resolution behavior.
>>> validator = Draft202012Validator({})
>>> validator.evolve(schema={"type": "number"})
Draft202012Validator(schema={'type': 'number'}, format_checker=None)
The returned object satisfies the validator protocol, but may not
be of the same concrete class! In particular this occurs
when a :kw:`$ref` occurs to a schema with a different
:kw:`$schema` than this one (i.e. for a different draft).
>>> validator.evolve(
... schema={"$schema": Draft7Validator.META_SCHEMA["$id"]}
... )
Draft7Validator(schema=..., format_checker=None)
"""
|
class Validator(Protocol):
'''
The protocol to which all validator classes adhere.
Arguments:
schema:
The schema that the validator object will validate with.
It is assumed to be valid, and providing
an invalid schema can lead to undefined behavior. See
`Validator.check_schema` to validate a schema first.
registry:
a schema registry that will be used for looking up JSON references
resolver:
a resolver that will be used to resolve :kw:`$ref`
properties (JSON references). If unprovided, one will be created.
.. deprecated:: v4.18.0
`RefResolver <_RefResolver>` has been deprecated in favor of
`referencing`, and with it, this argument.
format_checker:
if provided, a checker which will be used to assert about
:kw:`format` properties present in the schema. If unprovided,
*no* format validation is done, and the presence of format
within schemas is strictly informational. Certain formats
require additional packages to be installed in order to assert
against instances. Ensure you've installed `jsonschema` with
its `extra (optional) dependencies <index:extras>` when
invoking ``pip``.
.. deprecated:: v4.12.0
Subclassing validator classes now explicitly warns this is not part of
their public API.
'''
def __init__(
self,
schema: Mapping | bool,
registry: referencing.jsonschema.SchemaRegistry,
format_checker: jsonschema.FormatChecker | None = None,
) -> None:
pass
@classmethod
def check_schema(cls, schema: Mapping | bool) -> None:
'''
Validate the given schema against the validator's `META_SCHEMA`.
Raises:
`jsonschema.exceptions.SchemaError`:
if the schema is invalid
'''
pass
def is_type(self, instance: Any, type: str) -> bool:
'''
Check if the instance is of the given (JSON Schema) type.
Arguments:
instance:
the value to check
type:
the name of a known (JSON Schema) type
Returns:
whether the instance is of the given type
Raises:
`jsonschema.exceptions.UnknownType`:
if ``type`` is not a known type
'''
pass
def is_valid(self, instance: Any) -> bool:
'''
Check if the instance is valid under the current `schema`.
Returns:
whether the instance is valid or not
>>> schema = {"maxItems" : 2}
>>> Draft202012Validator(schema).is_valid([2, 3, 4])
False
'''
pass
def iter_errors(self, instance: Any) -> Iterable[ValidationError]:
'''
Lazily yield each of the validation errors in the given instance.
>>> schema = {
... "type" : "array",
... "items" : {"enum" : [1, 2, 3]},
... "maxItems" : 2,
... }
>>> v = Draft202012Validator(schema)
>>> for error in sorted(v.iter_errors([2, 3, 4]), key=str):
... print(error.message)
4 is not one of [1, 2, 3]
[2, 3, 4] is too long
.. deprecated:: v4.0.0
Calling this function with a second schema argument is deprecated.
Use `Validator.evolve` instead.
'''
pass
def validate(self, instance: Any) -> None:
'''
Check if the instance is valid under the current `schema`.
Raises:
`jsonschema.exceptions.ValidationError`:
if the instance is invalid
>>> schema = {"maxItems" : 2}
>>> Draft202012Validator(schema).validate([2, 3, 4])
Traceback (most recent call last):
...
ValidationError: [2, 3, 4] is too long
'''
pass
def evolve(self, **kwargs) -> Validator:
'''
Create a new validator like this one, but with given changes.
Preserves all other attributes, so can be used to e.g. create a
validator with a different schema but with the same :kw:`$ref`
resolution behavior.
>>> validator = Draft202012Validator({})
>>> validator.evolve(schema={"type": "number"})
Draft202012Validator(schema={'type': 'number'}, format_checker=None)
The returned object satisfies the validator protocol, but may not
be of the same concrete class! In particular this occurs
when a :kw:`$ref` occurs to a schema with a different
:kw:`$schema` than this one (i.e. for a different draft).
>>> validator.evolve(
... schema={"$schema": Draft7Validator.META_SCHEMA["$id"]}
... )
Draft7Validator(schema=..., format_checker=None)
'''
pass
| 9 | 7 | 16 | 4 | 2 | 10 | 1 | 5.29 | 1 | 7 | 0 | 0 | 6 | 0 | 7 | 31 | 190 | 58 | 21 | 14 | 7 | 111 | 15 | 8 | 7 | 1 | 5 | 0 | 7 |
140,244 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/_suite.py
|
jsonschema.tests._suite.Suite
|
class Suite:
_root: Path = field(factory=_find_suite)
def benchmark(self, runner: pyperf.Runner): # pragma: no cover
for name, Validator in _VALIDATORS.items():
self.version(name=name).benchmark(
runner=runner,
Validator=Validator,
)
def version(self, name) -> Version:
Validator = _VALIDATORS[name]
uri: str = Validator.ID_OF(Validator.META_SCHEMA) # type: ignore[assignment]
specification = referencing.jsonschema.specification_with(uri)
registry = Registry().with_contents(
remotes_in(root=self._root / "remotes", name=name, uri=uri),
default_specification=specification,
)
return Version(
name=name,
path=self._root / "tests" / name,
remotes=registry,
)
|
class Suite:
def benchmark(self, runner: pyperf.Runner):
pass
def version(self, name) -> Version:
pass
| 3 | 0 | 10 | 1 | 10 | 1 | 2 | 0.1 | 0 | 3 | 1 | 0 | 2 | 0 | 2 | 2 | 26 | 5 | 21 | 9 | 18 | 2 | 11 | 9 | 8 | 2 | 0 | 1 | 3 |
140,245 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/tests/_suite.py
|
jsonschema.tests._suite.Version
|
class Version:
_path: Path
_remotes: referencing.jsonschema.SchemaRegistry
name: str
def benchmark(self, **kwargs): # pragma: no cover
for case in self.cases():
case.benchmark(**kwargs)
def cases(self) -> Iterable[_Case]:
return self._cases_in(paths=self._path.glob("*.json"))
def format_cases(self) -> Iterable[_Case]:
return self._cases_in(paths=self._path.glob("optional/format/*.json"))
def optional_cases_of(self, name: str) -> Iterable[_Case]:
return self._cases_in(paths=[self._path / "optional" / f"{name}.json"])
def to_unittest_testcase(self, *groups, **kwargs):
name = kwargs.pop("name", "Test" + self.name.title().replace("-", ""))
methods = {
method.__name__: method
for method in (
test.to_unittest_method(**kwargs)
for group in groups
for case in group
for test in case.tests
)
}
cls = type(name, (unittest.TestCase,), methods)
# We're doing crazy things, so if they go wrong, like a function
# behaving differently on some other interpreter, just make them
# not happen.
with suppress(Exception):
cls.__module__ = _someone_save_us_the_module_of_the_caller()
return cls
def _cases_in(self, paths: Iterable[Path]) -> Iterable[_Case]:
for path in paths:
for case in json.loads(path.read_text(encoding="utf-8")):
yield _Case.from_dict(
case,
version=self,
subject=path.stem,
remotes=self._remotes,
)
|
class Version:
def benchmark(self, **kwargs):
pass
def cases(self) -> Iterable[_Case]:
pass
def format_cases(self) -> Iterable[_Case]:
pass
def optional_cases_of(self, name: str) -> Iterable[_Case]:
pass
def to_unittest_testcase(self, *groups, **kwargs):
pass
def _cases_in(self, paths: Iterable[Path]) -> Iterable[_Case]:
pass
| 7 | 0 | 6 | 0 | 6 | 1 | 2 | 0.11 | 0 | 8 | 1 | 0 | 6 | 0 | 6 | 6 | 50 | 10 | 37 | 15 | 30 | 4 | 24 | 13 | 17 | 3 | 0 | 2 | 9 |
140,246 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/exceptions.py
|
jsonschema.exceptions.SchemaError
|
class SchemaError(_Error):
"""
A schema was invalid under its corresponding metaschema.
"""
_word_for_schema_in_error_message = "metaschema"
_word_for_instance_in_error_message = "schema"
|
class SchemaError(_Error):
'''
A schema was invalid under its corresponding metaschema.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 20 | 7 | 1 | 3 | 3 | 2 | 3 | 3 | 3 | 2 | 0 | 4 | 0 | 0 |
140,247 |
Julian/jsonschema
|
Julian_jsonschema/jsonschema/exceptions.py
|
jsonschema.exceptions.FormatError
|
class FormatError(Exception):
"""
Validating a format failed.
"""
def __init__(self, message, cause=None):
super().__init__(message, cause)
self.message = message
self.cause = self.__cause__ = cause
def __str__(self):
return self.message
|
class FormatError(Exception):
'''
Validating a format failed.
'''
def __init__(self, message, cause=None):
pass
def __str__(self):
pass
| 3 | 1 | 3 | 0 | 3 | 0 | 1 | 0.43 | 1 | 1 | 0 | 0 | 2 | 3 | 2 | 12 | 12 | 2 | 7 | 5 | 4 | 3 | 7 | 5 | 4 | 1 | 3 | 0 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.