From 9d8c46a5bab7f8d5f41cd6bffe95392929c3cfc0 Mon Sep 17 00:00:00 2001 From: Rex Ledesma Date: Sun, 11 May 2025 10:45:35 -0400 Subject: [PATCH 1/2] chore: add `ruff format --check` --- .github/workflows/ci.yaml | 6 +- examples/atexit_example.py | 2 + examples/call_between_rust_and_python.py | 3 + examples/freeze/freeze.py | 1 - extra_tests/benchmarks/perf_fib.py | 9 +- extra_tests/custom_text_test_runner.py | 697 ++++++++---- extra_tests/jsontests.py | 11 +- extra_tests/snippets/3.1.3.4.py | 5 +- extra_tests/snippets/3.1.3.5.py | 4 +- extra_tests/snippets/builtin_abs.py | 1 - extra_tests/snippets/builtin_ascii.py | 10 +- extra_tests/snippets/builtin_bin.py | 24 +- extra_tests/snippets/builtin_bool.py | 31 +- extra_tests/snippets/builtin_bytearray.py | 223 ++-- extra_tests/snippets/builtin_bytes.py | 55 +- extra_tests/snippets/builtin_callable.py | 31 +- extra_tests/snippets/builtin_chr.py | 6 +- extra_tests/snippets/builtin_dict.py | 219 ++-- extra_tests/snippets/builtin_dict_union.py | 105 +- extra_tests/snippets/builtin_dir.py | 32 +- extra_tests/snippets/builtin_divmod.py | 6 +- extra_tests/snippets/builtin_ellipsis.py | 12 +- extra_tests/snippets/builtin_enumerate.py | 11 +- extra_tests/snippets/builtin_eval.py | 4 +- extra_tests/snippets/builtin_exceptions.py | 141 +-- extra_tests/snippets/builtin_exec.py | 31 +- extra_tests/snippets/builtin_exit.py | 2 +- extra_tests/snippets/builtin_format.py | 98 +- extra_tests/snippets/builtin_hash.py | 1 - extra_tests/snippets/builtin_hex.py | 6 +- extra_tests/snippets/builtin_isinstance.py | 15 +- extra_tests/snippets/builtin_issubclass.py | 4 +- extra_tests/snippets/builtin_len.py | 4 +- extra_tests/snippets/builtin_list.py | 497 +++++--- extra_tests/snippets/builtin_locals.py | 19 +- extra_tests/snippets/builtin_map.py | 4 +- extra_tests/snippets/builtin_mappingproxy.py | 11 +- extra_tests/snippets/builtin_max.py | 19 +- extra_tests/snippets/builtin_memoryview.py | 71 +- extra_tests/snippets/builtin_min.py | 19 +- extra_tests/snippets/builtin_none.py | 7 +- extra_tests/snippets/builtin_object.py | 5 +- extra_tests/snippets/builtin_open.py | 12 +- extra_tests/snippets/builtin_ord.py | 21 +- extra_tests/snippets/builtin_pow.py | 54 +- extra_tests/snippets/builtin_print.py | 12 +- extra_tests/snippets/builtin_property.py | 6 +- extra_tests/snippets/builtin_range.py | 44 +- extra_tests/snippets/builtin_reversed.py | 4 +- extra_tests/snippets/builtin_round.py | 6 +- extra_tests/snippets/builtin_set.py | 380 ++++--- extra_tests/snippets/builtin_slice.py | 66 +- extra_tests/snippets/builtin_str.py | 1007 +++++++++-------- extra_tests/snippets/builtin_str_encode.py | 2 + extra_tests/snippets/builtin_str_subclass.py | 2 + extra_tests/snippets/builtin_str_unicode.py | 30 +- .../snippets/builtin_str_unicode_slice.py | 36 +- extra_tests/snippets/builtin_tuple.py | 32 +- extra_tests/snippets/builtin_type.py | 436 +++---- extra_tests/snippets/builtin_type_mro.py | 11 +- extra_tests/snippets/builtin_zip.py | 10 +- extra_tests/snippets/builtins_module.py | 17 +- extra_tests/snippets/code_co_consts.py | 16 +- extra_tests/snippets/dir_main/__main__.py | 2 +- extra_tests/snippets/example_fizzbuzz.py | 1 + extra_tests/snippets/example_interactive.py | 10 +- .../snippets/forbidden_instantiation.py | 38 +- extra_tests/snippets/frozen.py | 1 + extra_tests/snippets/import.py | 47 +- extra_tests/snippets/import_file.py | 3 +- extra_tests/snippets/import_mutual1.py | 2 - extra_tests/snippets/import_mutual2.py | 1 - extra_tests/snippets/import_star.py | 2 +- extra_tests/snippets/import_target.py | 6 +- extra_tests/snippets/intro/3.1.1.1.py | 8 +- extra_tests/snippets/intro/3.1.1.3.py | 4 +- extra_tests/snippets/intro/3.1.2.1.py | 7 +- extra_tests/snippets/intro/3.1.2.10.py | 12 +- extra_tests/snippets/intro/3.1.2.3.py | 2 +- extra_tests/snippets/intro/3.1.2.5.py | 2 +- extra_tests/snippets/intro/3.1.2.6.py | 2 +- extra_tests/snippets/jit.py | 1 - extra_tests/snippets/name.py | 4 +- extra_tests/snippets/operator_arithmetic.py | 2 +- extra_tests/snippets/operator_cast.py | 24 +- extra_tests/snippets/operator_comparison.py | 41 +- extra_tests/snippets/operator_div.py | 14 +- extra_tests/snippets/operator_membership.py | 5 +- extra_tests/snippets/protocol_callable.py | 5 +- extra_tests/snippets/protocol_index_bad.py | 22 +- extra_tests/snippets/protocol_iterable.py | 22 +- extra_tests/snippets/protocol_iternext.py | 8 +- extra_tests/snippets/recursion.py | 2 + extra_tests/snippets/stdlib_abc_number.py | 2 +- extra_tests/snippets/stdlib_array.py | 34 +- extra_tests/snippets/stdlib_ast.py | 15 +- extra_tests/snippets/stdlib_collections.py | 5 +- .../snippets/stdlib_collections_deque.py | 40 +- extra_tests/snippets/stdlib_csv.py | 66 +- extra_tests/snippets/stdlib_ctypes.py | 115 +- extra_tests/snippets/stdlib_datetime.py | 40 +- extra_tests/snippets/stdlib_dir_module.py | 10 +- extra_tests/snippets/stdlib_dis.py | 27 +- extra_tests/snippets/stdlib_functools.py | 26 +- extra_tests/snippets/stdlib_hashlib.py | 43 +- extra_tests/snippets/stdlib_imp.py | 6 +- extra_tests/snippets/stdlib_io.py | 32 +- extra_tests/snippets/stdlib_io_bytesio.py | 55 +- extra_tests/snippets/stdlib_io_stringio.py | 59 +- extra_tests/snippets/stdlib_itertools.py | 241 ++-- extra_tests/snippets/stdlib_json.py | 186 +-- extra_tests/snippets/stdlib_logging.py | 10 +- extra_tests/snippets/stdlib_marshal.py | 21 +- extra_tests/snippets/stdlib_math.py | 139 ++- extra_tests/snippets/stdlib_os.py | 101 +- extra_tests/snippets/stdlib_pwd.py | 5 +- extra_tests/snippets/stdlib_random.py | 6 +- extra_tests/snippets/stdlib_re.py | 78 +- extra_tests/snippets/stdlib_signal.py | 34 +- extra_tests/snippets/stdlib_socket.py | 86 +- extra_tests/snippets/stdlib_sqlite.py | 8 +- extra_tests/snippets/stdlib_string.py | 30 +- extra_tests/snippets/stdlib_struct.py | 45 +- extra_tests/snippets/stdlib_subprocess.py | 5 + extra_tests/snippets/stdlib_sys.py | 64 +- extra_tests/snippets/stdlib_sys_getframe.py | 18 +- extra_tests/snippets/stdlib_time.py | 11 +- extra_tests/snippets/stdlib_traceback.py | 30 +- extra_tests/snippets/stdlib_types.py | 2 +- extra_tests/snippets/test_threading.py | 2 +- extra_tests/snippets/testutils.py | 48 +- extra_tests/test_snippets.py | 22 +- ruff.toml | 2 + wasm/demo/snippets/asyncbrowser.py | 1 + wasm/demo/snippets/fetch.py | 6 +- wasm/demo/snippets/import_pypi.py | 2 + wasm/demo/snippets/mandelbrot.py | 25 +- wasm/example/src/main.py | 12 +- 138 files changed, 4041 insertions(+), 2740 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index e00ad26f2f..db8f9056b1 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -327,8 +327,10 @@ jobs: run: python -m pip install ruff==0.11.8 - name: Ensure docs generate no warnings run: cargo doc - - name: run python lint - run: ruff check + - name: run ruff check + run: ruff check --diff + - name: run ruff format + run: ruff format --check - name: install prettier run: yarn global add prettier && echo "$(yarn global bin)" >>$GITHUB_PATH - name: check wasm code with prettier diff --git a/examples/atexit_example.py b/examples/atexit_example.py index 0324d5b50e..c9c61ca567 100644 --- a/examples/atexit_example.py +++ b/examples/atexit_example.py @@ -1,7 +1,9 @@ import atexit import sys + def myexit(): sys.exit(2) + atexit.register(myexit) diff --git a/examples/call_between_rust_and_python.py b/examples/call_between_rust_and_python.py index 60335d81e9..4a52e85eac 100644 --- a/examples/call_between_rust_and_python.py +++ b/examples/call_between_rust_and_python.py @@ -1,14 +1,17 @@ from rust_py_module import RustStruct, rust_function + class PythonPerson: def __init__(self, name): self.name = name + def python_callback(): python_person = PythonPerson("Peter Python") rust_object = rust_function(42, "This is a python string", python_person) print("Printing member 'numbers' from rust struct: ", rust_object.numbers) rust_object.print_in_rust_from_python() + def take_string(string): print("Calling python function from rust with string: " + string) diff --git a/examples/freeze/freeze.py b/examples/freeze/freeze.py index c600ebf959..9cd6551966 100644 --- a/examples/freeze/freeze.py +++ b/examples/freeze/freeze.py @@ -1,4 +1,3 @@ import time print("Hello world!!!", time.time()) - diff --git a/extra_tests/benchmarks/perf_fib.py b/extra_tests/benchmarks/perf_fib.py index 89ede85179..6b999f7443 100644 --- a/extra_tests/benchmarks/perf_fib.py +++ b/extra_tests/benchmarks/perf_fib.py @@ -2,14 +2,15 @@ def fib(n): a = 1 b = 1 for _ in range(n - 1): - temp = b - b = a + b - a = temp + temp = b + b = a + b + a = temp return b + print(fib(1)) print(fib(2)) print(fib(3)) print(fib(4)) -print(fib(5)) \ No newline at end of file +print(fib(5)) diff --git a/extra_tests/custom_text_test_runner.py b/extra_tests/custom_text_test_runner.py index 8e91d7c39d..4c48e615c3 100644 --- a/extra_tests/custom_text_test_runner.py +++ b/extra_tests/custom_text_test_runner.py @@ -36,10 +36,12 @@ from unittest.runner import registerResult from functools import reduce + class TablePrinter(object): # Modified from https://github.com/agramian/table-printer, same license as above "Print a list of dicts as a table" - def __init__(self, fmt, sep='', ul=None, tl=None, bl=None): + + def __init__(self, fmt, sep="", ul=None, tl=None, bl=None): """ @param fmt: list of tuple(heading, key, width) heading: str, column label @@ -50,20 +52,44 @@ def __init__(self, fmt, sep='', ul=None, tl=None, bl=None): @param tl: string, character to draw as top line over table, or None @param bl: string, character to draw as bottom line under table, or None """ - super(TablePrinter,self).__init__() - fmt = [x + ('left',) if len(x) < 4 else x for x in fmt] - self.fmt = str(sep).join('{lb}{0}:{align}{1}{rb}'.format(key, width, lb='{', rb='}', align='<' if alignment == 'left' else '>') for heading,key,width,alignment in fmt) - self.head = {key:heading for heading,key,width,alignment in fmt} - self.ul = {key:str(ul)*width for heading,key,width,alignment in fmt} if ul else None - self.width = {key:width for heading,key,width,alignment in fmt} - self.tl = {key:str(tl)*width for heading,key,width,alignment in fmt} if tl else None - self.bl = {key:str(bl)*width for heading,key,width,alignment in fmt} if bl else None + super(TablePrinter, self).__init__() + fmt = [x + ("left",) if len(x) < 4 else x for x in fmt] + self.fmt = str(sep).join( + "{lb}{0}:{align}{1}{rb}".format( + key, width, lb="{", rb="}", align="<" if alignment == "left" else ">" + ) + for heading, key, width, alignment in fmt + ) + self.head = {key: heading for heading, key, width, alignment in fmt} + self.ul = ( + {key: str(ul) * width for heading, key, width, alignment in fmt} + if ul + else None + ) + self.width = {key: width for heading, key, width, alignment in fmt} + self.tl = ( + {key: str(tl) * width for heading, key, width, alignment in fmt} + if tl + else None + ) + self.bl = ( + {key: str(bl) * width for heading, key, width, alignment in fmt} + if bl + else None + ) def row(self, data, separation_character=False): if separation_character: - return self.fmt.format(**{ k:str(data.get(k,''))[:w] for k,w in self.width.items() }) + return self.fmt.format( + **{k: str(data.get(k, ""))[:w] for k, w in self.width.items()} + ) else: - data = { k:str(data.get(k,'')) if len(str(data.get(k,''))) <= w else '%s...' %str(data.get(k,''))[:(w-3)] for k,w in self.width.items() } + data = { + k: str(data.get(k, "")) + if len(str(data.get(k, ""))) <= w + else "%s..." % str(data.get(k, ""))[: (w - 3)] + for k, w in self.width.items() + } return self.fmt.format(**data) def __call__(self, data_list, totals=None): @@ -80,89 +106,111 @@ def __call__(self, data_list, totals=None): res.insert(len(res), _r(totals)) if self.bl: res.insert(len(res), _r(self.bl, True)) - return '\n'.join(res) + return "\n".join(res) def get_function_args(func_ref): try: - return [p for p in inspect.getargspec(func_ref).args if p != 'self'] + return [p for p in inspect.getargspec(func_ref).args if p != "self"] except: return None + def store_class_fields(class_ref, args_passed): - """ Store the passed in class fields in self - """ + """Store the passed in class fields in self""" params = get_function_args(class_ref.__init__) - for p in params: setattr(class_ref, p, args_passed[p]) + for p in params: + setattr(class_ref, p, args_passed[p]) + def sum_dict_key(d, key, cast_type=None): - """ Sum together all values matching a key given a passed dict - """ - return reduce( (lambda x, y: x + y), [eval("%s(x['%s'])" %(cast_type, key)) if cast_type else x[key] for x in d] ) + """Sum together all values matching a key given a passed dict""" + return reduce( + (lambda x, y: x + y), + [eval("%s(x['%s'])" % (cast_type, key)) if cast_type else x[key] for x in d], + ) + def case_name(name): - """ Test case name decorator to override function name. - """ + """Test case name decorator to override function name.""" + def decorator(function): - function.__dict__['test_case_name'] = name + function.__dict__["test_case_name"] = name return function + return decorator + def skip_device(name): - """ Decorator to mark a test to only run on certain devices - Takes single device name or list of names as argument + """Decorator to mark a test to only run on certain devices + Takes single device name or list of names as argument """ + def decorator(function): name_list = name if type(name) == list else [name] - function.__dict__['skip_device'] = name_list + function.__dict__["skip_device"] = name_list return function + return decorator + def _set_test_type(function, test_type): - """ Test type setter - """ - if 'test_type' in function.__dict__: - function.__dict__['test_type'].append(test_type) + """Test type setter""" + if "test_type" in function.__dict__: + function.__dict__["test_type"].append(test_type) else: - function.__dict__['test_type'] = [test_type] + function.__dict__["test_type"] = [test_type] return function + def smoke(function): - """ Test decorator to mark test as smoke type - """ - return _set_test_type(function, 'smoke') + """Test decorator to mark test as smoke type""" + return _set_test_type(function, "smoke") + def guide_discovery(function): - """ Test decorator to mark test as guide_discovery type - """ - return _set_test_type(function, 'guide_discovery') + """Test decorator to mark test as guide_discovery type""" + return _set_test_type(function, "guide_discovery") + def focus(function): - """ Test decorator to mark test as focus type to all rspec style debugging of cases - """ - return _set_test_type(function, 'focus') + """Test decorator to mark test as focus type to all rspec style debugging of cases""" + return _set_test_type(function, "focus") + class _WritelnDecorator(object): """Used to decorate file-like objects with a handy 'writeln' method""" - def __init__(self,stream): + + def __init__(self, stream): self.stream = stream def __getattr__(self, attr): - if attr in ('stream', '__getstate__'): + if attr in ("stream", "__getstate__"): raise AttributeError(attr) - return getattr(self.stream,attr) + return getattr(self.stream, attr) def writeln(self, arg=None): if arg: self.write(arg) - self.write('\n') # text-mode streams translate to \r\n if needed + self.write("\n") # text-mode streams translate to \r\n if needed + class CustomTextTestResult(result.TestResult): _num_formatting_chars = 150 _execution_time_significant_digits = 4 _pass_percentage_significant_digits = 2 - def __init__(self, stream, descriptions, verbosity, results_file_path, result_screenshots_dir, show_previous_results, config, test_types): + def __init__( + self, + stream, + descriptions, + verbosity, + results_file_path, + result_screenshots_dir, + show_previous_results, + config, + test_types, + ): super(CustomTextTestResult, self).__init__(stream, descriptions, verbosity) store_class_fields(self, locals()) self.show_overall_results = verbosity > 0 @@ -178,12 +226,12 @@ def __init__(self, stream, descriptions, verbosity, results_file_path, result_sc self.separator3 = "_" * CustomTextTestResult._num_formatting_chars self.separator4 = "*" * CustomTextTestResult._num_formatting_chars self.separator_failure = "!" * CustomTextTestResult._num_formatting_chars - self.separator_pre_result = '.' * CustomTextTestResult._num_formatting_chars + self.separator_pre_result = "." * CustomTextTestResult._num_formatting_chars def getDescription(self, test): doc_first_line = test.shortDescription() if self.descriptions and doc_first_line: - return '\n'.join((str(test), doc_first_line)) + return "\n".join((str(test), doc_first_line)) else: return str(test) @@ -195,109 +243,170 @@ def startTestRun(self): self.results = None self.previous_suite_runs = [] if os.path.isfile(self.results_file_path): - with open(self.results_file_path, 'rb') as f: + with open(self.results_file_path, "rb") as f: try: self.results = json.load(f) # recreated results dict with int keys - self.results['suites'] = {int(k):v for (k,v) in list(self.results['suites'].items())} - self.suite_map = {v['name']:int(k) for (k,v) in list(self.results['suites'].items())} - self.previous_suite_runs = list(self.results['suites'].keys()) + self.results["suites"] = { + int(k): v for (k, v) in list(self.results["suites"].items()) + } + self.suite_map = { + v["name"]: int(k) + for (k, v) in list(self.results["suites"].items()) + } + self.previous_suite_runs = list(self.results["suites"].keys()) except: pass if not self.results: - self.results = {'suites': {}, - 'name': '', - 'num_passed': 0, - 'num_failed': 0, - 'num_skipped': 0, - 'num_expected_failures': 0, - 'execution_time': None} - self.suite_number = int(sorted(self.results['suites'].keys())[-1]) + 1 if len(self.results['suites']) else 0 + self.results = { + "suites": {}, + "name": "", + "num_passed": 0, + "num_failed": 0, + "num_skipped": 0, + "num_expected_failures": 0, + "execution_time": None, + } + self.suite_number = ( + int(sorted(self.results["suites"].keys())[-1]) + 1 + if len(self.results["suites"]) + else 0 + ) self.case_number = 0 self.suite_map = {} def stopTestRun(self): # if no tests or some failure occurred execution time may not have been set try: - self.results['suites'][self.suite_map[self.suite]]['execution_time'] = format(self.suite_execution_time, '.%sf' %CustomTextTestResult._execution_time_significant_digits) + self.results["suites"][self.suite_map[self.suite]]["execution_time"] = ( + format( + self.suite_execution_time, + ".%sf" % CustomTextTestResult._execution_time_significant_digits, + ) + ) except: pass - self.results['execution_time'] = format(self.total_execution_time, '.%sf' %CustomTextTestResult._execution_time_significant_digits) + self.results["execution_time"] = format( + self.total_execution_time, + ".%sf" % CustomTextTestResult._execution_time_significant_digits, + ) self.stream.writeln(self.separator3) - with open(self.results_file_path, 'w') as f: + with open(self.results_file_path, "w") as f: json.dump(self.results, f) def startTest(self, test): - suite_base_category = test.__class__.base_test_category if hasattr(test.__class__, 'base_test_category') else '' - self.next_suite = os.path.join(suite_base_category, test.__class__.name if hasattr(test.__class__, 'name') else test.__class__.__name__) + suite_base_category = ( + test.__class__.base_test_category + if hasattr(test.__class__, "base_test_category") + else "" + ) + self.next_suite = os.path.join( + suite_base_category, + test.__class__.name + if hasattr(test.__class__, "name") + else test.__class__.__name__, + ) self.case = test._testMethodName super(CustomTextTestResult, self).startTest(test) if not self.suite or self.suite != self.next_suite: if self.suite: - self.results['suites'][self.suite_map[self.suite]]['execution_time'] = format(self.suite_execution_time, '.%sf' %CustomTextTestResult._execution_time_significant_digits) + self.results["suites"][self.suite_map[self.suite]]["execution_time"] = ( + format( + self.suite_execution_time, + ".%sf" + % CustomTextTestResult._execution_time_significant_digits, + ) + ) self.suite_execution_time = 0 self.suite = self.next_suite if self.show_test_info: self.stream.writeln(self.separator1) - self.stream.writeln("TEST SUITE: %s" %self.suite) - self.stream.writeln("Description: %s" %self.getSuiteDescription(test)) + self.stream.writeln("TEST SUITE: %s" % self.suite) + self.stream.writeln("Description: %s" % self.getSuiteDescription(test)) try: - name_override = getattr(test, test._testMethodName).__func__.__dict__['test_case_name'] + name_override = getattr(test, test._testMethodName).__func__.__dict__[ + "test_case_name" + ] except: name_override = None self.case = name_override if name_override else self.case if self.show_test_info: # self.stream.writeln(self.separator2) - self.stream.write("CASE: %s" %self.case) - if desc := test.shortDescription(): self.stream.write(" (Description: %s)" % desc) + self.stream.write("CASE: %s" % self.case) + if desc := test.shortDescription(): + self.stream.write(" (Description: %s)" % desc) self.stream.write("... ") # self.stream.writeln(self.separator2) self.stream.flush() self.current_case_number = self.case_number if self.suite not in self.suite_map: self.suite_map[self.suite] = self.suite_number - self.results['suites'][self.suite_number] = { - 'name': self.suite, - 'class': test.__class__.__name__, - 'module': re.compile('.* \((.*)\)').match(str(test)).group(1), - 'description': self.getSuiteDescription(test), - 'cases': {}, - 'used_case_names': {}, - 'num_passed': 0, - 'num_failed': 0, - 'num_skipped': 0, - 'num_expected_failures': 0, - 'execution_time': None} + self.results["suites"][self.suite_number] = { + "name": self.suite, + "class": test.__class__.__name__, + "module": re.compile(".* \((.*)\)").match(str(test)).group(1), + "description": self.getSuiteDescription(test), + "cases": {}, + "used_case_names": {}, + "num_passed": 0, + "num_failed": 0, + "num_skipped": 0, + "num_expected_failures": 0, + "execution_time": None, + } self.suite_number += 1 self.num_cases = 0 self.num_passed = 0 self.num_failed = 0 self.num_skipped = 0 self.num_expected_failures = 0 - self.results['suites'][self.suite_map[self.suite]]['cases'][self.case_number] = { - 'name': self.case, - 'method': test._testMethodName, - 'result': None, - 'description': test.shortDescription(), - 'note': None, - 'errors': None, - 'failures': None, - 'screenshots': [], - 'new_version': 'No', - 'execution_time': None} + self.results["suites"][self.suite_map[self.suite]]["cases"][ + self.case_number + ] = { + "name": self.case, + "method": test._testMethodName, + "result": None, + "description": test.shortDescription(), + "note": None, + "errors": None, + "failures": None, + "screenshots": [], + "new_version": "No", + "execution_time": None, + } self.start_time = time.time() if self.test_types: - if ('test_type' in getattr(test, test._testMethodName).__func__.__dict__ - and set([s.lower() for s in self.test_types]) == set([s.lower() for s in getattr(test, test._testMethodName).__func__.__dict__['test_type']])): + if "test_type" in getattr( + test, test._testMethodName + ).__func__.__dict__ and set([s.lower() for s in self.test_types]) == set( + [ + s.lower() + for s in getattr(test, test._testMethodName).__func__.__dict__[ + "test_type" + ] + ] + ): pass else: - getattr(test, test._testMethodName).__func__.__dict__['__unittest_skip_why__'] = 'Test run specified to only run tests of type "%s"' %','.join(self.test_types) - getattr(test, test._testMethodName).__func__.__dict__['__unittest_skip__'] = True - if 'skip_device' in getattr(test, test._testMethodName).__func__.__dict__: - for device in getattr(test, test._testMethodName).__func__.__dict__['skip_device']: - if self.config and device.lower() in self.config['device_name'].lower(): - getattr(test, test._testMethodName).__func__.__dict__['__unittest_skip_why__'] = 'Test is marked to be skipped on %s' %device - getattr(test, test._testMethodName).__func__.__dict__['__unittest_skip__'] = True + getattr(test, test._testMethodName).__func__.__dict__[ + "__unittest_skip_why__" + ] = 'Test run specified to only run tests of type "%s"' % ",".join( + self.test_types + ) + getattr(test, test._testMethodName).__func__.__dict__[ + "__unittest_skip__" + ] = True + if "skip_device" in getattr(test, test._testMethodName).__func__.__dict__: + for device in getattr(test, test._testMethodName).__func__.__dict__[ + "skip_device" + ]: + if self.config and device.lower() in self.config["device_name"].lower(): + getattr(test, test._testMethodName).__func__.__dict__[ + "__unittest_skip_why__" + ] = "Test is marked to be skipped on %s" % device + getattr(test, test._testMethodName).__func__.__dict__[ + "__unittest_skip__" + ] = True break def stopTest(self, test): @@ -307,19 +416,32 @@ def stopTest(self, test): self.total_execution_time += self.execution_time super(CustomTextTestResult, self).stopTest(test) self.num_cases += 1 - self.results['suites'][self.suite_map[self.suite]]['num_passed'] = self.num_passed - self.results['suites'][self.suite_map[self.suite]]['num_failed'] = self.num_failed - self.results['suites'][self.suite_map[self.suite]]['num_skipped'] = self.num_skipped - self.results['suites'][self.suite_map[self.suite]]['num_expected_failures'] = self.num_expected_failures - self.results['suites'][self.suite_map[self.suite]]['cases'][self.current_case_number]['execution_time']= format(self.execution_time, '.%sf' %CustomTextTestResult._execution_time_significant_digits) - self.results['num_passed'] += self.num_passed - self.results['num_failed'] += self.num_failed - self.results['num_skipped'] += self.num_skipped - self.results['num_expected_failures'] += self.num_expected_failures + self.results["suites"][self.suite_map[self.suite]]["num_passed"] = ( + self.num_passed + ) + self.results["suites"][self.suite_map[self.suite]]["num_failed"] = ( + self.num_failed + ) + self.results["suites"][self.suite_map[self.suite]]["num_skipped"] = ( + self.num_skipped + ) + self.results["suites"][self.suite_map[self.suite]]["num_expected_failures"] = ( + self.num_expected_failures + ) + self.results["suites"][self.suite_map[self.suite]]["cases"][ + self.current_case_number + ]["execution_time"] = format( + self.execution_time, + ".%sf" % CustomTextTestResult._execution_time_significant_digits, + ) + self.results["num_passed"] += self.num_passed + self.results["num_failed"] += self.num_failed + self.results["num_skipped"] += self.num_skipped + self.results["num_expected_failures"] += self.num_expected_failures self.case_number += 1 def print_error_string(self, err): - error_string = ''.join(traceback.format_exception(err[0], err[1], err[2])) + error_string = "".join(traceback.format_exception(err[0], err[1], err[2])) if self.show_errors: self.stream.writeln(self.separator_failure) self.stream.write(error_string) @@ -328,7 +450,9 @@ def print_error_string(self, err): def addScreenshots(self, test): for root, dirs, files in os.walk(self.result_screenshots_dir): for file in files: - self.results['suites'][self.suite_map[self.suite]]['cases'][self.current_case_number]['screenshots'].append(os.path.join(root, file)) + self.results["suites"][self.suite_map[self.suite]]["cases"][ + self.current_case_number + ]["screenshots"].append(os.path.join(root, file)) def addSuccess(self, test): super(CustomTextTestResult, self).addSuccess(test) @@ -336,7 +460,9 @@ def addSuccess(self, test): # self.stream.writeln(self.separator_pre_result) self.stream.writeln("PASS") self.stream.flush() - self.results['suites'][self.suite_map[self.suite]]['cases'][self.current_case_number]['result'] = 'passed' + self.results["suites"][self.suite_map[self.suite]]["cases"][ + self.current_case_number + ]["result"] = "passed" self.num_passed += 1 self.addScreenshots(test) @@ -347,8 +473,12 @@ def addError(self, test, err): # self.stream.writeln(self.separator_pre_result) self.stream.writeln("ERROR") self.stream.flush() - self.results['suites'][self.suite_map[self.suite]]['cases'][self.current_case_number]['result'] = 'error' - self.results['suites'][self.suite_map[self.suite]]['cases'][self.current_case_number]['errors'] = error_string + self.results["suites"][self.suite_map[self.suite]]["cases"][ + self.current_case_number + ]["result"] = "error" + self.results["suites"][self.suite_map[self.suite]]["cases"][ + self.current_case_number + ]["errors"] = error_string self.num_failed += 1 self.addScreenshots(test) @@ -359,8 +489,12 @@ def addFailure(self, test, err): # self.stream.writeln(self.separator_pre_result) self.stream.writeln("FAIL") self.stream.flush() - self.results['suites'][self.suite_map[self.suite]]['cases'][self.current_case_number]['result'] = 'failed' - self.results['suites'][self.suite_map[self.suite]]['cases'][self.current_case_number]['failures'] = error_string + self.results["suites"][self.suite_map[self.suite]]["cases"][ + self.current_case_number + ]["result"] = "failed" + self.results["suites"][self.suite_map[self.suite]]["cases"][ + self.current_case_number + ]["failures"] = error_string self.num_failed += 1 self.addScreenshots(test) @@ -370,8 +504,12 @@ def addSkip(self, test, reason): # self.stream.writeln(self.separator_pre_result) self.stream.writeln("SKIPPED {0!r}".format(reason)) self.stream.flush() - self.results['suites'][self.suite_map[self.suite]]['cases'][self.current_case_number]['result'] = 'skipped' - self.results['suites'][self.suite_map[self.suite]]['cases'][self.current_case_number]['note'] = reason + self.results["suites"][self.suite_map[self.suite]]["cases"][ + self.current_case_number + ]["result"] = "skipped" + self.results["suites"][self.suite_map[self.suite]]["cases"][ + self.current_case_number + ]["note"] = reason self.num_skipped += 1 def addExpectedFailure(self, test, err): @@ -380,7 +518,9 @@ def addExpectedFailure(self, test, err): # self.stream.writeln(self.separator_pre_result) self.stream.writeln("EXPECTED FAILURE") self.stream.flush() - self.results['suites'][self.suite_map[self.suite]]['cases'][self.current_case_number]['result'] = 'expected_failure' + self.results["suites"][self.suite_map[self.suite]]["cases"][ + self.current_case_number + ]["result"] = "expected_failure" self.num_expected_failures += 1 self.addScreenshots(test) @@ -396,103 +536,189 @@ def addUnexpectedSuccess(self, test): def printOverallSuiteResults(self, r): self.stream.writeln() self.stream.writeln(self.separator4) - self.stream.writeln('OVERALL SUITE RESULTS') + self.stream.writeln("OVERALL SUITE RESULTS") fmt = [ - ('SUITE', 'suite', 50, 'left'), - ('CASES', 'cases', 15, 'right'), - ('PASSED', 'passed', 15, 'right'), - ('FAILED', 'failed', 15, 'right'), - ('SKIPPED', 'skipped', 15, 'right'), - ('%', 'percentage', 20, 'right'), - ('TIME (s)', 'time', 20, 'right') + ("SUITE", "suite", 50, "left"), + ("CASES", "cases", 15, "right"), + ("PASSED", "passed", 15, "right"), + ("FAILED", "failed", 15, "right"), + ("SKIPPED", "skipped", 15, "right"), + ("%", "percentage", 20, "right"), + ("TIME (s)", "time", 20, "right"), ] data = [] - for x in r: data.append({'suite': r[x]['name'], - 'cases': r[x]['num_passed'] + r[x]['num_failed'], - 'passed': r[x]['num_passed'], - 'failed': r[x]['num_failed'], - 'skipped': r[x]['num_skipped'], - 'expected_failures': r[x]['num_expected_failures'], - 'percentage': float(r[x]['num_passed'])/(r[x]['num_passed'] + r[x]['num_failed']) * 100 if (r[x]['num_passed'] + r[x]['num_failed']) > 0 else 0, - 'time': r[x]['execution_time']}) - total_suites_passed = len([x for x in data if not x['failed']]) - total_suites_passed_percentage = format(float(total_suites_passed)/len(data) * 100, '.%sf' %CustomTextTestResult._pass_percentage_significant_digits) - totals = {'suite': 'TOTALS %s/%s (%s%%) suites passed' %(total_suites_passed, len(data), total_suites_passed_percentage), - 'cases': sum_dict_key(data, 'cases'), - 'passed': sum_dict_key(data, 'passed'), - 'failed': sum_dict_key(data, 'failed'), - 'skipped': sum_dict_key(data, 'skipped'), - 'percentage': sum_dict_key(data, 'percentage')/len(data), - 'time': sum_dict_key(data, 'time', 'float')} - for x in data: operator.setitem(x, 'percentage', format(x['percentage'], '.%sf' %CustomTextTestResult._pass_percentage_significant_digits)) - totals['percentage'] = format(totals['percentage'], '.%sf' %CustomTextTestResult._pass_percentage_significant_digits) - self.stream.writeln( TablePrinter(fmt, tl=self.separator1, ul=self.separator2, bl=self.separator3)(data, totals) ) + for x in r: + data.append( + { + "suite": r[x]["name"], + "cases": r[x]["num_passed"] + r[x]["num_failed"], + "passed": r[x]["num_passed"], + "failed": r[x]["num_failed"], + "skipped": r[x]["num_skipped"], + "expected_failures": r[x]["num_expected_failures"], + "percentage": float(r[x]["num_passed"]) + / (r[x]["num_passed"] + r[x]["num_failed"]) + * 100 + if (r[x]["num_passed"] + r[x]["num_failed"]) > 0 + else 0, + "time": r[x]["execution_time"], + } + ) + total_suites_passed = len([x for x in data if not x["failed"]]) + total_suites_passed_percentage = format( + float(total_suites_passed) / len(data) * 100, + ".%sf" % CustomTextTestResult._pass_percentage_significant_digits, + ) + totals = { + "suite": "TOTALS %s/%s (%s%%) suites passed" + % (total_suites_passed, len(data), total_suites_passed_percentage), + "cases": sum_dict_key(data, "cases"), + "passed": sum_dict_key(data, "passed"), + "failed": sum_dict_key(data, "failed"), + "skipped": sum_dict_key(data, "skipped"), + "percentage": sum_dict_key(data, "percentage") / len(data), + "time": sum_dict_key(data, "time", "float"), + } + for x in data: + operator.setitem( + x, + "percentage", + format( + x["percentage"], + ".%sf" % CustomTextTestResult._pass_percentage_significant_digits, + ), + ) + totals["percentage"] = format( + totals["percentage"], + ".%sf" % CustomTextTestResult._pass_percentage_significant_digits, + ) + self.stream.writeln( + TablePrinter( + fmt, tl=self.separator1, ul=self.separator2, bl=self.separator3 + )(data, totals) + ) self.stream.writeln() def printIndividualSuiteResults(self, r): self.stream.writeln() self.stream.writeln(self.separator4) - self.stream.writeln('INDIVIDUAL SUITE RESULTS') + self.stream.writeln("INDIVIDUAL SUITE RESULTS") fmt = [ - ('CASE', 'case', 50, 'left'), - ('DESCRIPTION', 'description', 50, 'right'), - ('RESULT', 'result', 25, 'right'), - ('TIME (s)', 'time', 25, 'right') + ("CASE", "case", 50, "left"), + ("DESCRIPTION", "description", 50, "right"), + ("RESULT", "result", 25, "right"), + ("TIME (s)", "time", 25, "right"), ] for suite in r: self.stream.writeln(self.separator1) - self.stream.write('{0: <50}'.format('SUITE: %s' %r[suite]['name'])) - self.stream.writeln('{0: <100}'.format('DESCRIPTION: %s' %(r[suite]['description'] if not r[suite]['description'] or len(r[suite]['description']) <= (100 - len('DESCRIPTION: ')) - else '%s...' %r[suite]['description'][:(97 - len('DESCRIPTION: '))]))) + self.stream.write("{0: <50}".format("SUITE: %s" % r[suite]["name"])) + self.stream.writeln( + "{0: <100}".format( + "DESCRIPTION: %s" + % ( + r[suite]["description"] + if not r[suite]["description"] + or len(r[suite]["description"]) <= (100 - len("DESCRIPTION: ")) + else "%s..." + % r[suite]["description"][: (97 - len("DESCRIPTION: "))] + ) + ) + ) data = [] - cases = r[suite]['cases'] - for x in cases: data.append({'case': cases[x]['name'], - 'description': cases[x]['description'], - 'result': cases[x]['result'].upper() if cases[x]['result'] else cases[x]['result'], - 'time': cases[x]['execution_time']}) - self.stream.writeln( TablePrinter(fmt, tl=self.separator1, ul=self.separator2)(data) ) + cases = r[suite]["cases"] + for x in cases: + data.append( + { + "case": cases[x]["name"], + "description": cases[x]["description"], + "result": cases[x]["result"].upper() + if cases[x]["result"] + else cases[x]["result"], + "time": cases[x]["execution_time"], + } + ) + self.stream.writeln( + TablePrinter(fmt, tl=self.separator1, ul=self.separator2)(data) + ) self.stream.writeln(self.separator3) self.stream.writeln() def printErrorsOverview(self, r): self.stream.writeln() self.stream.writeln(self.separator4) - self.stream.writeln('FAILURES AND ERRORS OVERVIEW') + self.stream.writeln("FAILURES AND ERRORS OVERVIEW") fmt = [ - ('SUITE', 'suite', 50, 'left'), - ('CASE', 'case', 50, 'left'), - ('RESULT', 'result', 50, 'right') + ("SUITE", "suite", 50, "left"), + ("CASE", "case", 50, "left"), + ("RESULT", "result", 50, "right"), ] data = [] for suite in r: - cases = {k:v for (k,v) in list(r[suite]['cases'].items()) if v['failures'] or v['errors']} - for x in cases: data.append({'suite': '%s%s' %(r[suite]['name'], ' (%s)' %r[suite]['module'] if r[suite]['class'] != r[suite]['name'] else ''), - 'case': '%s%s' %(cases[x]['name'], ' (%s)' %cases[x]['method'] if cases[x]['name'] != cases[x]['method'] else ''), - 'result': cases[x]['result'].upper()}) - self.stream.writeln( TablePrinter(fmt, tl=self.separator1, ul=self.separator2)(data) ) + cases = { + k: v + for (k, v) in list(r[suite]["cases"].items()) + if v["failures"] or v["errors"] + } + for x in cases: + data.append( + { + "suite": "%s%s" + % ( + r[suite]["name"], + " (%s)" % r[suite]["module"] + if r[suite]["class"] != r[suite]["name"] + else "", + ), + "case": "%s%s" + % ( + cases[x]["name"], + " (%s)" % cases[x]["method"] + if cases[x]["name"] != cases[x]["method"] + else "", + ), + "result": cases[x]["result"].upper(), + } + ) + self.stream.writeln( + TablePrinter(fmt, tl=self.separator1, ul=self.separator2)(data) + ) self.stream.writeln(self.separator3) self.stream.writeln() def printErrorsDetail(self, r): self.stream.writeln() self.stream.writeln(self.separator4) - self.stream.writeln('FAILURES AND ERRORS DETAIL') + self.stream.writeln("FAILURES AND ERRORS DETAIL") for suite in r: - failures_and_errors = [k for (k,v) in list(r[suite]['cases'].items()) if v['failures'] or v['errors']] - #print failures_and_errors - suite_str = '%s%s' %(r[suite]['name'], ' (%s)' %r[suite]['module'] if r[suite]['class'] != r[suite]['name'] else '') + failures_and_errors = [ + k + for (k, v) in list(r[suite]["cases"].items()) + if v["failures"] or v["errors"] + ] + # print failures_and_errors + suite_str = "%s%s" % ( + r[suite]["name"], + " (%s)" % r[suite]["module"] + if r[suite]["class"] != r[suite]["name"] + else "", + ) for case in failures_and_errors: - case_ref = r[suite]['cases'][case] - case_str = '%s%s' %(case_ref['name'], ' (%s)' %case_ref['method'] if case_ref['name'] != case_ref['method'] else '') - errors = case_ref['errors'] - failures = case_ref['failures'] + case_ref = r[suite]["cases"][case] + case_str = "%s%s" % ( + case_ref["name"], + " (%s)" % case_ref["method"] + if case_ref["name"] != case_ref["method"] + else "", + ) + errors = case_ref["errors"] + failures = case_ref["failures"] self.stream.writeln(self.separator1) if errors: - self.stream.writeln('ERROR: %s [%s]' %(case_str, suite_str)) + self.stream.writeln("ERROR: %s [%s]" % (case_str, suite_str)) self.stream.writeln(self.separator2) self.stream.writeln(errors) if failures: - self.stream.writeln('FAILURE: %s [%s]' %(case_str, suite_str)) + self.stream.writeln("FAILURE: %s [%s]" % (case_str, suite_str)) self.stream.writeln(self.separator2) self.stream.writeln(failures) self.stream.writeln(self.separator3) @@ -501,52 +727,85 @@ def printErrorsDetail(self, r): def printSkippedDetail(self, r): self.stream.writeln() self.stream.writeln(self.separator4) - self.stream.writeln('SKIPPED DETAIL') + self.stream.writeln("SKIPPED DETAIL") fmt = [ - ('SUITE', 'suite', 50, 'left'), - ('CASE', 'case', 50, 'left'), - ('REASON', 'reason', 50, 'right') + ("SUITE", "suite", 50, "left"), + ("CASE", "case", 50, "left"), + ("REASON", "reason", 50, "right"), ] data = [] for suite in r: - cases = {k:v for (k,v) in list(r[suite]['cases'].items()) if v['result'] == 'skipped'} - for x in cases: data.append({'suite': '%s%s' %(r[suite]['name'], ' (%s)' %r[suite]['module'] if r[suite]['class'] != r[suite]['name'] else ''), - 'case': '%s%s' %(cases[x]['name'], ' (%s)' %cases[x]['method'] if cases[x]['name'] != cases[x]['method'] else ''), - 'reason': cases[x]['note']}) - self.stream.writeln( TablePrinter(fmt, tl=self.separator1, ul=self.separator2)(data) ) + cases = { + k: v + for (k, v) in list(r[suite]["cases"].items()) + if v["result"] == "skipped" + } + for x in cases: + data.append( + { + "suite": "%s%s" + % ( + r[suite]["name"], + " (%s)" % r[suite]["module"] + if r[suite]["class"] != r[suite]["name"] + else "", + ), + "case": "%s%s" + % ( + cases[x]["name"], + " (%s)" % cases[x]["method"] + if cases[x]["name"] != cases[x]["method"] + else "", + ), + "reason": cases[x]["note"], + } + ) + self.stream.writeln( + TablePrinter(fmt, tl=self.separator1, ul=self.separator2)(data) + ) self.stream.writeln(self.separator3) self.stream.writeln() def returnCode(self): return not self.wasSuccessful() + class CustomTextTestRunner(unittest.TextTestRunner): """A test runner class that displays results in textual form. It prints out the names of tests as they are run, errors as they occur, and a summary of the results at the end of the test run. """ - def __init__(self, - stream=sys.stderr, - descriptions=True, - verbosity=1, - failfast=False, - buffer=False, - resultclass=CustomTextTestResult, - results_file_path="results.json", - result_screenshots_dir='', - show_previous_results=False, - test_name=None, - test_description=None, - config=None, - test_types=None): + def __init__( + self, + stream=sys.stderr, + descriptions=True, + verbosity=1, + failfast=False, + buffer=False, + resultclass=CustomTextTestResult, + results_file_path="results.json", + result_screenshots_dir="", + show_previous_results=False, + test_name=None, + test_description=None, + config=None, + test_types=None, + ): store_class_fields(self, locals()) self.stream = _WritelnDecorator(stream) def _makeResult(self): - return self.resultclass(self.stream, self.descriptions, self.verbosity, - self.results_file_path, self.result_screenshots_dir, self.show_previous_results, - self.config, self.test_types) + return self.resultclass( + self.stream, + self.descriptions, + self.verbosity, + self.results_file_path, + self.result_screenshots_dir, + self.show_previous_results, + self.config, + self.test_types, + ) def run(self, test): output = "" @@ -556,22 +815,26 @@ def run(self, test): result.failfast = self.failfast result.buffer = self.buffer startTime = time.time() - startTestRun = getattr(result, 'startTestRun', None) + startTestRun = getattr(result, "startTestRun", None) if startTestRun is not None: startTestRun() try: test(result) finally: - stopTestRun = getattr(result, 'stopTestRun', None) + stopTestRun = getattr(result, "stopTestRun", None) if stopTestRun is not None: stopTestRun() stopTime = time.time() timeTaken = stopTime - startTime # filter results to output if result.show_previous_results: - r = result.results['suites'] + r = result.results["suites"] else: - r = {k:v for (k,v) in list(result.results['suites'].items()) if k not in result.previous_suite_runs} + r = { + k: v + for (k, v) in list(result.results["suites"].items()) + if k not in result.previous_suite_runs + } # print results based on verbosity if result.show_all: result.printSkippedDetail(r) @@ -584,15 +847,17 @@ def run(self, test): if result.show_overall_results: result.printOverallSuiteResults(r) run = result.testsRun - self.stream.writeln("Ran %d test case%s in %.4fs" % - (run, run != 1 and "s" or "", timeTaken)) + self.stream.writeln( + "Ran %d test case%s in %.4fs" % (run, run != 1 and "s" or "", timeTaken) + ) self.stream.writeln() expectedFails = unexpectedSuccesses = skipped = 0 try: - results = map(len, (result.expectedFailures, - result.unexpectedSuccesses, - result.skipped)) + results = map( + len, + (result.expectedFailures, result.unexpectedSuccesses, result.skipped), + ) except AttributeError: pass else: diff --git a/extra_tests/jsontests.py b/extra_tests/jsontests.py index 7bc743d8d3..a54fd4234e 100644 --- a/extra_tests/jsontests.py +++ b/extra_tests/jsontests.py @@ -6,8 +6,9 @@ testnames = findtests() # idk why this fixes the hanging, if it does -testnames.remove('test_importlib') -testnames.insert(0, 'test_importlib') +testnames.remove("test_importlib") +testnames.insert(0, "test_importlib") + def loadTestsOrSkip(loader, name): try: @@ -17,12 +18,16 @@ def loadTestsOrSkip(loader, name): @unittest.skip(str(exc)) def testSkipped(self): pass + attrs = {name: testSkipped} TestClass = type("ModuleSkipped", (unittest.TestCase,), attrs) return loader.suiteClass((TestClass(name),)) + loader = unittest.defaultTestLoader -suite = loader.suiteClass([loadTestsOrSkip(loader, 'test.' + name) for name in testnames]) +suite = loader.suiteClass( + [loadTestsOrSkip(loader, "test." + name) for name in testnames] +) resultsfile = os.path.join(os.path.dirname(__file__), "cpython_tests_results.json") if os.path.exists(resultsfile): diff --git a/extra_tests/snippets/3.1.3.4.py b/extra_tests/snippets/3.1.3.4.py index 426c78b42d..f254376329 100644 --- a/extra_tests/snippets/3.1.3.4.py +++ b/extra_tests/snippets/3.1.3.4.py @@ -1,3 +1,2 @@ -l = [1,2,3] -assert [1,2,3,4,5] == (l + [4,5]) - +l = [1, 2, 3] +assert [1, 2, 3, 4, 5] == (l + [4, 5]) diff --git a/extra_tests/snippets/3.1.3.5.py b/extra_tests/snippets/3.1.3.5.py index c841430b1b..11889d936c 100644 --- a/extra_tests/snippets/3.1.3.5.py +++ b/extra_tests/snippets/3.1.3.5.py @@ -1,3 +1,3 @@ -x = [1,999,3] +x = [1, 999, 3] x[1] = 2 -assert [1,2,3] == x +assert [1, 2, 3] == x diff --git a/extra_tests/snippets/builtin_abs.py b/extra_tests/snippets/builtin_abs.py index 1b744978e5..7add4f4bcf 100644 --- a/extra_tests/snippets/builtin_abs.py +++ b/extra_tests/snippets/builtin_abs.py @@ -2,4 +2,3 @@ assert abs(7) == 7 assert abs(-3.21) == 3.21 assert abs(6.25) == 6.25 - diff --git a/extra_tests/snippets/builtin_ascii.py b/extra_tests/snippets/builtin_ascii.py index 2132723c6b..5b5b45d999 100644 --- a/extra_tests/snippets/builtin_ascii.py +++ b/extra_tests/snippets/builtin_ascii.py @@ -1,7 +1,7 @@ -assert ascii('hello world') == "'hello world'" -assert ascii('안녕 세상') == "'\\uc548\\ub155 \\uc138\\uc0c1'" -assert ascii('안녕 RustPython') == "'\\uc548\\ub155 RustPython'" -assert ascii(5) == '5' +assert ascii("hello world") == "'hello world'" +assert ascii("안녕 세상") == "'\\uc548\\ub155 \\uc138\\uc0c1'" +assert ascii("안녕 RustPython") == "'\\uc548\\ub155 RustPython'" +assert ascii(5) == "5" assert ascii(chr(0x10001)) == "'\\U00010001'" assert ascii(chr(0x9999)) == "'\\u9999'" -assert ascii(chr(0x0A)) == "'\\n'" \ No newline at end of file +assert ascii(chr(0x0A)) == "'\\n'" diff --git a/extra_tests/snippets/builtin_bin.py b/extra_tests/snippets/builtin_bin.py index 97f57b2f13..4f7a54c1b2 100644 --- a/extra_tests/snippets/builtin_bin.py +++ b/extra_tests/snippets/builtin_bin.py @@ -1,13 +1,13 @@ -assert bin(0) == '0b0' -assert bin(1) == '0b1' -assert bin(-1) == '-0b1' -assert bin(2**24) == '0b1' + '0' * 24 -assert bin(2**24-1) == '0b' + '1' * 24 -assert bin(-(2**24)) == '-0b1' + '0' * 24 -assert bin(-(2**24-1)) == '-0b' + '1' * 24 +assert bin(0) == "0b0" +assert bin(1) == "0b1" +assert bin(-1) == "-0b1" +assert bin(2**24) == "0b1" + "0" * 24 +assert bin(2**24 - 1) == "0b" + "1" * 24 +assert bin(-(2**24)) == "-0b1" + "0" * 24 +assert bin(-(2**24 - 1)) == "-0b" + "1" * 24 -a = 2 ** 65 -assert bin(a) == '0b1' + '0' * 65 -assert bin(a-1) == '0b' + '1' * 65 -assert bin(-(a)) == '-0b1' + '0' * 65 -assert bin(-(a-1)) == '-0b' + '1' * 65 +a = 2**65 +assert bin(a) == "0b1" + "0" * 65 +assert bin(a - 1) == "0b" + "1" * 65 +assert bin(-(a)) == "-0b1" + "0" * 65 +assert bin(-(a - 1)) == "-0b" + "1" * 65 diff --git a/extra_tests/snippets/builtin_bool.py b/extra_tests/snippets/builtin_bool.py index a46dbaab93..6b6b4e0e08 100644 --- a/extra_tests/snippets/builtin_bool.py +++ b/extra_tests/snippets/builtin_bool.py @@ -30,18 +30,20 @@ if not object(): raise BaseException + class Falsey: def __bool__(self): return False + assert not Falsey() -assert (True or fake) # noqa: F821 -assert (False or True) +assert True or fake # noqa: F821 +assert False or True assert not (False or False) assert ("thing" or 0) == "thing" -assert (True and True) +assert True and True assert not (False and fake) # noqa: F821 assert (True and 5) == 5 @@ -92,15 +94,17 @@ def __bool__(self): assert bool({"key": "value"}) is True assert bool([1]) is True -assert bool(set([1,2])) is True +assert bool(set([1, 2])) is True assert repr(True) == "True" + # Check __len__ work class TestMagicMethodLenZero: def __len__(self): return 0 + class TestMagicMethodLenOne: def __len__(self): return 1 @@ -118,6 +122,7 @@ def __bool__(self): def __len__(self): return 0 + class TestMagicMethodBoolFalseLenTrue: def __bool__(self): return False @@ -125,6 +130,7 @@ def __bool__(self): def __len__(self): return 1 + assert bool(TestMagicMethodBoolTrueLenFalse()) is True assert bool(TestMagicMethodBoolFalseLenTrue()) is False @@ -134,9 +140,11 @@ class TestBoolThrowError: def __bool__(self): return object() + with assert_raises(TypeError): bool(TestBoolThrowError()) + class TestLenThrowError: def __len__(self): return object() @@ -145,6 +153,7 @@ def __len__(self): with assert_raises(TypeError): bool(TestLenThrowError()) + # Verify that TypeError occurs when bad things are returned # from __bool__(). This isn't really a bool test, but # it's related. @@ -152,31 +161,45 @@ def check(o): with assert_raises(TypeError): bool(o) + class Foo(object): def __bool__(self): return self + + check(Foo()) + class Bar(object): def __bool__(self): return "Yes" + + check(Bar()) + class Baz(int): def __bool__(self): return self + + check(Baz()) + # __bool__() must return a bool not an int class Spam(int): def __bool__(self): return 1 + + check(Spam()) + class Eggs: def __len__(self): return -1 + with assert_raises(ValueError): bool(Eggs()) diff --git a/extra_tests/snippets/builtin_bytearray.py b/extra_tests/snippets/builtin_bytearray.py index 008d3d23ee..1a6993e205 100644 --- a/extra_tests/snippets/builtin_bytearray.py +++ b/extra_tests/snippets/builtin_bytearray.py @@ -40,9 +40,11 @@ ) assert repr(bytearray(b"abcd")) == "bytearray(b'abcd')" + class B(bytearray): pass + assert repr(B()) == "B(b'')" assert ( repr(B([0, 1, 9, 10, 11, 13, 31, 32, 33, 89, 120, 255])) @@ -283,9 +285,9 @@ class B(bytearray): ) == bytearray(b"jiljlkmoomkaaaa") with assert_raises(TypeError): bytearray(b"").join((b"km", "kl")) -assert bytearray(b"abc").join(( - bytearray(b"123"), bytearray(b"xyz") -)) == bytearray(b"123abcxyz") +assert bytearray(b"abc").join((bytearray(b"123"), bytearray(b"xyz"))) == bytearray( + b"123abcxyz" +) # endswith startswith @@ -372,16 +374,45 @@ class B(bytearray): assert bytearray(b"mississippi").rstrip(b"ipz") == bytearray(b"mississ") - # split -assert bytearray(b"1,2,3").split(bytearray(b",")) == [bytearray(b"1"), bytearray(b"2"), bytearray(b"3")] -assert bytearray(b"1,2,3").split(bytearray(b","), maxsplit=1) == [bytearray(b"1"), bytearray(b"2,3")] -assert bytearray(b"1,2,,3,").split(bytearray(b",")) == [bytearray(b"1"), bytearray(b"2"), bytearray(b""), bytearray(b"3"), bytearray(b"")] -assert bytearray(b"1 2 3").split() == [bytearray(b"1"), bytearray(b"2"), bytearray(b"3")] +assert bytearray(b"1,2,3").split(bytearray(b",")) == [ + bytearray(b"1"), + bytearray(b"2"), + bytearray(b"3"), +] +assert bytearray(b"1,2,3").split(bytearray(b","), maxsplit=1) == [ + bytearray(b"1"), + bytearray(b"2,3"), +] +assert bytearray(b"1,2,,3,").split(bytearray(b",")) == [ + bytearray(b"1"), + bytearray(b"2"), + bytearray(b""), + bytearray(b"3"), + bytearray(b""), +] +assert bytearray(b"1 2 3").split() == [ + bytearray(b"1"), + bytearray(b"2"), + bytearray(b"3"), +] assert bytearray(b"1 2 3").split(maxsplit=1) == [bytearray(b"1"), bytearray(b"2 3")] -assert bytearray(b" 1 2 3 ").split() == [bytearray(b"1"), bytearray(b"2"), bytearray(b"3")] -assert bytearray(b"k\ruh\nfz e f").split() == [bytearray(b"k"), bytearray(b"uh"), bytearray(b"fz"), bytearray(b"e"), bytearray(b"f")] -assert bytearray(b"Two lines\n").split(bytearray(b"\n")) == [bytearray(b"Two lines"), bytearray(b"")] +assert bytearray(b" 1 2 3 ").split() == [ + bytearray(b"1"), + bytearray(b"2"), + bytearray(b"3"), +] +assert bytearray(b"k\ruh\nfz e f").split() == [ + bytearray(b"k"), + bytearray(b"uh"), + bytearray(b"fz"), + bytearray(b"e"), + bytearray(b"f"), +] +assert bytearray(b"Two lines\n").split(bytearray(b"\n")) == [ + bytearray(b"Two lines"), + bytearray(b""), +] assert bytearray(b"").split() == [] assert bytearray(b"").split(bytearray(b"\n")) == [bytearray(b"")] assert bytearray(b"\n").split(bytearray(b"\n")) == [bytearray(b""), bytearray(b"")] @@ -534,16 +565,21 @@ class B(bytearray): i = SPLIT_FIXTURES[n_sp] sep = None if i[1] == None else bytearray(i[1]) try: - assert bytearray(i[0]).split(sep=sep, maxsplit=i[4]) == [bytearray(j) for j in i[2]] + assert bytearray(i[0]).split(sep=sep, maxsplit=i[4]) == [ + bytearray(j) for j in i[2] + ] except AssertionError: print(i[0], i[1], i[2]) print( - "Expected : ", [list(x) for x in bytearray(i[0]).split(sep=sep, maxsplit=i[4])] + "Expected : ", + [list(x) for x in bytearray(i[0]).split(sep=sep, maxsplit=i[4])], ) break try: - assert bytearray(i[0]).rsplit(sep=sep, maxsplit=i[4]) == [bytearray(j) for j in i[3]] + assert bytearray(i[0]).rsplit(sep=sep, maxsplit=i[4]) == [ + bytearray(j) for j in i[3] + ] except AssertionError: print(i[0], i[1], i[2]) print( @@ -557,34 +593,61 @@ class B(bytearray): # expandtabs a = bytearray(b"\x01\x03\r\x05\t8CYZ\t\x06CYZ\t\x17cba`\n\x12\x13\x14") -assert ( - a.expandtabs() == bytearray(b"\x01\x03\r\x05 8CYZ \x06CYZ \x17cba`\n\x12\x13\x14") +assert a.expandtabs() == bytearray( + b"\x01\x03\r\x05 8CYZ \x06CYZ \x17cba`\n\x12\x13\x14" +) +assert a.expandtabs(5) == bytearray( + b"\x01\x03\r\x05 8CYZ \x06CYZ \x17cba`\n\x12\x13\x14" +) +assert bytearray(b"01\t012\t0123\t01234").expandtabs() == bytearray( + b"01 012 0123 01234" +) +assert bytearray(b"01\t012\t0123\t01234").expandtabs(4) == bytearray( + b"01 012 0123 01234" ) -assert a.expandtabs(5) == bytearray(b"\x01\x03\r\x05 8CYZ \x06CYZ \x17cba`\n\x12\x13\x14") -assert bytearray(b"01\t012\t0123\t01234").expandtabs() == bytearray(b"01 012 0123 01234") -assert bytearray(b"01\t012\t0123\t01234").expandtabs(4) == bytearray(b"01 012 0123 01234") assert bytearray(b"123\t123").expandtabs(-5) == bytearray(b"123123") assert bytearray(b"123\t123").expandtabs(0) == bytearray(b"123123") # # partition -assert bytearray(b"123456789").partition(b"45") == ((b"123"), bytearray(b"45"), bytearray(b"6789")) -assert bytearray(b"14523456789").partition(b"45") == ((b"1"), bytearray(b"45"), bytearray(b"23456789")) +assert bytearray(b"123456789").partition(b"45") == ( + (b"123"), + bytearray(b"45"), + bytearray(b"6789"), +) +assert bytearray(b"14523456789").partition(b"45") == ( + (b"1"), + bytearray(b"45"), + bytearray(b"23456789"), +) a = bytearray(b"14523456789").partition(b"45") assert isinstance(a[1], bytearray) a = bytearray(b"14523456789").partition(memoryview(b"45")) assert isinstance(a[1], bytearray) # partition -assert bytearray(b"123456789").rpartition(bytearray(b"45")) == ((bytearray(b"123")), bytearray(b"45"), bytearray(b"6789")) -assert bytearray(b"14523456789").rpartition(bytearray(b"45")) == ((bytearray(b"14523")), bytearray(b"45"), bytearray(b"6789")) +assert bytearray(b"123456789").rpartition(bytearray(b"45")) == ( + (bytearray(b"123")), + bytearray(b"45"), + bytearray(b"6789"), +) +assert bytearray(b"14523456789").rpartition(bytearray(b"45")) == ( + (bytearray(b"14523")), + bytearray(b"45"), + bytearray(b"6789"), +) a = bytearray(b"14523456789").rpartition(b"45") assert isinstance(a[1], bytearray) a = bytearray(b"14523456789").rpartition(memoryview(b"45")) assert isinstance(a[1], bytearray) # splitlines -assert bytearray(b"ab c\n\nde fg\rkl\r\n").splitlines() == [bytearray(b"ab c"), bytearray(b""), bytearray(b"de fg"), bytearray(b"kl")] +assert bytearray(b"ab c\n\nde fg\rkl\r\n").splitlines() == [ + bytearray(b"ab c"), + bytearray(b""), + bytearray(b"de fg"), + bytearray(b"kl"), +] assert bytearray(b"ab c\n\nde fg\rkl\r\n").splitlines(keepends=True) == [ bytearray(b"ab c\n"), bytearray(b"\n"), @@ -602,11 +665,15 @@ class B(bytearray): assert bytearray(b"42").zfill(-1) == bytearray(b"42") # replace -assert bytearray(b"123456789123").replace(b"23",b"XX") ==bytearray(b'1XX4567891XX') -assert bytearray(b"123456789123").replace(b"23",b"XX", 1) ==bytearray(b'1XX456789123') -assert bytearray(b"123456789123").replace(b"23",b"XX", 0) == bytearray(b"123456789123") -assert bytearray(b"123456789123").replace(b"23",b"XX", -1) ==bytearray(b'1XX4567891XX') -assert bytearray(b"123456789123").replace(b"23", bytearray(b"")) == bytearray(b"14567891") +assert bytearray(b"123456789123").replace(b"23", b"XX") == bytearray(b"1XX4567891XX") +assert bytearray(b"123456789123").replace(b"23", b"XX", 1) == bytearray(b"1XX456789123") +assert bytearray(b"123456789123").replace(b"23", b"XX", 0) == bytearray(b"123456789123") +assert bytearray(b"123456789123").replace(b"23", b"XX", -1) == bytearray( + b"1XX4567891XX" +) +assert bytearray(b"123456789123").replace(b"23", bytearray(b"")) == bytearray( + b"14567891" +) # clear @@ -642,25 +709,24 @@ class B(bytearray): # title assert bytearray(b"Hello world").title() == bytearray(b"Hello World") -assert ( - bytearray(b"they're bill's friends from the UK").title() - == bytearray(b"They'Re Bill'S Friends From The Uk") +assert bytearray(b"they're bill's friends from the UK").title() == bytearray( + b"They'Re Bill'S Friends From The Uk" ) # repeat by multiply -a = bytearray(b'abcd') -assert a * 0 == bytearray(b'') -assert a * -1 == bytearray(b'') -assert a * 1 == bytearray(b'abcd') -assert a * 3 == bytearray(b'abcdabcdabcd') -assert 3 * a == bytearray(b'abcdabcdabcd') - -a = bytearray(b'abcd') +a = bytearray(b"abcd") +assert a * 0 == bytearray(b"") +assert a * -1 == bytearray(b"") +assert a * 1 == bytearray(b"abcd") +assert a * 3 == bytearray(b"abcdabcdabcd") +assert 3 * a == bytearray(b"abcdabcdabcd") + +a = bytearray(b"abcd") a.__imul__(3) -assert a == bytearray(b'abcdabcdabcd') +assert a == bytearray(b"abcdabcdabcd") a.__imul__(0) -assert a == bytearray(b'') +assert a == bytearray(b"") # copy @@ -696,70 +762,89 @@ class B(bytearray): # remove -a = bytearray(b'abcdabcd') +a = bytearray(b"abcdabcd") a.remove(99) # the letter c # Only the first is removed -assert a == bytearray(b'abdabcd') +assert a == bytearray(b"abdabcd") # reverse -a = bytearray(b'hello, world') +a = bytearray(b"hello, world") a.reverse() -assert a == bytearray(b'dlrow ,olleh') +assert a == bytearray(b"dlrow ,olleh") # __setitem__ -a = bytearray(b'test') +a = bytearray(b"test") a[0] = 1 -assert a == bytearray(b'\x01est') +assert a == bytearray(b"\x01est") with assert_raises(TypeError): - a[0] = b'a' + a[0] = b"a" with assert_raises(TypeError): - a[0] = memoryview(b'a') + a[0] = memoryview(b"a") a[:2] = [0, 9] -assert a == bytearray(b'\x00\x09st') -a[1:3] = b'test' -assert a == bytearray(b'\x00testt') -a[:6] = memoryview(b'test') -assert a == bytearray(b'test') +assert a == bytearray(b"\x00\x09st") +a[1:3] = b"test" +assert a == bytearray(b"\x00testt") +a[:6] = memoryview(b"test") +assert a == bytearray(b"test") # mod -assert bytearray('rust%bpython%b', 'utf-8') % (b' ', b'!') == bytearray(b'rust python!') -assert bytearray('x=%i y=%f', 'utf-8') % (1, 2.5) == bytearray(b'x=1 y=2.500000') +assert bytearray("rust%bpython%b", "utf-8") % (b" ", b"!") == bytearray(b"rust python!") +assert bytearray("x=%i y=%f", "utf-8") % (1, 2.5) == bytearray(b"x=1 y=2.500000") # eq, ne -a = bytearray(b'hello, world') +a = bytearray(b"hello, world") b = a.copy() assert a.__ne__(b) is False -b = bytearray(b'my bytearray') +b = bytearray(b"my bytearray") assert a.__ne__(b) is True # pickle -a = bytearray(b'\xffab\x80\0\0\370\0\0') -assert pickle.dumps(a, 0) == b'c__builtin__\nbytearray\np0\n(c_codecs\nencode\np1\n(V\xffab\x80\\u0000\\u0000\xf8\\u0000\\u0000\np2\nVlatin1\np3\ntp4\nRp5\ntp6\nRp7\n.' -assert pickle.dumps(a, 1) == b'c__builtin__\nbytearray\nq\x00(c_codecs\nencode\nq\x01(X\x0c\x00\x00\x00\xc3\xbfab\xc2\x80\x00\x00\xc3\xb8\x00\x00q\x02X\x06\x00\x00\x00latin1q\x03tq\x04Rq\x05tq\x06Rq\x07.' -assert pickle.dumps(a, 2) == b'\x80\x02c__builtin__\nbytearray\nq\x00c_codecs\nencode\nq\x01X\x0c\x00\x00\x00\xc3\xbfab\xc2\x80\x00\x00\xc3\xb8\x00\x00q\x02X\x06\x00\x00\x00latin1q\x03\x86q\x04Rq\x05\x85q\x06Rq\x07.' -assert pickle.dumps(a, 3) == b'\x80\x03cbuiltins\nbytearray\nq\x00C\t\xffab\x80\x00\x00\xf8\x00\x00q\x01\x85q\x02Rq\x03.' -assert pickle.dumps(a, 4) == b'\x80\x04\x95*\x00\x00\x00\x00\x00\x00\x00\x8c\x08builtins\x94\x8c\tbytearray\x94\x93\x94C\t\xffab\x80\x00\x00\xf8\x00\x00\x94\x85\x94R\x94.' +a = bytearray(b"\xffab\x80\0\0\370\0\0") +assert ( + pickle.dumps(a, 0) + == b"c__builtin__\nbytearray\np0\n(c_codecs\nencode\np1\n(V\xffab\x80\\u0000\\u0000\xf8\\u0000\\u0000\np2\nVlatin1\np3\ntp4\nRp5\ntp6\nRp7\n." +) +assert ( + pickle.dumps(a, 1) + == b"c__builtin__\nbytearray\nq\x00(c_codecs\nencode\nq\x01(X\x0c\x00\x00\x00\xc3\xbfab\xc2\x80\x00\x00\xc3\xb8\x00\x00q\x02X\x06\x00\x00\x00latin1q\x03tq\x04Rq\x05tq\x06Rq\x07." +) +assert ( + pickle.dumps(a, 2) + == b"\x80\x02c__builtin__\nbytearray\nq\x00c_codecs\nencode\nq\x01X\x0c\x00\x00\x00\xc3\xbfab\xc2\x80\x00\x00\xc3\xb8\x00\x00q\x02X\x06\x00\x00\x00latin1q\x03\x86q\x04Rq\x05\x85q\x06Rq\x07." +) +assert ( + pickle.dumps(a, 3) + == b"\x80\x03cbuiltins\nbytearray\nq\x00C\t\xffab\x80\x00\x00\xf8\x00\x00q\x01\x85q\x02Rq\x03." +) +assert ( + pickle.dumps(a, 4) + == b"\x80\x04\x95*\x00\x00\x00\x00\x00\x00\x00\x8c\x08builtins\x94\x8c\tbytearray\x94\x93\x94C\t\xffab\x80\x00\x00\xf8\x00\x00\x94\x85\x94R\x94." +) + # pickle with subclass class A(bytes): pass + a = A() a.x = 10 -a.y = A(b'123') +a.y = A(b"123") b = pickle.loads(pickle.dumps(a, 4)) assert type(a) == type(b) assert a.x == b.x assert a.y == b.y assert a == b + class B(bytearray): pass + a = B() a.x = 10 -a.y = B(b'123') +a.y = B(b"123") b = pickle.loads(pickle.dumps(a, 4)) assert type(a) == type(b) assert a.x == b.x @@ -768,4 +853,6 @@ class B(bytearray): a = bytearray() for i in range(-1, 2, 1): - assert_raises(IndexError, lambda: a[-sys.maxsize - i], _msg='bytearray index out of range') \ No newline at end of file + assert_raises( + IndexError, lambda: a[-sys.maxsize - i], _msg="bytearray index out of range" + ) diff --git a/extra_tests/snippets/builtin_bytes.py b/extra_tests/snippets/builtin_bytes.py index 2a6d0f63eb..9347fbc8fa 100644 --- a/extra_tests/snippets/builtin_bytes.py +++ b/extra_tests/snippets/builtin_bytes.py @@ -596,51 +596,56 @@ # repeat by multiply -a = b'abcd' -assert a * 0 == b'' -assert a * -1 == b'' -assert a * 1 == b'abcd' -assert a * 3 == b'abcdabcdabcd' -assert 3 * a == b'abcdabcdabcd' +a = b"abcd" +assert a * 0 == b"" +assert a * -1 == b"" +assert a * 1 == b"abcd" +assert a * 3 == b"abcdabcdabcd" +assert 3 * a == b"abcdabcdabcd" # decode -assert b'\x72\x75\x73\x74'.decode('ascii') == 'rust' -assert b'\xc2\xae\x75\x73\x74'.decode('ascii', 'replace') == '��ust' -assert b'\xc2\xae\x75\x73\x74'.decode('ascii', 'ignore') == 'ust' -assert b'\xc2\xae\x75\x73\x74'.decode('utf-8') == '®ust' -assert b'\xc2\xae\x75\x73\x74'.decode() == '®ust' -assert b'\xe4\xb8\xad\xe6\x96\x87\xe5\xad\x97'.decode('utf-8') == '中文字' +assert b"\x72\x75\x73\x74".decode("ascii") == "rust" +assert b"\xc2\xae\x75\x73\x74".decode("ascii", "replace") == "��ust" +assert b"\xc2\xae\x75\x73\x74".decode("ascii", "ignore") == "ust" +assert b"\xc2\xae\x75\x73\x74".decode("utf-8") == "®ust" +assert b"\xc2\xae\x75\x73\x74".decode() == "®ust" +assert b"\xe4\xb8\xad\xe6\x96\x87\xe5\xad\x97".decode("utf-8") == "中文字" # mod -assert b'rust%bpython%b' % (b' ', b'!') == b'rust python!' -assert b'x=%i y=%f' % (1, 2.5) == b'x=1 y=2.500000' +assert b"rust%bpython%b" % (b" ", b"!") == b"rust python!" +assert b"x=%i y=%f" % (1, 2.5) == b"x=1 y=2.500000" + # __bytes__ def test__bytes__(): - foo = b'foo\x00bar' + foo = b"foo\x00bar" assert foo.__bytes__() == foo assert type(foo.__bytes__()) == bytes + class bytes_subclass(bytes): pass - bar = bytes_subclass(b'bar\x00foo') + + bar = bytes_subclass(b"bar\x00foo") assert bar.__bytes__() == bar assert type(bar.__bytes__()) == bytes + class A: def __bytes__(self): return b"bytess" + assert bytes(A()) == b"bytess" # Issue #2125 -b = b'abc' +b = b"abc" assert bytes(b) is b # Regression to # https://github.com/RustPython/RustPython/issues/2840 -a = b'123abc!?' +a = b"123abc!?" assert id(a) == id(a) assert id(a) != id(a * -1) assert id(a) != id(a * 0) @@ -652,20 +657,24 @@ def __bytes__(self): class SubBytes(bytes): pass -b = SubBytes(b'0123abc*&') + +b = SubBytes(b"0123abc*&") assert id(b) == id(b) assert id(b) != id(b * -1) assert id(b) != id(b * 0) assert id(b) != id(b * 1) assert id(b) != id(b * 2) + class B1(bytearray): def __new__(cls, value): assert type(value) == bytes me = super().__new__(cls, value) - me.foo = 'bar' + me.foo = "bar" return me -b = B1.fromhex('a0a1a2') -assert b.foo == 'bar' -skip_if_unsupported(3,11,test__bytes__) \ No newline at end of file + +b = B1.fromhex("a0a1a2") +assert b.foo == "bar" + +skip_if_unsupported(3, 11, test__bytes__) diff --git a/extra_tests/snippets/builtin_callable.py b/extra_tests/snippets/builtin_callable.py index db554df245..52458bda94 100644 --- a/extra_tests/snippets/builtin_callable.py +++ b/extra_tests/snippets/builtin_callable.py @@ -1,25 +1,48 @@ assert not callable(1) -def f(): pass + + +def f(): + pass + + assert callable(f) assert callable(len) assert callable(lambda: 1) assert callable(int) + class C: def __init__(self): # must be defined on class self.__call__ = lambda self: 1 - def f(self): pass + + def f(self): + pass + + assert callable(C) assert not callable(C()) assert callable(C().f) + class C: - def __call__(self): pass + def __call__(self): + pass + + assert callable(C()) -class C1(C): pass + + +class C1(C): + pass + + assert callable(C1()) + + class C: __call__ = 1 + + # CPython returns true here, but fails when actually calling it assert callable(C()) diff --git a/extra_tests/snippets/builtin_chr.py b/extra_tests/snippets/builtin_chr.py index 9b95452bda..6fa56203d7 100644 --- a/extra_tests/snippets/builtin_chr.py +++ b/extra_tests/snippets/builtin_chr.py @@ -4,5 +4,7 @@ assert "é" == chr(233) assert "🤡" == chr(129313) -assert_raises(TypeError, chr, _msg='chr() takes exactly one argument (0 given)') -assert_raises(ValueError, chr, 0x110005, _msg='ValueError: chr() arg not in range(0x110000)') +assert_raises(TypeError, chr, _msg="chr() takes exactly one argument (0 given)") +assert_raises( + ValueError, chr, 0x110005, _msg="ValueError: chr() arg not in range(0x110000)" +) diff --git a/extra_tests/snippets/builtin_dict.py b/extra_tests/snippets/builtin_dict.py index 3ccea97232..abd93539a5 100644 --- a/extra_tests/snippets/builtin_dict.py +++ b/extra_tests/snippets/builtin_dict.py @@ -5,49 +5,49 @@ assert len({}) == 0 assert len({"a": "b"}) == 1 assert len({"a": "b", "b": 1}) == 2 -assert len({"a": "b", "b": 1, "a" + "b": 2*2}) == 3 +assert len({"a": "b", "b": 1, "a" + "b": 2 * 2}) == 3 d = {} -d['a'] = d +d["a"] = d assert repr(d) == "{'a': {...}}" -assert {'a': 123}.get('a') == 123 -assert {'a': 123}.get('b') == None -assert {'a': 123}.get('b', 456) == 456 +assert {"a": 123}.get("a") == 123 +assert {"a": 123}.get("b") == None +assert {"a": 123}.get("b", 456) == 456 -d = {'a': 123, 'b': 456} -assert list(reversed(d)) == ['b', 'a'] -assert list(reversed(d.keys())) == ['b', 'a'] +d = {"a": 123, "b": 456} +assert list(reversed(d)) == ["b", "a"] +assert list(reversed(d.keys())) == ["b", "a"] assert list(reversed(d.values())) == [456, 123] -assert list(reversed(d.items())) == [('b', 456), ('a', 123)] +assert list(reversed(d.items())) == [("b", 456), ("a", 123)] with assert_raises(StopIteration): dict_reversed = reversed(d) for _ in range(len(d) + 1): next(dict_reversed) -assert 'dict' in dict().__doc__ +assert "dict" in dict().__doc__ -d = {'a': 123, 'b': 456} +d = {"a": 123, "b": 456} assert 1 not in d.items() -assert 'a' not in d.items() -assert 'a', 123 not in d.items() +assert "a" not in d.items() +assert "a", 123 not in d.items() assert () not in d.items() assert (1) not in d.items() -assert ('a') not in d.items() -assert ('a', 123) in d.items() -assert ('b', 456) in d.items() -assert ('a', 123, 3) not in d.items() -assert ('a', 123, 'b', 456) not in d.items() +assert ("a") not in d.items() +assert ("a", 123) in d.items() +assert ("b", 456) in d.items() +assert ("a", 123, 3) not in d.items() +assert ("a", 123, "b", 456) not in d.items() -d = {1: 10, "a": "ABC", (3,4): 5} +d = {1: 10, "a": "ABC", (3, 4): 5} assert 1 in d.keys() assert (1) in d.keys() assert "a" in d.keys() -assert (3,4) in d.keys() +assert (3, 4) in d.keys() assert () not in d.keys() assert 10 not in d.keys() assert (1, 10) not in d.keys() assert "abc" not in d.keys() -assert ((3,4),5) not in d.keys() +assert ((3, 4), 5) not in d.keys() d1 = {"a": 1, "b": 2} d2 = {"c": 3, "d": 4} @@ -64,55 +64,55 @@ assert not d1.keys().isdisjoint(d2.keys()) -assert dict(a=2, b=3) == {'a': 2, 'b': 3} -assert dict({'a': 2, 'b': 3}, b=4) == {'a': 2, 'b': 4} -assert dict([('a', 2), ('b', 3)]) == {'a': 2, 'b': 3} +assert dict(a=2, b=3) == {"a": 2, "b": 3} +assert dict({"a": 2, "b": 3}, b=4) == {"a": 2, "b": 4} +assert dict([("a", 2), ("b", 3)]) == {"a": 2, "b": 3} assert {} == {} -assert not {'a': 2} == {} -assert not {} == {'a': 2} -assert not {'b': 2} == {'a': 2} -assert not {'a': 4} == {'a': 2} -assert {'a': 2} == {'a': 2} +assert not {"a": 2} == {} +assert not {} == {"a": 2} +assert not {"b": 2} == {"a": 2} +assert not {"a": 4} == {"a": 2} +assert {"a": 2} == {"a": 2} -nan = float('nan') -assert {'a': nan} == {'a': nan} +nan = float("nan") +assert {"a": nan} == {"a": nan} -a = {'g': 5} -b = {'a': a, 'd': 9} +a = {"g": 5} +b = {"a": a, "d": 9} c = dict(b) -c['d'] = 3 -c['a']['g'] = 2 -assert a == {'g': 2} -assert b == {'a': a, 'd': 9} +c["d"] = 3 +c["a"]["g"] = 2 +assert a == {"g": 2} +assert b == {"a": a, "d": 9} a.clear() assert len(a) == 0 -a = {'a': 5, 'b': 6} +a = {"a": 5, "b": 6} res = set() for value in a.values(): - res.add(value) -assert res == set([5,6]) + res.add(value) +assert res == set([5, 6]) count = 0 -for (key, value) in a.items(): - assert a[key] == value - count += 1 +for key, value in a.items(): + assert a[key] == value + count += 1 assert count == len(a) res = set() for key in a.keys(): - res.add(key) -assert res == set(['a','b']) + res.add(key) +assert res == set(["a", "b"]) # Deleted values are correctly skipped over: -x = {'a': 1, 'b': 2, 'c': 3, 'd': 3} -del x['c'] +x = {"a": 1, "b": 2, "c": 3, "d": 3} +del x["c"] it = iter(x.items()) -assert ('a', 1) == next(it) -assert ('b', 2) == next(it) -assert ('d', 3) == next(it) +assert ("a", 1) == next(it) +assert ("b", 2) == next(it) +assert ("d", 3) == next(it) with assert_raises(StopIteration): next(it) @@ -121,7 +121,7 @@ assert cm.exception.args[0] == 10 # Iterating a dictionary is just its keys: -assert ['a', 'b', 'd'] == list(x) +assert ["a", "b", "d"] == list(x) # Iterating view captures dictionary when iterated. data = {1: 2, 3: 4} @@ -140,12 +140,12 @@ # But we can't add or delete items during iteration. d = {} a = iter(d.items()) -d['a'] = 2 +d["a"] = 2 b = iter(d.items()) -assert ('a', 2) == next(b) +assert ("a", 2) == next(b) with assert_raises(RuntimeError): next(a) -del d['a'] +del d["a"] with assert_raises(RuntimeError): next(b) @@ -164,21 +164,23 @@ x[(5, 6)] = 5 with assert_raises(TypeError): - x[[]] # Unhashable type. + x[[]] # Unhashable type. x["here"] = "here" assert x.get("not here", "default") == "default" assert x.get("here", "default") == "here" assert x.get("not here") == None + class LengthDict(dict): def __getitem__(self, k): return len(k) + x = LengthDict() assert type(x) == LengthDict -assert x['word'] == 4 -assert x.get('word') is None +assert x["word"] == 4 +assert x.get("word") is None assert 5 == eval("a + word", LengthDict()) @@ -189,15 +191,19 @@ def __missing__(self, k): self[k] = v return v + x = Squares() assert x[-5] == 25 + # An object that hashes to the same value always, and compares equal if any its values match. class Hashable(object): def __init__(self, *args): self.values = args + def __hash__(self): return 1 + def __eq__(self, other): for x in self.values: for y in other.values: @@ -205,39 +211,40 @@ def __eq__(self, other): return True return False + x = {} -x[Hashable(1,2)] = 8 +x[Hashable(1, 2)] = 8 -assert x[Hashable(1,2)] == 8 -assert x[Hashable(3,1)] == 8 +assert x[Hashable(1, 2)] == 8 +assert x[Hashable(3, 1)] == 8 x[Hashable(8)] = 19 -x[Hashable(19,8)] = 1 +x[Hashable(19, 8)] = 1 assert x[Hashable(8)] == 1 assert len(x) == 2 -assert list({'a': 2, 'b': 10}) == ['a', 'b'] +assert list({"a": 2, "b": 10}) == ["a", "b"] x = {} -x['a'] = 2 -x['b'] = 10 -assert list(x) == ['a', 'b'] +x["a"] = 2 +x["b"] = 10 +assert list(x) == ["a", "b"] y = x.copy() -x['c'] = 12 -assert y == {'a': 2, 'b': 10} +x["c"] = 12 +assert y == {"a": 2, "b": 10} -y.update({'c': 19, "d": -1, 'b': 12}) -assert y == {'a': 2, 'b': 12, 'c': 19, 'd': -1} +y.update({"c": 19, "d": -1, "b": 12}) +assert y == {"a": 2, "b": 12, "c": 19, "d": -1} y.update(y) -assert y == {'a': 2, 'b': 12, 'c': 19, 'd': -1} # hasn't changed +assert y == {"a": 2, "b": 12, "c": 19, "d": -1} # hasn't changed # KeyError has object that used as key as an .args[0] with assert_raises(KeyError) as cm: - x['not here'] + x["not here"] assert cm.exception.args[0] == "not here" with assert_raises(KeyError) as cm: - x.pop('not here') + x.pop("not here") assert cm.exception.args[0] == "not here" with assert_raises(KeyError) as cm: @@ -247,7 +254,11 @@ def __eq__(self, other): x.pop(10) assert cm.exception.args[0] == 10 -class MyClass: pass + +class MyClass: + pass + + obj = MyClass() with assert_raises(KeyError) as cm: @@ -257,49 +268,65 @@ class MyClass: pass x.pop(obj) assert cm.exception.args[0] == obj -x = {1: 'a', '1': None} -assert x.pop(1) == 'a' -assert x.pop('1') is None +x = {1: "a", "1": None} +assert x.pop(1) == "a" +assert x.pop("1") is None assert x == {} -x = {1: 'a'} -assert (1, 'a') == x.popitem() +x = {1: "a"} +assert (1, "a") == x.popitem() assert x == {} with assert_raises(KeyError) as cm: x.popitem() -assert cm.exception.args == ('popitem(): dictionary is empty',) +assert cm.exception.args == ("popitem(): dictionary is empty",) -x = {'a': 4} -assert 4 == x.setdefault('a', 0) -assert x['a'] == 4 -assert 0 == x.setdefault('b', 0) -assert x['b'] == 0 -assert None == x.setdefault('c') -assert x['c'] is None +x = {"a": 4} +assert 4 == x.setdefault("a", 0) +assert x["a"] == 4 +assert 0 == x.setdefault("b", 0) +assert x["b"] == 0 +assert None == x.setdefault("c") +assert x["c"] is None assert {1: None, "b": None} == dict.fromkeys([1, "b"]) assert {1: 0, "b": 0} == dict.fromkeys([1, "b"], 0) -x = {'a': 1, 'b': 1, 'c': 1} -y = {'b': 2, 'c': 2, 'd': 2} -z = {'c': 3, 'd': 3, 'e': 3} +x = {"a": 1, "b": 1, "c": 1} +y = {"b": 2, "c": 2, "d": 2} +z = {"c": 3, "d": 3, "e": 3} w = {1: 1, **x, 2: 2, **y, 3: 3, **z, 4: 4} -assert w == {1: 1, 'a': 1, 'b': 2, 'c': 3, 2: 2, 'd': 3, 3: 3, 'e': 3, 4: 4} # not in cpython test suite +assert w == { + 1: 1, + "a": 1, + "b": 2, + "c": 3, + 2: 2, + "d": 3, + 3: 3, + "e": 3, + 4: 4, +} # not in cpython test suite assert str({True: True, 1.0: 1.0}) == str({True: 1.0}) + class A: def __hash__(self): return 1 + def __eq__(self, other): return isinstance(other, A) + + class B: def __hash__(self): return 1 + def __eq__(self, other): return isinstance(other, B) + s = {1: 0, A(): 1, B(): 2} assert len(s) == 3 assert s[1] == 0 @@ -307,19 +334,19 @@ def __eq__(self, other): assert s[B()] == 2 # Test dict usage in set with star expressions! -a = {'bla': 2} -b = {'c': 44, 'bla': 332, 'd': 6} -x = ['bla', 'c', 'd', 'f'] +a = {"bla": 2} +b = {"c": 44, "bla": 332, "d": 6} +x = ["bla", "c", "d", "f"] c = {*a, *b, *x} # print(c, type(c)) assert isinstance(c, set) -assert c == {'bla', 'c', 'd', 'f'} +assert c == {"bla", "c", "d", "f"} assert not {}.__ne__({}) -assert {}.__ne__({'a':'b'}) +assert {}.__ne__({"a": "b"}) assert {}.__ne__(1) == NotImplemented -it = iter({0: 1, 2: 3, 4:5, 6:7}) +it = iter({0: 1, 2: 3, 4: 5, 6: 7}) assert it.__length_hint__() == 4 next(it) assert it.__length_hint__() == 3 diff --git a/extra_tests/snippets/builtin_dict_union.py b/extra_tests/snippets/builtin_dict_union.py index f33f32a5e4..ab3fa65d37 100644 --- a/extra_tests/snippets/builtin_dict_union.py +++ b/extra_tests/snippets/builtin_dict_union.py @@ -1,78 +1,91 @@ - from testutils import assert_raises, skip_if_unsupported + def test_dunion_ior0(): - a={1:2,2:3} - b={3:4,5:6} - a|=b + a = {1: 2, 2: 3} + b = {3: 4, 5: 6} + a |= b + + assert a == {1: 2, 2: 3, 3: 4, 5: 6}, f"wrong value assigned {a=}" + assert b == {3: 4, 5: 6}, f"right hand side modified, {b=}" - assert a == {1:2,2:3,3:4,5:6}, f"wrong value assigned {a=}" - assert b == {3:4,5:6}, f"right hand side modified, {b=}" def test_dunion_or0(): - a={1:2,2:3} - b={3:4,5:6} - c=a|b + a = {1: 2, 2: 3} + b = {3: 4, 5: 6} + c = a | b - assert a == {1:2,2:3}, f"left hand side of non-assignment operator modified {a=}" - assert b == {3:4,5:6}, f"right hand side of non-assignment operator modified, {b=}" - assert c == {1:2,2:3, 3:4, 5:6}, f"unexpected result of dict union {c=}" + assert a == {1: 2, 2: 3}, f"left hand side of non-assignment operator modified {a=}" + assert b == {3: 4, 5: 6}, ( + f"right hand side of non-assignment operator modified, {b=}" + ) + assert c == {1: 2, 2: 3, 3: 4, 5: 6}, f"unexpected result of dict union {c=}" def test_dunion_or1(): - a={1:2,2:3} - b={3:4,5:6} - c=a.__or__(b) + a = {1: 2, 2: 3} + b = {3: 4, 5: 6} + c = a.__or__(b) - assert a == {1:2,2:3}, f"left hand side of non-assignment operator modified {a=}" - assert b == {3:4,5:6}, f"right hand side of non-assignment operator modified, {b=}" - assert c == {1:2,2:3, 3:4, 5:6}, f"unexpected result of dict union {c=}" + assert a == {1: 2, 2: 3}, f"left hand side of non-assignment operator modified {a=}" + assert b == {3: 4, 5: 6}, ( + f"right hand side of non-assignment operator modified, {b=}" + ) + assert c == {1: 2, 2: 3, 3: 4, 5: 6}, f"unexpected result of dict union {c=}" def test_dunion_ror0(): - a={1:2,2:3} - b={3:4,5:6} - c=b.__ror__(a) + a = {1: 2, 2: 3} + b = {3: 4, 5: 6} + c = b.__ror__(a) - assert a == {1:2,2:3}, f"left hand side of non-assignment operator modified {a=}" - assert b == {3:4,5:6}, f"right hand side of non-assignment operator modified, {b=}" - assert c == {1:2,2:3, 3:4, 5:6}, f"unexpected result of dict union {c=}" + assert a == {1: 2, 2: 3}, f"left hand side of non-assignment operator modified {a=}" + assert b == {3: 4, 5: 6}, ( + f"right hand side of non-assignment operator modified, {b=}" + ) + assert c == {1: 2, 2: 3, 3: 4, 5: 6}, f"unexpected result of dict union {c=}" def test_dunion_other_types(): def perf_test_or(other_obj): - d={1:2} + d = {1: 2} return d.__or__(other_obj) is NotImplemented def perf_test_ror(other_obj): - d={1:2} + d = {1: 2} return d.__ror__(other_obj) is NotImplemented - test_fct={'__or__':perf_test_or, '__ror__':perf_test_ror} - others=['FooBar', 42, [36], set([19]), ['aa'], None] - for tfn,tf in test_fct.items(): + test_fct = {"__or__": perf_test_or, "__ror__": perf_test_ror} + others = ["FooBar", 42, [36], set([19]), ["aa"], None] + for tfn, tf in test_fct.items(): for other in others: assert tf(other), f"Failed: dict {tfn}, accepted {other}" # __ior__() has different behavior and needs to be tested separately d = {1: 2} - assert_raises(ValueError, - lambda: d.__ior__('FooBar'), - _msg='dictionary update sequence element #0 has length 1; 2 is required') - assert_raises(TypeError, - lambda: d.__ior__(42), - _msg='\'int\' object is not iterable') - assert_raises(TypeError, - lambda: d.__ior__([36]), - _msg='cannot convert dictionary update sequence element #0 to a sequence') - assert_raises(TypeError, - lambda: d.__ior__(set([36])), - _msg='cannot convert dictionary update sequence element #0 to a sequence') - res = d.__ior__(['aa']) - assert res == {1: 2, 'a': 'a'}, f"unexpected result of dict union {res=}" - assert_raises(TypeError, - lambda: d.__ior__(None), - _msg='TypeError: \'NoneType\' object is not iterable') + assert_raises( + ValueError, + lambda: d.__ior__("FooBar"), + _msg="dictionary update sequence element #0 has length 1; 2 is required", + ) + assert_raises(TypeError, lambda: d.__ior__(42), _msg="'int' object is not iterable") + assert_raises( + TypeError, + lambda: d.__ior__([36]), + _msg="cannot convert dictionary update sequence element #0 to a sequence", + ) + assert_raises( + TypeError, + lambda: d.__ior__(set([36])), + _msg="cannot convert dictionary update sequence element #0 to a sequence", + ) + res = d.__ior__(["aa"]) + assert res == {1: 2, "a": "a"}, f"unexpected result of dict union {res=}" + assert_raises( + TypeError, + lambda: d.__ior__(None), + _msg="TypeError: 'NoneType' object is not iterable", + ) skip_if_unsupported(3, 9, test_dunion_ior0) diff --git a/extra_tests/snippets/builtin_dir.py b/extra_tests/snippets/builtin_dir.py index 3e808597c1..cd2c8c33a2 100644 --- a/extra_tests/snippets/builtin_dir.py +++ b/extra_tests/snippets/builtin_dir.py @@ -1,9 +1,11 @@ assert isinstance(dir(), list) -assert '__builtins__' in dir() +assert "__builtins__" in dir() + class A: - def test(): - pass + def test(): + pass + a = A() @@ -13,24 +15,30 @@ def test(): a.x = 3 assert "x" in dir(a), "x not in a" + class B(A): - def __dir__(self): - return ('q', 'h') + def __dir__(self): + return ("q", "h") + # Gets sorted and turned into a list -assert ['h', 'q'] == dir(B()) +assert ["h", "q"] == dir(B()) # This calls type.__dir__ so isn't changed (but inheritance works)! -assert 'test' in dir(A) +assert "test" in dir(A) + # eval() takes any mapping-like type, so dir() must support them # TODO: eval() should take any mapping as locals, not just dict-derived types class A(dict): - def __getitem__(self, x): - return dir - def keys(self): - yield 6 - yield 5 + def __getitem__(self, x): + return dir + + def keys(self): + yield 6 + yield 5 + + assert eval("dir()", {}, A()) == [5, 6] import socket diff --git a/extra_tests/snippets/builtin_divmod.py b/extra_tests/snippets/builtin_divmod.py index 5a9443afe8..f62d0f8eea 100644 --- a/extra_tests/snippets/builtin_divmod.py +++ b/extra_tests/snippets/builtin_divmod.py @@ -1,9 +1,9 @@ from testutils import assert_raises assert divmod(11, 3) == (3, 2) -assert divmod(8,11) == (0, 8) +assert divmod(8, 11) == (0, 8) assert divmod(0.873, 0.252) == (3.0, 0.11699999999999999) assert divmod(-86340, 86400) == (-1, 60) -assert_raises(ZeroDivisionError, divmod, 5, 0, _msg='divmod by zero') -assert_raises(ZeroDivisionError, divmod, 5.0, 0.0, _msg='divmod by zero') +assert_raises(ZeroDivisionError, divmod, 5, 0, _msg="divmod by zero") +assert_raises(ZeroDivisionError, divmod, 5.0, 0.0, _msg="divmod by zero") diff --git a/extra_tests/snippets/builtin_ellipsis.py b/extra_tests/snippets/builtin_ellipsis.py index 5316b9f865..cf99f3cc82 100644 --- a/extra_tests/snippets/builtin_ellipsis.py +++ b/extra_tests/snippets/builtin_ellipsis.py @@ -1,5 +1,3 @@ - - a = ... b = ... c = type(a)() # Test singleton behavior @@ -11,22 +9,22 @@ assert b is d assert d is e -assert Ellipsis.__repr__() == 'Ellipsis' -assert Ellipsis.__reduce__() == 'Ellipsis' +assert Ellipsis.__repr__() == "Ellipsis" +assert Ellipsis.__reduce__() == "Ellipsis" assert type(Ellipsis).__new__(type(Ellipsis)) == Ellipsis -assert type(Ellipsis).__reduce__(Ellipsis) == 'Ellipsis' +assert type(Ellipsis).__reduce__(Ellipsis) == "Ellipsis" try: type(Ellipsis).__new__(type(1)) except TypeError: pass else: - assert False, '`Ellipsis.__new__` should only accept `type(Ellipsis)` as argument' + assert False, "`Ellipsis.__new__` should only accept `type(Ellipsis)` as argument" try: type(Ellipsis).__reduce__(1) except TypeError: pass else: - assert False, '`Ellipsis.__reduce__` should only accept `Ellipsis` as argument' + assert False, "`Ellipsis.__reduce__` should only accept `Ellipsis` as argument" assert Ellipsis is ... Ellipsis = 2 diff --git a/extra_tests/snippets/builtin_enumerate.py b/extra_tests/snippets/builtin_enumerate.py index 35edadd1d7..0f107ea7ae 100644 --- a/extra_tests/snippets/builtin_enumerate.py +++ b/extra_tests/snippets/builtin_enumerate.py @@ -1,9 +1,14 @@ -assert list(enumerate(['a', 'b', 'c'])) == [(0, 'a'), (1, 'b'), (2, 'c')] +assert list(enumerate(["a", "b", "c"])) == [(0, "a"), (1, "b"), (2, "c")] assert type(enumerate([])) == enumerate -assert list(enumerate(['a', 'b', 'c'], -100)) == [(-100, 'a'), (-99, 'b'), (-98, 'c')] -assert list(enumerate(['a', 'b', 'c'], 2**200)) == [(2**200, 'a'), (2**200 + 1, 'b'), (2**200 + 2, 'c')] +assert list(enumerate(["a", "b", "c"], -100)) == [(-100, "a"), (-99, "b"), (-98, "c")] +assert list(enumerate(["a", "b", "c"], 2**200)) == [ + (2**200, "a"), + (2**200 + 1, "b"), + (2**200 + 2, "c"), +] + # test infinite iterator class Counter(object): diff --git a/extra_tests/snippets/builtin_eval.py b/extra_tests/snippets/builtin_eval.py index 6375bd0c1a..314abee2bb 100644 --- a/extra_tests/snippets/builtin_eval.py +++ b/extra_tests/snippets/builtin_eval.py @@ -1,4 +1,4 @@ -assert 3 == eval('1+2') +assert 3 == eval("1+2") -code = compile('5+3', 'x.py', 'eval') +code = compile("5+3", "x.py", "eval") assert eval(code) == 8 diff --git a/extra_tests/snippets/builtin_exceptions.py b/extra_tests/snippets/builtin_exceptions.py index 4bff9c0096..82aa54d632 100644 --- a/extra_tests/snippets/builtin_exceptions.py +++ b/extra_tests/snippets/builtin_exceptions.py @@ -3,41 +3,48 @@ import pickle import sys + def exceptions_eq(e1, e2): return type(e1) is type(e2) and e1.args == e2.args + def round_trip_repr(e): return exceptions_eq(e, eval(repr(e))) + # KeyError empty_exc = KeyError() -assert str(empty_exc) == '' +assert str(empty_exc) == "" assert round_trip_repr(empty_exc) assert len(empty_exc.args) == 0 assert type(empty_exc.args) == tuple -exc = KeyError('message') +exc = KeyError("message") assert str(exc) == "'message'" assert round_trip_repr(exc) assert LookupError.__str__(exc) == "message" -exc = KeyError('message', 'another message') +exc = KeyError("message", "another message") assert str(exc) == "('message', 'another message')" assert round_trip_repr(exc) -assert exc.args[0] == 'message' -assert exc.args[1] == 'another message' +assert exc.args[0] == "message" +assert exc.args[1] == "another message" + class A: def __repr__(self): - return 'A()' + return "A()" + def __str__(self): - return 'str' + return "str" + def __eq__(self, other): return type(other) is A + exc = KeyError(A()) -assert str(exc) == 'A()' +assert str(exc) == "A()" assert round_trip_repr(exc) # ImportError / ModuleNotFoundError @@ -47,33 +54,32 @@ def __eq__(self, other): assert exc.msg is None assert exc.args == () -exc = ImportError('hello') +exc = ImportError("hello") assert exc.name is None assert exc.path is None -assert exc.msg == 'hello' -assert exc.args == ('hello',) +assert exc.msg == "hello" +assert exc.args == ("hello",) -exc = ImportError('hello', name='name', path='path') -assert exc.name == 'name' -assert exc.path == 'path' -assert exc.msg == 'hello' -assert exc.args == ('hello',) +exc = ImportError("hello", name="name", path="path") +assert exc.name == "name" +assert exc.path == "path" +assert exc.msg == "hello" +assert exc.args == ("hello",) class NewException(Exception): - - def __init__(self, value): - self.value = value + def __init__(self, value): + self.value = value try: - raise NewException("test") + raise NewException("test") except NewException as e: - assert e.value == "test" + assert e.value == "test" -exc = SyntaxError('msg', 1, 2, 3, 4, 5) -assert exc.msg == 'msg' +exc = SyntaxError("msg", 1, 2, 3, 4, 5) +assert exc.msg == "msg" assert exc.filename is None assert exc.lineno is None assert exc.offset is None @@ -82,11 +88,12 @@ def __init__(self, value): # Regression to: # https://github.com/RustPython/RustPython/issues/2779 + class MyError(Exception): pass -e = MyError('message') +e = MyError("message") try: raise e from e @@ -97,23 +104,23 @@ class MyError(Exception): assert exc.__cause__ is e assert exc.__context__ is None else: - assert False, 'exception not raised' + assert False, "exception not raised" try: - raise ValueError('test') from e + raise ValueError("test") from e except ValueError as exc: sys.excepthook(type(exc), exc, exc.__traceback__) # ok, will print two excs assert isinstance(exc, ValueError) assert exc.__cause__ is e assert exc.__context__ is None else: - assert False, 'exception not raised' + assert False, "exception not raised" # New case: # potential recursion on `__context__` field -e = MyError('message') +e = MyError("message") try: try: @@ -121,15 +128,15 @@ class MyError(Exception): except MyError as exc: raise e else: - assert False, 'exception not raised' + assert False, "exception not raised" except MyError as exc: sys.excepthook(type(exc), exc, exc.__traceback__) assert exc.__cause__ is None assert exc.__context__ is None else: - assert False, 'exception not raised' + assert False, "exception not raised" -e = MyError('message') +e = MyError("message") try: try: @@ -137,15 +144,15 @@ class MyError(Exception): except MyError as exc: raise exc else: - assert False, 'exception not raised' + assert False, "exception not raised" except MyError as exc: sys.excepthook(type(exc), exc, exc.__traceback__) assert exc.__cause__ is None assert exc.__context__ is None else: - assert False, 'exception not raised' + assert False, "exception not raised" -e = MyError('message') +e = MyError("message") try: try: @@ -153,15 +160,15 @@ class MyError(Exception): except MyError as exc: raise e from e else: - assert False, 'exception not raised' + assert False, "exception not raised" except MyError as exc: sys.excepthook(type(exc), exc, exc.__traceback__) assert exc.__cause__ is e assert exc.__context__ is None else: - assert False, 'exception not raised' + assert False, "exception not raised" -e = MyError('message') +e = MyError("message") try: try: @@ -169,23 +176,25 @@ class MyError(Exception): except MyError as exc: raise exc from e else: - assert False, 'exception not raised' + assert False, "exception not raised" except MyError as exc: sys.excepthook(type(exc), exc, exc.__traceback__) assert exc.__cause__ is e assert exc.__context__ is None else: - assert False, 'exception not raised' + assert False, "exception not raised" # New case: # two exception in a recursion loop + class SubError(MyError): pass -e = MyError('message') -d = SubError('sub') + +e = MyError("message") +d = SubError("sub") try: @@ -197,9 +206,9 @@ class SubError(MyError): assert exc.__cause__ is d assert exc.__context__ is None else: - assert False, 'exception not raised' + assert False, "exception not raised" -e = MyError('message') +e = MyError("message") try: raise d from e @@ -210,20 +219,20 @@ class SubError(MyError): assert exc.__cause__ is e assert exc.__context__ is None else: - assert False, 'exception not raised' + assert False, "exception not raised" # New case: # explicit `__context__` manipulation. -e = MyError('message') +e = MyError("message") e.__context__ = e try: raise e except MyError as exc: # It was a segmentation fault before, will print info to stdout: - if platform.python_implementation() == 'RustPython': + if platform.python_implementation() == "RustPython": # For some reason `CPython` hangs on this code: sys.excepthook(type(exc), exc, exc.__traceback__) assert isinstance(exc, MyError) @@ -235,30 +244,36 @@ class SubError(MyError): # https://github.com/RustPython/RustPython/issues/2771 # `BaseException` and `Exception`: -assert BaseException.__new__.__qualname__ == 'BaseException.__new__' -assert BaseException.__init__.__qualname__ == 'BaseException.__init__' +assert BaseException.__new__.__qualname__ == "BaseException.__new__" +assert BaseException.__init__.__qualname__ == "BaseException.__init__" assert BaseException().__dict__ == {} -assert Exception.__new__.__qualname__ == 'Exception.__new__', Exception.__new__.__qualname__ -assert Exception.__init__.__qualname__ == 'Exception.__init__', Exception.__init__.__qualname__ +assert Exception.__new__.__qualname__ == "Exception.__new__", ( + Exception.__new__.__qualname__ +) +assert Exception.__init__.__qualname__ == "Exception.__init__", ( + Exception.__init__.__qualname__ +) assert Exception().__dict__ == {} # Extends `BaseException`, simple: -assert KeyboardInterrupt.__new__.__qualname__ == 'KeyboardInterrupt.__new__', KeyboardInterrupt.__new__.__qualname__ -assert KeyboardInterrupt.__init__.__qualname__ == 'KeyboardInterrupt.__init__' +assert KeyboardInterrupt.__new__.__qualname__ == "KeyboardInterrupt.__new__", ( + KeyboardInterrupt.__new__.__qualname__ +) +assert KeyboardInterrupt.__init__.__qualname__ == "KeyboardInterrupt.__init__" assert KeyboardInterrupt().__dict__ == {} # Extends `Exception`, simple: -assert TypeError.__new__.__qualname__ == 'TypeError.__new__' -assert TypeError.__init__.__qualname__ == 'TypeError.__init__' +assert TypeError.__new__.__qualname__ == "TypeError.__new__" +assert TypeError.__init__.__qualname__ == "TypeError.__init__" assert TypeError().__dict__ == {} # Extends `Exception`, complex: -assert OSError.__new__.__qualname__ == 'OSError.__new__' -assert OSError.__init__.__qualname__ == 'OSError.__init__' +assert OSError.__new__.__qualname__ == "OSError.__new__" +assert OSError.__init__.__qualname__ == "OSError.__init__" assert OSError().__dict__ == {} assert OSError.errno assert OSError.strerror @@ -299,7 +314,7 @@ class SubError(MyError): assert x.filename2 == None assert str(x) == "0" -w = OSError('foo') +w = OSError("foo") assert w.errno == None assert not sys.platform.startswith("win") or w.winerror == None assert w.strerror == None @@ -315,7 +330,7 @@ class SubError(MyError): assert x.filename2 == None assert str(x) == "foo" -w = OSError('a', 'b', 'c', 'd', 'e', 'f') +w = OSError("a", "b", "c", "d", "e", "f") assert w.errno == None assert not sys.platform.startswith("win") or w.winerror == None assert w.strerror == None @@ -332,12 +347,10 @@ class SubError(MyError): assert str(x) == "('a', 'b', 'c', 'd', 'e', 'f')" # Custom `__new__` and `__init__`: -assert ImportError.__init__.__qualname__ == 'ImportError.__init__' -assert ImportError(name='a').name == 'a' -assert ( - ModuleNotFoundError.__init__.__qualname__ == 'ModuleNotFoundError.__init__' -) -assert ModuleNotFoundError(name='a').name == 'a' +assert ImportError.__init__.__qualname__ == "ImportError.__init__" +assert ImportError(name="a").name == "a" +assert ModuleNotFoundError.__init__.__qualname__ == "ModuleNotFoundError.__init__" +assert ModuleNotFoundError(name="a").name == "a" # Check that all exceptions have string `__doc__`: diff --git a/extra_tests/snippets/builtin_exec.py b/extra_tests/snippets/builtin_exec.py index 289f878cc0..2eae90e91c 100644 --- a/extra_tests/snippets/builtin_exec.py +++ b/extra_tests/snippets/builtin_exec.py @@ -3,11 +3,11 @@ d = {} exec("def square(x):\n return x * x\n", {}, d) -assert 16 == d['square'](4) +assert 16 == d["square"](4) -exec("assert 2 == x", {}, {'x': 2}) -exec("assert 2 == x", {'x': 2}, {}) -exec("assert 4 == x", {'x': 2}, {'x': 4}) +exec("assert 2 == x", {}, {"x": 2}) +exec("assert 2 == x", {"x": 2}, {}) +exec("assert 4 == x", {"x": 2}, {"x": 4}) exec("assert max(1, 2) == 2", {}, {}) @@ -16,9 +16,11 @@ # Local environment shouldn't replace global environment: exec("assert max(1, 5, square(5)) == 25", None, {}) + # Closures aren't available if local scope is replaced: def g(): seven = "seven" + def f(): try: exec("seven", None, {}) @@ -26,7 +28,10 @@ def f(): pass else: raise NameError("seven shouldn't be in scope") + f() + + g() try: @@ -37,16 +42,16 @@ def f(): raise TypeError("exec should fail unless globals is a dict or None") g = globals() -g['x'] = 2 -exec('x += 2') +g["x"] = 2 +exec("x += 2") assert x == 4 # noqa: F821 -assert g['x'] == x # noqa: F821 +assert g["x"] == x # noqa: F821 exec("del x") -assert 'x' not in g +assert "x" not in g -assert 'g' in globals() -assert 'g' in locals() +assert "g" in globals() +assert "g" in locals() exec("assert 'g' in globals()") exec("assert 'g' in locals()") exec("assert 'g' not in globals()", {}) @@ -54,13 +59,15 @@ def f(): del g + def f(): g = 1 - assert 'g' not in globals() - assert 'g' in locals() + assert "g" not in globals() + assert "g" in locals() exec("assert 'g' not in globals()") exec("assert 'g' in locals()") exec("assert 'g' not in globals()", {}) exec("assert 'g' not in locals()", {}) + f() diff --git a/extra_tests/snippets/builtin_exit.py b/extra_tests/snippets/builtin_exit.py index f6dc387322..a61ddbc6d8 100644 --- a/extra_tests/snippets/builtin_exit.py +++ b/extra_tests/snippets/builtin_exit.py @@ -36,4 +36,4 @@ sys.exit(1) with assert_raises(SystemExit): - sys.exit("AB") \ No newline at end of file + sys.exit("AB") diff --git a/extra_tests/snippets/builtin_format.py b/extra_tests/snippets/builtin_format.py index 6a8e6077ee..ac96b6545b 100644 --- a/extra_tests/snippets/builtin_format.py +++ b/extra_tests/snippets/builtin_format.py @@ -2,37 +2,52 @@ assert format(5, "b") == "101" -assert_raises(TypeError, format, 2, 3, _msg='format called with number') +assert_raises(TypeError, format, 2, 3, _msg="format called with number") assert format({}) == "{}" -assert_raises(TypeError, format, {}, 'b', _msg='format_spec not empty for dict') +assert_raises(TypeError, format, {}, "b", _msg="format_spec not empty for dict") + class BadFormat: def __format__(self, spec): return 42 + + assert_raises(TypeError, format, BadFormat()) + def test_zero_padding(): i = 1 - assert f'{i:04d}' == '0001' + assert f"{i:04d}" == "0001" + test_zero_padding() -assert '{:,}'.format(100) == '100' -assert '{:,}'.format(1024) == '1,024' -assert '{:_}'.format(65536) == '65_536' -assert '{:_}'.format(4294967296) == '4_294_967_296' -assert f'{100:_}' == '100' -assert f'{1024:_}' == '1_024' -assert f'{65536:,}' == '65,536' -assert f'{4294967296:,}' == '4,294,967,296' -assert 'F' == "{0:{base}}".format(15, base="X") -assert f'{255:#X}' == "0XFF" +assert "{:,}".format(100) == "100" +assert "{:,}".format(1024) == "1,024" +assert "{:_}".format(65536) == "65_536" +assert "{:_}".format(4294967296) == "4_294_967_296" +assert f"{100:_}" == "100" +assert f"{1024:_}" == "1_024" +assert f"{65536:,}" == "65,536" +assert f"{4294967296:,}" == "4,294,967,296" +assert "F" == "{0:{base}}".format(15, base="X") +assert f"{255:#X}" == "0XFF" assert f"{65:c}" == "A" -assert f"{0x1f5a5:c}" == "🖥" -assert_raises(ValueError, "{:+c}".format, 1, _msg="Sign not allowed with integer format specifier 'c'") -assert_raises(ValueError, "{:#c}".format, 1, _msg="Alternate form (#) not allowed with integer format specifier 'c'") +assert f"{0x1F5A5:c}" == "🖥" +assert_raises( + ValueError, + "{:+c}".format, + 1, + _msg="Sign not allowed with integer format specifier 'c'", +) +assert_raises( + ValueError, + "{:#c}".format, + 1, + _msg="Alternate form (#) not allowed with integer format specifier 'c'", +) assert f"{256:#010x}" == "0x00000100" assert f"{256:0=#10x}" == "0x00000100" assert f"{256:0>#10x}" == "000000x100" @@ -66,14 +81,31 @@ def test_zero_padding(): assert f"{123.456:+011,}" == "+00,123.456" assert f"{1234:.3g}" == "1.23e+03" assert f"{1234567:.6G}" == "1.23457E+06" -assert f'{"🐍":4}' == "🐍 " -assert_raises(ValueError, "{:,o}".format, 1, _msg="ValueError: Cannot specify ',' with 'o'.") -assert_raises(ValueError, "{:_n}".format, 1, _msg="ValueError: Cannot specify '_' with 'n'.") -assert_raises(ValueError, "{:,o}".format, 1.0, _msg="ValueError: Cannot specify ',' with 'o'.") -assert_raises(ValueError, "{:_n}".format, 1.0, _msg="ValueError: Cannot specify '_' with 'n'.") -assert_raises(ValueError, "{:,}".format, "abc", _msg="ValueError: Cannot specify ',' with 's'.") -assert_raises(ValueError, "{:,x}".format, "abc", _msg="ValueError: Cannot specify ',' with 'x'.") -assert_raises(OverflowError, "{:c}".format, 0x110000, _msg="OverflowError: %c arg not in range(0x110000)") +assert f"{'🐍':4}" == "🐍 " +assert_raises( + ValueError, "{:,o}".format, 1, _msg="ValueError: Cannot specify ',' with 'o'." +) +assert_raises( + ValueError, "{:_n}".format, 1, _msg="ValueError: Cannot specify '_' with 'n'." +) +assert_raises( + ValueError, "{:,o}".format, 1.0, _msg="ValueError: Cannot specify ',' with 'o'." +) +assert_raises( + ValueError, "{:_n}".format, 1.0, _msg="ValueError: Cannot specify '_' with 'n'." +) +assert_raises( + ValueError, "{:,}".format, "abc", _msg="ValueError: Cannot specify ',' with 's'." +) +assert_raises( + ValueError, "{:,x}".format, "abc", _msg="ValueError: Cannot specify ',' with 'x'." +) +assert_raises( + OverflowError, + "{:c}".format, + 0x110000, + _msg="OverflowError: %c arg not in range(0x110000)", +) assert f"{3:f}" == "3.000000" assert f"{3.1415:.0f}" == "3" assert f"{3.1415:.1f}" == "3.1" @@ -115,14 +147,14 @@ def test_zero_padding(): assert f"{3.1415:#.4e}" == "3.1415e+00" assert f"{3.1415:#.5e}" == "3.14150e+00" assert f"{3.1415:#.5E}" == "3.14150E+00" -assert f"{3.1415:.0%}" == '314%' -assert f"{3.1415:.1%}" == '314.2%' -assert f"{3.1415:.2%}" == '314.15%' -assert f"{3.1415:.3%}" == '314.150%' -assert f"{3.1415:#.0%}" == '314.%' -assert f"{3.1415:#.1%}" == '314.2%' -assert f"{3.1415:#.2%}" == '314.15%' -assert f"{3.1415:#.3%}" == '314.150%' +assert f"{3.1415:.0%}" == "314%" +assert f"{3.1415:.1%}" == "314.2%" +assert f"{3.1415:.2%}" == "314.15%" +assert f"{3.1415:.3%}" == "314.150%" +assert f"{3.1415:#.0%}" == "314.%" +assert f"{3.1415:#.1%}" == "314.2%" +assert f"{3.1415:#.2%}" == "314.15%" +assert f"{3.1415:#.3%}" == "314.150%" assert f"{3.1415:.0}" == "3e+00" assert f"{3.1415:.1}" == "3e+00" assert f"{3.1415:.2}" == "3.1" @@ -137,5 +169,5 @@ def test_zero_padding(): # test issue 4558 x = 123456789012345678901234567890 for i in range(0, 30): - format(x, ',') + format(x, ",") x = x // 10 diff --git a/extra_tests/snippets/builtin_hash.py b/extra_tests/snippets/builtin_hash.py index bd98199db9..96ccc46ba8 100644 --- a/extra_tests/snippets/builtin_hash.py +++ b/extra_tests/snippets/builtin_hash.py @@ -1,4 +1,3 @@ - from testutils import assert_raises diff --git a/extra_tests/snippets/builtin_hex.py b/extra_tests/snippets/builtin_hex.py index fac5e09c22..740817bc42 100644 --- a/extra_tests/snippets/builtin_hex.py +++ b/extra_tests/snippets/builtin_hex.py @@ -1,6 +1,6 @@ from testutils import assert_raises -assert hex(16) == '0x10' -assert hex(-16) == '-0x10' +assert hex(16) == "0x10" +assert hex(-16) == "-0x10" -assert_raises(TypeError, hex, {}, _msg='ord() called with dict') +assert_raises(TypeError, hex, {}, _msg="ord() called with dict") diff --git a/extra_tests/snippets/builtin_isinstance.py b/extra_tests/snippets/builtin_isinstance.py index c02f331d25..866c83f7cc 100644 --- a/extra_tests/snippets/builtin_isinstance.py +++ b/extra_tests/snippets/builtin_isinstance.py @@ -1,4 +1,3 @@ - class Regular: pass @@ -41,14 +40,17 @@ class AlwaysInstanceOf(metaclass=MCAlwaysInstanceOf): assert isinstance(Regular(), AlwaysInstanceOf) assert isinstance(1, AlwaysInstanceOf) + class GenericInstance: def __instancecheck__(self, _): return True + assert isinstance(Regular(), GenericInstance()) assert isinstance([], GenericInstance()) assert isinstance(1, GenericInstance()) + class MCReturnInt(type): def __instancecheck__(self, instance): return 3 @@ -60,4 +62,13 @@ class ReturnInt(metaclass=MCReturnInt): assert isinstance("a", ReturnInt) is True -assert isinstance(1, ((int, float,), str)) +assert isinstance( + 1, + ( + ( + int, + float, + ), + str, + ), +) diff --git a/extra_tests/snippets/builtin_issubclass.py b/extra_tests/snippets/builtin_issubclass.py index 7f1d87abb1..7c047515d4 100644 --- a/extra_tests/snippets/builtin_issubclass.py +++ b/extra_tests/snippets/builtin_issubclass.py @@ -1,4 +1,3 @@ - class A: pass @@ -49,14 +48,17 @@ class InheritedAlwaysSubClass(AlwaysSubClass): assert issubclass(InheritedAlwaysSubClass, AlwaysSubClass) assert issubclass(AlwaysSubClass, InheritedAlwaysSubClass) + class GenericInstance: def __subclasscheck__(self, _): return True + assert issubclass(A, GenericInstance()) assert issubclass(list, GenericInstance()) assert issubclass([], GenericInstance()) + class MCAVirtualSubClass(type): def __subclasscheck__(self, subclass): return subclass is A diff --git a/extra_tests/snippets/builtin_len.py b/extra_tests/snippets/builtin_len.py index 4872f20c42..4190e31698 100644 --- a/extra_tests/snippets/builtin_len.py +++ b/extra_tests/snippets/builtin_len.py @@ -1,2 +1,2 @@ -assert 3 == len([1,2,3]) -assert 2 == len((1,2)) +assert 3 == len([1, 2, 3]) +assert 2 == len((1, 2)) diff --git a/extra_tests/snippets/builtin_list.py b/extra_tests/snippets/builtin_list.py index b5c08796ba..cb02228c9f 100644 --- a/extra_tests/snippets/builtin_list.py +++ b/extra_tests/snippets/builtin_list.py @@ -12,38 +12,85 @@ assert y == [2, 1, 2, 3, 1, 2, 3] a = [] -a.extend((1,2,3,4)) +a.extend((1, 2, 3, 4)) assert a == [1, 2, 3, 4] -a.extend('abcdefg') -assert a == [1, 2, 3, 4, 'a', 'b', 'c', 'd', 'e', 'f', 'g'] +a.extend("abcdefg") +assert a == [1, 2, 3, 4, "a", "b", "c", "d", "e", "f", "g"] a.extend(range(10)) -assert a == [1, 2, 3, 4, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +assert a == [ + 1, + 2, + 3, + 4, + "a", + "b", + "c", + "d", + "e", + "f", + "g", + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, +] a = [] -a.extend({1,2,3,4}) +a.extend({1, 2, 3, 4}) assert a == [1, 2, 3, 4] -a.extend({'a': 1, 'b': 2, 'z': 51}) -assert a == [1, 2, 3, 4, 'a', 'b', 'z'] +a.extend({"a": 1, "b": 2, "z": 51}) +assert a == [1, 2, 3, 4, "a", "b", "z"] + class Iter: def __iter__(self): yield 12 yield 28 + a.extend(Iter()) -assert a == [1, 2, 3, 4, 'a', 'b', 'z', 12, 28] +assert a == [1, 2, 3, 4, "a", "b", "z", 12, 28] + +a.extend(bytes(b"hello world")) +assert a == [ + 1, + 2, + 3, + 4, + "a", + "b", + "z", + 12, + 28, + 104, + 101, + 108, + 108, + 111, + 32, + 119, + 111, + 114, + 108, + 100, +] -a.extend(bytes(b'hello world')) -assert a == [1, 2, 3, 4, 'a', 'b', 'z', 12, 28, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] class Next: def __next__(self): yield 12 yield 28 + assert_raises(TypeError, lambda: [].extend(3)) assert_raises(TypeError, lambda: [].extend(slice(0, 10, 1))) @@ -56,12 +103,12 @@ def __next__(self): assert x == [1, 2, 3] * 2 # index() -assert ['a', 'b', 'c'].index('b') == 1 +assert ["a", "b", "c"].index("b") == 1 assert [5, 6, 7].index(7) == 2 -assert_raises(ValueError, lambda: ['a', 'b', 'c'].index('z')) +assert_raises(ValueError, lambda: ["a", "b", "c"].index("z")) -x = [[1,0,-3], 'a', 1] -y = [[3,2,1], 'z', 2] +x = [[1, 0, -3], "a", 1] +y = [[3, 2, 1], "z", 2] assert x < y, "list __lt__ failed" x = [5, 13, 31] @@ -73,9 +120,12 @@ def __next__(self): assert x.pop() == 2 assert x == [0, 1] + def test_pop(lst, idx, value, new_lst): assert lst.pop(idx) == value assert lst == new_lst + + test_pop([0, 1, 2], -1, 2, [0, 1]) test_pop([0, 1, 2], 0, 0, [1, 2]) test_pop([0, 1, 2], 1, 1, [0, 2]) @@ -91,23 +141,23 @@ def test_pop(lst, idx, value, new_lst): assert repr(recursive) == "[[...]]" # insert() -x = ['a', 'b', 'c'] -x.insert(0, 'z') # insert is in-place, no return value -assert x == ['z', 'a', 'b', 'c'] +x = ["a", "b", "c"] +x.insert(0, "z") # insert is in-place, no return value +assert x == ["z", "a", "b", "c"] -x = ['a', 'b', 'c'] -x.insert(100, 'z') -assert x == ['a', 'b', 'c', 'z'] +x = ["a", "b", "c"] +x.insert(100, "z") +assert x == ["a", "b", "c", "z"] -x = ['a', 'b', 'c'] -x.insert(-1, 'z') -assert x == ['a', 'b', 'z', 'c'] +x = ["a", "b", "c"] +x.insert(-1, "z") +assert x == ["a", "b", "z", "c"] -x = ['a', 'b', 'c'] -x.insert(-100, 'z') -assert x == ['z', 'a', 'b', 'c'] +x = ["a", "b", "c"] +x.insert(-100, "z") +assert x == ["z", "a", "b", "c"] -assert_raises(OverflowError, lambda: x.insert(100000000000000000000, 'z')) +assert_raises(OverflowError, lambda: x.insert(100000000000000000000, "z")) x = [[], 2, {}] y = x.copy() @@ -123,7 +173,7 @@ def test_pop(lst, idx, value, new_lst): assert len(a) == 2 assert not 1 in a -assert_raises(ValueError, lambda: a.remove(10), _msg='Remove not exist element') +assert_raises(ValueError, lambda: a.remove(10), _msg="Remove not exist element") foo = bar = [1] foo += [2] @@ -138,10 +188,12 @@ def test_pop(lst, idx, value, new_lst): x.remove(x) assert x not in x + class Foo(object): def __eq__(self, x): return False + foo = Foo() foo1 = Foo() x = [1, foo, 2, foo, []] @@ -173,17 +225,17 @@ def __eq__(self, x): assert [foo] == [foo] for size in [1, 2, 3, 4, 5, 8, 10, 100, 1000]: - lst = list(range(size)) - orig = lst[:] - lst.sort() - assert lst == orig - assert sorted(lst) == orig - assert_raises(ZeroDivisionError, sorted, lst, key=lambda x: 1/x) - lst.reverse() - assert sorted(lst) == orig - assert sorted(lst, reverse=True) == lst - assert sorted(lst, key=lambda x: -x) == lst - assert sorted(lst, key=lambda x: -x, reverse=True) == orig + lst = list(range(size)) + orig = lst[:] + lst.sort() + assert lst == orig + assert sorted(lst) == orig + assert_raises(ZeroDivisionError, sorted, lst, key=lambda x: 1 / x) + lst.reverse() + assert sorted(lst) == orig + assert sorted(lst, reverse=True) == lst + assert sorted(lst, key=lambda x: -x) == lst + assert sorted(lst, key=lambda x: -x, reverse=True) == orig assert sorted([(1, 2, 3), (0, 3, 6)]) == [(0, 3, 6), (1, 2, 3)] assert sorted([(1, 2, 3), (0, 3, 6)], key=lambda x: x[0]) == [(0, 3, 6), (1, 2, 3)] @@ -191,34 +243,52 @@ def __eq__(self, x): assert sorted([(1, 2), (), (5,)], key=len) == [(), (5,), (1, 2)] lst = [3, 1, 5, 2, 4] + + class C: - def __init__(self, x): self.x = x - def __lt__(self, other): return self.x < other.x + def __init__(self, x): + self.x = x + + def __lt__(self, other): + return self.x < other.x + + lst.sort(key=C) assert lst == [1, 2, 3, 4, 5] lst = [3, 1, 5, 2, 4] + + class C: - def __init__(self, x): self.x = x - def __gt__(self, other): return self.x > other.x + def __init__(self, x): + self.x = x + + def __gt__(self, other): + return self.x > other.x + + lst.sort(key=C) assert lst == [1, 2, 3, 4, 5] lst = [5, 1, 2, 3, 4] + + def f(x): lst.append(1) return x -assert_raises(ValueError, lambda: lst.sort(key=f)) # "list modified during sort" + + +assert_raises(ValueError, lambda: lst.sort(key=f)) # "list modified during sort" assert lst == [1, 2, 3, 4, 5] # __delitem__ -x = ['a', 'b', 'c'] +x = ["a", "b", "c"] del x[0] -assert x == ['b', 'c'] +assert x == ["b", "c"] -x = ['a', 'b', 'c'] +x = ["a", "b", "c"] del x[-1] -assert x == ['a', 'b'] +assert x == ["a", "b"] x = y = [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15] del x[2:14:3] @@ -232,24 +302,30 @@ def f(x): x = list(range(12)) del x[10:2:-2] -assert x == [0,1,2,3,5,7,9,11] +assert x == [0, 1, 2, 3, 5, 7, 9, 11] + def bad_del_1(): - del ['a', 'b']['a'] + del ["a", "b"]["a"] + + assert_raises(TypeError, bad_del_1) + def bad_del_2(): - del ['a', 'b'][2] + del ["a", "b"][2] + + assert_raises(IndexError, bad_del_2) # __setitem__ # simple index x = [1, 2, 3, 4, 5] -x[0] = 'a' -assert x == ['a', 2, 3, 4, 5] -x[-1] = 'b' -assert x == ['a', 2, 3, 4, 'b'] +x[0] = "a" +assert x == ["a", 2, 3, 4, 5] +x[-1] = "b" +assert x == ["a", 2, 3, 4, "b"] # make sure refrences are assigned correctly y = [] x[1] = y @@ -257,14 +333,17 @@ def bad_del_2(): assert x[1] == y assert x[1] == [100] -#index bounds + +# index bounds def set_index_out_of_bounds_high(): - x = [0, 1, 2, 3, 4] - x[5] = 'a' + x = [0, 1, 2, 3, 4] + x[5] = "a" + def set_index_out_of_bounds_low(): - x = [0, 1, 2, 3, 4] - x[-6] = 'a' + x = [0, 1, 2, 3, 4] + x[-6] = "a" + assert_raises(IndexError, set_index_out_of_bounds_high) assert_raises(IndexError, set_index_out_of_bounds_low) @@ -275,20 +354,20 @@ def set_index_out_of_bounds_low(): y = a[:] assert x == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # replace whole list -x[:] = ['a', 'b', 'c'] -y[::1] = ['a', 'b', 'c'] -assert x == ['a', 'b', 'c'] +x[:] = ["a", "b", "c"] +y[::1] = ["a", "b", "c"] +assert x == ["a", "b", "c"] assert x == y # splice list start x = a[:] y = a[:] z = a[:] zz = a[:] -x[:1] = ['a', 'b', 'c'] -y[0:1] = ['a', 'b', 'c'] -z[:1:1] = ['a', 'b', 'c'] -zz[0:1:1] = ['a', 'b', 'c'] -assert x == ['a', 'b', 'c', 1, 2, 3, 4, 5, 6, 7, 8, 9] +x[:1] = ["a", "b", "c"] +y[0:1] = ["a", "b", "c"] +z[:1:1] = ["a", "b", "c"] +zz[0:1:1] = ["a", "b", "c"] +assert x == ["a", "b", "c", 1, 2, 3, 4, 5, 6, 7, 8, 9] assert x == y assert x == z assert x == zz @@ -297,11 +376,11 @@ def set_index_out_of_bounds_low(): y = a[:] z = a[:] zz = a[:] -x[5:] = ['a', 'b', 'c'] -y[5::1] = ['a', 'b', 'c'] -z[5:10] = ['a', 'b', 'c'] -zz[5:10:1] = ['a', 'b', 'c'] -assert x == [0, 1, 2, 3, 4, 'a', 'b', 'c'] +x[5:] = ["a", "b", "c"] +y[5::1] = ["a", "b", "c"] +z[5:10] = ["a", "b", "c"] +zz[5:10:1] = ["a", "b", "c"] +assert x == [0, 1, 2, 3, 4, "a", "b", "c"] assert x == y assert x == z assert x == zz @@ -310,11 +389,11 @@ def set_index_out_of_bounds_low(): y = a[:] z = a[:] zz = a[:] -x[1:1] = ['a', 'b', 'c'] -y[1:0] = ['a', 'b', 'c'] -z[1:1:1] = ['a', 'b', 'c'] -zz[1:0:1] = ['a', 'b', 'c'] -assert x == [0, 'a', 'b', 'c', 1, 2, 3, 4, 5, 6, 7, 8, 9] +x[1:1] = ["a", "b", "c"] +y[1:0] = ["a", "b", "c"] +z[1:1:1] = ["a", "b", "c"] +zz[1:0:1] = ["a", "b", "c"] +assert x == [0, "a", "b", "c", 1, 2, 3, 4, 5, 6, 7, 8, 9] assert x == y assert x == z assert x == zz @@ -323,24 +402,24 @@ def set_index_out_of_bounds_low(): y = a[:] z = a[:] zz = a[:] -x[-1:-1] = ['a', 'b', 'c'] -y[-1:9] = ['a', 'b', 'c'] -z[-1:-1:1] = ['a', 'b', 'c'] -zz[-1:9:1] = ['a', 'b', 'c'] -assert x == [0, 1, 2, 3, 4, 5, 6, 7, 8, 'a', 'b', 'c', 9] +x[-1:-1] = ["a", "b", "c"] +y[-1:9] = ["a", "b", "c"] +z[-1:-1:1] = ["a", "b", "c"] +zz[-1:9:1] = ["a", "b", "c"] +assert x == [0, 1, 2, 3, 4, 5, 6, 7, 8, "a", "b", "c", 9] assert x == y assert x == z assert x == zz # splice mid x = a[:] y = a[:] -x[3:5] = ['a', 'b', 'c', 'd', 'e'] -y[3:5:1] = ['a', 'b', 'c', 'd', 'e'] -assert x == [0, 1, 2, 'a', 'b', 'c', 'd', 'e', 5, 6, 7, 8, 9] +x[3:5] = ["a", "b", "c", "d", "e"] +y[3:5:1] = ["a", "b", "c", "d", "e"] +assert x == [0, 1, 2, "a", "b", "c", "d", "e", 5, 6, 7, 8, 9] assert x == y x = a[:] -x[3:5] = ['a'] -assert x == [0, 1, 2, 'a', 5, 6, 7, 8, 9] +x[3:5] = ["a"] +assert x == [0, 1, 2, "a", 5, 6, 7, 8, 9] # assign empty to non stepped empty slice does nothing x = a[:] y = a[:] @@ -359,84 +438,93 @@ def set_index_out_of_bounds_low(): yy = [] x = a[:] y = a[:] -x[3:5] = ['a', 'b', 'c', 'd', yy] -y[3:5:1] = ['a', 'b', 'c', 'd', yy] -assert x == [0, 1, 2, 'a', 'b', 'c', 'd', [], 5, 6, 7, 8, 9] +x[3:5] = ["a", "b", "c", "d", yy] +y[3:5:1] = ["a", "b", "c", "d", yy] +assert x == [0, 1, 2, "a", "b", "c", "d", [], 5, 6, 7, 8, 9] assert x == y yy.append(100) -assert x == [0, 1, 2, 'a', 'b', 'c', 'd', [100], 5, 6, 7, 8, 9] +assert x == [0, 1, 2, "a", "b", "c", "d", [100], 5, 6, 7, 8, 9] assert x == y assert x[7] == yy assert x[7] == [100] assert y[7] == yy assert y[7] == [100] + # no zero step def no_zero_step_set(): - x = [1, 2, 3, 4, 5] - x[0:4:0] = [11, 12, 13, 14, 15] + x = [1, 2, 3, 4, 5] + x[0:4:0] = [11, 12, 13, 14, 15] + + assert_raises(ValueError, no_zero_step_set) # stepped slice index # forward slice x = a[:] -x[2:8:2] = ['a', 'b', 'c'] -assert x == [0, 1, 'a', 3, 'b', 5, 'c', 7, 8, 9] +x[2:8:2] = ["a", "b", "c"] +assert x == [0, 1, "a", 3, "b", 5, "c", 7, 8, 9] x = a[:] y = a[:] z = a[:] zz = a[:] -c = ['a', 'b', 'c', 'd', 'e'] +c = ["a", "b", "c", "d", "e"] x[::2] = c y[-10::2] = c z[0:10:2] = c -zz[-13:13:2] = c # slice indexes will be truncated to bounds -assert x == ['a', 1, 'b', 3, 'c', 5, 'd', 7, 'e', 9] +zz[-13:13:2] = c # slice indexes will be truncated to bounds +assert x == ["a", 1, "b", 3, "c", 5, "d", 7, "e", 9] assert x == y assert x == z assert x == zz # backward slice x = a[:] -x[8:2:-2] = ['a', 'b', 'c'] -assert x == [0, 1, 2, 3, 'c', 5, 'b', 7, 'a', 9] +x[8:2:-2] = ["a", "b", "c"] +assert x == [0, 1, 2, 3, "c", 5, "b", 7, "a", 9] x = a[:] y = a[:] z = a[:] zz = a[:] -c = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] +c = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] x[::-1] = c y[9:-11:-1] = c z[9::-1] = c -zz[11:-13:-1] = c # slice indexes will be truncated to bounds -assert x == ['j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'] +zz[11:-13:-1] = c # slice indexes will be truncated to bounds +assert x == ["j", "i", "h", "g", "f", "e", "d", "c", "b", "a"] assert x == y assert x == z assert x == zz # step size bigger than len x = a[:] -x[::200] = ['a'] -assert x == ['a', 1, 2, 3, 4, 5, 6, 7, 8, 9] +x[::200] = ["a"] +assert x == ["a", 1, 2, 3, 4, 5, 6, 7, 8, 9] x = a[:] -x[5::200] = ['a'] -assert x == [0, 1, 2, 3, 4, 'a', 6, 7, 8, 9] +x[5::200] = ["a"] +assert x == [0, 1, 2, 3, 4, "a", 6, 7, 8, 9] + # bad stepped slices def stepped_slice_assign_too_big(): - x = [0, 1, 2, 3, 4] - x[::2] = ['a', 'b', 'c', 'd'] + x = [0, 1, 2, 3, 4] + x[::2] = ["a", "b", "c", "d"] + assert_raises(ValueError, stepped_slice_assign_too_big) + def stepped_slice_assign_too_small(): - x = [0, 1, 2, 3, 4] - x[::2] = ['a', 'b'] + x = [0, 1, 2, 3, 4] + x[::2] = ["a", "b"] + assert_raises(ValueError, stepped_slice_assign_too_small) + # must assign iter t0 slice def must_assign_iter_to_slice(): - x = [0, 1, 2, 3, 4] - x[::2] = 42 + x = [0, 1, 2, 3, 4] + x[::2] = 42 + assert_raises(TypeError, must_assign_iter_to_slice) @@ -446,74 +534,87 @@ def must_assign_iter_to_slice(): # string x = a[:] x[3:8] = "abcdefghi" -assert x == [0, 1, 2, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 8, 9] +assert x == [0, 1, 2, "a", "b", "c", "d", "e", "f", "g", "h", "i", 8, 9] # tuple x = a[:] x[3:8] = (11, 12, 13, 14, 15) assert x == [0, 1, 2, 11, 12, 13, 14, 15, 8, 9] + # class # __next__ class CIterNext: - def __init__(self, sec=(1, 2, 3)): - self.sec = sec - self.index = 0 - def __iter__(self): - return self - def __next__(self): - if self.index >= len(self.sec): - raise StopIteration - v = self.sec[self.index] - self.index += 1 - return v + def __init__(self, sec=(1, 2, 3)): + self.sec = sec + self.index = 0 + + def __iter__(self): + return self + + def __next__(self): + if self.index >= len(self.sec): + raise StopIteration + v = self.sec[self.index] + self.index += 1 + return v + x = list(range(10)) x[3:8] = CIterNext() assert x == [0, 1, 2, 1, 2, 3, 8, 9] + # __iter__ yield class CIter: - def __init__(self, sec=(1, 2, 3)): - self.sec = sec - def __iter__(self): - for n in self.sec: - yield n + def __init__(self, sec=(1, 2, 3)): + self.sec = sec + + def __iter__(self): + for n in self.sec: + yield n + x = list(range(10)) x[3:8] = CIter() assert x == [0, 1, 2, 1, 2, 3, 8, 9] + # __getitem but no __iter__ sequence class CGetItem: - def __init__(self, sec=(1, 2, 3)): - self.sec = sec - def __getitem__(self, sub): - return self.sec[sub] + def __init__(self, sec=(1, 2, 3)): + self.sec = sec + + def __getitem__(self, sub): + return self.sec[sub] + x = list(range(10)) x[3:8] = CGetItem() assert x == [0, 1, 2, 1, 2, 3, 8, 9] + # iter raises error class CIterError: - def __iter__(self): - for i in range(10): - if i > 5: - raise RuntimeError - yield i + def __iter__(self): + for i in range(10): + if i > 5: + raise RuntimeError + yield i + def bad_iter_assign(): - x = list(range(10)) - x[3:8] = CIterError() + x = list(range(10)) + x[3:8] = CIterError() + assert_raises(RuntimeError, bad_iter_assign) # slice assign when step or stop is -1 a = list(range(10)) x = a[:] -x[-1:-5:-1] = ['a', 'b', 'c', 'd'] -assert x == [0, 1, 2, 3, 4, 5, 'd', 'c', 'b', 'a'] +x[-1:-5:-1] = ["a", "b", "c", "d"] +assert x == [0, 1, 2, 3, 4, 5, "d", "c", "b", "a"] x = a[:] x[-5:-1:-1] = [] assert x == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] @@ -557,17 +658,17 @@ def bad_iter_assign(): assert not [0, 0] > [0, 0] assert not [0, 0] < [0, 0] -assert not [float('nan'), float('nan')] <= [float('nan'), 1] -assert not [float('nan'), float('nan')] <= [float('nan'), float('nan')] -assert not [float('nan'), float('nan')] >= [float('nan'), float('nan')] -assert not [float('nan'), float('nan')] < [float('nan'), float('nan')] -assert not [float('nan'), float('nan')] > [float('nan'), float('nan')] +assert not [float("nan"), float("nan")] <= [float("nan"), 1] +assert not [float("nan"), float("nan")] <= [float("nan"), float("nan")] +assert not [float("nan"), float("nan")] >= [float("nan"), float("nan")] +assert not [float("nan"), float("nan")] < [float("nan"), float("nan")] +assert not [float("nan"), float("nan")] > [float("nan"), float("nan")] -assert [float('inf'), float('inf')] >= [float('inf'), 1] -assert [float('inf'), float('inf')] <= [float('inf'), float('inf')] -assert [float('inf'), float('inf')] >= [float('inf'), float('inf')] -assert not [float('inf'), float('inf')] < [float('inf'), float('inf')] -assert not [float('inf'), float('inf')] > [float('inf'), float('inf')] +assert [float("inf"), float("inf")] >= [float("inf"), 1] +assert [float("inf"), float("inf")] <= [float("inf"), float("inf")] +assert [float("inf"), float("inf")] >= [float("inf"), float("inf")] +assert not [float("inf"), float("inf")] < [float("inf"), float("inf")] +assert not [float("inf"), float("inf")] > [float("inf"), float("inf")] # list __iadd__ a = [] @@ -575,62 +676,111 @@ def bad_iter_assign(): assert a == [1, 2, 3] a = [] -a += (1,2,3,4) +a += (1, 2, 3, 4) assert a == [1, 2, 3, 4] -a += 'abcdefg' -assert a == [1, 2, 3, 4, 'a', 'b', 'c', 'd', 'e', 'f', 'g'] +a += "abcdefg" +assert a == [1, 2, 3, 4, "a", "b", "c", "d", "e", "f", "g"] a += range(10) -assert a == [1, 2, 3, 4, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +assert a == [ + 1, + 2, + 3, + 4, + "a", + "b", + "c", + "d", + "e", + "f", + "g", + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, +] a = [] -a += {1,2,3,4} +a += {1, 2, 3, 4} assert a == [1, 2, 3, 4] -a += {'a': 1, 'b': 2, 'z': 51} -assert a == [1, 2, 3, 4, 'a', 'b', 'z'] +a += {"a": 1, "b": 2, "z": 51} +assert a == [1, 2, 3, 4, "a", "b", "z"] + class Iter: def __iter__(self): yield 12 yield 28 + a += Iter() -assert a == [1, 2, 3, 4, 'a', 'b', 'z', 12, 28] +assert a == [1, 2, 3, 4, "a", "b", "z", 12, 28] + +a += bytes(b"hello world") +assert a == [ + 1, + 2, + 3, + 4, + "a", + "b", + "z", + 12, + 28, + 104, + 101, + 108, + 108, + 111, + 32, + 119, + 111, + 114, + 108, + 100, +] -a += bytes(b'hello world') -assert a == [1, 2, 3, 4, 'a', 'b', 'z', 12, 28, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] class Next: def __next__(self): yield 12 yield 28 + def iadd_int(): a = [] a += 3 + def iadd_slice(): a = [] a += slice(0, 10, 1) + assert_raises(TypeError, iadd_int) assert_raises(TypeError, iadd_slice) -it = iter([1,2,3,4]) +it = iter([1, 2, 3, 4]) assert it.__length_hint__() == 4 assert next(it) == 1 assert it.__length_hint__() == 3 -assert list(it) == [2,3,4] +assert list(it) == [2, 3, 4] assert it.__length_hint__() == 0 -it = reversed([1,2,3,4]) +it = reversed([1, 2, 3, 4]) assert it.__length_hint__() == 4 assert next(it) == 4 assert it.__length_hint__() == 3 -assert list(it) == [3,2,1] +assert list(it) == [3, 2, 1] assert it.__length_hint__() == 0 a = [*[1, 2], 3, *[4, 5]] @@ -648,21 +798,25 @@ def iadd_slice(): class C(base): def __iter__(self): a.append(2) + def inner(): yield 3 a.append(4) + return inner() a = [1] b = [*a, *C(), *a.copy()] assert b == [1, 3, 1, 2, 4] + # Test for list entering daedlock or not (https://github.com/RustPython/RustPython/pull/2933) class MutatingCompare: def __eq__(self, other): self.list.pop() return True + m = MutatingCompare() l = [1, 2, 3, m, 4] @@ -675,18 +829,21 @@ def __eq__(self, other): l = [1, 2, 3, m, 4] m.list = l -l.remove(4) -assert_raises(ValueError, lambda: l.index(4)) # element 4 must not be in the list +l.remove(4) +assert_raises(ValueError, lambda: l.index(4)) # element 4 must not be in the list + # Test no panic occurred when list elements was deleted in __eq__ class rewrite_list_eq(list): pass + class poc: def __eq__(self, other): list1.clear() return self + list1 = rewrite_list_eq([poc()]) list1.remove(list1) assert list1 == [] diff --git a/extra_tests/snippets/builtin_locals.py b/extra_tests/snippets/builtin_locals.py index 6f3fd847c4..a10cfa389c 100644 --- a/extra_tests/snippets/builtin_locals.py +++ b/extra_tests/snippets/builtin_locals.py @@ -1,19 +1,18 @@ - a = 5 b = 6 loc = locals() -assert loc['a'] == 5 -assert loc['b'] == 6 +assert loc["a"] == 5 +assert loc["b"] == 6 -def f(): - c = 4 - a = 7 - loc = locals() +def f(): + c = 4 + a = 7 - assert loc['a'] == 4 - assert loc['c'] == 7 - assert not 'b' in loc + loc = locals() + assert loc["a"] == 4 + assert loc["c"] == 7 + assert not "b" in loc diff --git a/extra_tests/snippets/builtin_map.py b/extra_tests/snippets/builtin_map.py index 0de8d2c597..559d108e38 100644 --- a/extra_tests/snippets/builtin_map.py +++ b/extra_tests/snippets/builtin_map.py @@ -1,5 +1,5 @@ a = list(map(str, [1, 2, 3])) -assert a == ['1', '2', '3'] +assert a == ["1", "2", "3"] b = list(map(lambda x, y: x + y, [1, 2, 4], [3, 5])) @@ -20,7 +20,7 @@ def __iter__(self): return self -it = map(lambda x: x+1, Counter()) +it = map(lambda x: x + 1, Counter()) assert next(it) == 2 assert next(it) == 3 diff --git a/extra_tests/snippets/builtin_mappingproxy.py b/extra_tests/snippets/builtin_mappingproxy.py index cfba56a8df..fdd653c408 100644 --- a/extra_tests/snippets/builtin_mappingproxy.py +++ b/extra_tests/snippets/builtin_mappingproxy.py @@ -1,5 +1,6 @@ from testutils import assert_raises + class A(dict): def a(): pass @@ -8,16 +9,16 @@ def b(): pass -assert A.__dict__['a'] == A.a +assert A.__dict__["a"] == A.a with assert_raises(KeyError) as cm: - A.__dict__['not here'] + A.__dict__["not here"] assert cm.exception.args[0] == "not here" -assert 'b' in A.__dict__ -assert 'c' not in A.__dict__ +assert "b" in A.__dict__ +assert "c" not in A.__dict__ -assert '__dict__' in A.__dict__ +assert "__dict__" in A.__dict__ assert A.__dict__.get("not here", "default") == "default" assert A.__dict__.get("a", "default") is A.a diff --git a/extra_tests/snippets/builtin_max.py b/extra_tests/snippets/builtin_max.py index cb62123656..fbb0626768 100644 --- a/extra_tests/snippets/builtin_max.py +++ b/extra_tests/snippets/builtin_max.py @@ -3,17 +3,22 @@ # simple values assert max(0, 0) == 0 assert max(1, 0) == 1 -assert max(1., 0.) == 1. +assert max(1.0, 0.0) == 1.0 assert max(-1, 0) == 0 assert max(1, 2, 3) == 3 # iterables assert max([1, 2, 3]) == 3 assert max((1, 2, 3)) == 3 -assert max({ - "a": 0, - "b": 1, -}) == "b" +assert ( + max( + { + "a": 0, + "b": 1, + } + ) + == "b" +) assert max([1, 2], default=0) == 2 assert max([], default=0) == 0 assert_raises(ValueError, max, []) @@ -30,7 +35,7 @@ # custom class -class MyComparable(): +class MyComparable: nb = 0 def __init__(self): @@ -47,7 +52,7 @@ def __gt__(self, other): assert max([first, second]) == second -class MyNotComparable(): +class MyNotComparable: pass diff --git a/extra_tests/snippets/builtin_memoryview.py b/extra_tests/snippets/builtin_memoryview.py index 81cd5015c1..f206056ebf 100644 --- a/extra_tests/snippets/builtin_memoryview.py +++ b/extra_tests/snippets/builtin_memoryview.py @@ -10,48 +10,52 @@ assert hash(obj) == hash(a) -class A(array.array): - ... -class B(bytes): - ... +class A(array.array): ... -class C(): - ... -memoryview(bytearray('abcde', encoding='utf-8')) -memoryview(array.array('i', [1, 2, 3])) -memoryview(A('b', [0])) -memoryview(B('abcde', encoding='utf-8')) +class B(bytes): ... + + +class C: ... + + +memoryview(bytearray("abcde", encoding="utf-8")) +memoryview(array.array("i", [1, 2, 3])) +memoryview(A("b", [0])) +memoryview(B("abcde", encoding="utf-8")) assert_raises(TypeError, lambda: memoryview([1, 2, 3])) assert_raises(TypeError, lambda: memoryview((1, 2, 3))) assert_raises(TypeError, lambda: memoryview({})) -assert_raises(TypeError, lambda: memoryview('string')) +assert_raises(TypeError, lambda: memoryview("string")) assert_raises(TypeError, lambda: memoryview(C())) + def test_slice(): - b = b'123456789' + b = b"123456789" m = memoryview(b) m2 = memoryview(b) assert m == m assert m == m2 - assert m.tobytes() == b'123456789' + assert m.tobytes() == b"123456789" assert m == b - assert m[::2].tobytes() == b'13579' - assert m[::2] == b'13579' - assert m[1::2].tobytes() == b'2468' - assert m[::2][1:].tobytes() == b'3579' - assert m[::2][1:-1].tobytes() == b'357' - assert m[::2][::2].tobytes() == b'159' - assert m[::2][1::2].tobytes() == b'37' - assert m[::-1].tobytes() == b'987654321' - assert m[::-2].tobytes() == b'97531' + assert m[::2].tobytes() == b"13579" + assert m[::2] == b"13579" + assert m[1::2].tobytes() == b"2468" + assert m[::2][1:].tobytes() == b"3579" + assert m[::2][1:-1].tobytes() == b"357" + assert m[::2][::2].tobytes() == b"159" + assert m[::2][1::2].tobytes() == b"37" + assert m[::-1].tobytes() == b"987654321" + assert m[::-2].tobytes() == b"97531" + test_slice() + def test_resizable(): - b = bytearray(b'123') + b = bytearray(b"123") b.append(4) m = memoryview(b) assert_raises(BufferError, lambda: b.append(5)) @@ -68,18 +72,21 @@ def test_resizable(): m4.release() b.append(7) + test_resizable() + def test_delitem(): - a = b'abc' + a = b"abc" b = memoryview(a) - assert_raises(TypeError, lambda : b.__delitem__()) - assert_raises(TypeError, lambda : b.__delitem__(0)) - assert_raises(TypeError, lambda : b.__delitem__(10)) - a = bytearray(b'abc') + assert_raises(TypeError, lambda: b.__delitem__()) + assert_raises(TypeError, lambda: b.__delitem__(0)) + assert_raises(TypeError, lambda: b.__delitem__(10)) + a = bytearray(b"abc") b = memoryview(a) - assert_raises(TypeError, lambda : b.__delitem__()) - assert_raises(TypeError, lambda : b.__delitem__(1)) - assert_raises(TypeError, lambda : b.__delitem__(12)) + assert_raises(TypeError, lambda: b.__delitem__()) + assert_raises(TypeError, lambda: b.__delitem__(1)) + assert_raises(TypeError, lambda: b.__delitem__(12)) + -test_delitem() \ No newline at end of file +test_delitem() diff --git a/extra_tests/snippets/builtin_min.py b/extra_tests/snippets/builtin_min.py index 50ebc91f54..fc8eebba2c 100644 --- a/extra_tests/snippets/builtin_min.py +++ b/extra_tests/snippets/builtin_min.py @@ -3,17 +3,22 @@ # simple values assert min(0, 0) == 0 assert min(1, 0) == 0 -assert min(1., 0.) == 0. +assert min(1.0, 0.0) == 0.0 assert min(-1, 0) == -1 assert min(1, 2, 3) == 1 # iterables assert min([1, 2, 3]) == 1 assert min((1, 2, 3)) == 1 -assert min({ - "a": 0, - "b": 1, -}) == "a" +assert ( + min( + { + "a": 0, + "b": 1, + } + ) + == "a" +) assert min([1, 2], default=0) == 1 assert min([], default=0) == 0 @@ -31,7 +36,7 @@ # custom class -class MyComparable(): +class MyComparable: nb = 0 def __init__(self): @@ -48,7 +53,7 @@ def __gt__(self, other): assert min([first, second]) == first -class MyNotComparable(): +class MyNotComparable: pass diff --git a/extra_tests/snippets/builtin_none.py b/extra_tests/snippets/builtin_none.py index d605f1d742..230a7229e0 100644 --- a/extra_tests/snippets/builtin_none.py +++ b/extra_tests/snippets/builtin_none.py @@ -4,19 +4,22 @@ x = None assert x is y + def none(): pass + def none2(): return None + assert none() is none() assert none() is x assert none() is none2() -assert str(None) == 'None' -assert repr(None) == 'None' +assert str(None) == "None" +assert repr(None) == "None" assert type(None)() is None assert None.__eq__(3) is NotImplemented diff --git a/extra_tests/snippets/builtin_object.py b/extra_tests/snippets/builtin_object.py index 0cb6f31d66..64486e1673 100644 --- a/extra_tests/snippets/builtin_object.py +++ b/extra_tests/snippets/builtin_object.py @@ -1,6 +1,7 @@ class MyObject: pass + assert not MyObject() == MyObject() assert MyObject() != MyObject() myobj = MyObject() @@ -21,8 +22,8 @@ class MyObject: assert obj.__eq__(obj) is True assert obj.__ne__(obj) is False -assert not hasattr(obj, 'a') -obj.__dict__ = {'a': 1} +assert not hasattr(obj, "a") +obj.__dict__ = {"a": 1} assert obj.a == 1 # Value inside the formatter goes through a different path of resolution. diff --git a/extra_tests/snippets/builtin_open.py b/extra_tests/snippets/builtin_open.py index f2c783f2a5..99dd337414 100644 --- a/extra_tests/snippets/builtin_open.py +++ b/extra_tests/snippets/builtin_open.py @@ -1,19 +1,19 @@ from testutils import assert_raises -fd = open('README.md') -assert 'RustPython' in fd.read() +fd = open("README.md") +assert "RustPython" in fd.read() -assert_raises(FileNotFoundError, open, 'DoesNotExist') +assert_raises(FileNotFoundError, open, "DoesNotExist") # Use open as a context manager -with open('README.md', 'rt') as fp: +with open("README.md", "rt") as fp: contents = fp.read() assert type(contents) == str, "type is " + str(type(contents)) -with open('README.md', 'r') as fp: +with open("README.md", "r") as fp: contents = fp.read() assert type(contents) == str, "type is " + str(type(contents)) -with open('README.md', 'rb') as fp: +with open("README.md", "rb") as fp: contents = fp.read() assert type(contents) == bytes, "type is " + str(type(contents)) diff --git a/extra_tests/snippets/builtin_ord.py b/extra_tests/snippets/builtin_ord.py index 271728b84a..e451e078c3 100644 --- a/extra_tests/snippets/builtin_ord.py +++ b/extra_tests/snippets/builtin_ord.py @@ -3,11 +3,18 @@ assert ord("a") == 97 assert ord("é") == 233 assert ord("🤡") == 129313 -assert ord(b'a') == 97 -assert ord(bytearray(b'a')) == 97 +assert ord(b"a") == 97 +assert ord(bytearray(b"a")) == 97 -assert_raises(TypeError, ord, _msg='ord() is called with no argument') -assert_raises(TypeError, ord, "", _msg='ord() is called with an empty string') -assert_raises(TypeError, ord, "ab", _msg='ord() is called with more than one character') -assert_raises(TypeError, ord, b"ab", _msg='ord() expected a character, but string of length 2 found') -assert_raises(TypeError, ord, 1, _msg='ord() expected a string, bytes or bytearray, but found int') +assert_raises(TypeError, ord, _msg="ord() is called with no argument") +assert_raises(TypeError, ord, "", _msg="ord() is called with an empty string") +assert_raises(TypeError, ord, "ab", _msg="ord() is called with more than one character") +assert_raises( + TypeError, + ord, + b"ab", + _msg="ord() expected a character, but string of length 2 found", +) +assert_raises( + TypeError, ord, 1, _msg="ord() expected a string, bytes or bytearray, but found int" +) diff --git a/extra_tests/snippets/builtin_pow.py b/extra_tests/snippets/builtin_pow.py index d31e5dd713..c769914231 100644 --- a/extra_tests/snippets/builtin_pow.py +++ b/extra_tests/snippets/builtin_pow.py @@ -12,7 +12,7 @@ assert pow(2.0, 1) == 2.0 assert pow(0, 10**1000) == 0 assert pow(1, 10**1000) == 1 -assert pow(-1, 10**1000+1) == -1 +assert pow(-1, 10**1000 + 1) == -1 assert pow(-1, 10**1000) == 1 assert pow(2, 4, 5) == 1 @@ -59,7 +59,7 @@ def powtest(type): assert_raises(ZeroDivisionError, pow, zero, exp) il, ih = -20, 20 - jl, jh = -5, 5 + jl, jh = -5, 5 kl, kh = -10, 10 asseq = assert_equal if type == float: @@ -76,10 +76,7 @@ def powtest(type): if type == float or j < 0: assert_raises(TypeError, pow, type(i), j, k) continue - asseq( - pow(type(i), j, k), - pow(type(i), j) % type(k) - ) + asseq(pow(type(i), j, k), pow(type(i), j) % type(k)) def test_powint(): @@ -92,40 +89,35 @@ def test_powfloat(): def test_other(): # Other tests-- not very systematic - assert_equal(pow(3,3) % 8, pow(3,3,8)) - assert_equal(pow(3,3) % -8, pow(3,3,-8)) - assert_equal(pow(3,2) % -2, pow(3,2,-2)) - assert_equal(pow(-3,3) % 8, pow(-3,3,8)) - assert_equal(pow(-3,3) % -8, pow(-3,3,-8)) - assert_equal(pow(5,2) % -8, pow(5,2,-8)) - - assert_equal(pow(3,3) % 8, pow(3,3,8)) - assert_equal(pow(3,3) % -8, pow(3,3,-8)) - assert_equal(pow(3,2) % -2, pow(3,2,-2)) - assert_equal(pow(-3,3) % 8, pow(-3,3,8)) - assert_equal(pow(-3,3) % -8, pow(-3,3,-8)) - assert_equal(pow(5,2) % -8, pow(5,2,-8)) + assert_equal(pow(3, 3) % 8, pow(3, 3, 8)) + assert_equal(pow(3, 3) % -8, pow(3, 3, -8)) + assert_equal(pow(3, 2) % -2, pow(3, 2, -2)) + assert_equal(pow(-3, 3) % 8, pow(-3, 3, 8)) + assert_equal(pow(-3, 3) % -8, pow(-3, 3, -8)) + assert_equal(pow(5, 2) % -8, pow(5, 2, -8)) + + assert_equal(pow(3, 3) % 8, pow(3, 3, 8)) + assert_equal(pow(3, 3) % -8, pow(3, 3, -8)) + assert_equal(pow(3, 2) % -2, pow(3, 2, -2)) + assert_equal(pow(-3, 3) % 8, pow(-3, 3, 8)) + assert_equal(pow(-3, 3) % -8, pow(-3, 3, -8)) + assert_equal(pow(5, 2) % -8, pow(5, 2, -8)) for i in range(-10, 11): for j in range(0, 6): for k in range(-7, 11): if j >= 0 and k != 0: - assert_equal( - pow(i,j) % k, - pow(i,j,k) - ) + assert_equal(pow(i, j) % k, pow(i, j, k)) if j >= 0 and k != 0: - assert_equal( - pow(int(i),j) % k, - pow(int(i),j,k) - ) + assert_equal(pow(int(i), j) % k, pow(int(i), j, k)) def test_bug643260(): class TestRpow: def __rpow__(self, other): return None - None ** TestRpow() # Won't fail when __rpow__ invoked. SF bug #643260. + + None ** TestRpow() # Won't fail when __rpow__ invoked. SF bug #643260. def test_bug705231(): @@ -141,15 +133,15 @@ def test_bug705231(): for b in range(-10, 11): eq(pow(a, float(b)), b & 1 and -1.0 or 1.0) for n in range(0, 100): - fiveto = float(5 ** n) + fiveto = float(5**n) # For small n, fiveto will be odd. Eventually we run out of # mantissa bits, though, and thereafer fiveto will be even. expected = fiveto % 2.0 and -1.0 or 1.0 eq(pow(a, fiveto), expected) eq(pow(a, -fiveto), expected) - eq(expected, 1.0) # else we didn't push fiveto to evenness + eq(expected, 1.0) # else we didn't push fiveto to evenness -tests = [f for name, f in locals().items() if name.startswith('test_')] +tests = [f for name, f in locals().items() if name.startswith("test_")] for f in tests: f() diff --git a/extra_tests/snippets/builtin_print.py b/extra_tests/snippets/builtin_print.py index db53c80edb..b9f3b8cc17 100644 --- a/extra_tests/snippets/builtin_print.py +++ b/extra_tests/snippets/builtin_print.py @@ -3,14 +3,14 @@ print(2 + 3) -assert_raises(TypeError, print, 'test', end=4, _msg='wrong type passed to end') -assert_raises(TypeError, print, 'test', sep=['a'], _msg='wrong type passed to sep') +assert_raises(TypeError, print, "test", end=4, _msg="wrong type passed to end") +assert_raises(TypeError, print, "test", sep=["a"], _msg="wrong type passed to sep") try: - print('test', end=None, sep=None, flush=None) + print("test", end=None, sep=None, flush=None) except: - assert False, 'Expected None passed to end, sep, and flush to not raise errors' + assert False, "Expected None passed to end, sep, and flush to not raise errors" buf = io.StringIO() -print('hello, world', file=buf) -assert buf.getvalue() == 'hello, world\n', buf.getvalue() +print("hello, world", file=buf) +assert buf.getvalue() == "hello, world\n", buf.getvalue() diff --git a/extra_tests/snippets/builtin_property.py b/extra_tests/snippets/builtin_property.py index 2a97c99b3b..de64e52622 100644 --- a/extra_tests/snippets/builtin_property.py +++ b/extra_tests/snippets/builtin_property.py @@ -62,8 +62,8 @@ def foo(self): assert p.__doc__ is None # Test property instance __doc__ attribute: -p.__doc__ = '222' -assert p.__doc__ == '222' +p.__doc__ = "222" +assert p.__doc__ == "222" p1 = property("a", "b", "c") @@ -83,5 +83,5 @@ def foo(self): assert p1.__get__(None, object) is p1 # assert p1.__doc__ is 'a'.__doc__ -p2 = property('a', doc='pdoc') +p2 = property("a", doc="pdoc") # assert p2.__doc__ == 'pdoc' diff --git a/extra_tests/snippets/builtin_range.py b/extra_tests/snippets/builtin_range.py index 9f8f03b63c..6bfb99f453 100644 --- a/extra_tests/snippets/builtin_range.py +++ b/extra_tests/snippets/builtin_range.py @@ -1,11 +1,11 @@ from testutils import assert_raises -assert range(2**63+1)[2**63] == 9223372036854775808 +assert range(2**63 + 1)[2**63] == 9223372036854775808 # len tests -assert len(range(10, 5)) == 0, 'Range with no elements should have length = 0' -assert len(range(10, 5, -2)) == 3, 'Expected length 3, for elements: 10, 8, 6' -assert len(range(5, 10, 2)) == 3, 'Expected length 3, for elements: 5, 7, 9' +assert len(range(10, 5)) == 0, "Range with no elements should have length = 0" +assert len(range(10, 5, -2)) == 3, "Expected length 3, for elements: 10, 8, 6" +assert len(range(5, 10, 2)) == 3, "Expected length 3, for elements: 5, 7, 9" # index tests assert range(10).index(6) == 6 @@ -13,18 +13,18 @@ assert range(4, 10, 2).index(6) == 1 assert range(10, 4, -2).index(8) == 1 -assert_raises(ValueError, lambda: range(10).index(-1), _msg='out of bounds') -assert_raises(ValueError, lambda: range(10).index(10), _msg='out of bounds') -assert_raises(ValueError, lambda: range(4, 10, 2).index(5), _msg='out of step') -assert_raises(ValueError, lambda: range(10).index('foo'), _msg='not an int') -assert_raises(ValueError, lambda: range(1, 10, 0), _msg='step is zero') +assert_raises(ValueError, lambda: range(10).index(-1), _msg="out of bounds") +assert_raises(ValueError, lambda: range(10).index(10), _msg="out of bounds") +assert_raises(ValueError, lambda: range(4, 10, 2).index(5), _msg="out of step") +assert_raises(ValueError, lambda: range(10).index("foo"), _msg="not an int") +assert_raises(ValueError, lambda: range(1, 10, 0), _msg="step is zero") # get tests assert range(10)[0] == 0 assert range(10)[9] == 9 assert range(10, 0, -1)[0] == 10 assert range(10, 0, -1)[9] == 1 -assert_raises(IndexError, lambda: range(10)[10], _msg='out of bound') +assert_raises(IndexError, lambda: range(10)[10], _msg="out of bound") # slice tests assert range(10)[0:3] == range(3) @@ -34,13 +34,17 @@ assert range(10, 100, 3)[4:1000:5] == range(22, 100, 15) assert range(10)[:] == range(10) assert range(10, 0, -2)[0:5:2] == range(10, 0, -4) -assert range(10)[10:11] == range(10,10) +assert range(10)[10:11] == range(10, 10) assert range(0, 10, -1)[::-1] == range(1, 1) assert range(0, 10)[::-1] == range(9, -1, -1) assert range(0, -10)[::-1] == range(-1, -1, -1) assert range(0, -10)[::-1][::-1] == range(0, 0) -assert_raises(ValueError, lambda: range(0, 10)[::0], _msg='slice step cannot be zero') -assert_raises(TypeError, lambda: range(0, 10)['a':], _msg='slice indices must be integers or None or have an __index__ method') +assert_raises(ValueError, lambda: range(0, 10)[::0], _msg="slice step cannot be zero") +assert_raises( + TypeError, + lambda: range(0, 10)["a":], + _msg="slice indices must be integers or None or have an __index__ method", +) # count tests assert range(10).count(2) == 1 @@ -64,22 +68,22 @@ assert range(10).__ne__(range(0, 11, 1)) is True assert range(0, 10, 3).__eq__(range(0, 11, 3)) is True assert range(0, 10, 3).__ne__(range(0, 11, 3)) is False -#__lt__ +# __lt__ assert range(1, 2, 3).__lt__(range(1, 2, 3)) == NotImplemented assert range(1, 2, 1).__lt__(range(1, 2)) == NotImplemented assert range(2).__lt__(range(0, 2)) == NotImplemented -#__gt__ +# __gt__ assert range(1, 2, 3).__gt__(range(1, 2, 3)) == NotImplemented assert range(1, 2, 1).__gt__(range(1, 2)) == NotImplemented assert range(2).__gt__(range(0, 2)) == NotImplemented -#__le__ +# __le__ assert range(1, 2, 3).__le__(range(1, 2, 3)) == NotImplemented assert range(1, 2, 1).__le__(range(1, 2)) == NotImplemented assert range(2).__le__(range(0, 2)) == NotImplemented -#__ge__ +# __ge__ assert range(1, 2, 3).__ge__(range(1, 2, 3)) == NotImplemented assert range(1, 2, 1).__ge__(range(1, 2)) == NotImplemented assert range(2).__ge__(range(0, 2)) == NotImplemented @@ -101,12 +105,12 @@ assert -1 not in range(10) assert 9 not in range(10, 4, -2) assert 4 not in range(10, 4, -2) -assert 'foo' not in range(10) +assert "foo" not in range(10) # __reversed__ assert list(reversed(range(5))) == [4, 3, 2, 1, 0] assert list(reversed(range(5, 0, -1))) == [1, 2, 3, 4, 5] -assert list(reversed(range(1,10,5))) == [6, 1] +assert list(reversed(range(1, 10, 5))) == [6, 1] # __reduce__ assert range(10).__reduce__()[0] == range @@ -120,7 +124,7 @@ # negative index assert range(10)[-1] == 9 -assert_raises(IndexError, lambda: range(10)[-11], _msg='out of bound') +assert_raises(IndexError, lambda: range(10)[-11], _msg="out of bound") assert range(10)[-2:4] == range(8, 4) assert range(10)[-6:-2] == range(4, 8) assert range(50, 0, -2)[-5] == 10 diff --git a/extra_tests/snippets/builtin_reversed.py b/extra_tests/snippets/builtin_reversed.py index 261b5c3263..0ec2f2828b 100644 --- a/extra_tests/snippets/builtin_reversed.py +++ b/extra_tests/snippets/builtin_reversed.py @@ -1,4 +1,4 @@ assert list(reversed(range(5))) == [4, 3, 2, 1, 0] -l = [5,4,3,2,1] -assert list(reversed(l)) == [1,2,3,4,5] +l = [5, 4, 3, 2, 1] +assert list(reversed(l)) == [1, 2, 3, 4, 5] diff --git a/extra_tests/snippets/builtin_round.py b/extra_tests/snippets/builtin_round.py index b4b070c4cc..99c4ed1d27 100644 --- a/extra_tests/snippets/builtin_round.py +++ b/extra_tests/snippets/builtin_round.py @@ -8,11 +8,11 @@ assert round(-1.5) == -2 # ValueError: cannot convert float NaN to integer -assert_raises(ValueError, round, float('nan')) +assert_raises(ValueError, round, float("nan")) # OverflowError: cannot convert float infinity to integer -assert_raises(OverflowError, round, float('inf')) +assert_raises(OverflowError, round, float("inf")) # OverflowError: cannot convert float infinity to integer -assert_raises(OverflowError, round, -float('inf')) +assert_raises(OverflowError, round, -float("inf")) assert round(0) == 0 assert isinstance(round(0), int) diff --git a/extra_tests/snippets/builtin_set.py b/extra_tests/snippets/builtin_set.py index 79f0602aea..1b2f6ff096 100644 --- a/extra_tests/snippets/builtin_set.py +++ b/extra_tests/snippets/builtin_set.py @@ -1,38 +1,54 @@ from testutils import assert_raises -assert set([1,2]) == set([1,2]) -assert not set([1,2,3]) == set([1,2]) +assert set([1, 2]) == set([1, 2]) +assert not set([1, 2, 3]) == set([1, 2]) -assert set([1,2,3]) >= set([1,2]) -assert set([1,2]) >= set([1,2]) -assert not set([1,3]) >= set([1,2]) +assert set([1, 2, 3]) >= set([1, 2]) +assert set([1, 2]) >= set([1, 2]) +assert not set([1, 3]) >= set([1, 2]) -assert set([1,2,3]).issuperset(set([1,2])) -assert set([1,2]).issuperset(set([1,2])) -assert not set([1,3]).issuperset(set([1,2])) +assert set([1, 2, 3]).issuperset(set([1, 2])) +assert set([1, 2]).issuperset(set([1, 2])) +assert not set([1, 3]).issuperset(set([1, 2])) -assert set([1,2,3]) > set([1,2]) -assert not set([1,2]) > set([1,2]) -assert not set([1,3]) > set([1,2]) +assert set([1, 2, 3]) > set([1, 2]) +assert not set([1, 2]) > set([1, 2]) +assert not set([1, 3]) > set([1, 2]) -assert set([1,2]) <= set([1,2,3]) -assert set([1,2]) <= set([1,2]) -assert not set([1,3]) <= set([1,2]) +assert set([1, 2]) <= set([1, 2, 3]) +assert set([1, 2]) <= set([1, 2]) +assert not set([1, 3]) <= set([1, 2]) -assert set([1,2]).issubset(set([1,2,3])) -assert set([1,2]).issubset(set([1,2])) -assert not set([1,3]).issubset(set([1,2])) +assert set([1, 2]).issubset(set([1, 2, 3])) +assert set([1, 2]).issubset(set([1, 2])) +assert not set([1, 3]).issubset(set([1, 2])) -assert set([1,2]) < set([1,2,3]) -assert not set([1,2]) < set([1,2]) -assert not set([1,3]) < set([1,2]) +assert set([1, 2]) < set([1, 2, 3]) +assert not set([1, 2]) < set([1, 2]) +assert not set([1, 3]) < set([1, 2]) assert (set() == []) is False assert set().__eq__([]) == NotImplemented -assert_raises(TypeError, lambda: set() < [], _msg="'<' not supported between instances of 'set' and 'list'") -assert_raises(TypeError, lambda: set() <= [], _msg="'<=' not supported between instances of 'set' and 'list'") -assert_raises(TypeError, lambda: set() > [], _msg="'>' not supported between instances of 'set' and 'list'") -assert_raises(TypeError, lambda: set() >= [], _msg="'>=' not supported between instances of 'set' and 'list'") +assert_raises( + TypeError, + lambda: set() < [], + _msg="'<' not supported between instances of 'set' and 'list'", +) +assert_raises( + TypeError, + lambda: set() <= [], + _msg="'<=' not supported between instances of 'set' and 'list'", +) +assert_raises( + TypeError, + lambda: set() > [], + _msg="'>' not supported between instances of 'set' and 'list'", +) +assert_raises( + TypeError, + lambda: set() >= [], + _msg="'>=' not supported between instances of 'set' and 'list'", +) assert set().issuperset([]) assert set().issubset([]) assert not set().issuperset([1, 2, 3]) @@ -47,6 +63,7 @@ assert_raises(TypeError, set().issuperset, 3, _msg="'int' object is not iterable") assert_raises(TypeError, set().issubset, 3, _msg="'int' object is not iterable") + class Hashable(object): def __init__(self, obj): self.obj = obj @@ -57,6 +74,7 @@ def __repr__(self): def __hash__(self): return id(self) + assert repr(set()) == "set()" assert repr(set([1, 2, 3])) == "{1, 2, 3}" @@ -64,9 +82,11 @@ def __hash__(self): recursive.add(Hashable(recursive)) assert repr(recursive) == "{set(...)}" + class S(set): pass + assert repr(S()) == "S()" assert repr(S([1, 2, 3])) == "S({1, 2, 3})" @@ -79,44 +99,44 @@ class S(set): a.clear() assert len(a) == 0 -assert set([1,2,3]).union(set([4,5])) == set([1,2,3,4,5]) -assert set([1,2,3]).union(set([1,2,3,4,5])) == set([1,2,3,4,5]) -assert set([1,2,3]).union([1,2,3,4,5]) == set([1,2,3,4,5]) +assert set([1, 2, 3]).union(set([4, 5])) == set([1, 2, 3, 4, 5]) +assert set([1, 2, 3]).union(set([1, 2, 3, 4, 5])) == set([1, 2, 3, 4, 5]) +assert set([1, 2, 3]).union([1, 2, 3, 4, 5]) == set([1, 2, 3, 4, 5]) -assert set([1,2,3]) | set([4,5]) == set([1,2,3,4,5]) -assert set([1,2,3]) | set([1,2,3,4,5]) == set([1,2,3,4,5]) -assert_raises(TypeError, lambda: set([1,2,3]) | [1,2,3,4,5]) +assert set([1, 2, 3]) | set([4, 5]) == set([1, 2, 3, 4, 5]) +assert set([1, 2, 3]) | set([1, 2, 3, 4, 5]) == set([1, 2, 3, 4, 5]) +assert_raises(TypeError, lambda: set([1, 2, 3]) | [1, 2, 3, 4, 5]) -assert set([1,2,3]).intersection(set([1,2])) == set([1,2]) -assert set([1,2,3]).intersection(set([5,6])) == set([]) -assert set([1,2,3]).intersection([1,2]) == set([1,2]) +assert set([1, 2, 3]).intersection(set([1, 2])) == set([1, 2]) +assert set([1, 2, 3]).intersection(set([5, 6])) == set([]) +assert set([1, 2, 3]).intersection([1, 2]) == set([1, 2]) -assert set([1,2,3]) & set([4,5]) == set([]) -assert set([1,2,3]) & set([1,2,3,4,5]) == set([1,2,3]) -assert_raises(TypeError, lambda: set([1,2,3]) & [1,2,3,4,5]) +assert set([1, 2, 3]) & set([4, 5]) == set([]) +assert set([1, 2, 3]) & set([1, 2, 3, 4, 5]) == set([1, 2, 3]) +assert_raises(TypeError, lambda: set([1, 2, 3]) & [1, 2, 3, 4, 5]) -assert set([1,2,3]).difference(set([1,2])) == set([3]) -assert set([1,2,3]).difference(set([5,6])) == set([1,2,3]) -assert set([1,2,3]).difference([1,2]) == set([3]) +assert set([1, 2, 3]).difference(set([1, 2])) == set([3]) +assert set([1, 2, 3]).difference(set([5, 6])) == set([1, 2, 3]) +assert set([1, 2, 3]).difference([1, 2]) == set([3]) -assert set([1,2,3]) - set([4,5]) == set([1,2,3]) -assert set([1,2,3]) - set([1,2,3,4,5]) == set([]) -assert_raises(TypeError, lambda: set([1,2,3]) - [1,2,3,4,5]) +assert set([1, 2, 3]) - set([4, 5]) == set([1, 2, 3]) +assert set([1, 2, 3]) - set([1, 2, 3, 4, 5]) == set([]) +assert_raises(TypeError, lambda: set([1, 2, 3]) - [1, 2, 3, 4, 5]) -assert set([1,2]).__sub__(set([2,3])) == set([1]) -assert set([1,2]).__rsub__(set([2,3])) == set([3]) +assert set([1, 2]).__sub__(set([2, 3])) == set([1]) +assert set([1, 2]).__rsub__(set([2, 3])) == set([3]) -assert set([1,2,3]).symmetric_difference(set([1,2])) == set([3]) -assert set([1,2,3]).symmetric_difference(set([5,6])) == set([1,2,3,5,6]) -assert set([1,2,3]).symmetric_difference([1,2]) == set([3]) +assert set([1, 2, 3]).symmetric_difference(set([1, 2])) == set([3]) +assert set([1, 2, 3]).symmetric_difference(set([5, 6])) == set([1, 2, 3, 5, 6]) +assert set([1, 2, 3]).symmetric_difference([1, 2]) == set([3]) -assert set([1,2,3]) ^ set([4,5]) == set([1,2,3,4,5]) -assert set([1,2,3]) ^ set([1,2,3,4,5]) == set([4,5]) -assert_raises(TypeError, lambda: set([1,2,3]) ^ [1,2,3,4,5]) +assert set([1, 2, 3]) ^ set([4, 5]) == set([1, 2, 3, 4, 5]) +assert set([1, 2, 3]) ^ set([1, 2, 3, 4, 5]) == set([4, 5]) +assert_raises(TypeError, lambda: set([1, 2, 3]) ^ [1, 2, 3, 4, 5]) -assert set([1,2,3]).isdisjoint(set([5,6])) == True -assert set([1,2,3]).isdisjoint(set([2,5,6])) == False -assert set([1,2,3]).isdisjoint([5,6]) == True +assert set([1, 2, 3]).isdisjoint(set([5, 6])) == True +assert set([1, 2, 3]).isdisjoint(set([2, 5, 6])) == False +assert set([1, 2, 3]).isdisjoint([5, 6]) == True assert_raises(TypeError, lambda: set() & []) assert_raises(TypeError, lambda: set() | []) @@ -132,7 +152,7 @@ class S(set): assert not 1 in a assert a.discard(42) is None -a = set([1,2,3]) +a = set([1, 2, 3]) b = a.copy() assert len(a) == 3 assert len(b) == 3 @@ -140,71 +160,71 @@ class S(set): assert len(a) == 3 assert len(b) == 0 -a = set([1,2]) +a = set([1, 2]) b = a.pop() -assert b in [1,2] +assert b in [1, 2] c = a.pop() -assert (c in [1,2] and c != b) +assert c in [1, 2] and c != b assert_raises(KeyError, lambda: a.pop()) -a = set([1,2,3]) -a.update([3,4,5]) -assert a == set([1,2,3,4,5]) +a = set([1, 2, 3]) +a.update([3, 4, 5]) +assert a == set([1, 2, 3, 4, 5]) assert_raises(TypeError, lambda: a.update(1)) -a = set([1,2,3]) +a = set([1, 2, 3]) b = set() for e in a: - assert e == 1 or e == 2 or e == 3 - b.add(e) + assert e == 1 or e == 2 or e == 3 + b.add(e) assert a == b -a = set([1,2,3]) -a |= set([3,4,5]) -assert a == set([1,2,3,4,5]) +a = set([1, 2, 3]) +a |= set([3, 4, 5]) +assert a == set([1, 2, 3, 4, 5]) with assert_raises(TypeError): - a |= 1 + a |= 1 with assert_raises(TypeError): - a |= [1,2,3] + a |= [1, 2, 3] -a = set([1,2,3]) -a.intersection_update([2,3,4,5]) -assert a == set([2,3]) +a = set([1, 2, 3]) +a.intersection_update([2, 3, 4, 5]) +assert a == set([2, 3]) assert_raises(TypeError, lambda: a.intersection_update(1)) -a = set([1,2,3]) -a &= set([2,3,4,5]) -assert a == set([2,3]) +a = set([1, 2, 3]) +a &= set([2, 3, 4, 5]) +assert a == set([2, 3]) with assert_raises(TypeError): - a &= 1 + a &= 1 with assert_raises(TypeError): - a &= [1,2,3] + a &= [1, 2, 3] -a = set([1,2,3]) -a.difference_update([3,4,5]) -assert a == set([1,2]) +a = set([1, 2, 3]) +a.difference_update([3, 4, 5]) +assert a == set([1, 2]) assert_raises(TypeError, lambda: a.difference_update(1)) -a = set([1,2,3]) -a -= set([3,4,5]) -assert a == set([1,2]) +a = set([1, 2, 3]) +a -= set([3, 4, 5]) +assert a == set([1, 2]) with assert_raises(TypeError): - a -= 1 + a -= 1 with assert_raises(TypeError): - a -= [1,2,3] + a -= [1, 2, 3] -a = set([1,2,3]) -a.symmetric_difference_update([3,4,5]) -assert a == set([1,2,4,5]) +a = set([1, 2, 3]) +a.symmetric_difference_update([3, 4, 5]) +assert a == set([1, 2, 4, 5]) assert_raises(TypeError, lambda: a.difference_update(1)) -a = set([1,2,3]) -a ^= set([3,4,5]) -assert a == set([1,2,4,5]) +a = set([1, 2, 3]) +a ^= set([3, 4, 5]) +assert a == set([1, 2, 4, 5]) with assert_raises(TypeError): - a ^= 1 + a ^= 1 with assert_raises(TypeError): - a ^= [1,2,3] + a ^= [1, 2, 3] a = set([1, 2, 3]) i = iter(a) @@ -218,142 +238,154 @@ class S(set): # frozen set -assert frozenset([1,2]) == frozenset([1,2]) -assert not frozenset([1,2,3]) == frozenset([1,2]) +assert frozenset([1, 2]) == frozenset([1, 2]) +assert not frozenset([1, 2, 3]) == frozenset([1, 2]) -assert frozenset([1,2,3]) >= frozenset([1,2]) -assert frozenset([1,2]) >= frozenset([1,2]) -assert not frozenset([1,3]) >= frozenset([1,2]) +assert frozenset([1, 2, 3]) >= frozenset([1, 2]) +assert frozenset([1, 2]) >= frozenset([1, 2]) +assert not frozenset([1, 3]) >= frozenset([1, 2]) -assert frozenset([1,2,3]).issuperset(frozenset([1,2])) -assert frozenset([1,2]).issuperset(frozenset([1,2])) -assert not frozenset([1,3]).issuperset(frozenset([1,2])) +assert frozenset([1, 2, 3]).issuperset(frozenset([1, 2])) +assert frozenset([1, 2]).issuperset(frozenset([1, 2])) +assert not frozenset([1, 3]).issuperset(frozenset([1, 2])) -assert frozenset([1,2,3]) > frozenset([1,2]) -assert not frozenset([1,2]) > frozenset([1,2]) -assert not frozenset([1,3]) > frozenset([1,2]) +assert frozenset([1, 2, 3]) > frozenset([1, 2]) +assert not frozenset([1, 2]) > frozenset([1, 2]) +assert not frozenset([1, 3]) > frozenset([1, 2]) -assert frozenset([1,2]) <= frozenset([1,2,3]) -assert frozenset([1,2]) <= frozenset([1,2]) -assert not frozenset([1,3]) <= frozenset([1,2]) +assert frozenset([1, 2]) <= frozenset([1, 2, 3]) +assert frozenset([1, 2]) <= frozenset([1, 2]) +assert not frozenset([1, 3]) <= frozenset([1, 2]) -assert frozenset([1,2]).issubset(frozenset([1,2,3])) -assert frozenset([1,2]).issubset(frozenset([1,2])) -assert not frozenset([1,3]).issubset(frozenset([1,2])) +assert frozenset([1, 2]).issubset(frozenset([1, 2, 3])) +assert frozenset([1, 2]).issubset(frozenset([1, 2])) +assert not frozenset([1, 3]).issubset(frozenset([1, 2])) -assert frozenset([1,2]) < frozenset([1,2,3]) -assert not frozenset([1,2]) < frozenset([1,2]) -assert not frozenset([1,3]) < frozenset([1,2]) +assert frozenset([1, 2]) < frozenset([1, 2, 3]) +assert not frozenset([1, 2]) < frozenset([1, 2]) +assert not frozenset([1, 3]) < frozenset([1, 2]) a = frozenset([1, 2, 3]) assert len(a) == 3 b = a.copy() assert b == a -assert frozenset([1,2,3]).union(frozenset([4,5])) == frozenset([1,2,3,4,5]) -assert frozenset([1,2,3]).union(frozenset([1,2,3,4,5])) == frozenset([1,2,3,4,5]) -assert frozenset([1,2,3]).union([1,2,3,4,5]) == frozenset([1,2,3,4,5]) +assert frozenset([1, 2, 3]).union(frozenset([4, 5])) == frozenset([1, 2, 3, 4, 5]) +assert frozenset([1, 2, 3]).union(frozenset([1, 2, 3, 4, 5])) == frozenset( + [1, 2, 3, 4, 5] +) +assert frozenset([1, 2, 3]).union([1, 2, 3, 4, 5]) == frozenset([1, 2, 3, 4, 5]) -assert frozenset([1,2,3]) | frozenset([4,5]) == frozenset([1,2,3,4,5]) -assert frozenset([1,2,3]) | frozenset([1,2,3,4,5]) == frozenset([1,2,3,4,5]) -assert_raises(TypeError, lambda: frozenset([1,2,3]) | [1,2,3,4,5]) +assert frozenset([1, 2, 3]) | frozenset([4, 5]) == frozenset([1, 2, 3, 4, 5]) +assert frozenset([1, 2, 3]) | frozenset([1, 2, 3, 4, 5]) == frozenset([1, 2, 3, 4, 5]) +assert_raises(TypeError, lambda: frozenset([1, 2, 3]) | [1, 2, 3, 4, 5]) -assert frozenset([1,2,3]).intersection(frozenset([1,2])) == frozenset([1,2]) -assert frozenset([1,2,3]).intersection(frozenset([5,6])) == frozenset([]) -assert frozenset([1,2,3]).intersection([1,2]) == frozenset([1,2]) +assert frozenset([1, 2, 3]).intersection(frozenset([1, 2])) == frozenset([1, 2]) +assert frozenset([1, 2, 3]).intersection(frozenset([5, 6])) == frozenset([]) +assert frozenset([1, 2, 3]).intersection([1, 2]) == frozenset([1, 2]) -assert frozenset([1,2,3]) & frozenset([4,5]) == frozenset([]) -assert frozenset([1,2,3]) & frozenset([1,2,3,4,5]) == frozenset([1,2,3]) -assert_raises(TypeError, lambda: frozenset([1,2,3]) & [1,2,3,4,5]) +assert frozenset([1, 2, 3]) & frozenset([4, 5]) == frozenset([]) +assert frozenset([1, 2, 3]) & frozenset([1, 2, 3, 4, 5]) == frozenset([1, 2, 3]) +assert_raises(TypeError, lambda: frozenset([1, 2, 3]) & [1, 2, 3, 4, 5]) -assert frozenset([1,2,3]).difference(frozenset([1,2])) == frozenset([3]) -assert frozenset([1,2,3]).difference(frozenset([5,6])) == frozenset([1,2,3]) -assert frozenset([1,2,3]).difference([1,2]) == frozenset([3]) +assert frozenset([1, 2, 3]).difference(frozenset([1, 2])) == frozenset([3]) +assert frozenset([1, 2, 3]).difference(frozenset([5, 6])) == frozenset([1, 2, 3]) +assert frozenset([1, 2, 3]).difference([1, 2]) == frozenset([3]) -assert frozenset([1,2,3]) - frozenset([4,5]) == frozenset([1,2,3]) -assert frozenset([1,2,3]) - frozenset([1,2,3,4,5]) == frozenset([]) -assert_raises(TypeError, lambda: frozenset([1,2,3]) - [1,2,3,4,5]) +assert frozenset([1, 2, 3]) - frozenset([4, 5]) == frozenset([1, 2, 3]) +assert frozenset([1, 2, 3]) - frozenset([1, 2, 3, 4, 5]) == frozenset([]) +assert_raises(TypeError, lambda: frozenset([1, 2, 3]) - [1, 2, 3, 4, 5]) -assert frozenset([1,2]).__sub__(frozenset([2,3])) == frozenset([1]) -assert frozenset([1,2]).__rsub__(frozenset([2,3])) == frozenset([3]) +assert frozenset([1, 2]).__sub__(frozenset([2, 3])) == frozenset([1]) +assert frozenset([1, 2]).__rsub__(frozenset([2, 3])) == frozenset([3]) -assert frozenset([1,2,3]).symmetric_difference(frozenset([1,2])) == frozenset([3]) -assert frozenset([1,2,3]).symmetric_difference(frozenset([5,6])) == frozenset([1,2,3,5,6]) -assert frozenset([1,2,3]).symmetric_difference([1,2]) == frozenset([3]) +assert frozenset([1, 2, 3]).symmetric_difference(frozenset([1, 2])) == frozenset([3]) +assert frozenset([1, 2, 3]).symmetric_difference(frozenset([5, 6])) == frozenset( + [1, 2, 3, 5, 6] +) +assert frozenset([1, 2, 3]).symmetric_difference([1, 2]) == frozenset([3]) -assert frozenset([1,2,3]) ^ frozenset([4,5]) == frozenset([1,2,3,4,5]) -assert frozenset([1,2,3]) ^ frozenset([1,2,3,4,5]) == frozenset([4,5]) -assert_raises(TypeError, lambda: frozenset([1,2,3]) ^ [1,2,3,4,5]) +assert frozenset([1, 2, 3]) ^ frozenset([4, 5]) == frozenset([1, 2, 3, 4, 5]) +assert frozenset([1, 2, 3]) ^ frozenset([1, 2, 3, 4, 5]) == frozenset([4, 5]) +assert_raises(TypeError, lambda: frozenset([1, 2, 3]) ^ [1, 2, 3, 4, 5]) -assert frozenset([1,2,3]).isdisjoint(frozenset([5,6])) == True -assert frozenset([1,2,3]).isdisjoint(frozenset([2,5,6])) == False -assert frozenset([1,2,3]).isdisjoint([5,6]) == True +assert frozenset([1, 2, 3]).isdisjoint(frozenset([5, 6])) == True +assert frozenset([1, 2, 3]).isdisjoint(frozenset([2, 5, 6])) == False +assert frozenset([1, 2, 3]).isdisjoint([5, 6]) == True assert_raises(TypeError, frozenset, [[]]) -a = frozenset([1,2,3]) +a = frozenset([1, 2, 3]) b = set() for e in a: - assert e == 1 or e == 2 or e == 3 - b.add(e) + assert e == 1 or e == 2 or e == 3 + b.add(e) assert a == b # set and frozen set -assert frozenset([1,2,3]).union(set([4,5])) == frozenset([1,2,3,4,5]) -assert set([1,2,3]).union(frozenset([4,5])) == set([1,2,3,4,5]) +assert frozenset([1, 2, 3]).union(set([4, 5])) == frozenset([1, 2, 3, 4, 5]) +assert set([1, 2, 3]).union(frozenset([4, 5])) == set([1, 2, 3, 4, 5]) + +assert frozenset([1, 2, 3]) | set([4, 5]) == frozenset([1, 2, 3, 4, 5]) +assert set([1, 2, 3]) | frozenset([4, 5]) == set([1, 2, 3, 4, 5]) -assert frozenset([1,2,3]) | set([4,5]) == frozenset([1,2,3,4,5]) -assert set([1,2,3]) | frozenset([4,5]) == set([1,2,3,4,5]) +assert frozenset([1, 2, 3]).intersection(set([5, 6])) == frozenset([]) +assert set([1, 2, 3]).intersection(frozenset([5, 6])) == set([]) -assert frozenset([1,2,3]).intersection(set([5,6])) == frozenset([]) -assert set([1,2,3]).intersection(frozenset([5,6])) == set([]) +assert frozenset([1, 2, 3]) & set([1, 2, 3, 4, 5]) == frozenset([1, 2, 3]) +assert set([1, 2, 3]) & frozenset([1, 2, 3, 4, 5]) == set([1, 2, 3]) -assert frozenset([1,2,3]) & set([1,2,3,4,5]) == frozenset([1,2,3]) -assert set([1,2,3]) & frozenset([1,2,3,4,5]) == set([1,2,3]) +assert frozenset([1, 2, 3]).difference(set([5, 6])) == frozenset([1, 2, 3]) +assert set([1, 2, 3]).difference(frozenset([5, 6])) == set([1, 2, 3]) -assert frozenset([1,2,3]).difference(set([5,6])) == frozenset([1,2,3]) -assert set([1,2,3]).difference(frozenset([5,6])) == set([1,2,3]) +assert frozenset([1, 2, 3]) - set([4, 5]) == frozenset([1, 2, 3]) +assert set([1, 2, 3]) - frozenset([4, 5]) == frozenset([1, 2, 3]) -assert frozenset([1,2,3]) - set([4,5]) == frozenset([1,2,3]) -assert set([1,2,3]) - frozenset([4,5]) == frozenset([1,2,3]) +assert frozenset([1, 2]).__sub__(set([2, 3])) == frozenset([1]) +assert frozenset([1, 2]).__rsub__(set([2, 3])) == set([3]) +assert set([1, 2]).__sub__(frozenset([2, 3])) == set([1]) +assert set([1, 2]).__rsub__(frozenset([2, 3])) == frozenset([3]) -assert frozenset([1,2]).__sub__(set([2,3])) == frozenset([1]) -assert frozenset([1,2]).__rsub__(set([2,3])) == set([3]) -assert set([1,2]).__sub__(frozenset([2,3])) == set([1]) -assert set([1,2]).__rsub__(frozenset([2,3])) == frozenset([3]) +assert frozenset([1, 2, 3]).symmetric_difference(set([1, 2])) == frozenset([3]) +assert set([1, 2, 3]).symmetric_difference(frozenset([1, 2])) == set([3]) -assert frozenset([1,2,3]).symmetric_difference(set([1,2])) == frozenset([3]) -assert set([1,2,3]).symmetric_difference(frozenset([1,2])) == set([3]) +assert frozenset([1, 2, 3]) ^ set([4, 5]) == frozenset([1, 2, 3, 4, 5]) +assert set([1, 2, 3]) ^ frozenset([4, 5]) == set([1, 2, 3, 4, 5]) -assert frozenset([1,2,3]) ^ set([4,5]) == frozenset([1,2,3,4,5]) -assert set([1,2,3]) ^ frozenset([4,5]) == set([1,2,3,4,5]) class A: def __hash__(self): return 1 + + class B: def __hash__(self): return 1 + s = {1, A(), B()} assert len(s) == 3 s = {True} s.add(1.0) -assert str(s) == '{True}' +assert str(s) == "{True}" + class EqObject: def __init__(self, eq): self.eq = eq + def __eq__(self, other): return self.eq + def __hash__(self): return bool(self.eq) -assert 'x' == (EqObject('x') == EqObject('x')) -s = {EqObject('x')} -assert EqObject('x') in s -assert '[]' == (EqObject('[]') == EqObject('[]')) + +assert "x" == (EqObject("x") == EqObject("x")) +s = {EqObject("x")} +assert EqObject("x") in s +assert "[]" == (EqObject("[]") == EqObject("[]")) s = {EqObject([])} assert EqObject([]) not in s x = object() @@ -372,8 +404,8 @@ def __hash__(self): assert frozenset().__ne__(1) == NotImplemented empty_set = set() -non_empty_set = set([1,2,3]) -set_from_literal = {1,2,3} +non_empty_set = set([1, 2, 3]) +set_from_literal = {1, 2, 3} assert 1 in non_empty_set assert 4 not in non_empty_set @@ -382,8 +414,8 @@ def __hash__(self): assert 4 not in set_from_literal # TODO: Assert that empty aruguments raises exception. -non_empty_set.add('a') -assert 'a' in non_empty_set +non_empty_set.add("a") +assert "a" in non_empty_set # TODO: Assert that empty arguments, or item not in set raises exception. non_empty_set.remove(1) @@ -394,8 +426,10 @@ def __hash__(self): assert repr(frozenset()) == "frozenset()" assert repr(frozenset([1, 2, 3])) == "frozenset({1, 2, 3})" + class FS(frozenset): pass + assert repr(FS()) == "FS()" assert repr(FS([1, 2, 3])) == "FS({1, 2, 3})" diff --git a/extra_tests/snippets/builtin_slice.py b/extra_tests/snippets/builtin_slice.py index b5c3a8ceb4..9a5c1bc78d 100644 --- a/extra_tests/snippets/builtin_slice.py +++ b/extra_tests/snippets/builtin_slice.py @@ -10,16 +10,16 @@ assert a.stop == 10 assert a.step == 1 -assert slice(10).__repr__() == 'slice(None, 10, None)' -assert slice(None).__repr__() == 'slice(None, None, None)' -assert slice(0, 10, 13).__repr__() == 'slice(0, 10, 13)' -assert slice('0', 1.1, 2+3j).__repr__() == "slice('0', 1.1, (2+3j))" +assert slice(10).__repr__() == "slice(None, 10, None)" +assert slice(None).__repr__() == "slice(None, None, None)" +assert slice(0, 10, 13).__repr__() == "slice(0, 10, 13)" +assert slice("0", 1.1, 2 + 3j).__repr__() == "slice('0', 1.1, (2+3j))" assert slice(10) == slice(10) assert slice(-1) != slice(1) assert slice(0, 10, 3) != slice(0, 11, 3) -assert slice(0, None, 3) != slice(0, 'a', 3) -assert slice(0, 'a', 3) == slice(0, 'a', 3) +assert slice(0, None, 3) != slice(0, "a", 3) +assert slice(0, "a", 3) == slice(0, "a", 3) assert slice(0, 0, 0).__eq__(slice(0, 0, 0)) assert not slice(0, 0, 1).__eq__(slice(0, 0, 0)) @@ -65,29 +65,29 @@ assert not slice(0, 0, 0) > slice(0, 0, 0) assert not slice(0, 0, 0) < slice(0, 0, 0) -assert not slice(0, float('nan'), float('nan')) <= slice(0, float('nan'), 1) -assert not slice(0, float('nan'), float('nan')) <= slice(0, float('nan'), float('nan')) -assert not slice(0, float('nan'), float('nan')) >= slice(0, float('nan'), float('nan')) -assert not slice(0, float('nan'), float('nan')) < slice(0, float('nan'), float('nan')) -assert not slice(0, float('nan'), float('nan')) > slice(0, float('nan'), float('nan')) +assert not slice(0, float("nan"), float("nan")) <= slice(0, float("nan"), 1) +assert not slice(0, float("nan"), float("nan")) <= slice(0, float("nan"), float("nan")) +assert not slice(0, float("nan"), float("nan")) >= slice(0, float("nan"), float("nan")) +assert not slice(0, float("nan"), float("nan")) < slice(0, float("nan"), float("nan")) +assert not slice(0, float("nan"), float("nan")) > slice(0, float("nan"), float("nan")) -assert slice(0, float('inf'), float('inf')) >= slice(0, float('inf'), 1) -assert slice(0, float('inf'), float('inf')) <= slice(0, float('inf'), float('inf')) -assert slice(0, float('inf'), float('inf')) >= slice(0, float('inf'), float('inf')) -assert not slice(0, float('inf'), float('inf')) < slice(0, float('inf'), float('inf')) -assert not slice(0, float('inf'), float('inf')) > slice(0, float('inf'), float('inf')) +assert slice(0, float("inf"), float("inf")) >= slice(0, float("inf"), 1) +assert slice(0, float("inf"), float("inf")) <= slice(0, float("inf"), float("inf")) +assert slice(0, float("inf"), float("inf")) >= slice(0, float("inf"), float("inf")) +assert not slice(0, float("inf"), float("inf")) < slice(0, float("inf"), float("inf")) +assert not slice(0, float("inf"), float("inf")) > slice(0, float("inf"), float("inf")) assert_raises(TypeError, lambda: slice(0) < 3) assert_raises(TypeError, lambda: slice(0) > 3) assert_raises(TypeError, lambda: slice(0) <= 3) assert_raises(TypeError, lambda: slice(0) >= 3) -assert slice(None ).indices(10) == (0, 10, 1) -assert slice(None, None, 2).indices(10) == (0, 10, 2) -assert slice(1, None, 2).indices(10) == (1, 10, 2) -assert slice(None, None, -1).indices(10) == (9, -1, -1) -assert slice(None, None, -2).indices(10) == (9, -1, -2) -assert slice(3, None, -2).indices(10) == (3, -1, -2) +assert slice(None).indices(10) == (0, 10, 1) +assert slice(None, None, 2).indices(10) == (0, 10, 2) +assert slice(1, None, 2).indices(10) == (1, 10, 2) +assert slice(None, None, -1).indices(10) == (9, -1, -1) +assert slice(None, None, -2).indices(10) == (9, -1, -2) +assert slice(3, None, -2).indices(10) == (3, -1, -2) # issue 3004 tests assert slice(None, -9).indices(10) == (0, 1, 1) @@ -103,21 +103,17 @@ assert slice(None, 9, -1).indices(10) == (9, 9, -1) assert slice(None, 10, -1).indices(10) == (9, 9, -1) -assert \ - slice(-100, 100).indices(10) == \ - slice(None ).indices(10) +assert slice(-100, 100).indices(10) == slice(None).indices(10) -assert \ - slice(100, -100, -1).indices(10) == \ - slice(None, None, -1).indices(10) +assert slice(100, -100, -1).indices(10) == slice(None, None, -1).indices(10) -assert slice(-100, 100, 2).indices(10) == (0, 10, 2) +assert slice(-100, 100, 2).indices(10) == (0, 10, 2) try: - slice(None, None, 0) - assert "zero step" == "throws an exception" + slice(None, None, 0) + assert "zero step" == "throws an exception" except: - pass + pass a = [] b = [1, 2] @@ -167,8 +163,8 @@ def __index__(self): return self.x -assert c[CustomIndex(1):CustomIndex(3)] == [1, 2] -assert d[CustomIndex(1):CustomIndex(3)] == "23" +assert c[CustomIndex(1) : CustomIndex(3)] == [1, 2] +assert d[CustomIndex(1) : CustomIndex(3)] == "23" def test_all_slices(): @@ -176,7 +172,7 @@ def test_all_slices(): test all possible slices except big number """ - mod = __import__('cpython_generated_slices') + mod = __import__("cpython_generated_slices") ll = mod.LL start = mod.START diff --git a/extra_tests/snippets/builtin_str.py b/extra_tests/snippets/builtin_str.py index cd7133e355..1b9a7bde1a 100644 --- a/extra_tests/snippets/builtin_str.py +++ b/extra_tests/snippets/builtin_str.py @@ -1,14 +1,17 @@ from testutils import assert_raises, AssertRaises, skip_if_unsupported assert "".__eq__(1) == NotImplemented -assert "a" == 'a' +assert "a" == "a" assert """a""" == "a" assert len(""" " "" " "" """) == 11 -assert "\"" == '"' -assert "\"" == """\"""" +assert '"' == '"' +assert '"' == """\"""" -assert "\n" == """ +assert ( + "\n" + == """ """ +) assert len(""" " \" """) == 5 assert len("é") == 1 @@ -30,7 +33,7 @@ assert repr("a") == "'a'" assert repr("can't") == '"can\'t"' assert repr('"won\'t"') == "'\"won\\'t\"'" -assert repr('\n\t') == "'\\n\\t'" +assert repr("\n\t") == "'\\n\\t'" assert str(["a", "b", "can't"]) == "['a', 'b', \"can't\"]" @@ -42,22 +45,22 @@ assert 0 * "x" == "" assert -1 * "x" == "" -assert_raises(OverflowError, lambda: 'xy' * 234234234234234234234234234234) - -a = 'Hallo' -assert a.lower() == 'hallo' -assert a.upper() == 'HALLO' -assert a.startswith('H') -assert a.startswith(('H', 1)) -assert a.startswith(('A', 'H')) -assert not a.startswith('f') -assert not a.startswith(('A', 'f')) -assert a.endswith('llo') -assert a.endswith(('lo', 1)) -assert a.endswith(('A', 'lo')) -assert not a.endswith('on') -assert not a.endswith(('A', 'll')) -assert a.zfill(8) == '000Hallo' +assert_raises(OverflowError, lambda: "xy" * 234234234234234234234234234234) + +a = "Hallo" +assert a.lower() == "hallo" +assert a.upper() == "HALLO" +assert a.startswith("H") +assert a.startswith(("H", 1)) +assert a.startswith(("A", "H")) +assert not a.startswith("f") +assert not a.startswith(("A", "f")) +assert a.endswith("llo") +assert a.endswith(("lo", 1)) +assert a.endswith(("A", "lo")) +assert not a.endswith("on") +assert not a.endswith(("A", "ll")) +assert a.zfill(8) == "000Hallo" assert a.isalnum() assert not a.isdigit() assert not a.isdecimal() @@ -65,34 +68,34 @@ assert a.istitle() assert a.isalpha() -s = '1 2 3' -assert s.split(' ', 1) == ['1', '2 3'] -assert s.rsplit(' ', 1) == ['1 2', '3'] - -b = ' hallo ' -assert b.strip() == 'hallo' -assert b.lstrip() == 'hallo ' -assert b.rstrip() == ' hallo' - -s = '^*RustPython*^' -assert s.strip('^*') == 'RustPython' -assert s.lstrip('^*') == 'RustPython*^' -assert s.rstrip('^*') == '^*RustPython' - -s = 'RustPython' -assert s.ljust(8) == 'RustPython' -assert s.rjust(8) == 'RustPython' -assert s.ljust(12) == 'RustPython ' -assert s.rjust(12) == ' RustPython' -assert s.ljust(12, '_') == 'RustPython__' -assert s.rjust(12, '_') == '__RustPython' +s = "1 2 3" +assert s.split(" ", 1) == ["1", "2 3"] +assert s.rsplit(" ", 1) == ["1 2", "3"] + +b = " hallo " +assert b.strip() == "hallo" +assert b.lstrip() == "hallo " +assert b.rstrip() == " hallo" + +s = "^*RustPython*^" +assert s.strip("^*") == "RustPython" +assert s.lstrip("^*") == "RustPython*^" +assert s.rstrip("^*") == "^*RustPython" + +s = "RustPython" +assert s.ljust(8) == "RustPython" +assert s.rjust(8) == "RustPython" +assert s.ljust(12) == "RustPython " +assert s.rjust(12) == " RustPython" +assert s.ljust(12, "_") == "RustPython__" +assert s.rjust(12, "_") == "__RustPython" # The fill character must be exactly one character long -assert_raises(TypeError, lambda: s.ljust(12, '__')) -assert_raises(TypeError, lambda: s.rjust(12, '__')) +assert_raises(TypeError, lambda: s.ljust(12, "__")) +assert_raises(TypeError, lambda: s.rjust(12, "__")) -c = 'hallo' -assert c.capitalize() == 'Hallo' -assert c.center(11, '-') == '---hallo---' +c = "hallo" +assert c.capitalize() == "Hallo" +assert c.center(11, "-") == "---hallo---" assert ["koki".center(i, "|") for i in range(3, 10)] == [ "koki", "koki", @@ -118,110 +121,157 @@ # requires CPython 3.7, and the CI currently runs with 3.6 # assert c.isascii() -assert c.index('a') == 1 -assert c.rindex('l') == 3 -assert c.find('h') == 0 -assert c.rfind('x') == -1 +assert c.index("a") == 1 +assert c.rindex("l") == 3 +assert c.find("h") == 0 +assert c.rfind("x") == -1 assert c.islower() -assert c.title() == 'Hallo' -assert c.count('l') == 2 - -assert 'aaa'.count('a') == 3 -assert 'aaa'.count('a', 1) == 2 -assert 'aaa'.count('a', 1, 2) == 1 -assert 'aaa'.count('a', 2, 2) == 0 -assert 'aaa'.count('a', 2, 1) == 0 - -assert '___a__'.find('a') == 3 -assert '___a__'.find('a', -10) == 3 -assert '___a__'.find('a', -3) == 3 -assert '___a__'.find('a', -2) == -1 -assert '___a__'.find('a', -1) == -1 -assert '___a__'.find('a', 0) == 3 -assert '___a__'.find('a', 3) == 3 -assert '___a__'.find('a', 4) == -1 -assert '___a__'.find('a', 10) == -1 -assert '___a__'.rfind('a', 3) == 3 -assert '___a__'.index('a', 3) == 3 - -assert '___a__'.find('a', 0, -10) == -1 -assert '___a__'.find('a', 0, -3) == -1 -assert '___a__'.find('a', 0, -2) == 3 -assert '___a__'.find('a', 0, -1) == 3 -assert '___a__'.find('a', 0, 0) == -1 -assert '___a__'.find('a', 0, 3) == -1 -assert '___a__'.find('a', 0, 4) == 3 -assert '___a__'.find('a', 0, 10) == 3 - -assert '___a__'.find('a', 3, 3) == -1 -assert '___a__'.find('a', 3, 4) == 3 -assert '___a__'.find('a', 4, 3) == -1 - -assert 'abcd'.startswith('b', 1) -assert 'abcd'.startswith(('b', 'z'), 1) -assert not 'abcd'.startswith('b', -4) -assert 'abcd'.startswith('b', -3) - -assert not 'abcd'.startswith('b', 3, 3) -assert 'abcd'.startswith('', 3, 3) -assert not 'abcd'.startswith('', 4, 3) - -assert ' '.isspace() -assert 'hello\nhallo\nHallo'.splitlines() == ['hello', 'hallo', 'Hallo'] -assert 'hello\nhallo\nHallo\n'.splitlines() == ['hello', 'hallo', 'Hallo'] -assert 'hello\nhallo\nHallo'.splitlines(keepends=True) == ['hello\n', 'hallo\n', 'Hallo'] -assert 'hello\nhallo\nHallo\n'.splitlines(keepends=True) == ['hello\n', 'hallo\n', 'Hallo\n'] -assert 'hello\vhallo\x0cHallo\x1cHELLO\x1dhoho\x1ehaha\x85another\u2028yetanother\u2029last\r\n.'.splitlines() == ['hello', 'hallo', 'Hallo', 'HELLO', 'hoho', 'haha', 'another', 'yetanother', 'last', '.'] -assert 'hello\vhallo\x0cHallo\x1cHELLO\x1dhoho\x1ehaha\x85another\u2028yetanother\u2029last\r\n.'.splitlines(keepends=True) == ['hello\x0b', 'hallo\x0c', 'Hallo\x1c', 'HELLO\x1d', 'hoho\x1e', 'haha\x85', 'another\u2028', 'yetanother\u2029', 'last\r\n', '.'] -assert 'abc\t12345\txyz'.expandtabs() == 'abc 12345 xyz' -assert '-'.join(['1', '2', '3']) == '1-2-3' -assert 'HALLO'.isupper() -assert "hello, my name is".partition("my ") == ('hello, ', 'my ', 'name is') -assert "hello".partition("is") == ('hello', '', '') -assert "hello, my name is".rpartition("is") == ('hello, my name ', 'is', '') -assert "hello".rpartition("is") == ('', '', 'hello') -assert not ''.isdecimal() -assert '123'.isdecimal() -assert not '\u00B2'.isdecimal() - -assert not ''.isidentifier() -assert 'python'.isidentifier() -assert '_'.isidentifier() -assert '유니코드'.isidentifier() -assert not '😂'.isidentifier() -assert not '123'.isidentifier() +assert c.title() == "Hallo" +assert c.count("l") == 2 + +assert "aaa".count("a") == 3 +assert "aaa".count("a", 1) == 2 +assert "aaa".count("a", 1, 2) == 1 +assert "aaa".count("a", 2, 2) == 0 +assert "aaa".count("a", 2, 1) == 0 + +assert "___a__".find("a") == 3 +assert "___a__".find("a", -10) == 3 +assert "___a__".find("a", -3) == 3 +assert "___a__".find("a", -2) == -1 +assert "___a__".find("a", -1) == -1 +assert "___a__".find("a", 0) == 3 +assert "___a__".find("a", 3) == 3 +assert "___a__".find("a", 4) == -1 +assert "___a__".find("a", 10) == -1 +assert "___a__".rfind("a", 3) == 3 +assert "___a__".index("a", 3) == 3 + +assert "___a__".find("a", 0, -10) == -1 +assert "___a__".find("a", 0, -3) == -1 +assert "___a__".find("a", 0, -2) == 3 +assert "___a__".find("a", 0, -1) == 3 +assert "___a__".find("a", 0, 0) == -1 +assert "___a__".find("a", 0, 3) == -1 +assert "___a__".find("a", 0, 4) == 3 +assert "___a__".find("a", 0, 10) == 3 + +assert "___a__".find("a", 3, 3) == -1 +assert "___a__".find("a", 3, 4) == 3 +assert "___a__".find("a", 4, 3) == -1 + +assert "abcd".startswith("b", 1) +assert "abcd".startswith(("b", "z"), 1) +assert not "abcd".startswith("b", -4) +assert "abcd".startswith("b", -3) + +assert not "abcd".startswith("b", 3, 3) +assert "abcd".startswith("", 3, 3) +assert not "abcd".startswith("", 4, 3) + +assert " ".isspace() +assert "hello\nhallo\nHallo".splitlines() == ["hello", "hallo", "Hallo"] +assert "hello\nhallo\nHallo\n".splitlines() == ["hello", "hallo", "Hallo"] +assert "hello\nhallo\nHallo".splitlines(keepends=True) == [ + "hello\n", + "hallo\n", + "Hallo", +] +assert "hello\nhallo\nHallo\n".splitlines(keepends=True) == [ + "hello\n", + "hallo\n", + "Hallo\n", +] +assert ( + "hello\vhallo\x0cHallo\x1cHELLO\x1dhoho\x1ehaha\x85another\u2028yetanother\u2029last\r\n.".splitlines() + == [ + "hello", + "hallo", + "Hallo", + "HELLO", + "hoho", + "haha", + "another", + "yetanother", + "last", + ".", + ] +) +assert ( + "hello\vhallo\x0cHallo\x1cHELLO\x1dhoho\x1ehaha\x85another\u2028yetanother\u2029last\r\n.".splitlines( + keepends=True + ) + == [ + "hello\x0b", + "hallo\x0c", + "Hallo\x1c", + "HELLO\x1d", + "hoho\x1e", + "haha\x85", + "another\u2028", + "yetanother\u2029", + "last\r\n", + ".", + ] +) +assert "abc\t12345\txyz".expandtabs() == "abc 12345 xyz" +assert "-".join(["1", "2", "3"]) == "1-2-3" +assert "HALLO".isupper() +assert "hello, my name is".partition("my ") == ("hello, ", "my ", "name is") +assert "hello".partition("is") == ("hello", "", "") +assert "hello, my name is".rpartition("is") == ("hello, my name ", "is", "") +assert "hello".rpartition("is") == ("", "", "hello") +assert not "".isdecimal() +assert "123".isdecimal() +assert not "\u00b2".isdecimal() + +assert not "".isidentifier() +assert "python".isidentifier() +assert "_".isidentifier() +assert "유니코드".isidentifier() +assert not "😂".isidentifier() +assert not "123".isidentifier() # String Formatting assert "{} {}".format(1, 2) == "1 2" assert "{0} {1}".format(2, 3) == "2 3" assert "--{:s>4}--".format(1) == "--sss1--" assert "{keyword} {0}".format(1, keyword=2) == "2 1" -assert "repr() shows quotes: {!r}; str() doesn't: {!s}".format( - 'test1', 'test2' -) == "repr() shows quotes: 'test1'; str() doesn't: test2", 'Output: {!r}, {!s}'.format('test1', 'test2') +assert ( + "repr() shows quotes: {!r}; str() doesn't: {!s}".format("test1", "test2") + == "repr() shows quotes: 'test1'; str() doesn't: test2" +), "Output: {!r}, {!s}".format("test1", "test2") class Foo: def __str__(self): - return 'str(Foo)' + return "str(Foo)" def __repr__(self): - return 'repr(Foo)' + return "repr(Foo)" f = Foo() -assert "{} {!s} {!r} {!a}".format(f, f, f, f) == 'str(Foo) str(Foo) repr(Foo) repr(Foo)' -assert "{foo} {foo!s} {foo!r} {foo!a}".format(foo=f) == 'str(Foo) str(Foo) repr(Foo) repr(Foo)' +assert "{} {!s} {!r} {!a}".format(f, f, f, f) == "str(Foo) str(Foo) repr(Foo) repr(Foo)" +assert ( + "{foo} {foo!s} {foo!r} {foo!a}".format(foo=f) + == "str(Foo) str(Foo) repr(Foo) repr(Foo)" +) # assert '{} {!r} {:10} {!r:10} {foo!r:10} {foo!r} {foo}'.format('txt1', 'txt2', 'txt3', 'txt4', 'txt5', foo='bar') # Printf-style String formatting assert "%d %d" % (1, 2) == "1 2" -assert "%*c " % (3, '❤') == " ❤ " -assert "%(first)s %(second)s" % {'second': 'World!', 'first': "Hello,"} == "Hello, World!" -assert "%(key())s" % {'key()': 'aaa'} +assert "%*c " % (3, "❤") == " ❤ " +assert ( + "%(first)s %(second)s" % {"second": "World!", "first": "Hello,"} == "Hello, World!" +) +assert "%(key())s" % {"key()": "aaa"} assert "%s %a %r" % (f, f, f) == "str(Foo) repr(Foo) repr(Foo)" -assert "repr() shows quotes: %r; str() doesn't: %s" % ("test1", "test2") == "repr() shows quotes: 'test1'; str() doesn't: test2" +assert ( + "repr() shows quotes: %r; str() doesn't: %s" % ("test1", "test2") + == "repr() shows quotes: 'test1'; str() doesn't: test2" +) assert "%f" % (1.2345) == "1.234500" assert "%+f" % (1.2345) == "+1.234500" assert "% f" % (1.2345) == " 1.234500" @@ -229,111 +279,132 @@ def __repr__(self): assert "%f" % (1.23456789012) == "1.234568" assert "%f" % (123) == "123.000000" assert "%f" % (-123) == "-123.000000" -assert "%e" % 1 == '1.000000e+00' -assert "%e" % 0 == '0.000000e+00' -assert "%e" % 0.1 == '1.000000e-01' -assert "%e" % 10 == '1.000000e+01' -assert "%.10e" % 1.2345678901234567890 == '1.2345678901e+00' -assert '%e' % float('nan') == 'nan' -assert '%e' % float('-nan') == 'nan' -assert '%E' % float('nan') == 'NAN' -assert '%e' % float('inf') == 'inf' -assert '%e' % float('-inf') == '-inf' -assert '%E' % float('inf') == 'INF' -assert "%g" % 123456.78901234567890 == '123457' -assert "%.0g" % 123456.78901234567890 == '1e+05' -assert "%.1g" % 123456.78901234567890 == '1e+05' -assert "%.2g" % 123456.78901234567890 == '1.2e+05' -assert "%g" % 1234567.8901234567890 == '1.23457e+06' -assert "%.0g" % 1234567.8901234567890 == '1e+06' -assert "%.1g" % 1234567.8901234567890 == '1e+06' -assert "%.2g" % 1234567.8901234567890 == '1.2e+06' -assert "%.3g" % 1234567.8901234567890 == '1.23e+06' -assert "%.5g" % 1234567.8901234567890 == '1.2346e+06' -assert "%.6g" % 1234567.8901234567890 == '1.23457e+06' -assert "%.7g" % 1234567.8901234567890 == '1234568' -assert "%.8g" % 1234567.8901234567890 == '1234567.9' -assert "%G" % 123456.78901234567890 == '123457' -assert "%.0G" % 123456.78901234567890 == '1E+05' -assert "%.1G" % 123456.78901234567890 == '1E+05' -assert "%.2G" % 123456.78901234567890 == '1.2E+05' -assert "%G" % 1234567.8901234567890 == '1.23457E+06' -assert "%.0G" % 1234567.8901234567890 == '1E+06' -assert "%.1G" % 1234567.8901234567890 == '1E+06' -assert "%.2G" % 1234567.8901234567890 == '1.2E+06' -assert "%.3G" % 1234567.8901234567890 == '1.23E+06' -assert "%.5G" % 1234567.8901234567890 == '1.2346E+06' -assert "%.6G" % 1234567.8901234567890 == '1.23457E+06' -assert "%.7G" % 1234567.8901234567890 == '1234568' -assert "%.8G" % 1234567.8901234567890 == '1234567.9' -assert '%g' % 0.12345678901234567890 == '0.123457' -assert '%g' % 0.12345678901234567890e-1 == '0.0123457' -assert '%g' % 0.12345678901234567890e-2 == '0.00123457' -assert '%g' % 0.12345678901234567890e-3 == '0.000123457' -assert '%g' % 0.12345678901234567890e-4 == '1.23457e-05' -assert '%g' % 0.12345678901234567890e-5 == '1.23457e-06' -assert '%.6g' % 0.12345678901234567890e-5 == '1.23457e-06' -assert '%.10g' % 0.12345678901234567890e-5 == '1.23456789e-06' -assert '%.20g' % 0.12345678901234567890e-5 == '1.2345678901234567384e-06' -assert '%G' % 0.12345678901234567890 == '0.123457' -assert '%G' % 0.12345678901234567890E-1 == '0.0123457' -assert '%G' % 0.12345678901234567890E-2 == '0.00123457' -assert '%G' % 0.12345678901234567890E-3 == '0.000123457' -assert '%G' % 0.12345678901234567890E-4 == '1.23457E-05' -assert '%G' % 0.12345678901234567890E-5 == '1.23457E-06' -assert '%.6G' % 0.12345678901234567890E-5 == '1.23457E-06' -assert '%.10G' % 0.12345678901234567890E-5 == '1.23456789E-06' -assert '%.20G' % 0.12345678901234567890E-5 == '1.2345678901234567384E-06' -assert '%g' % float('nan') == 'nan' -assert '%g' % float('-nan') == 'nan' -assert '%G' % float('nan') == 'NAN' -assert '%g' % float('inf') == 'inf' -assert '%g' % float('-inf') == '-inf' -assert '%G' % float('inf') == 'INF' -assert "%.0g" % 1.020e-13 == '1e-13' -assert "%.0g" % 1.020e-13 == '1e-13' -assert "%.1g" % 1.020e-13 == '1e-13' -assert "%.2g" % 1.020e-13 == '1e-13' -assert "%.3g" % 1.020e-13 == '1.02e-13' -assert "%.4g" % 1.020e-13 == '1.02e-13' -assert "%.5g" % 1.020e-13 == '1.02e-13' -assert "%.6g" % 1.020e-13 == '1.02e-13' -assert "%.7g" % 1.020e-13 == '1.02e-13' -assert "%g" % 1.020e-13 == '1.02e-13' -assert "%g" % 1.020e-4 == '0.000102' - -assert_raises(TypeError, lambda: "My name is %s and I'm %(age)d years old" % ("Foo", 25), _msg='format requires a mapping') -assert_raises(TypeError, lambda: "My name is %(name)s" % "Foo", _msg='format requires a mapping') -assert_raises(ValueError, lambda: "This %(food}s is great!" % {"food": "cookie"}, _msg='incomplete format key') -assert_raises(ValueError, lambda: "My name is %" % "Foo", _msg='incomplete format') - -assert 'a' < 'b' -assert 'a' <= 'b' -assert 'a' <= 'a' -assert 'z' > 'b' -assert 'z' >= 'b' -assert 'a' >= 'a' +assert "%e" % 1 == "1.000000e+00" +assert "%e" % 0 == "0.000000e+00" +assert "%e" % 0.1 == "1.000000e-01" +assert "%e" % 10 == "1.000000e+01" +assert "%.10e" % 1.2345678901234567890 == "1.2345678901e+00" +assert "%e" % float("nan") == "nan" +assert "%e" % float("-nan") == "nan" +assert "%E" % float("nan") == "NAN" +assert "%e" % float("inf") == "inf" +assert "%e" % float("-inf") == "-inf" +assert "%E" % float("inf") == "INF" +assert "%g" % 123456.78901234567890 == "123457" +assert "%.0g" % 123456.78901234567890 == "1e+05" +assert "%.1g" % 123456.78901234567890 == "1e+05" +assert "%.2g" % 123456.78901234567890 == "1.2e+05" +assert "%g" % 1234567.8901234567890 == "1.23457e+06" +assert "%.0g" % 1234567.8901234567890 == "1e+06" +assert "%.1g" % 1234567.8901234567890 == "1e+06" +assert "%.2g" % 1234567.8901234567890 == "1.2e+06" +assert "%.3g" % 1234567.8901234567890 == "1.23e+06" +assert "%.5g" % 1234567.8901234567890 == "1.2346e+06" +assert "%.6g" % 1234567.8901234567890 == "1.23457e+06" +assert "%.7g" % 1234567.8901234567890 == "1234568" +assert "%.8g" % 1234567.8901234567890 == "1234567.9" +assert "%G" % 123456.78901234567890 == "123457" +assert "%.0G" % 123456.78901234567890 == "1E+05" +assert "%.1G" % 123456.78901234567890 == "1E+05" +assert "%.2G" % 123456.78901234567890 == "1.2E+05" +assert "%G" % 1234567.8901234567890 == "1.23457E+06" +assert "%.0G" % 1234567.8901234567890 == "1E+06" +assert "%.1G" % 1234567.8901234567890 == "1E+06" +assert "%.2G" % 1234567.8901234567890 == "1.2E+06" +assert "%.3G" % 1234567.8901234567890 == "1.23E+06" +assert "%.5G" % 1234567.8901234567890 == "1.2346E+06" +assert "%.6G" % 1234567.8901234567890 == "1.23457E+06" +assert "%.7G" % 1234567.8901234567890 == "1234568" +assert "%.8G" % 1234567.8901234567890 == "1234567.9" +assert "%g" % 0.12345678901234567890 == "0.123457" +assert "%g" % 0.12345678901234567890e-1 == "0.0123457" +assert "%g" % 0.12345678901234567890e-2 == "0.00123457" +assert "%g" % 0.12345678901234567890e-3 == "0.000123457" +assert "%g" % 0.12345678901234567890e-4 == "1.23457e-05" +assert "%g" % 0.12345678901234567890e-5 == "1.23457e-06" +assert "%.6g" % 0.12345678901234567890e-5 == "1.23457e-06" +assert "%.10g" % 0.12345678901234567890e-5 == "1.23456789e-06" +assert "%.20g" % 0.12345678901234567890e-5 == "1.2345678901234567384e-06" +assert "%G" % 0.12345678901234567890 == "0.123457" +assert "%G" % 0.12345678901234567890e-1 == "0.0123457" +assert "%G" % 0.12345678901234567890e-2 == "0.00123457" +assert "%G" % 0.12345678901234567890e-3 == "0.000123457" +assert "%G" % 0.12345678901234567890e-4 == "1.23457E-05" +assert "%G" % 0.12345678901234567890e-5 == "1.23457E-06" +assert "%.6G" % 0.12345678901234567890e-5 == "1.23457E-06" +assert "%.10G" % 0.12345678901234567890e-5 == "1.23456789E-06" +assert "%.20G" % 0.12345678901234567890e-5 == "1.2345678901234567384E-06" +assert "%g" % float("nan") == "nan" +assert "%g" % float("-nan") == "nan" +assert "%G" % float("nan") == "NAN" +assert "%g" % float("inf") == "inf" +assert "%g" % float("-inf") == "-inf" +assert "%G" % float("inf") == "INF" +assert "%.0g" % 1.020e-13 == "1e-13" +assert "%.0g" % 1.020e-13 == "1e-13" +assert "%.1g" % 1.020e-13 == "1e-13" +assert "%.2g" % 1.020e-13 == "1e-13" +assert "%.3g" % 1.020e-13 == "1.02e-13" +assert "%.4g" % 1.020e-13 == "1.02e-13" +assert "%.5g" % 1.020e-13 == "1.02e-13" +assert "%.6g" % 1.020e-13 == "1.02e-13" +assert "%.7g" % 1.020e-13 == "1.02e-13" +assert "%g" % 1.020e-13 == "1.02e-13" +assert "%g" % 1.020e-4 == "0.000102" + +assert_raises( + TypeError, + lambda: "My name is %s and I'm %(age)d years old" % ("Foo", 25), + _msg="format requires a mapping", +) +assert_raises( + TypeError, lambda: "My name is %(name)s" % "Foo", _msg="format requires a mapping" +) +assert_raises( + ValueError, + lambda: "This %(food}s is great!" % {"food": "cookie"}, + _msg="incomplete format key", +) +assert_raises(ValueError, lambda: "My name is %" % "Foo", _msg="incomplete format") + +assert "a" < "b" +assert "a" <= "b" +assert "a" <= "a" +assert "z" > "b" +assert "z" >= "b" +assert "a" >= "a" # str.translate -assert "abc".translate({97: '🎅', 98: None, 99: "xd"}) == "🎅xd" +assert "abc".translate({97: "🎅", 98: None, 99: "xd"}) == "🎅xd" # str.maketrans assert str.maketrans({"a": "abc", "b": None, "c": 33}) == {97: "abc", 98: None, 99: 33} -assert str.maketrans("hello", "world", "rust") == {104: 119, 101: 111, 108: 108, 111: 100, 114: None, 117: None, 115: None, 116: None} +assert str.maketrans("hello", "world", "rust") == { + 104: 119, + 101: 111, + 108: 108, + 111: 100, + 114: None, + 117: None, + 115: None, + 116: None, +} + def try_mutate_str(): - word = "word" - word[0] = 'x' + word = "word" + word[0] = "x" + assert_raises(TypeError, try_mutate_str) -ss = ['Hello', '안녕', '👋'] -bs = [b'Hello', b'\xec\x95\x88\xeb\x85\x95', b'\xf0\x9f\x91\x8b'] +ss = ["Hello", "안녕", "👋"] +bs = [b"Hello", b"\xec\x95\x88\xeb\x85\x95", b"\xf0\x9f\x91\x8b"] for s, b in zip(ss, bs): assert s.encode() == b -for s, b, e in zip(ss, bs, ['u8', 'U8', 'utf-8', 'UTF-8', 'utf_8']): +for s, b, e in zip(ss, bs, ["u8", "U8", "utf-8", "UTF-8", "utf_8"]): assert s.encode(e) == b # assert s.encode(encoding=e) == b @@ -349,9 +420,9 @@ def try_mutate_str(): assert "\u0037" == "7" assert "\u0040" == "@" assert "\u0041" == "A" -assert "\u00BE" == "¾" +assert "\u00be" == "¾" assert "\u9487" == "钇" -assert "\U0001F609" == "😉" +assert "\U0001f609" == "😉" # test str iter iterable_str = "12345678😉" @@ -383,16 +454,16 @@ def try_mutate_str(): assert next(str_iter_reversed, None) == None assert_raises(StopIteration, next, str_iter_reversed) -assert str.__rmod__('%i', 30) == NotImplemented -assert_raises(TypeError, lambda: str.__rmod__(30, '%i')) +assert str.__rmod__("%i", 30) == NotImplemented +assert_raises(TypeError, lambda: str.__rmod__(30, "%i")) # test str index -index_str = 'Rust Python' +index_str = "Rust Python" -assert index_str[0] == 'R' -assert index_str[-1] == 'n' +assert index_str[0] == "R" +assert index_str[-1] == "n" -assert_raises(TypeError, lambda: index_str['a']) +assert_raises(TypeError, lambda: index_str["a"]) assert chr(9).__repr__() == "'\\t'" assert chr(99).__repr__() == "'c'" @@ -424,321 +495,330 @@ def try_mutate_str(): # >>> '{x} {y}'.format_map({'x': 1, 'y': 2}) # '1 2' -assert '{x} {y}'.format_map({'x': 1, 'y': 2}) == '1 2' +assert "{x} {y}".format_map({"x": 1, "y": 2}) == "1 2" # >>> '{x:04d}'.format_map({'x': 1}) # '0001' -assert '{x:04d}'.format_map({'x': 1}) == '0001' +assert "{x:04d}".format_map({"x": 1}) == "0001" # >>> '{x} {y}'.format_map('foo') # Traceback (most recent call last): # File "", line 1, in # TypeError: string indices must be integers with AssertRaises(TypeError, None): - '{x} {y}'.format_map('foo') + "{x} {y}".format_map("foo") # >>> '{x} {y}'.format_map(['foo']) # Traceback (most recent call last): # File "", line 1, in # TypeError: list indices must be integers or slices, not str with AssertRaises(TypeError, None): - '{x} {y}'.format_map(['foo']) + "{x} {y}".format_map(["foo"]) # >>> '{x} {y}'.format_map() # Traceback (most recent call last): # File "", line 1, in # TypeError: format_map() takes exactly one argument (0 given) -with AssertRaises(TypeError, msg='TypeError: format_map() takes exactly one argument (0 given)'): - '{x} {y}'.format_map(), +with AssertRaises( + TypeError, msg="TypeError: format_map() takes exactly one argument (0 given)" +): + ("{x} {y}".format_map(),) # >>> '{x} {y}'.format_map('foo', 'bar') # Traceback (most recent call last): # File "", line 1, in # TypeError: format_map() takes exactly one argument (2 given) -with AssertRaises(TypeError, msg='TypeError: format_map() takes exactly one argument (2 given)'): - '{x} {y}'.format_map('foo', 'bar') +with AssertRaises( + TypeError, msg="TypeError: format_map() takes exactly one argument (2 given)" +): + "{x} {y}".format_map("foo", "bar") # >>> '{x} {y}'.format_map({'x': 1}) # Traceback (most recent call last): # File "", line 1, in # KeyError: 'y' with AssertRaises(KeyError, msg="KeyError: 'y'"): - '{x} {y}'.format_map({'x': 1}) + "{x} {y}".format_map({"x": 1}) # >>> '{x} {y}'.format_map({'x': 1, 'z': 2}) # Traceback (most recent call last): # File "", line 1, in # KeyError: 'y' with AssertRaises(KeyError, msg="KeyError: 'y'"): - '{x} {y}'.format_map({'x': 1, 'z': 2}) + "{x} {y}".format_map({"x": 1, "z": 2}) # >>> '{{literal}}'.format_map('foo') # '{literal}' -assert '{{literal}}'.format_map('foo') == '{literal}' +assert "{{literal}}".format_map("foo") == "{literal}" # test formatting float values -assert f'{5:f}' == '5.000000' -assert f'{-5:f}' == '-5.000000' -assert f'{5.0:f}' == '5.000000' -assert f'{-5.0:f}' == '-5.000000' -assert f'{5:.2f}' == '5.00' -assert f'{5.0:.2f}' == '5.00' -assert f'{-5:.2f}' == '-5.00' -assert f'{-5.0:.2f}' == '-5.00' -assert f'{5.0:04f}' == '5.000000' -assert f'{5.1234:+f}' == '+5.123400' -assert f'{5.1234: f}' == ' 5.123400' -assert f'{5.1234:-f}' == '5.123400' -assert f'{-5.1234:-f}' == '-5.123400' -assert f'{1.0:+}' == '+1.0' -assert f'--{1.0:f>4}--' == '--f1.0--' -assert f'--{1.0:f<4}--' == '--1.0f--' -assert f'--{1.0:d^4}--' == '--1.0d--' -assert f'--{1.0:d^5}--' == '--d1.0d--' -assert f'--{1.1:f>6}--' == '--fff1.1--' -assert '{}'.format(float('nan')) == 'nan' -assert '{:f}'.format(float('nan')) == 'nan' -assert '{:f}'.format(float('-nan')) == 'nan' -assert '{:F}'.format(float('nan')) == 'NAN' -assert '{}'.format(float('inf')) == 'inf' -assert '{:f}'.format(float('inf')) == 'inf' -assert '{:f}'.format(float('-inf')) == '-inf' -assert '{:F}'.format(float('inf')) == 'INF' -assert f'{1234567890.1234:,.2f}' == '1,234,567,890.12' -assert f'{1234567890.1234:_.2f}' == '1_234_567_890.12' +assert f"{5:f}" == "5.000000" +assert f"{-5:f}" == "-5.000000" +assert f"{5.0:f}" == "5.000000" +assert f"{-5.0:f}" == "-5.000000" +assert f"{5:.2f}" == "5.00" +assert f"{5.0:.2f}" == "5.00" +assert f"{-5:.2f}" == "-5.00" +assert f"{-5.0:.2f}" == "-5.00" +assert f"{5.0:04f}" == "5.000000" +assert f"{5.1234:+f}" == "+5.123400" +assert f"{5.1234: f}" == " 5.123400" +assert f"{5.1234:-f}" == "5.123400" +assert f"{-5.1234:-f}" == "-5.123400" +assert f"{1.0:+}" == "+1.0" +assert f"--{1.0:f>4}--" == "--f1.0--" +assert f"--{1.0:f<4}--" == "--1.0f--" +assert f"--{1.0:d^4}--" == "--1.0d--" +assert f"--{1.0:d^5}--" == "--d1.0d--" +assert f"--{1.1:f>6}--" == "--fff1.1--" +assert "{}".format(float("nan")) == "nan" +assert "{:f}".format(float("nan")) == "nan" +assert "{:f}".format(float("-nan")) == "nan" +assert "{:F}".format(float("nan")) == "NAN" +assert "{}".format(float("inf")) == "inf" +assert "{:f}".format(float("inf")) == "inf" +assert "{:f}".format(float("-inf")) == "-inf" +assert "{:F}".format(float("inf")) == "INF" +assert f"{1234567890.1234:,.2f}" == "1,234,567,890.12" +assert f"{1234567890.1234:_.2f}" == "1_234_567_890.12" with AssertRaises(ValueError, msg="Unknown format code 'd' for object of type 'float'"): - f'{5.0:04d}' + f"{5.0:04d}" # Test % formatting -assert f'{10:%}' == '1000.000000%' -assert f'{10.0:%}' == '1000.000000%' -assert f'{10.0:.2%}' == '1000.00%' -assert f'{10.0:.8%}' == '1000.00000000%' -assert f'{-10:%}' == '-1000.000000%' -assert f'{-10.0:%}' == '-1000.000000%' -assert f'{-10.0:.2%}' == '-1000.00%' -assert f'{-10.0:.8%}' == '-1000.00000000%' -assert '{:%}'.format(float('nan')) == 'nan%' -assert '{:.2%}'.format(float('nan')) == 'nan%' -assert '{:%}'.format(float('inf')) == 'inf%' -assert '{:.2%}'.format(float('inf')) == 'inf%' -with AssertRaises(ValueError, msg='Invalid format specifier'): - f'{10.0:%3}' +assert f"{10:%}" == "1000.000000%" +assert f"{10.0:%}" == "1000.000000%" +assert f"{10.0:.2%}" == "1000.00%" +assert f"{10.0:.8%}" == "1000.00000000%" +assert f"{-10:%}" == "-1000.000000%" +assert f"{-10.0:%}" == "-1000.000000%" +assert f"{-10.0:.2%}" == "-1000.00%" +assert f"{-10.0:.8%}" == "-1000.00000000%" +assert "{:%}".format(float("nan")) == "nan%" +assert "{:.2%}".format(float("nan")) == "nan%" +assert "{:%}".format(float("inf")) == "inf%" +assert "{:.2%}".format(float("inf")) == "inf%" +with AssertRaises(ValueError, msg="Invalid format specifier"): + f"{10.0:%3}" # Test e & E formatting -assert '{:e}'.format(10) == '1.000000e+01' -assert '{:.2e}'.format(11) == '1.10e+01' -assert '{:e}'.format(10.0) == '1.000000e+01' -assert '{:e}'.format(-10.0) == '-1.000000e+01' -assert '{:.2e}'.format(10.0) == '1.00e+01' -assert '{:.2e}'.format(-10.0) == '-1.00e+01' -assert '{:.2e}'.format(10.1) == '1.01e+01' -assert '{:.2e}'.format(-10.1) == '-1.01e+01' -assert '{:.2e}'.format(10.001) == '1.00e+01' -assert '{:.4e}'.format(100.234) == '1.0023e+02' -assert '{:.5e}'.format(100.234) == '1.00234e+02' -assert '{:.2E}'.format(10.0) == '1.00E+01' -assert '{:.2E}'.format(-10.0) == '-1.00E+01' -assert '{:e}'.format(float('nan')) == 'nan' -assert '{:e}'.format(float('-nan')) == 'nan' -assert '{:E}'.format(float('nan')) == 'NAN' -assert '{:e}'.format(float('inf')) == 'inf' -assert '{:e}'.format(float('-inf')) == '-inf' -assert '{:E}'.format(float('inf')) == 'INF' +assert "{:e}".format(10) == "1.000000e+01" +assert "{:.2e}".format(11) == "1.10e+01" +assert "{:e}".format(10.0) == "1.000000e+01" +assert "{:e}".format(-10.0) == "-1.000000e+01" +assert "{:.2e}".format(10.0) == "1.00e+01" +assert "{:.2e}".format(-10.0) == "-1.00e+01" +assert "{:.2e}".format(10.1) == "1.01e+01" +assert "{:.2e}".format(-10.1) == "-1.01e+01" +assert "{:.2e}".format(10.001) == "1.00e+01" +assert "{:.4e}".format(100.234) == "1.0023e+02" +assert "{:.5e}".format(100.234) == "1.00234e+02" +assert "{:.2E}".format(10.0) == "1.00E+01" +assert "{:.2E}".format(-10.0) == "-1.00E+01" +assert "{:e}".format(float("nan")) == "nan" +assert "{:e}".format(float("-nan")) == "nan" +assert "{:E}".format(float("nan")) == "NAN" +assert "{:e}".format(float("inf")) == "inf" +assert "{:e}".format(float("-inf")) == "-inf" +assert "{:E}".format(float("inf")) == "INF" # Test g & G formatting -assert '{:g}'.format(10.0) == '10' -assert '{:g}'.format(100000.0) == '100000' -assert '{:g}'.format(123456.78901234567890) == '123457' -assert '{:.0g}'.format(123456.78901234567890) == '1e+05' -assert '{:.1g}'.format(123456.78901234567890) == '1e+05' -assert '{:.2g}'.format(123456.78901234567890) == '1.2e+05' -assert '{:g}'.format(1234567.8901234567890) == '1.23457e+06' -assert '{:.0g}'.format(1234567.8901234567890) == '1e+06' -assert '{:.1g}'.format(1234567.8901234567890) == '1e+06' -assert '{:.2g}'.format(1234567.8901234567890) == '1.2e+06' -assert '{:.3g}'.format(1234567.8901234567890) == '1.23e+06' -assert '{:.5g}'.format(1234567.8901234567890) == '1.2346e+06' -assert '{:.6g}'.format(1234567.8901234567890) == '1.23457e+06' -assert '{:.7g}'.format(1234567.8901234567890) == '1234568' -assert '{:.8g}'.format(1234567.8901234567890) == '1234567.9' -assert '{:G}'.format(123456.78901234567890) == '123457' -assert '{:.0G}'.format(123456.78901234567890) == '1E+05' -assert '{:.1G}'.format(123456.78901234567890) == '1E+05' -assert '{:.2G}'.format(123456.78901234567890) == '1.2E+05' -assert '{:G}'.format(1234567.8901234567890) == '1.23457E+06' -assert '{:.0G}'.format(1234567.8901234567890) == '1E+06' -assert '{:.1G}'.format(1234567.8901234567890) == '1E+06' -assert '{:.2G}'.format(1234567.8901234567890) == '1.2E+06' -assert '{:.3G}'.format(1234567.8901234567890) == '1.23E+06' -assert '{:.5G}'.format(1234567.8901234567890) == '1.2346E+06' -assert '{:.6G}'.format(1234567.8901234567890) == '1.23457E+06' -assert '{:.7G}'.format(1234567.8901234567890) == '1234568' -assert '{:.8G}'.format(1234567.8901234567890) == '1234567.9' -assert '{:g}'.format(0.12345678901234567890) == '0.123457' -assert '{:g}'.format(0.12345678901234567890e-1) == '0.0123457' -assert '{:g}'.format(0.12345678901234567890e-2) == '0.00123457' -assert '{:g}'.format(0.12345678901234567890e-3) == '0.000123457' -assert '{:g}'.format(0.12345678901234567890e-4) == '1.23457e-05' -assert '{:g}'.format(0.12345678901234567890e-5) == '1.23457e-06' -assert '{:.6g}'.format(0.12345678901234567890e-5) == '1.23457e-06' -assert '{:.10g}'.format(0.12345678901234567890e-5) == '1.23456789e-06' -assert '{:.20g}'.format(0.12345678901234567890e-5) == '1.2345678901234567384e-06' -assert '{:G}'.format(0.12345678901234567890) == '0.123457' -assert '{:G}'.format(0.12345678901234567890E-1) == '0.0123457' -assert '{:G}'.format(0.12345678901234567890E-2) == '0.00123457' -assert '{:G}'.format(0.12345678901234567890E-3) == '0.000123457' -assert '{:G}'.format(0.12345678901234567890E-4) == '1.23457E-05' -assert '{:G}'.format(0.12345678901234567890E-5) == '1.23457E-06' -assert '{:.6G}'.format(0.12345678901234567890E-5) == '1.23457E-06' -assert '{:.10G}'.format(0.12345678901234567890E-5) == '1.23456789E-06' -assert '{:.20G}'.format(0.12345678901234567890E-5) == '1.2345678901234567384E-06' -assert '{:g}'.format(float('nan')) == 'nan' -assert '{:g}'.format(float('-nan')) == 'nan' -assert '{:G}'.format(float('nan')) == 'NAN' -assert '{:g}'.format(float('inf')) == 'inf' -assert '{:g}'.format(float('-inf')) == '-inf' -assert '{:G}'.format(float('inf')) == 'INF' -assert '{:.0g}'.format(1.020e-13) == '1e-13' -assert '{:.0g}'.format(1.020e-13) == '1e-13' -assert '{:.1g}'.format(1.020e-13) == '1e-13' -assert '{:.2g}'.format(1.020e-13) == '1e-13' -assert '{:.3g}'.format(1.020e-13) == '1.02e-13' -assert '{:.4g}'.format(1.020e-13) == '1.02e-13' -assert '{:.5g}'.format(1.020e-13) == '1.02e-13' -assert '{:.6g}'.format(1.020e-13) == '1.02e-13' -assert '{:.7g}'.format(1.020e-13) == '1.02e-13' -assert '{:g}'.format(1.020e-13) == '1.02e-13' -assert "{:g}".format(1.020e-4) == '0.000102' +assert "{:g}".format(10.0) == "10" +assert "{:g}".format(100000.0) == "100000" +assert "{:g}".format(123456.78901234567890) == "123457" +assert "{:.0g}".format(123456.78901234567890) == "1e+05" +assert "{:.1g}".format(123456.78901234567890) == "1e+05" +assert "{:.2g}".format(123456.78901234567890) == "1.2e+05" +assert "{:g}".format(1234567.8901234567890) == "1.23457e+06" +assert "{:.0g}".format(1234567.8901234567890) == "1e+06" +assert "{:.1g}".format(1234567.8901234567890) == "1e+06" +assert "{:.2g}".format(1234567.8901234567890) == "1.2e+06" +assert "{:.3g}".format(1234567.8901234567890) == "1.23e+06" +assert "{:.5g}".format(1234567.8901234567890) == "1.2346e+06" +assert "{:.6g}".format(1234567.8901234567890) == "1.23457e+06" +assert "{:.7g}".format(1234567.8901234567890) == "1234568" +assert "{:.8g}".format(1234567.8901234567890) == "1234567.9" +assert "{:G}".format(123456.78901234567890) == "123457" +assert "{:.0G}".format(123456.78901234567890) == "1E+05" +assert "{:.1G}".format(123456.78901234567890) == "1E+05" +assert "{:.2G}".format(123456.78901234567890) == "1.2E+05" +assert "{:G}".format(1234567.8901234567890) == "1.23457E+06" +assert "{:.0G}".format(1234567.8901234567890) == "1E+06" +assert "{:.1G}".format(1234567.8901234567890) == "1E+06" +assert "{:.2G}".format(1234567.8901234567890) == "1.2E+06" +assert "{:.3G}".format(1234567.8901234567890) == "1.23E+06" +assert "{:.5G}".format(1234567.8901234567890) == "1.2346E+06" +assert "{:.6G}".format(1234567.8901234567890) == "1.23457E+06" +assert "{:.7G}".format(1234567.8901234567890) == "1234568" +assert "{:.8G}".format(1234567.8901234567890) == "1234567.9" +assert "{:g}".format(0.12345678901234567890) == "0.123457" +assert "{:g}".format(0.12345678901234567890e-1) == "0.0123457" +assert "{:g}".format(0.12345678901234567890e-2) == "0.00123457" +assert "{:g}".format(0.12345678901234567890e-3) == "0.000123457" +assert "{:g}".format(0.12345678901234567890e-4) == "1.23457e-05" +assert "{:g}".format(0.12345678901234567890e-5) == "1.23457e-06" +assert "{:.6g}".format(0.12345678901234567890e-5) == "1.23457e-06" +assert "{:.10g}".format(0.12345678901234567890e-5) == "1.23456789e-06" +assert "{:.20g}".format(0.12345678901234567890e-5) == "1.2345678901234567384e-06" +assert "{:G}".format(0.12345678901234567890) == "0.123457" +assert "{:G}".format(0.12345678901234567890e-1) == "0.0123457" +assert "{:G}".format(0.12345678901234567890e-2) == "0.00123457" +assert "{:G}".format(0.12345678901234567890e-3) == "0.000123457" +assert "{:G}".format(0.12345678901234567890e-4) == "1.23457E-05" +assert "{:G}".format(0.12345678901234567890e-5) == "1.23457E-06" +assert "{:.6G}".format(0.12345678901234567890e-5) == "1.23457E-06" +assert "{:.10G}".format(0.12345678901234567890e-5) == "1.23456789E-06" +assert "{:.20G}".format(0.12345678901234567890e-5) == "1.2345678901234567384E-06" +assert "{:g}".format(float("nan")) == "nan" +assert "{:g}".format(float("-nan")) == "nan" +assert "{:G}".format(float("nan")) == "NAN" +assert "{:g}".format(float("inf")) == "inf" +assert "{:g}".format(float("-inf")) == "-inf" +assert "{:G}".format(float("inf")) == "INF" +assert "{:.0g}".format(1.020e-13) == "1e-13" +assert "{:.0g}".format(1.020e-13) == "1e-13" +assert "{:.1g}".format(1.020e-13) == "1e-13" +assert "{:.2g}".format(1.020e-13) == "1e-13" +assert "{:.3g}".format(1.020e-13) == "1.02e-13" +assert "{:.4g}".format(1.020e-13) == "1.02e-13" +assert "{:.5g}".format(1.020e-13) == "1.02e-13" +assert "{:.6g}".format(1.020e-13) == "1.02e-13" +assert "{:.7g}".format(1.020e-13) == "1.02e-13" +assert "{:g}".format(1.020e-13) == "1.02e-13" +assert "{:g}".format(1.020e-4) == "0.000102" # Test n & N formatting -assert '{:n}'.format(999999.1234) == '999999' -assert '{:n}'.format(9999.1234) == '9999.12' -assert '{:n}'.format(-1000000.1234) == '-1e+06' -assert '{:n}'.format(1000000.1234) == '1e+06' -assert '{:.1n}'.format(1000000.1234) == '1e+06' -assert '{:.2n}'.format(1000000.1234) == '1e+06' -assert '{:.3n}'.format(1000000.1234) == '1e+06' -assert '{:.4n}'.format(1000000.1234) == '1e+06' -assert '{:.5n}'.format(1000000.1234) == '1e+06' -assert '{:.6n}'.format(1000000.1234) == '1e+06' -assert '{:.7n}'.format(1000000.1234) == '1000000' -assert '{:.8n}'.format(1000000.1234) == '1000000.1' -assert '{:.10n}'.format(1000000.1234) == '1000000.123' -assert '{:.11n}'.format(1000000.1234) == '1000000.1234' -assert '{:.11n}'.format(-1000000.1234) == '-1000000.1234' -assert '{:0n}'.format(-1000000.1234) == '-1e+06' -assert '{:n}'.format(-1000000.1234) == '-1e+06' -assert '{:-1n}'.format(-1000000.1234) == '-1e+06' +assert "{:n}".format(999999.1234) == "999999" +assert "{:n}".format(9999.1234) == "9999.12" +assert "{:n}".format(-1000000.1234) == "-1e+06" +assert "{:n}".format(1000000.1234) == "1e+06" +assert "{:.1n}".format(1000000.1234) == "1e+06" +assert "{:.2n}".format(1000000.1234) == "1e+06" +assert "{:.3n}".format(1000000.1234) == "1e+06" +assert "{:.4n}".format(1000000.1234) == "1e+06" +assert "{:.5n}".format(1000000.1234) == "1e+06" +assert "{:.6n}".format(1000000.1234) == "1e+06" +assert "{:.7n}".format(1000000.1234) == "1000000" +assert "{:.8n}".format(1000000.1234) == "1000000.1" +assert "{:.10n}".format(1000000.1234) == "1000000.123" +assert "{:.11n}".format(1000000.1234) == "1000000.1234" +assert "{:.11n}".format(-1000000.1234) == "-1000000.1234" +assert "{:0n}".format(-1000000.1234) == "-1e+06" +assert "{:n}".format(-1000000.1234) == "-1e+06" +assert "{:-1n}".format(-1000000.1234) == "-1e+06" with AssertRaises(ValueError, msg="Unknown format code 'N' for object of type 'float'"): - '{:N}'.format(999999.1234) + "{:N}".format(999999.1234) with AssertRaises(ValueError, msg="Unknown format code 'N' for object of type 'float'"): - '{:.1N}'.format(1000000.1234) + "{:.1N}".format(1000000.1234) with AssertRaises(ValueError, msg="Unknown format code 'N' for object of type 'float'"): - '{:0N}'.format(-1000000.1234) + "{:0N}".format(-1000000.1234) with AssertRaises(ValueError, msg="Unknown format code 'N' for object of type 'float'"): - '{:-1N}'.format(-1000000.1234) + "{:-1N}".format(-1000000.1234) + # remove*fix test def test_removeprefix(): - s = 'foobarfoo' - s_ref='foobarfoo' - assert s.removeprefix('f') == s_ref[1:] - assert s.removeprefix('fo') == s_ref[2:] - assert s.removeprefix('foo') == s_ref[3:] - - assert s.removeprefix('') == s_ref - assert s.removeprefix('bar') == s_ref - assert s.removeprefix('lol') == s_ref - assert s.removeprefix('_foo') == s_ref - assert s.removeprefix('-foo') == s_ref - assert s.removeprefix('afoo') == s_ref - assert s.removeprefix('*foo') == s_ref - - assert s==s_ref, 'undefined test fail' - - s_uc = '😱foobarfoo🖖' - s_ref_uc = '😱foobarfoo🖖' - assert s_uc.removeprefix('😱') == s_ref_uc[1:] - assert s_uc.removeprefix('😱fo') == s_ref_uc[3:] - assert s_uc.removeprefix('😱foo') == s_ref_uc[4:] - - assert s_uc.removeprefix('🖖') == s_ref_uc - assert s_uc.removeprefix('foo') == s_ref_uc - assert s_uc.removeprefix(' ') == s_ref_uc - assert s_uc.removeprefix('_😱') == s_ref_uc - assert s_uc.removeprefix(' 😱') == s_ref_uc - assert s_uc.removeprefix('-😱') == s_ref_uc - assert s_uc.removeprefix('#😱') == s_ref_uc + s = "foobarfoo" + s_ref = "foobarfoo" + assert s.removeprefix("f") == s_ref[1:] + assert s.removeprefix("fo") == s_ref[2:] + assert s.removeprefix("foo") == s_ref[3:] + + assert s.removeprefix("") == s_ref + assert s.removeprefix("bar") == s_ref + assert s.removeprefix("lol") == s_ref + assert s.removeprefix("_foo") == s_ref + assert s.removeprefix("-foo") == s_ref + assert s.removeprefix("afoo") == s_ref + assert s.removeprefix("*foo") == s_ref + + assert s == s_ref, "undefined test fail" + + s_uc = "😱foobarfoo🖖" + s_ref_uc = "😱foobarfoo🖖" + assert s_uc.removeprefix("😱") == s_ref_uc[1:] + assert s_uc.removeprefix("😱fo") == s_ref_uc[3:] + assert s_uc.removeprefix("😱foo") == s_ref_uc[4:] + + assert s_uc.removeprefix("🖖") == s_ref_uc + assert s_uc.removeprefix("foo") == s_ref_uc + assert s_uc.removeprefix(" ") == s_ref_uc + assert s_uc.removeprefix("_😱") == s_ref_uc + assert s_uc.removeprefix(" 😱") == s_ref_uc + assert s_uc.removeprefix("-😱") == s_ref_uc + assert s_uc.removeprefix("#😱") == s_ref_uc + def test_removeprefix_types(): - s='0123456' - s_ref='0123456' - others=[0,['012']] - found=False + s = "0123456" + s_ref = "0123456" + others = [0, ["012"]] + found = False for o in others: try: s.removeprefix(o) except: - found=True + found = True + + assert found, f"Removeprefix accepts other type: {type(o)}: {o=}" - assert found, f'Removeprefix accepts other type: {type(o)}: {o=}' def test_removesuffix(): - s='foobarfoo' - s_ref='foobarfoo' - assert s.removesuffix('o') == s_ref[:-1] - assert s.removesuffix('oo') == s_ref[:-2] - assert s.removesuffix('foo') == s_ref[:-3] - - assert s.removesuffix('') == s_ref - assert s.removesuffix('bar') == s_ref - assert s.removesuffix('lol') == s_ref - assert s.removesuffix('foo_') == s_ref - assert s.removesuffix('foo-') == s_ref - assert s.removesuffix('foo*') == s_ref - assert s.removesuffix('fooa') == s_ref - - assert s==s_ref, 'undefined test fail' - - s_uc = '😱foobarfoo🖖' - s_ref_uc = '😱foobarfoo🖖' - assert s_uc.removesuffix('🖖') == s_ref_uc[:-1] - assert s_uc.removesuffix('oo🖖') == s_ref_uc[:-3] - assert s_uc.removesuffix('foo🖖') == s_ref_uc[:-4] - - assert s_uc.removesuffix('😱') == s_ref_uc - assert s_uc.removesuffix('foo') == s_ref_uc - assert s_uc.removesuffix(' ') == s_ref_uc - assert s_uc.removesuffix('🖖_') == s_ref_uc - assert s_uc.removesuffix('🖖 ') == s_ref_uc - assert s_uc.removesuffix('🖖-') == s_ref_uc - assert s_uc.removesuffix('🖖#') == s_ref_uc + s = "foobarfoo" + s_ref = "foobarfoo" + assert s.removesuffix("o") == s_ref[:-1] + assert s.removesuffix("oo") == s_ref[:-2] + assert s.removesuffix("foo") == s_ref[:-3] + + assert s.removesuffix("") == s_ref + assert s.removesuffix("bar") == s_ref + assert s.removesuffix("lol") == s_ref + assert s.removesuffix("foo_") == s_ref + assert s.removesuffix("foo-") == s_ref + assert s.removesuffix("foo*") == s_ref + assert s.removesuffix("fooa") == s_ref + + assert s == s_ref, "undefined test fail" + + s_uc = "😱foobarfoo🖖" + s_ref_uc = "😱foobarfoo🖖" + assert s_uc.removesuffix("🖖") == s_ref_uc[:-1] + assert s_uc.removesuffix("oo🖖") == s_ref_uc[:-3] + assert s_uc.removesuffix("foo🖖") == s_ref_uc[:-4] + + assert s_uc.removesuffix("😱") == s_ref_uc + assert s_uc.removesuffix("foo") == s_ref_uc + assert s_uc.removesuffix(" ") == s_ref_uc + assert s_uc.removesuffix("🖖_") == s_ref_uc + assert s_uc.removesuffix("🖖 ") == s_ref_uc + assert s_uc.removesuffix("🖖-") == s_ref_uc + assert s_uc.removesuffix("🖖#") == s_ref_uc + def test_removesuffix_types(): - s='0123456' - s_ref='0123456' - others=[0,6,['6']] - found=False + s = "0123456" + s_ref = "0123456" + others = [0, 6, ["6"]] + found = False for o in others: try: s.removesuffix(o) except: - found=True + found = True - assert found, f'Removesuffix accepts other type: {type(o)}: {o=}' + assert found, f"Removesuffix accepts other type: {type(o)}: {o=}" -skip_if_unsupported(3,9,test_removeprefix) -skip_if_unsupported(3,9,test_removeprefix_types) -skip_if_unsupported(3,9,test_removesuffix) -skip_if_unsupported(3,9,test_removesuffix_types) + +skip_if_unsupported(3, 9, test_removeprefix) +skip_if_unsupported(3, 9, test_removeprefix_types) +skip_if_unsupported(3, 9, test_removesuffix) +skip_if_unsupported(3, 9, test_removesuffix_types) # Regression to # https://github.com/RustPython/RustPython/issues/2840 -a = 'abc123()' +a = "abc123()" assert id(a) == id(a) assert id(a) != id(a * -1) @@ -751,7 +831,8 @@ def test_removesuffix_types(): class MyString(str): pass -b = MyString('0123abc*&') + +b = MyString("0123abc*&") assert id(b) == id(b) assert id(b) != id(b * -1) assert id(b) != id(b * 0) diff --git a/extra_tests/snippets/builtin_str_encode.py b/extra_tests/snippets/builtin_str_encode.py index 790e156e6f..156a83e205 100644 --- a/extra_tests/snippets/builtin_str_encode.py +++ b/extra_tests/snippets/builtin_str_encode.py @@ -10,11 +10,13 @@ assert_raises(UnicodeEncodeError, "¿como estás?".encode, "ascii") + def round_trip(s, encoding="utf-8"): encoded = s.encode(encoding) decoded = encoded.decode(encoding) assert s == decoded + round_trip("👺♦ 𝐚Şđƒ ☆☝") round_trip("☢🐣 ᖇ𝓤𝕊тⓟ𝕐𝕥卄σ𝔫 ♬👣") round_trip("💀👌 ק𝔂tℍⓞ𝓷 3 🔥👤") diff --git a/extra_tests/snippets/builtin_str_subclass.py b/extra_tests/snippets/builtin_str_subclass.py index 3ec266d5c3..73e23615c4 100644 --- a/extra_tests/snippets/builtin_str_subclass.py +++ b/extra_tests/snippets/builtin_str_subclass.py @@ -3,6 +3,7 @@ x = "An interesting piece of text" assert x is str(x) + class Stringy(str): def __new__(cls, value=""): return str.__new__(cls, value) @@ -10,6 +11,7 @@ def __new__(cls, value=""): def __init__(self, value): self.x = "substr" + y = Stringy(1) assert type(y) is Stringy, "Type of Stringy should be stringy" assert type(str(y)) is str, "Str of a str-subtype should be a str." diff --git a/extra_tests/snippets/builtin_str_unicode.py b/extra_tests/snippets/builtin_str_unicode.py index 8858cf9bfd..ca4a99199c 100644 --- a/extra_tests/snippets/builtin_str_unicode.py +++ b/extra_tests/snippets/builtin_str_unicode.py @@ -1,29 +1,29 @@ - # Test the unicode support! 👋 -ᚴ=2 +ᚴ = 2 -assert ᚴ*8 == 16 +assert ᚴ * 8 == 16 -ᚴ="👋" +ᚴ = "👋" -c = ᚴ*3 +c = ᚴ * 3 -assert c == '👋👋👋' +assert c == "👋👋👋" import unicodedata -assert unicodedata.category('a') == 'Ll' -assert unicodedata.category('A') == 'Lu' -assert unicodedata.name('a') == 'LATIN SMALL LETTER A' -assert unicodedata.lookup('LATIN SMALL LETTER A') == 'a' -assert unicodedata.bidirectional('a') == 'L' -assert unicodedata.east_asian_width('\u231a') == 'W' -assert unicodedata.normalize('NFC', 'bla') == 'bla' + +assert unicodedata.category("a") == "Ll" +assert unicodedata.category("A") == "Lu" +assert unicodedata.name("a") == "LATIN SMALL LETTER A" +assert unicodedata.lookup("LATIN SMALL LETTER A") == "a" +assert unicodedata.bidirectional("a") == "L" +assert unicodedata.east_asian_width("\u231a") == "W" +assert unicodedata.normalize("NFC", "bla") == "bla" # testing unicodedata.ucd_3_2_0 for idna -assert "abcСĤ".encode("idna") == b'xn--abc-7sa390b' -assert "abc䄣IJ".encode("idna") == b'xn--abcij-zb5f' +assert "abcСĤ".encode("idna") == b"xn--abc-7sa390b" +assert "abc䄣IJ".encode("idna") == b"xn--abcij-zb5f" # from CPython tests assert "python.org".encode("idna") == b"python.org" diff --git a/extra_tests/snippets/builtin_str_unicode_slice.py b/extra_tests/snippets/builtin_str_unicode_slice.py index c6ce88d549..252f84b1c7 100644 --- a/extra_tests/snippets/builtin_str_unicode_slice.py +++ b/extra_tests/snippets/builtin_str_unicode_slice.py @@ -1,13 +1,14 @@ def test_slice_bounds(s): # End out of range assert s[0:100] == s - assert s[0:-100] == '' + assert s[0:-100] == "" # Start out of range - assert s[100:1] == '' + assert s[100:1] == "" # Out of range both sides # This is the behaviour in cpython # assert s[-100:100] == s + def expect_index_error(s, index): try: s[index] @@ -16,6 +17,7 @@ def expect_index_error(s, index): else: assert False + unicode_str = "∀∂" assert unicode_str[0] == "∀" assert unicode_str[1] == "∂" @@ -35,25 +37,25 @@ def expect_index_error(s, index): hebrew_text = "בְּרֵאשִׁית, בָּרָא אֱלֹהִים, אֵת הַשָּׁמַיִם, וְאֵת הָאָרֶץ" assert len(hebrew_text) == 60 assert len(hebrew_text[:]) == 60 -assert hebrew_text[0] == 'ב' -assert hebrew_text[1] == 'ְ' -assert hebrew_text[2] == 'ּ' -assert hebrew_text[3] == 'ר' -assert hebrew_text[4] == 'ֵ' -assert hebrew_text[5] == 'א' -assert hebrew_text[6] == 'ש' -assert hebrew_text[5:10] == 'אשִׁי' +assert hebrew_text[0] == "ב" +assert hebrew_text[1] == "ְ" +assert hebrew_text[2] == "ּ" +assert hebrew_text[3] == "ר" +assert hebrew_text[4] == "ֵ" +assert hebrew_text[5] == "א" +assert hebrew_text[6] == "ש" +assert hebrew_text[5:10] == "אשִׁי" assert len(hebrew_text[5:10]) == 5 -assert hebrew_text[-20:50] == 'מַיִם, וְא' +assert hebrew_text[-20:50] == "מַיִם, וְא" assert len(hebrew_text[-20:50]) == 10 -assert hebrew_text[:-30:1] == 'בְּרֵאשִׁית, בָּרָא אֱלֹהִים, ' +assert hebrew_text[:-30:1] == "בְּרֵאשִׁית, בָּרָא אֱלֹהִים, " assert len(hebrew_text[:-30:1]) == 30 -assert hebrew_text[10:-30] == 'ת, בָּרָא אֱלֹהִים, ' +assert hebrew_text[10:-30] == "ת, בָּרָא אֱלֹהִים, " assert len(hebrew_text[10:-30]) == 20 -assert hebrew_text[10:30:3] == 'תבר לִ,' +assert hebrew_text[10:30:3] == "תבר לִ," assert len(hebrew_text[10:30:3]) == 7 -assert hebrew_text[10:30:-3] == '' -assert hebrew_text[30:10:-3] == 'אםהֱאּ ' +assert hebrew_text[10:30:-3] == "" +assert hebrew_text[30:10:-3] == "אםהֱאּ " assert len(hebrew_text[30:10:-3]) == 7 -assert hebrew_text[30:10:-1] == 'א ,םיִהֹלֱא אָרָּב ,' +assert hebrew_text[30:10:-1] == "א ,םיִהֹלֱא אָרָּב ," assert len(hebrew_text[30:10:-1]) == 20 diff --git a/extra_tests/snippets/builtin_tuple.py b/extra_tests/snippets/builtin_tuple.py index fd59e90609..fc2f8d5bb7 100644 --- a/extra_tests/snippets/builtin_tuple.py +++ b/extra_tests/snippets/builtin_tuple.py @@ -1,8 +1,8 @@ from testutils import assert_raises -assert (1,2) == (1,2) +assert (1, 2) == (1, 2) -x = (1,2) +x = (1, 2) assert x[0] == 1 y = (1,) @@ -19,7 +19,7 @@ assert x > y, "tuple __gt__ failed" -b = (1,2,3) +b = (1, 2, 3) assert b.index(2) == 1 recursive_list = [] @@ -30,15 +30,17 @@ assert (None, "", 1).index(1) == 2 assert 1 in (None, "", 1) + class Foo(object): def __eq__(self, x): return False + foo = Foo() assert (foo,) == (foo,) a = (1, 2, 3) -a += 1, +a += (1,) assert a == (1, 2, 3, 1) b = (55, *a) @@ -80,14 +82,14 @@ def __eq__(self, x): assert not (0, 0) > (0, 0) assert not (0, 0) < (0, 0) -assert not (float('nan'), float('nan')) <= (float('nan'), 1) -assert not (float('nan'), float('nan')) <= (float('nan'), float('nan')) -assert not (float('nan'), float('nan')) >= (float('nan'), float('nan')) -assert not (float('nan'), float('nan')) < (float('nan'), float('nan')) -assert not (float('nan'), float('nan')) > (float('nan'), float('nan')) - -assert (float('inf'), float('inf')) >= (float('inf'), 1) -assert (float('inf'), float('inf')) <= (float('inf'), float('inf')) -assert (float('inf'), float('inf')) >= (float('inf'), float('inf')) -assert not (float('inf'), float('inf')) < (float('inf'), float('inf')) -assert not (float('inf'), float('inf')) > (float('inf'), float('inf')) +assert not (float("nan"), float("nan")) <= (float("nan"), 1) +assert not (float("nan"), float("nan")) <= (float("nan"), float("nan")) +assert not (float("nan"), float("nan")) >= (float("nan"), float("nan")) +assert not (float("nan"), float("nan")) < (float("nan"), float("nan")) +assert not (float("nan"), float("nan")) > (float("nan"), float("nan")) + +assert (float("inf"), float("inf")) >= (float("inf"), 1) +assert (float("inf"), float("inf")) <= (float("inf"), float("inf")) +assert (float("inf"), float("inf")) >= (float("inf"), float("inf")) +assert not (float("inf"), float("inf")) < (float("inf"), float("inf")) +assert not (float("inf"), float("inf")) > (float("inf"), float("inf")) diff --git a/extra_tests/snippets/builtin_type.py b/extra_tests/snippets/builtin_type.py index 9f30b9b0ed..923028f2cd 100644 --- a/extra_tests/snippets/builtin_type.py +++ b/extra_tests/snippets/builtin_type.py @@ -13,9 +13,9 @@ print("abc") # print(u"abc") # Structural below -print((1, 2)) # Tuple can be any length, but fixed after declared -x = (1,2) -print(x[0]) # Tuple can be any length, but fixed after declared +print((1, 2)) # Tuple can be any length, but fixed after declared +x = (1, 2) +print(x[0]) # Tuple can be any length, but fixed after declared print([1, 2, 3]) # print({"first":1,"second":2}) @@ -52,25 +52,25 @@ a = complex(2, 4) assert type(a) is complex assert type(a + a) is complex -assert repr(a) == '(2+4j)' +assert repr(a) == "(2+4j)" a = 10j -assert repr(a) == '10j' +assert repr(a) == "10j" a = 1 assert a.conjugate() == a a = 12345 -b = a*a*a*a*a*a*a*a +b = a * a * a * a * a * a * a * a assert b.bit_length() == 109 -assert type.__module__ == 'builtins' -assert type.__qualname__ == 'type' -assert type.__name__ == 'type' +assert type.__module__ == "builtins" +assert type.__qualname__ == "type" +assert type.__name__ == "type" assert isinstance(type.__doc__, str) -assert object.__qualname__ == 'object' -assert int.__qualname__ == 'int' +assert object.__qualname__ == "object" +assert int.__qualname__ == "int" class A(type): @@ -78,8 +78,8 @@ class A(type): class B(type): - __module__ = 'b' - __qualname__ = 'BB' + __module__ = "b" + __qualname__ = "BB" class C: @@ -87,23 +87,23 @@ class C: class D: - __module__ = 'd' - __qualname__ = 'DD' - - -assert A.__module__ == '__main__' -assert A.__qualname__ == 'A' -assert B.__module__ == 'b' -assert B.__qualname__ == 'BB' -assert C.__module__ == '__main__' -assert C.__qualname__ == 'C' -assert D.__module__ == 'd' -assert D.__qualname__ == 'DD' - -A.__qualname__ = 'AA' -B.__qualname__ = 'b' -assert A.__qualname__ == 'AA' -assert B.__qualname__ == 'b' + __module__ = "d" + __qualname__ = "DD" + + +assert A.__module__ == "__main__" +assert A.__qualname__ == "A" +assert B.__module__ == "b" +assert B.__qualname__ == "BB" +assert C.__module__ == "__main__" +assert C.__qualname__ == "C" +assert D.__module__ == "d" +assert D.__qualname__ == "DD" + +A.__qualname__ = "AA" +B.__qualname__ = "b" +assert A.__qualname__ == "AA" +assert B.__qualname__ == "b" with assert_raises(TypeError): del D.__qualname__ with assert_raises(TypeError): @@ -114,7 +114,8 @@ class D: from testutils import assert_raises import platform -if platform.python_implementation() == 'RustPython': + +if platform.python_implementation() == "RustPython": gc = None else: import gc @@ -123,13 +124,13 @@ class D: assert type(object) is type assert type(object()) is object -new_type = type('New', (object,), {}) +new_type = type("New", (object,), {}) assert type(new_type) is type assert type(new_type()) is new_type -metaclass = type('MCl', (type,), {}) -cls = metaclass('Cls', (object,), {}) +metaclass = type("MCl", (type,), {}) +cls = metaclass("Cls", (object,), {}) inst = cls() assert type(inst) is cls @@ -154,10 +155,22 @@ class D: assert not issubclass(type, (int, float)) assert issubclass(type, (int, type)) -class A: pass -class B(A): pass -class C(A): pass -class D(B, C): pass + +class A: + pass + + +class B(A): + pass + + +class C(A): + pass + + +class D(B, C): + pass + assert A.__subclasses__() == [B, C] assert B.__subclasses__() == [D] @@ -174,7 +187,7 @@ class D(B, C): pass if gc: # gc sweep is needed here for CPython... gc.collect() - # ...while RustPython doesn't have `gc` yet. + # ...while RustPython doesn't have `gc` yet. if gc: # D.__new__ is a method bound to the D type, so just deleting D @@ -185,43 +198,53 @@ class D(B, C): pass assert type in object.__subclasses__() -assert cls.__name__ == 'Cls' +assert cls.__name__ == "Cls" # mro assert int.mro() == [int, object] assert bool.mro() == [bool, int, object] assert object.mro() == [object] + class A: pass + class B(A): pass + assert A.mro() == [A, object] assert B.mro() == [B, A, object] + class AA: pass + class BB(AA): pass + class C(B, BB): pass + assert C.mro() == [C, B, A, BB, AA, object] -assert type(Exception.args).__name__ == 'getset_descriptor' +assert type(Exception.args).__name__ == "getset_descriptor" assert type(None).__bool__(None) is False + class A: pass + class B: pass + a = A() a.__class__ = B assert isinstance(a, B) @@ -234,30 +257,33 @@ class B: # Regression to # https://github.com/RustPython/RustPython/issues/2310 import builtins -assert builtins.iter.__class__.__module__ == 'builtins' -assert builtins.iter.__class__.__qualname__ == 'builtin_function_or_method' -assert iter.__class__.__module__ == 'builtins' -assert iter.__class__.__qualname__ == 'builtin_function_or_method' -assert type(iter).__module__ == 'builtins' -assert type(iter).__qualname__ == 'builtin_function_or_method' +assert builtins.iter.__class__.__module__ == "builtins" +assert builtins.iter.__class__.__qualname__ == "builtin_function_or_method" + +assert iter.__class__.__module__ == "builtins" +assert iter.__class__.__qualname__ == "builtin_function_or_method" +assert type(iter).__module__ == "builtins" +assert type(iter).__qualname__ == "builtin_function_or_method" # Regression to # https://github.com/RustPython/RustPython/issues/2767 # Marked as `#[pymethod]`: -assert str.replace.__qualname__ == 'str.replace' -assert str().replace.__qualname__ == 'str.replace' -assert int.to_bytes.__qualname__ == 'int.to_bytes' -assert int().to_bytes.__qualname__ == 'int.to_bytes' +assert str.replace.__qualname__ == "str.replace" +assert str().replace.__qualname__ == "str.replace" +assert int.to_bytes.__qualname__ == "int.to_bytes" +assert int().to_bytes.__qualname__ == "int.to_bytes" # Marked as `#[pyclassmethod]`: -assert dict.fromkeys.__qualname__ == 'dict.fromkeys' -assert object.__init_subclass__.__qualname__ == 'object.__init_subclass__' +assert dict.fromkeys.__qualname__ == "dict.fromkeys" +assert object.__init_subclass__.__qualname__ == "object.__init_subclass__" # Dynamic with `#[extend_class]`: -assert bytearray.maketrans.__qualname__ == 'bytearray.maketrans', bytearray.maketrans.__qualname__ +assert bytearray.maketrans.__qualname__ == "bytearray.maketrans", ( + bytearray.maketrans.__qualname__ +) # Third-party: @@ -285,47 +311,48 @@ def c(cls): def s(): pass -assert MyTypeWithMethod.method.__name__ == 'method' -assert MyTypeWithMethod().method.__name__ == 'method' -assert MyTypeWithMethod.clsmethod.__name__ == 'clsmethod' -assert MyTypeWithMethod().clsmethod.__name__ == 'clsmethod' -assert MyTypeWithMethod.stmethod.__name__ == 'stmethod' -assert MyTypeWithMethod().stmethod.__name__ == 'stmethod' - -assert MyTypeWithMethod.method.__qualname__ == 'MyTypeWithMethod.method' -assert MyTypeWithMethod().method.__qualname__ == 'MyTypeWithMethod.method' -assert MyTypeWithMethod.clsmethod.__qualname__ == 'MyTypeWithMethod.clsmethod' -assert MyTypeWithMethod().clsmethod.__qualname__ == 'MyTypeWithMethod.clsmethod' -assert MyTypeWithMethod.stmethod.__qualname__ == 'MyTypeWithMethod.stmethod' -assert MyTypeWithMethod().stmethod.__qualname__ == 'MyTypeWithMethod.stmethod' - -assert MyTypeWithMethod.N.m.__name__ == 'm' -assert MyTypeWithMethod().N.m.__name__ == 'm' -assert MyTypeWithMethod.N.c.__name__ == 'c' -assert MyTypeWithMethod().N.c.__name__ == 'c' -assert MyTypeWithMethod.N.s.__name__ == 's' -assert MyTypeWithMethod().N.s.__name__ == 's' - -assert MyTypeWithMethod.N.m.__qualname__ == 'MyTypeWithMethod.N.m' -assert MyTypeWithMethod().N.m.__qualname__ == 'MyTypeWithMethod.N.m' -assert MyTypeWithMethod.N.c.__qualname__ == 'MyTypeWithMethod.N.c' -assert MyTypeWithMethod().N.c.__qualname__ == 'MyTypeWithMethod.N.c' -assert MyTypeWithMethod.N.s.__qualname__ == 'MyTypeWithMethod.N.s' -assert MyTypeWithMethod().N.s.__qualname__ == 'MyTypeWithMethod.N.s' - -assert MyTypeWithMethod.N().m.__name__ == 'm' -assert MyTypeWithMethod().N().m.__name__ == 'm' -assert MyTypeWithMethod.N().c.__name__ == 'c' -assert MyTypeWithMethod().N().c.__name__ == 'c' -assert MyTypeWithMethod.N().s.__name__ == 's' -assert MyTypeWithMethod().N.s.__name__ == 's' - -assert MyTypeWithMethod.N().m.__qualname__ == 'MyTypeWithMethod.N.m' -assert MyTypeWithMethod().N().m.__qualname__ == 'MyTypeWithMethod.N.m' -assert MyTypeWithMethod.N().c.__qualname__ == 'MyTypeWithMethod.N.c' -assert MyTypeWithMethod().N().c.__qualname__ == 'MyTypeWithMethod.N.c' -assert MyTypeWithMethod.N().s.__qualname__ == 'MyTypeWithMethod.N.s' -assert MyTypeWithMethod().N().s.__qualname__ == 'MyTypeWithMethod.N.s' + +assert MyTypeWithMethod.method.__name__ == "method" +assert MyTypeWithMethod().method.__name__ == "method" +assert MyTypeWithMethod.clsmethod.__name__ == "clsmethod" +assert MyTypeWithMethod().clsmethod.__name__ == "clsmethod" +assert MyTypeWithMethod.stmethod.__name__ == "stmethod" +assert MyTypeWithMethod().stmethod.__name__ == "stmethod" + +assert MyTypeWithMethod.method.__qualname__ == "MyTypeWithMethod.method" +assert MyTypeWithMethod().method.__qualname__ == "MyTypeWithMethod.method" +assert MyTypeWithMethod.clsmethod.__qualname__ == "MyTypeWithMethod.clsmethod" +assert MyTypeWithMethod().clsmethod.__qualname__ == "MyTypeWithMethod.clsmethod" +assert MyTypeWithMethod.stmethod.__qualname__ == "MyTypeWithMethod.stmethod" +assert MyTypeWithMethod().stmethod.__qualname__ == "MyTypeWithMethod.stmethod" + +assert MyTypeWithMethod.N.m.__name__ == "m" +assert MyTypeWithMethod().N.m.__name__ == "m" +assert MyTypeWithMethod.N.c.__name__ == "c" +assert MyTypeWithMethod().N.c.__name__ == "c" +assert MyTypeWithMethod.N.s.__name__ == "s" +assert MyTypeWithMethod().N.s.__name__ == "s" + +assert MyTypeWithMethod.N.m.__qualname__ == "MyTypeWithMethod.N.m" +assert MyTypeWithMethod().N.m.__qualname__ == "MyTypeWithMethod.N.m" +assert MyTypeWithMethod.N.c.__qualname__ == "MyTypeWithMethod.N.c" +assert MyTypeWithMethod().N.c.__qualname__ == "MyTypeWithMethod.N.c" +assert MyTypeWithMethod.N.s.__qualname__ == "MyTypeWithMethod.N.s" +assert MyTypeWithMethod().N.s.__qualname__ == "MyTypeWithMethod.N.s" + +assert MyTypeWithMethod.N().m.__name__ == "m" +assert MyTypeWithMethod().N().m.__name__ == "m" +assert MyTypeWithMethod.N().c.__name__ == "c" +assert MyTypeWithMethod().N().c.__name__ == "c" +assert MyTypeWithMethod.N().s.__name__ == "s" +assert MyTypeWithMethod().N.s.__name__ == "s" + +assert MyTypeWithMethod.N().m.__qualname__ == "MyTypeWithMethod.N.m" +assert MyTypeWithMethod().N().m.__qualname__ == "MyTypeWithMethod.N.m" +assert MyTypeWithMethod.N().c.__qualname__ == "MyTypeWithMethod.N.c" +assert MyTypeWithMethod().N().c.__qualname__ == "MyTypeWithMethod.N.c" +assert MyTypeWithMethod.N().s.__qualname__ == "MyTypeWithMethod.N.s" +assert MyTypeWithMethod().N().s.__qualname__ == "MyTypeWithMethod.N.s" # Regresesion to @@ -339,26 +366,27 @@ def s(): # Regression to # https://github.com/RustPython/RustPython/issues/2788 -assert iter.__qualname__ == iter.__name__ == 'iter' -assert max.__qualname__ == max.__name__ == 'max' -assert min.__qualname__ == min.__name__ == 'min' +assert iter.__qualname__ == iter.__name__ == "iter" +assert max.__qualname__ == max.__name__ == "max" +assert min.__qualname__ == min.__name__ == "min" def custom_func(): pass -assert custom_func.__qualname__ == 'custom_func' + +assert custom_func.__qualname__ == "custom_func" # Regression to # https://github.com/RustPython/RustPython/issues/2786 -assert object.__new__.__name__ == '__new__' -assert object.__new__.__qualname__ == 'object.__new__' -assert object.__subclasshook__.__name__ == '__subclasshook__' -assert object.__subclasshook__.__qualname__ == 'object.__subclasshook__' -assert type.__new__.__name__ == '__new__' -assert type.__new__.__qualname__ == 'type.__new__' +assert object.__new__.__name__ == "__new__" +assert object.__new__.__qualname__ == "object.__new__" +assert object.__subclasshook__.__name__ == "__subclasshook__" +assert object.__subclasshook__.__qualname__ == "object.__subclasshook__" +assert type.__new__.__name__ == "__new__" +assert type.__new__.__qualname__ == "type.__new__" class AQ: @@ -414,75 +442,76 @@ def three_cls(cls): def three_st(): pass -assert AQ.one.__name__ == 'one' -assert AQ().one.__name__ == 'one' -assert AQ.one_cls.__name__ == 'one_cls' -assert AQ().one_cls.__name__ == 'one_cls' -assert AQ.one_st.__name__ == 'one_st' -assert AQ().one_st.__name__ == 'one_st' - -assert AQ.one.__qualname__ == 'AQ.one' -assert AQ().one.__qualname__ == 'AQ.one' -assert AQ.one_cls.__qualname__ == 'AQ.one_cls' -assert AQ().one_cls.__qualname__ == 'AQ.one_cls' -assert AQ.one_st.__qualname__ == 'AQ.one_st' -assert AQ().one_st.__qualname__ == 'AQ.one_st' - -assert AQ.two.__name__ == 'two' -assert AQ().two.__name__ == 'two' -assert AQ.two_cls.__name__ == 'two_cls' -assert AQ().two_cls.__name__ == 'two_cls' -assert AQ.two_st.__name__ == 'two_st' -assert AQ().two_st.__name__ == 'two_st' - -assert AQ.two.__qualname__ == 'AQ.two' -assert AQ().two.__qualname__ == 'AQ.two' -assert AQ.two_cls.__qualname__ == 'AQ.two_cls' -assert AQ().two_cls.__qualname__ == 'AQ.two_cls' -assert AQ.two_st.__qualname__ == 'AQ.two_st' -assert AQ().two_st.__qualname__ == 'AQ.two_st' - -assert BQ.one.__name__ == 'one' -assert BQ().one.__name__ == 'one' -assert BQ.one_cls.__name__ == 'one_cls' -assert BQ().one_cls.__name__ == 'one_cls' -assert BQ.one_st.__name__ == 'one_st' -assert BQ().one_st.__name__ == 'one_st' - -assert BQ.one.__qualname__ == 'BQ.one' -assert BQ().one.__qualname__ == 'BQ.one' -assert BQ.one_cls.__qualname__ == 'BQ.one_cls' -assert BQ().one_cls.__qualname__ == 'BQ.one_cls' -assert BQ.one_st.__qualname__ == 'BQ.one_st' -assert BQ().one_st.__qualname__ == 'BQ.one_st' - -assert BQ.two.__name__ == 'two' -assert BQ().two.__name__ == 'two' -assert BQ.two_cls.__name__ == 'two_cls' -assert BQ().two_cls.__name__ == 'two_cls' -assert BQ.two_st.__name__ == 'two_st' -assert BQ().two_st.__name__ == 'two_st' - -assert BQ.two.__qualname__ == 'AQ.two' -assert BQ().two.__qualname__ == 'AQ.two' -assert BQ.two_cls.__qualname__ == 'AQ.two_cls' -assert BQ().two_cls.__qualname__ == 'AQ.two_cls' -assert BQ.two_st.__qualname__ == 'AQ.two_st' -assert BQ().two_st.__qualname__ == 'AQ.two_st' - -assert BQ.three.__name__ == 'three' -assert BQ().three.__name__ == 'three' -assert BQ.three_cls.__name__ == 'three_cls' -assert BQ().three_cls.__name__ == 'three_cls' -assert BQ.three_st.__name__ == 'three_st' -assert BQ().three_st.__name__ == 'three_st' - -assert BQ.three.__qualname__ == 'BQ.three' -assert BQ().three.__qualname__ == 'BQ.three' -assert BQ.three_cls.__qualname__ == 'BQ.three_cls' -assert BQ().three_cls.__qualname__ == 'BQ.three_cls' -assert BQ.three_st.__qualname__ == 'BQ.three_st' -assert BQ().three_st.__qualname__ == 'BQ.three_st' + +assert AQ.one.__name__ == "one" +assert AQ().one.__name__ == "one" +assert AQ.one_cls.__name__ == "one_cls" +assert AQ().one_cls.__name__ == "one_cls" +assert AQ.one_st.__name__ == "one_st" +assert AQ().one_st.__name__ == "one_st" + +assert AQ.one.__qualname__ == "AQ.one" +assert AQ().one.__qualname__ == "AQ.one" +assert AQ.one_cls.__qualname__ == "AQ.one_cls" +assert AQ().one_cls.__qualname__ == "AQ.one_cls" +assert AQ.one_st.__qualname__ == "AQ.one_st" +assert AQ().one_st.__qualname__ == "AQ.one_st" + +assert AQ.two.__name__ == "two" +assert AQ().two.__name__ == "two" +assert AQ.two_cls.__name__ == "two_cls" +assert AQ().two_cls.__name__ == "two_cls" +assert AQ.two_st.__name__ == "two_st" +assert AQ().two_st.__name__ == "two_st" + +assert AQ.two.__qualname__ == "AQ.two" +assert AQ().two.__qualname__ == "AQ.two" +assert AQ.two_cls.__qualname__ == "AQ.two_cls" +assert AQ().two_cls.__qualname__ == "AQ.two_cls" +assert AQ.two_st.__qualname__ == "AQ.two_st" +assert AQ().two_st.__qualname__ == "AQ.two_st" + +assert BQ.one.__name__ == "one" +assert BQ().one.__name__ == "one" +assert BQ.one_cls.__name__ == "one_cls" +assert BQ().one_cls.__name__ == "one_cls" +assert BQ.one_st.__name__ == "one_st" +assert BQ().one_st.__name__ == "one_st" + +assert BQ.one.__qualname__ == "BQ.one" +assert BQ().one.__qualname__ == "BQ.one" +assert BQ.one_cls.__qualname__ == "BQ.one_cls" +assert BQ().one_cls.__qualname__ == "BQ.one_cls" +assert BQ.one_st.__qualname__ == "BQ.one_st" +assert BQ().one_st.__qualname__ == "BQ.one_st" + +assert BQ.two.__name__ == "two" +assert BQ().two.__name__ == "two" +assert BQ.two_cls.__name__ == "two_cls" +assert BQ().two_cls.__name__ == "two_cls" +assert BQ.two_st.__name__ == "two_st" +assert BQ().two_st.__name__ == "two_st" + +assert BQ.two.__qualname__ == "AQ.two" +assert BQ().two.__qualname__ == "AQ.two" +assert BQ.two_cls.__qualname__ == "AQ.two_cls" +assert BQ().two_cls.__qualname__ == "AQ.two_cls" +assert BQ.two_st.__qualname__ == "AQ.two_st" +assert BQ().two_st.__qualname__ == "AQ.two_st" + +assert BQ.three.__name__ == "three" +assert BQ().three.__name__ == "three" +assert BQ.three_cls.__name__ == "three_cls" +assert BQ().three_cls.__name__ == "three_cls" +assert BQ.three_st.__name__ == "three_st" +assert BQ().three_st.__name__ == "three_st" + +assert BQ.three.__qualname__ == "BQ.three" +assert BQ().three.__qualname__ == "BQ.three" +assert BQ.three_cls.__qualname__ == "BQ.three_cls" +assert BQ().three_cls.__qualname__ == "BQ.three_cls" +assert BQ.three_st.__qualname__ == "BQ.three_st" +assert BQ().three_st.__qualname__ == "BQ.three_st" class ClassWithNew: @@ -494,73 +523,74 @@ def __new__(cls, *args, **kwargs): return super().__new__(cls, *args, **kwargs) -assert ClassWithNew.__new__.__qualname__ == 'ClassWithNew.__new__' -assert ClassWithNew().__new__.__qualname__ == 'ClassWithNew.__new__' -assert ClassWithNew.__new__.__name__ == '__new__' -assert ClassWithNew().__new__.__name__ == '__new__' +assert ClassWithNew.__new__.__qualname__ == "ClassWithNew.__new__" +assert ClassWithNew().__new__.__qualname__ == "ClassWithNew.__new__" +assert ClassWithNew.__new__.__name__ == "__new__" +assert ClassWithNew().__new__.__name__ == "__new__" -assert ClassWithNew.N.__new__.__qualname__ == 'ClassWithNew.N.__new__' -assert ClassWithNew().N.__new__.__qualname__ == 'ClassWithNew.N.__new__' -assert ClassWithNew.N.__new__.__name__ == '__new__' -assert ClassWithNew().N.__new__.__name__ == '__new__' -assert ClassWithNew.N().__new__.__qualname__ == 'ClassWithNew.N.__new__' -assert ClassWithNew().N().__new__.__qualname__ == 'ClassWithNew.N.__new__' -assert ClassWithNew.N().__new__.__name__ == '__new__' -assert ClassWithNew().N().__new__.__name__ == '__new__' +assert ClassWithNew.N.__new__.__qualname__ == "ClassWithNew.N.__new__" +assert ClassWithNew().N.__new__.__qualname__ == "ClassWithNew.N.__new__" +assert ClassWithNew.N.__new__.__name__ == "__new__" +assert ClassWithNew().N.__new__.__name__ == "__new__" +assert ClassWithNew.N().__new__.__qualname__ == "ClassWithNew.N.__new__" +assert ClassWithNew().N().__new__.__qualname__ == "ClassWithNew.N.__new__" +assert ClassWithNew.N().__new__.__name__ == "__new__" +assert ClassWithNew().N().__new__.__name__ == "__new__" # Regression to: # https://github.com/RustPython/RustPython/issues/2762 assert type.__prepare__() == {} -assert type.__prepare__('name') == {} -assert type.__prepare__('name', object) == {} -assert type.__prepare__('name', (bytes, str)) == {} +assert type.__prepare__("name") == {} +assert type.__prepare__("name", object) == {} +assert type.__prepare__("name", (bytes, str)) == {} assert type.__prepare__(a=1, b=2) == {} -assert type.__prepare__('name', (object, int), kw=True) == {} +assert type.__prepare__("name", (object, int), kw=True) == {} # Previously we needed `name` to be `str`: assert type.__prepare__(1) == {} assert int.__prepare__() == {} -assert int.__prepare__('name', (object, int), kw=True) == {} +assert int.__prepare__("name", (object, int), kw=True) == {} # Regression to # https://github.com/RustPython/RustPython/issues/2790 # `#[pyproperty]` -assert BaseException.args.__qualname__ == 'BaseException.args' +assert BaseException.args.__qualname__ == "BaseException.args" # class extension without `#[pyproperty]` override -assert Exception.args.__qualname__ == 'BaseException.args' +assert Exception.args.__qualname__ == "BaseException.args" # dynamic with `.new_readonly_getset` -assert SyntaxError.msg.__qualname__ == 'SyntaxError.msg' +assert SyntaxError.msg.__qualname__ == "SyntaxError.msg" # Regression to # https://github.com/RustPython/RustPython/issues/2794 -assert type.__subclasshook__.__qualname__ == 'type.__subclasshook__' -assert object.__subclasshook__.__qualname__ == 'object.__subclasshook__' +assert type.__subclasshook__.__qualname__ == "type.__subclasshook__" +assert object.__subclasshook__.__qualname__ == "object.__subclasshook__" # Regression to # https://github.com/RustPython/RustPython/issues/2776 -assert repr(BQ.one).startswith(' 3 < 4 assert not 1 > 2 < 3 < 4 + def test_type_error(x, y): assert_raises(TypeError, lambda: x < y) assert_raises(TypeError, lambda: x <= y) assert_raises(TypeError, lambda: x > y) assert_raises(TypeError, lambda: x >= y) + test_type_error([], 0) test_type_error((), 0) @@ -34,6 +36,7 @@ def test_type_error(x, y): # floats that cannot be converted to big ints shouldn’t crash the vm import math + assert not (10**500 == math.inf) assert not (math.inf == 10**500) assert not (10**500 == math.nan) @@ -41,23 +44,23 @@ def test_type_error(x, y): # comparisons # floats with worse than integer precision -assert 2.**54 > 2**54 - 1 -assert 2.**54 < 2**54 + 1 -assert 2.**54 >= 2**54 - 1 -assert 2.**54 <= 2**54 + 1 -assert 2.**54 == 2**54 -assert not 2.**54 == 2**54 + 1 +assert 2.0**54 > 2**54 - 1 +assert 2.0**54 < 2**54 + 1 +assert 2.0**54 >= 2**54 - 1 +assert 2.0**54 <= 2**54 + 1 +assert 2.0**54 == 2**54 +assert not 2.0**54 == 2**54 + 1 # inverse operands -assert 2**54 - 1 < 2.**54 -assert 2**54 + 1 > 2.**54 -assert 2**54 - 1 <= 2.**54 -assert 2**54 + 1 >= 2.**54 -assert 2**54 == 2.**54 -assert not 2**54 + 1 == 2.**54 +assert 2**54 - 1 < 2.0**54 +assert 2**54 + 1 > 2.0**54 +assert 2**54 - 1 <= 2.0**54 +assert 2**54 + 1 >= 2.0**54 +assert 2**54 == 2.0**54 +assert not 2**54 + 1 == 2.0**54 -assert not 2.**54 < 2**54 - 1 -assert not 2.**54 > 2**54 + 1 +assert not 2.0**54 < 2**54 - 1 +assert not 2.0**54 > 2**54 + 1 # sub-int numbers assert 1.3 > 1 @@ -68,17 +71,17 @@ def test_type_error(x, y): assert -0.3 <= 0 # int out of float range comparisons -assert 10**500 > 2.**54 -assert -10**500 < -0.12 +assert 10**500 > 2.0**54 +assert -(10**500) < -0.12 # infinity and NaN comparisons assert math.inf > 10**500 assert math.inf >= 10**500 assert not math.inf < 10**500 -assert -math.inf < -10*500 -assert -math.inf <= -10*500 -assert not -math.inf > -10*500 +assert -math.inf < -10 * 500 +assert -math.inf <= -10 * 500 +assert not -math.inf > -10 * 500 assert not math.nan > 123 assert not math.nan < 123 diff --git a/extra_tests/snippets/operator_div.py b/extra_tests/snippets/operator_div.py index 8520a877c5..e99533cbd5 100644 --- a/extra_tests/snippets/operator_div.py +++ b/extra_tests/snippets/operator_div.py @@ -2,7 +2,7 @@ assert_raises(ZeroDivisionError, lambda: 5 / 0) assert_raises(ZeroDivisionError, lambda: 5 / -0.0) -assert_raises(ZeroDivisionError, lambda: 5 / (2-2)) +assert_raises(ZeroDivisionError, lambda: 5 / (2 - 2)) assert_raises(ZeroDivisionError, lambda: 5 % 0) assert_raises(ZeroDivisionError, lambda: 5 // 0) assert_raises(ZeroDivisionError, lambda: 5.3 // (-0.0)) @@ -18,12 +18,16 @@ res = 10**3000 / (10**2998 + 5 * 10**2996) assert 95.238095 <= res <= 95.238096 -assert 10**500 / (2*10**(500-308)) == 5e307 -assert 10**500 / (10**(500-308)) == 1e308 -assert_raises(OverflowError, lambda: 10**500 / (10**(500-309)), _msg='too big result') +assert 10**500 / (2 * 10 ** (500 - 308)) == 5e307 +assert 10**500 / (10 ** (500 - 308)) == 1e308 +assert_raises( + OverflowError, lambda: 10**500 / (10 ** (500 - 309)), _msg="too big result" +) # a bit more than f64::MAX = 1.7976931348623157e+308_f64 assert (2 * 10**308) / 2 == 1e308 # when dividing too big int by a float, the operation should fail -assert_raises(OverflowError, lambda: (2 * 10**308) / 2.0, _msg='division of big int by float') +assert_raises( + OverflowError, lambda: (2 * 10**308) / 2.0, _msg="division of big int by float" +) diff --git a/extra_tests/snippets/operator_membership.py b/extra_tests/snippets/operator_membership.py index 2987c3c0fe..07065e2244 100644 --- a/extra_tests/snippets/operator_membership.py +++ b/extra_tests/snippets/operator_membership.py @@ -46,15 +46,16 @@ assert 1 in range(0, 2) assert 3 not in range(0, 2) + # test __contains__ in user objects -class MyNotContainingClass(): +class MyNotContainingClass: pass assert_raises(TypeError, lambda: 1 in MyNotContainingClass()) -class MyContainingClass(): +class MyContainingClass: def __init__(self, value): self.value = value diff --git a/extra_tests/snippets/protocol_callable.py b/extra_tests/snippets/protocol_callable.py index c549ef468e..1df0e71793 100644 --- a/extra_tests/snippets/protocol_callable.py +++ b/extra_tests/snippets/protocol_callable.py @@ -1,4 +1,4 @@ -class Callable(): +class Callable: def __init__(self): self.count = 0 @@ -6,13 +6,16 @@ def __call__(self): self.count += 1 return self.count + c = Callable() assert 1 == c() assert 2 == c() + class Inherited(Callable): pass + i = Inherited() assert 1 == i() diff --git a/extra_tests/snippets/protocol_index_bad.py b/extra_tests/snippets/protocol_index_bad.py index af71f2e689..d4ac003c85 100644 --- a/extra_tests/snippets/protocol_index_bad.py +++ b/extra_tests/snippets/protocol_index_bad.py @@ -1,5 +1,6 @@ -""" Test that indexing ops don't hang when an object with a mutating +"""Test that indexing ops don't hang when an object with a mutating __index__ is used.""" + from testutils import assert_raises from array import array @@ -15,18 +16,19 @@ def __index__(self): def run_setslice(): with assert_raises(IndexError): e[BadIndex()] = 42 - e[BadIndex():0:-1] = e - e[0:BadIndex():1] = e - e[0:10:BadIndex()] = e + e[BadIndex() : 0 : -1] = e + e[0 : BadIndex() : 1] = e + e[0 : 10 : BadIndex()] = e def run_delslice(): - del e[BadIndex():0:-1] - del e[0:BadIndex():1] - del e[0:10:BadIndex()] + del e[BadIndex() : 0 : -1] + del e[0 : BadIndex() : 1] + del e[0 : 10 : BadIndex()] + -# Check types -instances = [list(), bytearray(), array('b')] +# Check types +instances = [list(), bytearray(), array("b")] for e in instances: run_setslice() - run_delslice() \ No newline at end of file + run_delslice() diff --git a/extra_tests/snippets/protocol_iterable.py b/extra_tests/snippets/protocol_iterable.py index 7158296c38..7f32504d0a 100644 --- a/extra_tests/snippets/protocol_iterable.py +++ b/extra_tests/snippets/protocol_iterable.py @@ -1,5 +1,6 @@ from testutils import assert_raises + def test_container(x): assert 3 in x assert 4 not in x @@ -10,27 +11,40 @@ def test_container(x): lst.extend(x) assert lst == [0, 1, 2, 3] + class C: def __iter__(self): return iter([0, 1, 2, 3]) + + test_container(C()) + class C: def __getitem__(self, x): - return (0, 1, 2, 3)[x] # raises IndexError on x==4 + return (0, 1, 2, 3)[x] # raises IndexError on x==4 + + test_container(C()) + class C: def __getitem__(self, x): if x > 3: raise StopIteration return x + + test_container(C()) -class C: pass + +class C: + pass + + assert_raises(TypeError, lambda: 5 in C()) assert_raises(TypeError, iter, C) -it = iter([1,2,3,4,5]) +it = iter([1, 2, 3, 4, 5]) call_it = iter(lambda: next(it), 4) -assert list(call_it) == [1,2,3] +assert list(call_it) == [1, 2, 3] diff --git a/extra_tests/snippets/protocol_iternext.py b/extra_tests/snippets/protocol_iternext.py index b2b30961c0..0eff9cff4e 100644 --- a/extra_tests/snippets/protocol_iternext.py +++ b/extra_tests/snippets/protocol_iternext.py @@ -1,5 +1,3 @@ - - ls = [1, 2, 3] i = iter(ls) @@ -7,10 +5,10 @@ assert i.__next__() == 2 assert next(i) == 3 -assert next(i, 'w00t') == 'w00t' +assert next(i, "w00t") == "w00t" -s = '你好' +s = "你好" i = iter(s) i.__setstate__(1) -assert i.__next__() == '好' +assert i.__next__() == "好" assert i.__reduce__()[2] == 2 diff --git a/extra_tests/snippets/recursion.py b/extra_tests/snippets/recursion.py index f2a8d4e11d..2d3b2205d6 100644 --- a/extra_tests/snippets/recursion.py +++ b/extra_tests/snippets/recursion.py @@ -1,8 +1,10 @@ from testutils import assert_raises + class Foo(object): pass + Foo.__repr__ = Foo.__str__ foo = Foo() diff --git a/extra_tests/snippets/stdlib_abc_number.py b/extra_tests/snippets/stdlib_abc_number.py index c6aee97ec8..2c1e81c1f8 100644 --- a/extra_tests/snippets/stdlib_abc_number.py +++ b/extra_tests/snippets/stdlib_abc_number.py @@ -71,4 +71,4 @@ class A(int): assert 1_2.3_4e0_0 == 12.34 with assert_raises(SyntaxError): - eval('1__2') + eval("1__2") diff --git a/extra_tests/snippets/stdlib_array.py b/extra_tests/snippets/stdlib_array.py index 6c4af54597..a31b2f8e42 100644 --- a/extra_tests/snippets/stdlib_array.py +++ b/extra_tests/snippets/stdlib_array.py @@ -23,6 +23,7 @@ b = array("B", [3, 2, 1, 0]) assert a.__ne__(b) is True + def test_float_with_integer_input(): f = array("f", [0, 1, 2.0, 3.0]) f.append(4) @@ -33,10 +34,11 @@ def test_float_with_integer_input(): f[0] = -2 assert f == array("f", [-2, 0, 2, 3, 4]) + test_float_with_integer_input() # slice assignment step overflow behaviour test -T = 'I' +T = "I" a = array(T, range(10)) b = array(T, [100]) a[::9999999999] = b @@ -57,9 +59,10 @@ def test_float_with_integer_input(): del a[0:0:-9999999999] assert a == array(T, [1, 2, 3, 4, 5, 6, 7, 8]) + def test_float_with_nan(): - f = float('nan') - a = array('f') + f = float("nan") + a = array("f") a.append(f) assert not (a == a) assert a != a @@ -68,30 +71,35 @@ def test_float_with_nan(): assert not (a > a) assert not (a >= a) + test_float_with_nan() + def test_different_type_cmp(): - a = array('i', [-1, -2, -3, -4]) - b = array('I', [1, 2, 3, 4]) - c = array('f', [1, 2, 3, 4]) + a = array("i", [-1, -2, -3, -4]) + b = array("I", [1, 2, 3, 4]) + c = array("f", [1, 2, 3, 4]) assert a < b assert b > a assert b == c assert a < c assert c > a + test_different_type_cmp() + def test_array_frombytes(): - a = array('b', [-1, -2]) + a = array("b", [-1, -2]) b = bytearray(a.tobytes()) - c = array('b', b) + c = array("b", b) assert a == c + test_array_frombytes() # test that indexing on an empty array doesn't panic -a = array('b') +a = array("b") with assert_raises(IndexError): a[0] with assert_raises(IndexError): @@ -99,21 +107,21 @@ def test_array_frombytes(): with assert_raises(IndexError): del a[42] -test_str = '🌉abc🌐def🌉🌐' -u = array('u', test_str) +test_str = "🌉abc🌐def🌉🌐" +u = array("u", test_str) # skip as 2 bytes character environment with CPython is failing the test if u.itemsize >= 4: assert u.__reduce_ex__(1)[1][1] == list(test_str) assert loads(dumps(u, 1)) == loads(dumps(u, 3)) # test array name -a = array('b', []) +a = array("b", []) assert str(a.__class__.__name__) == "array" # test arrayiterator name i = iter(a) assert str(i.__class__.__name__) == "arrayiterator" # teset array.__contains__ -a = array('B', [0]) +a = array("B", [0]) assert a.__contains__(0) assert not a.__contains__(1) diff --git a/extra_tests/snippets/stdlib_ast.py b/extra_tests/snippets/stdlib_ast.py index 08c1b3b76e..dc626506fa 100644 --- a/extra_tests/snippets/stdlib_ast.py +++ b/extra_tests/snippets/stdlib_ast.py @@ -1,5 +1,5 @@ - import ast + print(ast) source = """ @@ -11,30 +11,29 @@ def foo(): print(n) print(n.body) print(n.body[0].name) -assert n.body[0].name == 'foo' +assert n.body[0].name == "foo" foo = n.body[0] assert foo.lineno == 2 print(foo.body) assert len(foo.body) == 2 print(foo.body[0]) print(foo.body[0].value.func.id) -assert foo.body[0].value.func.id == 'print' +assert foo.body[0].value.func.id == "print" assert foo.body[0].lineno == 3 assert foo.body[1].lineno == 4 n = ast.parse("3 < 4 > 5\n") assert n.body[0].value.left.value == 3 -assert 'Lt' in str(n.body[0].value.ops[0]) -assert 'Gt' in str(n.body[0].value.ops[1]) +assert "Lt" in str(n.body[0].value.ops[0]) +assert "Gt" in str(n.body[0].value.ops[1]) assert n.body[0].value.comparators[0].value == 4 assert n.body[0].value.comparators[1].value == 5 -n = ast.parse('from ... import a\n') +n = ast.parse("from ... import a\n") print(n) i = n.body[0] assert i.level == 3 assert i.module is None -assert i.names[0].name == 'a' +assert i.names[0].name == "a" assert i.names[0].asname is None - diff --git a/extra_tests/snippets/stdlib_collections.py b/extra_tests/snippets/stdlib_collections.py index 641a6e2a25..8fd7cb6a88 100644 --- a/extra_tests/snippets/stdlib_collections.py +++ b/extra_tests/snippets/stdlib_collections.py @@ -50,9 +50,10 @@ class BadRepr: def __repr__(self): self.d.pop() - return '' + return "" + b = BadRepr() d = deque([1, b, 2]) b.d = d -repr(d) \ No newline at end of file +repr(d) diff --git a/extra_tests/snippets/stdlib_collections_deque.py b/extra_tests/snippets/stdlib_collections_deque.py index 44498633bf..86e566f418 100644 --- a/extra_tests/snippets/stdlib_collections_deque.py +++ b/extra_tests/snippets/stdlib_collections_deque.py @@ -5,9 +5,9 @@ def test_deque_iterator__new__(): klass = type(iter(deque())) - s = 'abcd' + s = "abcd" d = klass(deque(s)) - assert (list(d) == list(s)) + assert list(d) == list(s) test_deque_iterator__new__() @@ -17,22 +17,22 @@ def test_deque_iterator__new__positional_index(): klass = type(iter(deque())) # index between 0 and len - for s in ('abcd', range(200)): + for s in ("abcd", range(200)): for i in range(len(s)): d = klass(deque(s), i) - assert (list(d) == list(s)[i:]) + assert list(d) == list(s)[i:] # negative index - for s in ('abcd', range(200)): + for s in ("abcd", range(200)): for i in range(-100, 0): d = klass(deque(s), i) - assert (list(d) == list(s)) + assert list(d) == list(s) # index ge len - for s in ('abcd', range(200)): + for s in ("abcd", range(200)): for i in range(len(s), 400): d = klass(deque(s), i) - assert (list(d) == list()) + assert list(d) == list() test_deque_iterator__new__positional_index() @@ -41,10 +41,10 @@ def test_deque_iterator__new__positional_index(): def test_deque_iterator__new__not_using_keyword_index(): klass = type(iter(deque())) - for s in ('abcd', range(200)): + for s in ("abcd", range(200)): for i in range(-100, 400): d = klass(deque(s), index=i) - assert (list(d) == list(s)) + assert list(d) == list(s) test_deque_iterator__new__not_using_keyword_index() @@ -54,22 +54,22 @@ def test_deque_reverse_iterator__new__positional_index(): klass = type(reversed(deque())) # index between 0 and len - for s in ('abcd', range(200)): + for s in ("abcd", range(200)): for i in range(len(s)): d = klass(deque(s), i) - assert (list(d) == list(reversed(s))[i:]) + assert list(d) == list(reversed(s))[i:] # negative index - for s in ('abcd', range(200)): + for s in ("abcd", range(200)): for i in range(-100, 0): d = klass(deque(s), i) - assert (list(d) == list(reversed(s))) + assert list(d) == list(reversed(s)) # index ge len - for s in ('abcd', range(200)): + for s in ("abcd", range(200)): for i in range(len(s), 400): d = klass(deque(s), i) - assert (list(d) == list()) + assert list(d) == list() test_deque_reverse_iterator__new__positional_index() @@ -78,10 +78,10 @@ def test_deque_reverse_iterator__new__positional_index(): def test_deque_reverse_iterator__new__not_using_keyword_index(): klass = type(reversed(deque())) - for s in ('abcd', range(200)): + for s in ("abcd", range(200)): for i in range(-100, 400): d = klass(deque(s), index=i) - assert (list(d) == list(reversed(s))) + assert list(d) == list(reversed(s)) test_deque_reverse_iterator__new__not_using_keyword_index() @@ -89,11 +89,13 @@ def test_deque_reverse_iterator__new__not_using_keyword_index(): assert repr(deque()) == "deque([])" assert repr(deque([1, 2, 3])) == "deque([1, 2, 3])" + class D(deque): pass + assert repr(D()) == "D([])" assert repr(D([1, 2, 3])) == "D([1, 2, 3])" -assert_raises(ValueError, lambda: deque().index(10,0,10000000000000000000000000)) \ No newline at end of file +assert_raises(ValueError, lambda: deque().index(10, 0, 10000000000000000000000000)) diff --git a/extra_tests/snippets/stdlib_csv.py b/extra_tests/snippets/stdlib_csv.py index 6ba66d30f7..f762c58010 100644 --- a/extra_tests/snippets/stdlib_csv.py +++ b/extra_tests/snippets/stdlib_csv.py @@ -2,44 +2,48 @@ import csv -for row in csv.reader(['one,two,three']): - [one, two, three] = row - assert one == 'one' - assert two == 'two' - assert three == 'three' +for row in csv.reader(["one,two,three"]): + [one, two, three] = row + assert one == "one" + assert two == "two" + assert three == "three" + def f(): - iter = ['one,two,three', 'four,five,six'] - reader = csv.reader(iter) + iter = ["one,two,three", "four,five,six"] + reader = csv.reader(iter) + + [one, two, three] = next(reader) + [four, five, six] = next(reader) - [one,two,three] = next(reader) - [four,five,six] = next(reader) + assert one == "one" + assert two == "two" + assert three == "three" + assert four == "four" + assert five == "five" + assert six == "six" - assert one == 'one' - assert two == 'two' - assert three == 'three' - assert four == 'four' - assert five == 'five' - assert six == 'six' f() + def test_delim(): - iter = ['one|two|three', 'four|five|six'] - reader = csv.reader(iter, delimiter='|') - - [one,two,three] = next(reader) - [four,five,six] = next(reader) - - assert one == 'one' - assert two == 'two' - assert three == 'three' - assert four == 'four' - assert five == 'five' - assert six == 'six' - - with assert_raises(TypeError): - iter = ['one,,two,,three'] - csv.reader(iter, delimiter=',,') + iter = ["one|two|three", "four|five|six"] + reader = csv.reader(iter, delimiter="|") + + [one, two, three] = next(reader) + [four, five, six] = next(reader) + + assert one == "one" + assert two == "two" + assert three == "three" + assert four == "four" + assert five == "five" + assert six == "six" + + with assert_raises(TypeError): + iter = ["one,,two,,three"] + csv.reader(iter, delimiter=",,") + test_delim() diff --git a/extra_tests/snippets/stdlib_ctypes.py b/extra_tests/snippets/stdlib_ctypes.py index 95ee9900fb..32ed17d19f 100644 --- a/extra_tests/snippets/stdlib_ctypes.py +++ b/extra_tests/snippets/stdlib_ctypes.py @@ -9,8 +9,8 @@ from struct import calcsize as _calcsize -assert Array.__class__.__name__ == 'PyCArrayType' -assert Array.__base__.__name__ == '_CData' +assert Array.__class__.__name__ == "PyCArrayType" +assert Array.__base__.__name__ == "_CData" DEFAULT_MODE = RTLD_LOCAL if _os.name == "posix" and _sys.platform == "darwin": @@ -19,13 +19,16 @@ # libraries. OS X 10.3 is Darwin 7, so we check for # that. - if int(_os.uname().release.split('.')[0]) < 8: + if int(_os.uname().release.split(".")[0]) < 8: DEFAULT_MODE = RTLD_GLOBAL -from _ctypes import FUNCFLAG_CDECL as _FUNCFLAG_CDECL, \ - FUNCFLAG_PYTHONAPI as _FUNCFLAG_PYTHONAPI, \ - FUNCFLAG_USE_ERRNO as _FUNCFLAG_USE_ERRNO, \ - FUNCFLAG_USE_LASTERROR as _FUNCFLAG_USE_LASTERROR +from _ctypes import ( + FUNCFLAG_CDECL as _FUNCFLAG_CDECL, + FUNCFLAG_PYTHONAPI as _FUNCFLAG_PYTHONAPI, + FUNCFLAG_USE_ERRNO as _FUNCFLAG_USE_ERRNO, + FUNCFLAG_USE_LASTERROR as _FUNCFLAG_USE_LASTERROR, +) + def create_string_buffer(init, size=None): """create_string_buffer(aBytes) -> character array @@ -34,7 +37,7 @@ def create_string_buffer(init, size=None): """ if isinstance(init, bytes): if size is None: - size = len(init)+1 + size = len(init) + 1 _sys.audit("ctypes.create_string_buffer", init, size) buftype = c_char.__mul__(size) print(type(c_char.__mul__(size))) @@ -50,32 +53,47 @@ def create_string_buffer(init, size=None): return buf raise TypeError(init) + def _check_size(typ, typecode=None): # Check if sizeof(ctypes_type) against struct.calcsize. This # should protect somewhat against a misconfigured libffi. from struct import calcsize + if typecode is None: # Most _type_ codes are the same as used in struct typecode = typ._type_ actual, required = sizeof(typ), calcsize(typecode) if actual != required: - raise SystemError("sizeof(%s) wrong: %d instead of %d" % \ - (typ, actual, required)) + raise SystemError( + "sizeof(%s) wrong: %d instead of %d" % (typ, actual, required) + ) + class c_short(_SimpleCData): _type_ = "h" + + _check_size(c_short) + class c_ushort(_SimpleCData): _type_ = "H" + + _check_size(c_ushort) + class c_long(_SimpleCData): _type_ = "l" + + _check_size(c_long) + class c_ulong(_SimpleCData): _type_ = "L" + + _check_size(c_ulong) if _calcsize("i") == _calcsize("l"): @@ -83,24 +101,36 @@ class c_ulong(_SimpleCData): c_int = c_long c_uint = c_ulong else: + class c_int(_SimpleCData): _type_ = "i" + _check_size(c_int) class c_uint(_SimpleCData): _type_ = "I" + _check_size(c_uint) + class c_float(_SimpleCData): _type_ = "f" + + _check_size(c_float) + class c_double(_SimpleCData): _type_ = "d" + + _check_size(c_double) + class c_longdouble(_SimpleCData): _type_ = "g" + + if sizeof(c_longdouble) == sizeof(c_double): c_longdouble = c_double @@ -109,54 +139,76 @@ class c_longdouble(_SimpleCData): c_longlong = c_long c_ulonglong = c_ulong else: + class c_longlong(_SimpleCData): _type_ = "q" + _check_size(c_longlong) class c_ulonglong(_SimpleCData): _type_ = "Q" + ## def from_param(cls, val): ## return ('d', float(val), val) ## from_param = classmethod(from_param) _check_size(c_ulonglong) + class c_ubyte(_SimpleCData): _type_ = "B" + + c_ubyte.__ctype_le__ = c_ubyte.__ctype_be__ = c_ubyte # backward compatibility: ##c_uchar = c_ubyte _check_size(c_ubyte) + class c_byte(_SimpleCData): _type_ = "b" + + c_byte.__ctype_le__ = c_byte.__ctype_be__ = c_byte _check_size(c_byte) + class c_char(_SimpleCData): _type_ = "c" + + c_char.__ctype_le__ = c_char.__ctype_be__ = c_char _check_size(c_char) + class c_char_p(_SimpleCData): _type_ = "z" + def __repr__(self): return "%s(%s)" % (self.__class__.__name__, c_void_p.from_buffer(self).value) + + _check_size(c_char_p, "P") + class c_void_p(_SimpleCData): _type_ = "P" -c_voidp = c_void_p # backwards compatibility (to a bug) + + +c_voidp = c_void_p # backwards compatibility (to a bug) _check_size(c_void_p) + class c_bool(_SimpleCData): _type_ = "?" + + _check_size(c_bool) i = c_int(42) f = c_float(3.14) # s = create_string_buffer(b'\000' * 32) assert i.value == 42 -assert abs(f.value - 3.14) < 1e-06 +assert abs(f.value - 3.14) < 1e-06 if _os.name == "nt": from _ctypes import LoadLibrary as _dlopen @@ -164,6 +216,7 @@ class c_bool(_SimpleCData): elif _os.name == "posix": from _ctypes import dlopen as _dlopen + class CDLL(object): """An instance of this class represents a loaded dll/shared library, exporting functions using the standard C calling @@ -178,17 +231,23 @@ class CDLL(object): Calling the functions releases the Python GIL during the call and reacquires it afterwards. """ + _func_flags_ = _FUNCFLAG_CDECL _func_restype_ = c_int # default values for repr - _name = '' + _name = "" _handle = 0 _FuncPtr = None - def __init__(self, name, mode=DEFAULT_MODE, handle=None, - use_errno=False, - use_last_error=False, - winmode=None): + def __init__( + self, + name, + mode=DEFAULT_MODE, + handle=None, + use_errno=False, + use_last_error=False, + winmode=None, + ): self._name = name flags = self._func_flags_ if use_errno: @@ -202,20 +261,22 @@ def __init__(self, name, mode=DEFAULT_MODE, handle=None, Otherwise, name is presented to dlopen() as a file argument. """ if name and name.endswith(")") and ".a(" in name: - mode |= ( _os.RTLD_MEMBER | _os.RTLD_NOW ) + mode |= _os.RTLD_MEMBER | _os.RTLD_NOW if _os.name == "nt": if winmode is not None: mode = winmode else: import nt + mode = 4096 - if '/' in name or '\\' in name: + if "/" in name or "\\" in name: self._name = nt._getfullpathname(self._name) mode |= nt._LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR class _FuncPtr(_CFuncPtr): _flags_ = flags _restype_ = self._func_restype_ + self._FuncPtr = _FuncPtr if handle is None: @@ -224,13 +285,15 @@ class _FuncPtr(_CFuncPtr): self._handle = handle def __repr__(self): - return "<%s '%s', handle %x at %#x>" % \ - (self.__class__.__name__, self._name, - (self._handle & (_sys.maxsize*2 + 1)), - id(self) & (_sys.maxsize*2 + 1)) + return "<%s '%s', handle %x at %#x>" % ( + self.__class__.__name__, + self._name, + (self._handle & (_sys.maxsize * 2 + 1)), + id(self) & (_sys.maxsize * 2 + 1), + ) def __getattr__(self, name): - if name.startswith('__') and name.endswith('__'): + if name.startswith("__") and name.endswith("__"): raise AttributeError(name) func = self.__getitem__(name) setattr(self, name, func) @@ -242,12 +305,13 @@ def __getitem__(self, name_or_ordinal): func.__name__ = name_or_ordinal return func + class LibraryLoader(object): def __init__(self, dlltype): self._dlltype = dlltype def __getattr__(self, name): - if name[0] == '_': + if name[0] == "_": raise AttributeError(name) try: dll = self._dlltype(name) @@ -264,6 +328,7 @@ def LoadLibrary(self, name): __class_getitem__ = classmethod(_types.GenericAlias) + cdll = LibraryLoader(CDLL) test_byte_array = create_string_buffer(b"Hello, World!\n") diff --git a/extra_tests/snippets/stdlib_datetime.py b/extra_tests/snippets/stdlib_datetime.py index cd1f27733b..60e8049401 100644 --- a/extra_tests/snippets/stdlib_datetime.py +++ b/extra_tests/snippets/stdlib_datetime.py @@ -19,8 +19,13 @@ import time as _time from testutils import ( - assert_raises, assert_equal, assert_true, assert_false, assert_isinstance, - assert_in) + assert_raises, + assert_equal, + assert_true, + assert_false, + assert_isinstance, + assert_in, +) # An arbitrary collection of objects of non-datetime types, for testing # mixed-type comparisons. @@ -40,7 +45,7 @@ assert_equal(datetime_module.MINYEAR, 1) assert_equal(datetime_module.MAXYEAR, 9999) -if hasattr(datetime_module, '_divide_and_round'): +if hasattr(datetime_module, "_divide_and_round"): # def test_divide_and_round(self): dar = datetime_module._divide_and_round @@ -68,8 +73,8 @@ ############################################################################# # tzinfo tests -class FixedOffset(tzinfo): +class FixedOffset(tzinfo): def __init__(self, offset, name, dstoffset=42): if isinstance(offset, int): offset = timedelta(minutes=offset) @@ -78,24 +83,30 @@ def __init__(self, offset, name, dstoffset=42): self.__offset = offset self.__name = name self.__dstoffset = dstoffset + def __repr__(self): return self.__name.lower() + def utcoffset(self, dt): return self.__offset + def tzname(self, dt): return self.__name + def dst(self, dt): return self.__dstoffset -class PicklableFixedOffset(FixedOffset): +class PicklableFixedOffset(FixedOffset): def __init__(self, offset=None, name=None, dstoffset=None): FixedOffset.__init__(self, offset, name, dstoffset) + class _TZInfo(tzinfo): def utcoffset(self, datetime_module): return random.random() + # class TestTZInfo(unittest.TestCase): # def test_refcnt_crash_bug_22044(self): @@ -117,11 +128,14 @@ def utcoffset(self, datetime_module): with assert_raises(NotImplementedError): useless.dst(dt) + # def test_subclass_must_override(self): class NotEnough(tzinfo): def __init__(self, offset, name): self.__offset = offset self.__name = name + + assert_true(issubclass(NotEnough, tzinfo)) ne = NotEnough(3, "NotByALongShot") assert_isinstance(ne, tzinfo) @@ -138,14 +152,14 @@ def __init__(self, offset, name): # XXX: bug #1302 # def test_normal(self): -#fo = FixedOffset(3, "Three") -#assert_isinstance(fo, tzinfo) -#for dt in datetime.now(), None: +# fo = FixedOffset(3, "Three") +# assert_isinstance(fo, tzinfo) +# for dt in datetime.now(), None: # assert_equal(fo.utcoffset(dt), timedelta(minutes=3)) # assert_equal(fo.tzname(dt), "Three") # assert_equal(fo.dst(dt), timedelta(minutes=42)) -''' +""" class TestTimeZone(unittest.TestCase): def setUp(self): @@ -277,17 +291,17 @@ def test_deepcopy(self): tz = timezone.utc tz_copy = copy.deepcopy(tz) self.assertIs(tz_copy, tz) -''' +""" ############################################################################# # Base class for testing a particular aspect of timedelta, time, date and # datetime comparisons. # class HarmlessMixedComparison: - # Test that __eq__ and __ne__ don't complain for mixed-type comparisons. +# Test that __eq__ and __ne__ don't complain for mixed-type comparisons. - # Subclasses must define 'theclass', and theclass(1, 1, 1) must be a - # legit constructor. +# Subclasses must define 'theclass', and theclass(1, 1, 1) must be a +# legit constructor. for theclass in timedelta, date, time: # def test_harmless_mixed_comparison(self): diff --git a/extra_tests/snippets/stdlib_dir_module.py b/extra_tests/snippets/stdlib_dir_module.py index 560fb02bf6..a8ab233f37 100644 --- a/extra_tests/snippets/stdlib_dir_module.py +++ b/extra_tests/snippets/stdlib_dir_module.py @@ -1,13 +1,14 @@ from testutils import assert_equal import dir_module + assert dir_module.value == 5 assert dir_module.value2 == 7 try: dir_module.unknown_attr except AttributeError as e: - assert 'dir_module' in str(e) + assert "dir_module" in str(e) else: assert False @@ -15,7 +16,7 @@ try: dir_module.unknown_attr except AttributeError as e: - assert 'dir_module' not in str(e) + assert "dir_module" not in str(e) else: assert False @@ -23,9 +24,10 @@ try: dir_module.unknown_attr except AttributeError as e: - assert 'dir_module' not in str(e) + assert "dir_module" not in str(e) else: assert False from dir_module import dir_module_inner -assert dir_module_inner.__name__ == 'dir_module.dir_module_inner' + +assert dir_module_inner.__name__ == "dir_module.dir_module_inner" diff --git a/extra_tests/snippets/stdlib_dis.py b/extra_tests/snippets/stdlib_dis.py index e9951ef402..42296168f8 100644 --- a/extra_tests/snippets/stdlib_dis.py +++ b/extra_tests/snippets/stdlib_dis.py @@ -2,37 +2,53 @@ dis.dis(compile("5 + x + 5 or 2", "", "eval")) print("\n") -dis.dis(compile(""" +dis.dis( + compile( + """ def f(x): return 1 -""", "", "exec")) +""", + "", + "exec", + ) +) print("\n") -dis.dis(compile(""" +dis.dis( + compile( + """ if a: 1 or 2 elif x == 'hello': 3 else: 4 -""", "", "exec")) +""", + "", + "exec", + ) +) print("\n") dis.dis(compile("f(x=1, y=2)", "", "eval")) print("\n") + def f(): with g(): # noqa: F821 try: for a in {1: 4, 2: 5}: yield [True and False or True, []] except Exception: - raise not ValueError({1 for i in [1,2,3]}) + raise not ValueError({1 for i in [1, 2, 3]}) + dis.dis(f) + class A(object): def f(): x += 1 # noqa: F821 pass + def g(): for i in range(5): if i: @@ -40,5 +56,6 @@ def g(): else: break + print("A.f\n") dis.dis(A.f) diff --git a/extra_tests/snippets/stdlib_functools.py b/extra_tests/snippets/stdlib_functools.py index 0bdafcb3b8..3d323bfbad 100644 --- a/extra_tests/snippets/stdlib_functools.py +++ b/extra_tests/snippets/stdlib_functools.py @@ -1,6 +1,7 @@ from functools import reduce from testutils import assert_raises + class Squares: def __init__(self, max): self.max = max @@ -10,21 +11,24 @@ def __len__(self): return len(self.sofar) def __getitem__(self, i): - if not 0 <= i < self.max: raise IndexError + if not 0 <= i < self.max: + raise IndexError n = len(self.sofar) while n <= i: - self.sofar.append(n*n) + self.sofar.append(n * n) n += 1 return self.sofar[i] + def add(a, b): return a + b -assert reduce(add, ['a', 'b', 'c']) == 'abc' -assert reduce(add, ['a', 'b', 'c'], str(42)) == '42abc' -assert reduce(add, [['a', 'c'], [], ['d', 'w']], []) == ['a','c','d','w'] -assert reduce(add, [['a', 'c'], [], ['d', 'w']], []) == ['a','c','d','w'] -assert reduce(lambda x, y: x*y, range(2, 21), 1) == 2432902008176640000 + +assert reduce(add, ["a", "b", "c"]) == "abc" +assert reduce(add, ["a", "b", "c"], str(42)) == "42abc" +assert reduce(add, [["a", "c"], [], ["d", "w"]], []) == ["a", "c", "d", "w"] +assert reduce(add, [["a", "c"], [], ["d", "w"]], []) == ["a", "c", "d", "w"] +assert reduce(lambda x, y: x * y, range(2, 21), 1) == 2432902008176640000 assert reduce(add, Squares(10)) == 285 assert reduce(add, Squares(10), 0) == 285 assert reduce(add, Squares(0), 0) == 0 @@ -40,32 +44,40 @@ def add(a, b): with assert_raises(TypeError): reduce(42, 42, 42) + class TestFailingIter: def __iter__(self): raise RuntimeError + with assert_raises(RuntimeError): reduce(add, TestFailingIter()) assert reduce(add, [], None) == None assert reduce(add, [], 42) == 42 + class BadSeq: def __getitem__(self, index): raise ValueError + + with assert_raises(ValueError): reduce(42, BadSeq()) + # Test reduce()'s use of iterators. class SequenceClass: def __init__(self, n): self.n = n + def __getitem__(self, i): if 0 <= i < self.n: return i else: raise IndexError + assert reduce(add, SequenceClass(5)) == 10 assert reduce(add, SequenceClass(5), 42) == 52 with assert_raises(TypeError): diff --git a/extra_tests/snippets/stdlib_hashlib.py b/extra_tests/snippets/stdlib_hashlib.py index 811e3d27b6..c5feb709e1 100644 --- a/extra_tests/snippets/stdlib_hashlib.py +++ b/extra_tests/snippets/stdlib_hashlib.py @@ -1,39 +1,50 @@ - import hashlib # print(hashlib.md5) h = hashlib.md5() -h.update(b'a') -g = hashlib.md5(b'a') -assert h.name == g.name == 'md5' +h.update(b"a") +g = hashlib.md5(b"a") +assert h.name == g.name == "md5" print(h.hexdigest()) print(g.hexdigest()) -assert h.hexdigest() == g.hexdigest() == '0cc175b9c0f1b6a831c399e269772661' +assert h.hexdigest() == g.hexdigest() == "0cc175b9c0f1b6a831c399e269772661" assert h.digest_size == g.digest_size == 16 h = hashlib.sha256() -h.update(b'a') -g = hashlib.sha256(b'a') -assert h.name == g.name == 'sha256' +h.update(b"a") +g = hashlib.sha256(b"a") +assert h.name == g.name == "sha256" assert h.digest_size == g.digest_size == 32 print(h.hexdigest()) print(g.hexdigest()) -assert h.hexdigest() == g.hexdigest() == 'ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb' +assert ( + h.hexdigest() + == g.hexdigest() + == "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb" +) h = hashlib.sha512() -g = hashlib.sha512(b'a') -assert h.name == g.name == 'sha512' -h.update(b'a') +g = hashlib.sha512(b"a") +assert h.name == g.name == "sha512" +h.update(b"a") print(h.hexdigest()) print(g.hexdigest()) -assert h.hexdigest() == g.hexdigest() == '1f40fc92da241694750979ee6cf582f2d5d7d28e18335de05abc54d0560e0f5302860c652bf08d560252aa5e74210546f369fbbbce8c12cfc7957b2652fe9a75' +assert ( + h.hexdigest() + == g.hexdigest() + == "1f40fc92da241694750979ee6cf582f2d5d7d28e18335de05abc54d0560e0f5302860c652bf08d560252aa5e74210546f369fbbbce8c12cfc7957b2652fe9a75" +) h = hashlib.new("blake2s", b"fubar") print(h.hexdigest()) -assert h.hexdigest() == 'a0e1ad0c123c9c65e8ef850db2ce4b5cef2c35b06527c615b0154353574d0415' -h.update(b'bla') +assert ( + h.hexdigest() == "a0e1ad0c123c9c65e8ef850db2ce4b5cef2c35b06527c615b0154353574d0415" +) +h.update(b"bla") print(h.hexdigest()) -assert h.hexdigest() == '25738bfe4cc104131e1b45bece4dfd4e7e1d6f0dffda1211e996e9d5d3b66e81' +assert ( + h.hexdigest() == "25738bfe4cc104131e1b45bece4dfd4e7e1d6f0dffda1211e996e9d5d3b66e81" +) diff --git a/extra_tests/snippets/stdlib_imp.py b/extra_tests/snippets/stdlib_imp.py index bd28e95f3d..835b50d617 100644 --- a/extra_tests/snippets/stdlib_imp.py +++ b/extra_tests/snippets/stdlib_imp.py @@ -8,9 +8,11 @@ assert _imp.is_frozen("__hello__") == True assert _imp.is_frozen("math") == False + class FakeSpec: - def __init__(self, name): - self.name = name + def __init__(self, name): + self.name = name + A = FakeSpec("time") diff --git a/extra_tests/snippets/stdlib_io.py b/extra_tests/snippets/stdlib_io.py index 3dda7278c0..011bb051c2 100644 --- a/extra_tests/snippets/stdlib_io.py +++ b/extra_tests/snippets/stdlib_io.py @@ -2,30 +2,30 @@ import os from testutils import assert_raises -fi = FileIO('README.md') +fi = FileIO("README.md") assert fi.seekable() bb = BufferedReader(fi) assert bb.seekable() result = bb.read() -assert len(result) <= 8*1024 +assert len(result) <= 8 * 1024 assert len(result) >= 0 assert isinstance(result, bytes) -with FileIO('README.md') as fio: - res = fio.read() - assert len(result) <= 8*1024 - assert len(result) >= 0 - assert isinstance(result, bytes) +with FileIO("README.md") as fio: + res = fio.read() + assert len(result) <= 8 * 1024 + assert len(result) >= 0 + assert isinstance(result, bytes) -fd = os.open('README.md', os.O_RDONLY) +fd = os.open("README.md", os.O_RDONLY) with FileIO(fd) as fio: - res2 = fio.read() - assert res == res2 + res2 = fio.read() + assert res == res2 -fi = FileIO('README.md') +fi = FileIO("README.md") fi.read() fi.close() assert fi.closefd @@ -34,8 +34,8 @@ with assert_raises(ValueError): fi.read() -with FileIO('README.md') as fio: - nres = fio.read(1) - assert len(nres) == 1 - nres = fio.read(2) - assert len(nres) == 2 +with FileIO("README.md") as fio: + nres = fio.read(1) + assert len(nres) == 1 + nres = fio.read(2) + assert len(nres) == 2 diff --git a/extra_tests/snippets/stdlib_io_bytesio.py b/extra_tests/snippets/stdlib_io_bytesio.py index 5714448764..d6ed298a0a 100644 --- a/extra_tests/snippets/stdlib_io_bytesio.py +++ b/extra_tests/snippets/stdlib_io_bytesio.py @@ -1,8 +1,8 @@ - from io import BytesIO + def test_01(): - bytes_string = b'Test String 1' + bytes_string = b"Test String 1" f = BytesIO() f.write(bytes_string) @@ -10,45 +10,49 @@ def test_01(): assert f.tell() == len(bytes_string) assert f.getvalue() == bytes_string + def test_02(): - bytes_string = b'Test String 2' + bytes_string = b"Test String 2" f = BytesIO(bytes_string) assert f.read() == bytes_string - assert f.read() == b'' + assert f.read() == b"" + def test_03(): """ - Tests that the read method (integer arg) - returns the expected value + Tests that the read method (integer arg) + returns the expected value """ - string = b'Test String 3' + string = b"Test String 3" f = BytesIO(string) - assert f.read(1) == b'T' - assert f.read(1) == b'e' - assert f.read(1) == b's' - assert f.read(1) == b't' + assert f.read(1) == b"T" + assert f.read(1) == b"e" + assert f.read(1) == b"s" + assert f.read(1) == b"t" + def test_04(): """ - Tests that the read method increments the - cursor position and the seek method moves - the cursor to the appropriate position + Tests that the read method increments the + cursor position and the seek method moves + the cursor to the appropriate position """ - string = b'Test String 4' + string = b"Test String 4" f = BytesIO(string) - assert f.read(4) == b'Test' + assert f.read(4) == b"Test" assert f.tell() == 4 assert f.seek(0) == 0 - assert f.read(4) == b'Test' + assert f.read(4) == b"Test" + def test_05(): """ - Tests that the write method accpets bytearray + Tests that the write method accpets bytearray """ - bytes_string = b'Test String 5' + bytes_string = b"Test String 5" f = BytesIO() f.write(bytearray(bytes_string)) @@ -58,16 +62,16 @@ def test_05(): def test_06(): """ - Tests readline + Tests readline """ - bytes_string = b'Test String 6\nnew line is here\nfinished' + bytes_string = b"Test String 6\nnew line is here\nfinished" f = BytesIO(bytes_string) - assert f.readline() == b'Test String 6\n' - assert f.readline() == b'new line is here\n' - assert f.readline() == b'finished' - assert f.readline() == b'' + assert f.readline() == b"Test String 6\n" + assert f.readline() == b"new line is here\n" + assert f.readline() == b"finished" + assert f.readline() == b"" if __name__ == "__main__": @@ -77,4 +81,3 @@ def test_06(): test_04() test_05() test_06() - diff --git a/extra_tests/snippets/stdlib_io_stringio.py b/extra_tests/snippets/stdlib_io_stringio.py index 828f0506ed..5419eef2bb 100644 --- a/extra_tests/snippets/stdlib_io_stringio.py +++ b/extra_tests/snippets/stdlib_io_stringio.py @@ -1,68 +1,73 @@ - from io import StringIO + def test_01(): """ - Test that the constructor and getvalue - method return expected values + Test that the constructor and getvalue + method return expected values """ - string = 'Test String 1' + string = "Test String 1" f = StringIO() f.write(string) assert f.tell() == len(string) assert f.getvalue() == string + def test_02(): """ - Test that the read method (no arg) - results the expected value + Test that the read method (no arg) + results the expected value """ - string = 'Test String 2' + string = "Test String 2" f = StringIO(string) assert f.read() == string - assert f.read() == '' + assert f.read() == "" + def test_03(): """ - Tests that the read method (integer arg) - returns the expected value + Tests that the read method (integer arg) + returns the expected value """ - string = 'Test String 3' + string = "Test String 3" f = StringIO(string) - assert f.read(1) == 'T' - assert f.read(1) == 'e' - assert f.read(1) == 's' - assert f.read(1) == 't' + assert f.read(1) == "T" + assert f.read(1) == "e" + assert f.read(1) == "s" + assert f.read(1) == "t" + def test_04(): """ - Tests that the read method increments the - cursor position and the seek method moves - the cursor to the appropriate position + Tests that the read method increments the + cursor position and the seek method moves + the cursor to the appropriate position """ - string = 'Test String 4' + string = "Test String 4" f = StringIO(string) - assert f.read(4) == 'Test' + assert f.read(4) == "Test" assert f.tell() == 4 assert f.seek(0) == 0 - assert f.read(4) == 'Test' + assert f.read(4) == "Test" + def test_05(): """ - Tests readline + Tests readline """ - string = 'Test String 6\nnew line is here\nfinished' + string = "Test String 6\nnew line is here\nfinished" f = StringIO(string) - assert f.readline() == 'Test String 6\n' - assert f.readline() == 'new line is here\n' - assert f.readline() == 'finished' - assert f.readline() == '' + assert f.readline() == "Test String 6\n" + assert f.readline() == "new line is here\n" + assert f.readline() == "finished" + assert f.readline() == "" + if __name__ == "__main__": test_01() diff --git a/extra_tests/snippets/stdlib_itertools.py b/extra_tests/snippets/stdlib_itertools.py index 58684f611d..724e9f1d5f 100644 --- a/extra_tests/snippets/stdlib_itertools.py +++ b/extra_tests/snippets/stdlib_itertools.py @@ -12,13 +12,13 @@ assert list(chain([], "", b"", ())) == [] assert list(chain([1, 2, 3, 4])) == [1, 2, 3, 4] -assert list(chain("ab", "cd", (), 'e')) == ['a', 'b', 'c', 'd', 'e'] +assert list(chain("ab", "cd", (), "e")) == ["a", "b", "c", "d", "e"] with assert_raises(TypeError): list(chain(1)) x = chain("ab", 1) -assert next(x) == 'a' -assert next(x) == 'b' +assert next(x) == "a" +assert next(x) == "b" with assert_raises(TypeError): next(x) @@ -37,17 +37,17 @@ list(chain(1)) args = ["abc", "def"] -assert list(chain.from_iterable(args)) == ['a', 'b', 'c', 'd', 'e', 'f'] +assert list(chain.from_iterable(args)) == ["a", "b", "c", "d", "e", "f"] args = [[], "", b"", ()] assert list(chain.from_iterable(args)) == [] -args = ["ab", "cd", (), 'e'] -assert list(chain.from_iterable(args)) == ['a', 'b', 'c', 'd', 'e'] +args = ["ab", "cd", (), "e"] +assert list(chain.from_iterable(args)) == ["a", "b", "c", "d", "e"] x = chain.from_iterable(["ab", 1]) -assert next(x) == 'a' -assert next(x) == 'b' +assert next(x) == "a" +assert next(x) == "b" with assert_raises(TypeError): next(x) @@ -174,16 +174,17 @@ # itertools.starmap tests starmap = itertools.starmap -assert list(starmap(pow, zip(range(3), range(1,7)))) == [0**1, 1**2, 2**3] +assert list(starmap(pow, zip(range(3), range(1, 7)))) == [0**1, 1**2, 2**3] assert list(starmap(pow, [])) == [] -assert list(starmap(pow, [iter([4,5])])) == [4**5] +assert list(starmap(pow, [iter([4, 5])])) == [4**5] with assert_raises(TypeError): starmap(pow) # itertools.takewhile tests def underten(x): - return x<10 + return x < 10 + from itertools import takewhile as tw @@ -227,12 +228,30 @@ def underten(x): next(t) it = tw(underten, [1, 3, 5, 20, 2, 4, 6, 8]) -assert pickle.dumps(it, 0) == b'citertools\ntakewhile\np0\n(c__main__\nunderten\np1\nc__builtin__\niter\np2\n((lp3\nI1\naI3\naI5\naI20\naI2\naI4\naI6\naI8\natp4\nRp5\nI0\nbtp6\nRp7\nI0\nb.' -assert pickle.dumps(it, 1) == b'citertools\ntakewhile\nq\x00(c__main__\nunderten\nq\x01c__builtin__\niter\nq\x02(]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08etq\x04Rq\x05K\x00btq\x06Rq\x07K\x00b.' -assert pickle.dumps(it, 2) == b'\x80\x02citertools\ntakewhile\nq\x00c__main__\nunderten\nq\x01c__builtin__\niter\nq\x02]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85q\x04Rq\x05K\x00b\x86q\x06Rq\x07K\x00b.' -assert pickle.dumps(it, 3) == b'\x80\x03citertools\ntakewhile\nq\x00c__main__\nunderten\nq\x01cbuiltins\niter\nq\x02]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85q\x04Rq\x05K\x00b\x86q\x06Rq\x07K\x00b.' -assert pickle.dumps(it, 4) == b'\x80\x04\x95i\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x94\x8c\ttakewhile\x94\x93\x94\x8c\x08__main__\x94\x8c\x08underten\x94\x93\x94\x8c\x08builtins\x94\x8c\x04iter\x94\x93\x94]\x94(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85\x94R\x94K\x00b\x86\x94R\x94K\x00b.' -assert pickle.dumps(it, 5) == b'\x80\x05\x95i\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x94\x8c\ttakewhile\x94\x93\x94\x8c\x08__main__\x94\x8c\x08underten\x94\x93\x94\x8c\x08builtins\x94\x8c\x04iter\x94\x93\x94]\x94(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85\x94R\x94K\x00b\x86\x94R\x94K\x00b.' +assert ( + pickle.dumps(it, 0) + == b"citertools\ntakewhile\np0\n(c__main__\nunderten\np1\nc__builtin__\niter\np2\n((lp3\nI1\naI3\naI5\naI20\naI2\naI4\naI6\naI8\natp4\nRp5\nI0\nbtp6\nRp7\nI0\nb." +) +assert ( + pickle.dumps(it, 1) + == b"citertools\ntakewhile\nq\x00(c__main__\nunderten\nq\x01c__builtin__\niter\nq\x02(]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08etq\x04Rq\x05K\x00btq\x06Rq\x07K\x00b." +) +assert ( + pickle.dumps(it, 2) + == b"\x80\x02citertools\ntakewhile\nq\x00c__main__\nunderten\nq\x01c__builtin__\niter\nq\x02]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85q\x04Rq\x05K\x00b\x86q\x06Rq\x07K\x00b." +) +assert ( + pickle.dumps(it, 3) + == b"\x80\x03citertools\ntakewhile\nq\x00c__main__\nunderten\nq\x01cbuiltins\niter\nq\x02]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85q\x04Rq\x05K\x00b\x86q\x06Rq\x07K\x00b." +) +assert ( + pickle.dumps(it, 4) + == b"\x80\x04\x95i\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x94\x8c\ttakewhile\x94\x93\x94\x8c\x08__main__\x94\x8c\x08underten\x94\x93\x94\x8c\x08builtins\x94\x8c\x04iter\x94\x93\x94]\x94(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85\x94R\x94K\x00b\x86\x94R\x94K\x00b." +) +assert ( + pickle.dumps(it, 5) + == b"\x80\x05\x95i\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x94\x8c\ttakewhile\x94\x93\x94\x8c\x08__main__\x94\x8c\x08underten\x94\x93\x94\x8c\x08builtins\x94\x8c\x04iter\x94\x93\x94]\x94(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85\x94R\x94K\x00b\x86\x94R\x94K\x00b." +) next(it) next(it) next(it) @@ -240,12 +259,30 @@ def underten(x): next(it) except StopIteration: pass -assert pickle.dumps(it, 0) == b'citertools\ntakewhile\np0\n(c__main__\nunderten\np1\nc__builtin__\niter\np2\n((lp3\nI1\naI3\naI5\naI20\naI2\naI4\naI6\naI8\natp4\nRp5\nI4\nbtp6\nRp7\nI1\nb.' -assert pickle.dumps(it, 1) == b'citertools\ntakewhile\nq\x00(c__main__\nunderten\nq\x01c__builtin__\niter\nq\x02(]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08etq\x04Rq\x05K\x04btq\x06Rq\x07K\x01b.' -assert pickle.dumps(it, 2) == b'\x80\x02citertools\ntakewhile\nq\x00c__main__\nunderten\nq\x01c__builtin__\niter\nq\x02]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85q\x04Rq\x05K\x04b\x86q\x06Rq\x07K\x01b.' -assert pickle.dumps(it, 3) == b'\x80\x03citertools\ntakewhile\nq\x00c__main__\nunderten\nq\x01cbuiltins\niter\nq\x02]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85q\x04Rq\x05K\x04b\x86q\x06Rq\x07K\x01b.' -assert pickle.dumps(it, 4) == b'\x80\x04\x95i\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x94\x8c\ttakewhile\x94\x93\x94\x8c\x08__main__\x94\x8c\x08underten\x94\x93\x94\x8c\x08builtins\x94\x8c\x04iter\x94\x93\x94]\x94(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85\x94R\x94K\x04b\x86\x94R\x94K\x01b.' -assert pickle.dumps(it, 5) == b'\x80\x05\x95i\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x94\x8c\ttakewhile\x94\x93\x94\x8c\x08__main__\x94\x8c\x08underten\x94\x93\x94\x8c\x08builtins\x94\x8c\x04iter\x94\x93\x94]\x94(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85\x94R\x94K\x04b\x86\x94R\x94K\x01b.' +assert ( + pickle.dumps(it, 0) + == b"citertools\ntakewhile\np0\n(c__main__\nunderten\np1\nc__builtin__\niter\np2\n((lp3\nI1\naI3\naI5\naI20\naI2\naI4\naI6\naI8\natp4\nRp5\nI4\nbtp6\nRp7\nI1\nb." +) +assert ( + pickle.dumps(it, 1) + == b"citertools\ntakewhile\nq\x00(c__main__\nunderten\nq\x01c__builtin__\niter\nq\x02(]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08etq\x04Rq\x05K\x04btq\x06Rq\x07K\x01b." +) +assert ( + pickle.dumps(it, 2) + == b"\x80\x02citertools\ntakewhile\nq\x00c__main__\nunderten\nq\x01c__builtin__\niter\nq\x02]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85q\x04Rq\x05K\x04b\x86q\x06Rq\x07K\x01b." +) +assert ( + pickle.dumps(it, 3) + == b"\x80\x03citertools\ntakewhile\nq\x00c__main__\nunderten\nq\x01cbuiltins\niter\nq\x02]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85q\x04Rq\x05K\x04b\x86q\x06Rq\x07K\x01b." +) +assert ( + pickle.dumps(it, 4) + == b"\x80\x04\x95i\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x94\x8c\ttakewhile\x94\x93\x94\x8c\x08__main__\x94\x8c\x08underten\x94\x93\x94\x8c\x08builtins\x94\x8c\x04iter\x94\x93\x94]\x94(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85\x94R\x94K\x04b\x86\x94R\x94K\x01b." +) +assert ( + pickle.dumps(it, 5) + == b"\x80\x05\x95i\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x94\x8c\ttakewhile\x94\x93\x94\x8c\x08__main__\x94\x8c\x08underten\x94\x93\x94\x8c\x08builtins\x94\x8c\x04iter\x94\x93\x94]\x94(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85\x94R\x94K\x04b\x86\x94R\x94K\x01b." +) for proto in range(pickle.HIGHEST_PROTOCOL + 1): try: next(pickle.loads(pickle.dumps(it, proto))) @@ -254,16 +291,18 @@ def underten(x): pass - # itertools.islice tests + def assert_matches_seq(it, seq): assert list(it) == list(seq) + def test_islice_pickle(it): for p in range(pickle.HIGHEST_PROTOCOL + 1): it == pickle.loads(pickle.dumps(it, p)) + i = itertools.islice it = i([1, 2, 3, 4, 5], 3) @@ -295,7 +334,7 @@ def test_islice_pickle(it): test_islice_pickle(it) # itertools.filterfalse -it = itertools.filterfalse(lambda x: x%2, range(10)) +it = itertools.filterfalse(lambda x: x % 2, range(10)) assert 0 == next(it) assert 2 == next(it) assert 4 == next(it) @@ -314,7 +353,7 @@ def test_islice_pickle(it): # itertools.dropwhile -it = itertools.dropwhile(lambda x: x<5, [1,4,6,4,1]) +it = itertools.dropwhile(lambda x: x < 5, [1, 4, 6, 4, 1]) assert 6 == next(it) assert 4 == next(it) assert 1 == next(it) @@ -322,19 +361,55 @@ def test_islice_pickle(it): next(it) it = itertools.dropwhile(underten, [1, 3, 5, 20, 2, 4, 6, 8]) -assert pickle.dumps(it, 0) == b'citertools\ndropwhile\np0\n(c__main__\nunderten\np1\nc__builtin__\niter\np2\n((lp3\nI1\naI3\naI5\naI20\naI2\naI4\naI6\naI8\natp4\nRp5\nI0\nbtp6\nRp7\nI0\nb.' -assert pickle.dumps(it, 1) == b'citertools\ndropwhile\nq\x00(c__main__\nunderten\nq\x01c__builtin__\niter\nq\x02(]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08etq\x04Rq\x05K\x00btq\x06Rq\x07K\x00b.' -assert pickle.dumps(it, 2) == b'\x80\x02citertools\ndropwhile\nq\x00c__main__\nunderten\nq\x01c__builtin__\niter\nq\x02]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85q\x04Rq\x05K\x00b\x86q\x06Rq\x07K\x00b.' -assert pickle.dumps(it, 3) == b'\x80\x03citertools\ndropwhile\nq\x00c__main__\nunderten\nq\x01cbuiltins\niter\nq\x02]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85q\x04Rq\x05K\x00b\x86q\x06Rq\x07K\x00b.' -assert pickle.dumps(it, 4) == b'\x80\x04\x95i\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x94\x8c\tdropwhile\x94\x93\x94\x8c\x08__main__\x94\x8c\x08underten\x94\x93\x94\x8c\x08builtins\x94\x8c\x04iter\x94\x93\x94]\x94(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85\x94R\x94K\x00b\x86\x94R\x94K\x00b.' -assert pickle.dumps(it, 5) == b'\x80\x05\x95i\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x94\x8c\tdropwhile\x94\x93\x94\x8c\x08__main__\x94\x8c\x08underten\x94\x93\x94\x8c\x08builtins\x94\x8c\x04iter\x94\x93\x94]\x94(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85\x94R\x94K\x00b\x86\x94R\x94K\x00b.' +assert ( + pickle.dumps(it, 0) + == b"citertools\ndropwhile\np0\n(c__main__\nunderten\np1\nc__builtin__\niter\np2\n((lp3\nI1\naI3\naI5\naI20\naI2\naI4\naI6\naI8\natp4\nRp5\nI0\nbtp6\nRp7\nI0\nb." +) +assert ( + pickle.dumps(it, 1) + == b"citertools\ndropwhile\nq\x00(c__main__\nunderten\nq\x01c__builtin__\niter\nq\x02(]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08etq\x04Rq\x05K\x00btq\x06Rq\x07K\x00b." +) +assert ( + pickle.dumps(it, 2) + == b"\x80\x02citertools\ndropwhile\nq\x00c__main__\nunderten\nq\x01c__builtin__\niter\nq\x02]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85q\x04Rq\x05K\x00b\x86q\x06Rq\x07K\x00b." +) +assert ( + pickle.dumps(it, 3) + == b"\x80\x03citertools\ndropwhile\nq\x00c__main__\nunderten\nq\x01cbuiltins\niter\nq\x02]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85q\x04Rq\x05K\x00b\x86q\x06Rq\x07K\x00b." +) +assert ( + pickle.dumps(it, 4) + == b"\x80\x04\x95i\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x94\x8c\tdropwhile\x94\x93\x94\x8c\x08__main__\x94\x8c\x08underten\x94\x93\x94\x8c\x08builtins\x94\x8c\x04iter\x94\x93\x94]\x94(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85\x94R\x94K\x00b\x86\x94R\x94K\x00b." +) +assert ( + pickle.dumps(it, 5) + == b"\x80\x05\x95i\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x94\x8c\tdropwhile\x94\x93\x94\x8c\x08__main__\x94\x8c\x08underten\x94\x93\x94\x8c\x08builtins\x94\x8c\x04iter\x94\x93\x94]\x94(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85\x94R\x94K\x00b\x86\x94R\x94K\x00b." +) next(it) -assert pickle.dumps(it, 0) == b'citertools\ndropwhile\np0\n(c__main__\nunderten\np1\nc__builtin__\niter\np2\n((lp3\nI1\naI3\naI5\naI20\naI2\naI4\naI6\naI8\natp4\nRp5\nI4\nbtp6\nRp7\nI1\nb.' -assert pickle.dumps(it, 1) == b'citertools\ndropwhile\nq\x00(c__main__\nunderten\nq\x01c__builtin__\niter\nq\x02(]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08etq\x04Rq\x05K\x04btq\x06Rq\x07K\x01b.' -assert pickle.dumps(it, 2) == b'\x80\x02citertools\ndropwhile\nq\x00c__main__\nunderten\nq\x01c__builtin__\niter\nq\x02]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85q\x04Rq\x05K\x04b\x86q\x06Rq\x07K\x01b.' -assert pickle.dumps(it, 3) == b'\x80\x03citertools\ndropwhile\nq\x00c__main__\nunderten\nq\x01cbuiltins\niter\nq\x02]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85q\x04Rq\x05K\x04b\x86q\x06Rq\x07K\x01b.' -assert pickle.dumps(it, 4) == b'\x80\x04\x95i\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x94\x8c\tdropwhile\x94\x93\x94\x8c\x08__main__\x94\x8c\x08underten\x94\x93\x94\x8c\x08builtins\x94\x8c\x04iter\x94\x93\x94]\x94(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85\x94R\x94K\x04b\x86\x94R\x94K\x01b.' -assert pickle.dumps(it, 5) == b'\x80\x05\x95i\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x94\x8c\tdropwhile\x94\x93\x94\x8c\x08__main__\x94\x8c\x08underten\x94\x93\x94\x8c\x08builtins\x94\x8c\x04iter\x94\x93\x94]\x94(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85\x94R\x94K\x04b\x86\x94R\x94K\x01b.' +assert ( + pickle.dumps(it, 0) + == b"citertools\ndropwhile\np0\n(c__main__\nunderten\np1\nc__builtin__\niter\np2\n((lp3\nI1\naI3\naI5\naI20\naI2\naI4\naI6\naI8\natp4\nRp5\nI4\nbtp6\nRp7\nI1\nb." +) +assert ( + pickle.dumps(it, 1) + == b"citertools\ndropwhile\nq\x00(c__main__\nunderten\nq\x01c__builtin__\niter\nq\x02(]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08etq\x04Rq\x05K\x04btq\x06Rq\x07K\x01b." +) +assert ( + pickle.dumps(it, 2) + == b"\x80\x02citertools\ndropwhile\nq\x00c__main__\nunderten\nq\x01c__builtin__\niter\nq\x02]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85q\x04Rq\x05K\x04b\x86q\x06Rq\x07K\x01b." +) +assert ( + pickle.dumps(it, 3) + == b"\x80\x03citertools\ndropwhile\nq\x00c__main__\nunderten\nq\x01cbuiltins\niter\nq\x02]q\x03(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85q\x04Rq\x05K\x04b\x86q\x06Rq\x07K\x01b." +) +assert ( + pickle.dumps(it, 4) + == b"\x80\x04\x95i\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x94\x8c\tdropwhile\x94\x93\x94\x8c\x08__main__\x94\x8c\x08underten\x94\x93\x94\x8c\x08builtins\x94\x8c\x04iter\x94\x93\x94]\x94(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85\x94R\x94K\x04b\x86\x94R\x94K\x01b." +) +assert ( + pickle.dumps(it, 5) + == b"\x80\x05\x95i\x00\x00\x00\x00\x00\x00\x00\x8c\titertools\x94\x8c\tdropwhile\x94\x93\x94\x8c\x08__main__\x94\x8c\x08underten\x94\x93\x94\x8c\x08builtins\x94\x8c\x04iter\x94\x93\x94]\x94(K\x01K\x03K\x05K\x14K\x02K\x04K\x06K\x08e\x85\x94R\x94K\x04b\x86\x94R\x94K\x01b." +) for proto in range(pickle.HIGHEST_PROTOCOL + 1): assert next(pickle.loads(pickle.dumps(it, proto))) == 2 @@ -352,7 +427,7 @@ def test_islice_pickle(it): with assert_raises(StopIteration): next(it) -it = itertools.accumulate([3, 2, 4, 1, 0, 5, 8], lambda a, v: a*v) +it = itertools.accumulate([3, 2, 4, 1, 0, 5, 8], lambda a, v: a * v) assert 3 == next(it) assert 6 == next(it) assert 24 == next(it) @@ -364,12 +439,12 @@ def test_islice_pickle(it): next(it) # itertools.compress -assert list(itertools.compress("ABCDEF", [1,0,1,0,1,1])) == list("ACEF") -assert list(itertools.compress("ABCDEF", [0,0,0,0,0,0])) == list("") -assert list(itertools.compress("ABCDEF", [1,1,1,1,1,1])) == list("ABCDEF") -assert list(itertools.compress("ABCDEF", [1,0,1])) == list("AC") -assert list(itertools.compress("ABC", [0,1,1,1,1,1])) == list("BC") -assert list(itertools.compress("ABCDEF", [True,False,"t","",1,9])) == list("ACEF") +assert list(itertools.compress("ABCDEF", [1, 0, 1, 0, 1, 1])) == list("ACEF") +assert list(itertools.compress("ABCDEF", [0, 0, 0, 0, 0, 0])) == list("") +assert list(itertools.compress("ABCDEF", [1, 1, 1, 1, 1, 1])) == list("ABCDEF") +assert list(itertools.compress("ABCDEF", [1, 0, 1])) == list("AC") +assert list(itertools.compress("ABC", [0, 1, 1, 1, 1, 1])) == list("BC") +assert list(itertools.compress("ABCDEF", [True, False, "t", "", 1, 9])) == list("ACEF") # itertools.tee @@ -384,7 +459,7 @@ def test_islice_pickle(it): t = itertools.tee(range(1000)) assert list(t[0]) == list(t[1]) == list(range(1000)) -t = itertools.tee([1,22,333], 3) +t = itertools.tee([1, 22, 333], 3) assert len(t) == 3 assert 1 == next(t[0]) assert 1 == next(t[1]) @@ -402,29 +477,29 @@ def test_islice_pickle(it): with assert_raises(StopIteration): next(t[1]) -t0, t1 = itertools.tee([1,2,3]) +t0, t1 = itertools.tee([1, 2, 3]) tc = t0.__copy__() -assert list(t0) == [1,2,3] -assert list(t1) == [1,2,3] -assert list(tc) == [1,2,3] +assert list(t0) == [1, 2, 3] +assert list(t1) == [1, 2, 3] +assert list(tc) == [1, 2, 3] -t0, t1 = itertools.tee([1,2,3]) +t0, t1 = itertools.tee([1, 2, 3]) assert 1 == next(t0) # advance index of t0 by 1 before __copy__() t0c = t0.__copy__() t1c = t1.__copy__() -assert list(t0) == [2,3] -assert list(t0c) == [2,3] -assert list(t1) == [1,2,3] -assert list(t1c) == [1,2,3] +assert list(t0) == [2, 3] +assert list(t0c) == [2, 3] +assert list(t1) == [1, 2, 3] +assert list(t1c) == [1, 2, 3] -t0, t1 = itertools.tee([1,2,3]) +t0, t1 = itertools.tee([1, 2, 3]) t2, t3 = itertools.tee(t0) -assert list(t1) == [1,2,3] -assert list(t2) == [1,2,3] -assert list(t3) == [1,2,3] +assert list(t1) == [1, 2, 3] +assert list(t2) == [1, 2, 3] +assert list(t3) == [1, 2, 3] -t = itertools.tee([1,2,3]) -assert list(t[0]) == [1,2,3] +t = itertools.tee([1, 2, 3]) +assert list(t[0]) == [1, 2, 3] assert list(t[0]) == [] # itertools.product @@ -530,22 +605,36 @@ def test_islice_pickle(it): # itertools.zip_longest tests zl = itertools.zip_longest -assert list(zl(['a', 'b', 'c'], range(3), [9, 8, 7])) \ - == [('a', 0, 9), ('b', 1, 8), ('c', 2, 7)] -assert list(zl(['a', 'b', 'c'], range(3), [9, 8, 7, 99])) \ - == [('a', 0, 9), ('b', 1, 8), ('c', 2, 7), (None, None, 99)] -assert list(zl(['a', 'b', 'c'], range(3), [9, 8, 7, 99], fillvalue='d')) \ - == [('a', 0, 9), ('b', 1, 8), ('c', 2, 7), ('d', 'd', 99)] - -assert list(zl(['a', 'b', 'c'])) == [('a',), ('b',), ('c',)] +assert list(zl(["a", "b", "c"], range(3), [9, 8, 7])) == [ + ("a", 0, 9), + ("b", 1, 8), + ("c", 2, 7), +] +assert list(zl(["a", "b", "c"], range(3), [9, 8, 7, 99])) == [ + ("a", 0, 9), + ("b", 1, 8), + ("c", 2, 7), + (None, None, 99), +] +assert list(zl(["a", "b", "c"], range(3), [9, 8, 7, 99], fillvalue="d")) == [ + ("a", 0, 9), + ("b", 1, 8), + ("c", 2, 7), + ("d", "d", 99), +] + +assert list(zl(["a", "b", "c"])) == [("a",), ("b",), ("c",)] assert list(zl()) == [] -assert list(zl(*zl(['a', 'b', 'c'], range(1, 4)))) \ - == [('a', 'b', 'c'), (1, 2, 3)] -assert list(zl(*zl(['a', 'b', 'c'], range(1, 5)))) \ - == [('a', 'b', 'c', None), (1, 2, 3, 4)] -assert list(zl(*zl(['a', 'b', 'c'], range(1, 5), fillvalue=100))) \ - == [('a', 'b', 'c', 100), (1, 2, 3, 4)] +assert list(zl(*zl(["a", "b", "c"], range(1, 4)))) == [("a", "b", "c"), (1, 2, 3)] +assert list(zl(*zl(["a", "b", "c"], range(1, 5)))) == [ + ("a", "b", "c", None), + (1, 2, 3, 4), +] +assert list(zl(*zl(["a", "b", "c"], range(1, 5), fillvalue=100))) == [ + ("a", "b", "c", 100), + (1, 2, 3, 4), +] # test infinite iterator @@ -565,7 +654,7 @@ def __iter__(self): assert next(it) == (1, 4) assert next(it) == (2, 5) -it = zl([1,2], [3]) +it = zl([1, 2], [3]) assert next(it) == (1, 3) assert next(it) == (2, None) with assert_raises(StopIteration): diff --git a/extra_tests/snippets/stdlib_json.py b/extra_tests/snippets/stdlib_json.py index a91f3bd817..ca35c2c2b2 100644 --- a/extra_tests/snippets/stdlib_json.py +++ b/extra_tests/snippets/stdlib_json.py @@ -2,22 +2,26 @@ import json from io import StringIO, BytesIO + def round_trip_test(obj): # serde_json and Python's json module produce slightly differently spaced # output; direct string comparison can't pass on both so we use this as a # proxy return obj == json.loads(json.dumps(obj)) + def json_dump(obj): f = StringIO() json.dump(obj, f) f.seek(0) return f.getvalue() + def json_load(obj): f = StringIO(obj) if isinstance(obj, str) else BytesIO(bytes(obj)) return json.load(f) + assert '"string"' == json.dumps("string") assert '"string"' == json_dump("string") @@ -33,41 +37,41 @@ def json_load(obj): assert "false" == json.dumps(False) assert "false" == json_dump(False) -assert 'null' == json.dumps(None) -assert 'null' == json_dump(None) +assert "null" == json.dumps(None) +assert "null" == json_dump(None) -assert '[]' == json.dumps([]) -assert '[]' == json_dump([]) +assert "[]" == json.dumps([]) +assert "[]" == json_dump([]) -assert '[1]' == json.dumps([1]) -assert '[1]' == json_dump([1]) +assert "[1]" == json.dumps([1]) +assert "[1]" == json_dump([1]) -assert '[[1]]' == json.dumps([[1]]) -assert '[[1]]' == json_dump([[1]]) +assert "[[1]]" == json.dumps([[1]]) +assert "[[1]]" == json_dump([[1]]) assert round_trip_test([1, "string", 1.0, True]) -assert '[]' == json.dumps(()) -assert '[]' == json_dump(()) +assert "[]" == json.dumps(()) +assert "[]" == json_dump(()) -assert '[1]' == json.dumps((1,)) -assert '[1]' == json_dump((1,)) +assert "[1]" == json.dumps((1,)) +assert "[1]" == json_dump((1,)) -assert '[[1]]' == json.dumps(((1,),)) -assert '[[1]]' == json_dump(((1,),)) +assert "[[1]]" == json.dumps(((1,),)) +assert "[[1]]" == json_dump(((1,),)) # tuples don't round-trip through json assert [1, "string", 1.0, True] == json.loads(json.dumps((1, "string", 1.0, True))) -assert '{}' == json.dumps({}) -assert '{}' == json_dump({}) -assert round_trip_test({'a': 'b'}) +assert "{}" == json.dumps({}) +assert "{}" == json_dump({}) +assert round_trip_test({"a": "b"}) # should reject non-str keys in jsons assert_raises(json.JSONDecodeError, lambda: json.loads('{3: "abc"}')) assert_raises(json.JSONDecodeError, lambda: json_load('{3: "abc"}')) # should serialize non-str keys as strings -assert json.dumps({'3': 'abc'}) == json.dumps({3: 'abc'}) +assert json.dumps({"3": "abc"}) == json.dumps({3: "abc"}) assert 1 == json.loads("1") assert 1 == json.loads(b"1") @@ -104,51 +108,60 @@ def json_load(obj): assert "str" == json_load(b'"str"') assert "str" == json_load(bytearray(b'"str"')) -assert True is json.loads('true') -assert True is json.loads(b'true') -assert True is json.loads(bytearray(b'true')) -assert True is json_load('true') -assert True is json_load(b'true') -assert True is json_load(bytearray(b'true')) - -assert False is json.loads('false') -assert False is json.loads(b'false') -assert False is json.loads(bytearray(b'false')) -assert False is json_load('false') -assert False is json_load(b'false') -assert False is json_load(bytearray(b'false')) - -assert None is json.loads('null') -assert None is json.loads(b'null') -assert None is json.loads(bytearray(b'null')) -assert None is json_load('null') -assert None is json_load(b'null') -assert None is json_load(bytearray(b'null')) - -assert [] == json.loads('[]') -assert [] == json.loads(b'[]') -assert [] == json.loads(bytearray(b'[]')) -assert [] == json_load('[]') -assert [] == json_load(b'[]') -assert [] == json_load(bytearray(b'[]')) - -assert ['a'] == json.loads('["a"]') -assert ['a'] == json.loads(b'["a"]') -assert ['a'] == json.loads(bytearray(b'["a"]')) -assert ['a'] == json_load('["a"]') -assert ['a'] == json_load(b'["a"]') -assert ['a'] == json_load(bytearray(b'["a"]')) - -assert [['a'], 'b'] == json.loads('[["a"], "b"]') -assert [['a'], 'b'] == json.loads(b'[["a"], "b"]') -assert [['a'], 'b'] == json.loads(bytearray(b'[["a"], "b"]')) -assert [['a'], 'b'] == json_load('[["a"], "b"]') -assert [['a'], 'b'] == json_load(b'[["a"], "b"]') -assert [['a'], 'b'] == json_load(bytearray(b'[["a"], "b"]')) - -class String(str): pass -class Bytes(bytes): pass -class ByteArray(bytearray): pass +assert True is json.loads("true") +assert True is json.loads(b"true") +assert True is json.loads(bytearray(b"true")) +assert True is json_load("true") +assert True is json_load(b"true") +assert True is json_load(bytearray(b"true")) + +assert False is json.loads("false") +assert False is json.loads(b"false") +assert False is json.loads(bytearray(b"false")) +assert False is json_load("false") +assert False is json_load(b"false") +assert False is json_load(bytearray(b"false")) + +assert None is json.loads("null") +assert None is json.loads(b"null") +assert None is json.loads(bytearray(b"null")) +assert None is json_load("null") +assert None is json_load(b"null") +assert None is json_load(bytearray(b"null")) + +assert [] == json.loads("[]") +assert [] == json.loads(b"[]") +assert [] == json.loads(bytearray(b"[]")) +assert [] == json_load("[]") +assert [] == json_load(b"[]") +assert [] == json_load(bytearray(b"[]")) + +assert ["a"] == json.loads('["a"]') +assert ["a"] == json.loads(b'["a"]') +assert ["a"] == json.loads(bytearray(b'["a"]')) +assert ["a"] == json_load('["a"]') +assert ["a"] == json_load(b'["a"]') +assert ["a"] == json_load(bytearray(b'["a"]')) + +assert [["a"], "b"] == json.loads('[["a"], "b"]') +assert [["a"], "b"] == json.loads(b'[["a"], "b"]') +assert [["a"], "b"] == json.loads(bytearray(b'[["a"], "b"]')) +assert [["a"], "b"] == json_load('[["a"], "b"]') +assert [["a"], "b"] == json_load(b'[["a"], "b"]') +assert [["a"], "b"] == json_load(bytearray(b'[["a"], "b"]')) + + +class String(str): + pass + + +class Bytes(bytes): + pass + + +class ByteArray(bytearray): + pass + assert "string" == json.loads(String('"string"')) assert "string" == json.loads(Bytes(b'"string"')) @@ -160,29 +173,46 @@ class ByteArray(bytearray): pass assert '"string"' == json.dumps(String("string")) assert '"string"' == json_dump(String("string")) -class Int(int): pass -class Float(float): pass -assert '1' == json.dumps(Int(1)) -assert '1' == json_dump(Int(1)) +class Int(int): + pass + + +class Float(float): + pass + + +assert "1" == json.dumps(Int(1)) +assert "1" == json_dump(Int(1)) + +assert "0.5" == json.dumps(Float(0.5)) +assert "0.5" == json_dump(Float(0.5)) + + +class List(list): + pass + + +class Tuple(tuple): + pass + -assert '0.5' == json.dumps(Float(0.5)) -assert '0.5' == json_dump(Float(0.5)) +class Dict(dict): + pass -class List(list): pass -class Tuple(tuple): pass -class Dict(dict): pass -assert '[1]' == json.dumps(List([1])) -assert '[1]' == json_dump(List([1])) +assert "[1]" == json.dumps(List([1])) +assert "[1]" == json_dump(List([1])) -assert json.dumps((1, "string", 1.0, True)) == json.dumps(Tuple((1, "string", 1.0, True))) +assert json.dumps((1, "string", 1.0, True)) == json.dumps( + Tuple((1, "string", 1.0, True)) +) assert json_dump((1, "string", 1.0, True)) == json_dump(Tuple((1, "string", 1.0, True))) -assert json.dumps({'a': 'b'}) == json.dumps(Dict({'a': 'b'})) -assert json_dump({'a': 'b'}) == json_dump(Dict({'a': 'b'})) +assert json.dumps({"a": "b"}) == json.dumps(Dict({"a": "b"})) +assert json_dump({"a": "b"}) == json_dump(Dict({"a": "b"})) i = 7**500 assert json.dumps(i) == str(i) -assert json.decoder.scanstring('✨x"', 1) == ('x', 3) +assert json.decoder.scanstring('✨x"', 1) == ("x", 3) diff --git a/extra_tests/snippets/stdlib_logging.py b/extra_tests/snippets/stdlib_logging.py index 0356404624..18c26f0fb6 100644 --- a/extra_tests/snippets/stdlib_logging.py +++ b/extra_tests/snippets/stdlib_logging.py @@ -1,4 +1,3 @@ - import io import sys @@ -7,12 +6,11 @@ import logging -logging.error('WOOT') -logging.warning('WARN') +logging.error("WOOT") +logging.warning("WARN") res = f.getvalue() -assert 'WOOT' in res -assert 'WARN' in res +assert "WOOT" in res +assert "WARN" in res print(res) - diff --git a/extra_tests/snippets/stdlib_marshal.py b/extra_tests/snippets/stdlib_marshal.py index 8ad11c3cc6..c5fb1e533e 100644 --- a/extra_tests/snippets/stdlib_marshal.py +++ b/extra_tests/snippets/stdlib_marshal.py @@ -1,11 +1,12 @@ import unittest import marshal + class MarshalTests(unittest.TestCase): """ Testing the (incomplete) marshal module. """ - + def dump_then_load(self, data): return marshal.loads(marshal.dumps(data)) @@ -34,7 +35,7 @@ def test_marshal_str(self): def test_marshal_list(self): self._test_marshal([]) self._test_marshal([1, "hello", 1.0]) - self._test_marshal([[0], ['a','b']]) + self._test_marshal([[0], ["a", "b"]]) def test_marshal_tuple(self): self._test_marshal(()) @@ -42,31 +43,31 @@ def test_marshal_tuple(self): def test_marshal_dict(self): self._test_marshal({}) - self._test_marshal({'a':1, 1:'a'}) - self._test_marshal({'a':{'b':2}, 'c':[0.0, 4.0, 6, 9]}) - + self._test_marshal({"a": 1, 1: "a"}) + self._test_marshal({"a": {"b": 2}, "c": [0.0, 4.0, 6, 9]}) + def test_marshal_set(self): self._test_marshal(set()) self._test_marshal({1, 2, 3}) - self._test_marshal({1, 'a', 'b'}) + self._test_marshal({1, "a", "b"}) def test_marshal_frozen_set(self): self._test_marshal(frozenset()) self._test_marshal(frozenset({1, 2, 3})) - self._test_marshal(frozenset({1, 'a', 'b'})) + self._test_marshal(frozenset({1, "a", "b"})) def test_marshal_bytearray(self): self.assertEqual( self.dump_then_load(bytearray([])), - bytearray(b''), + bytearray(b""), ) self.assertEqual( self.dump_then_load(bytearray([1, 2])), - bytearray(b'\x01\x02'), + bytearray(b"\x01\x02"), ) def test_roundtrip(self): - orig = compile("1 + 1", "", 'eval') + orig = compile("1 + 1", "", "eval") dumped = marshal.dumps(orig) loaded = marshal.loads(dumped) diff --git a/extra_tests/snippets/stdlib_math.py b/extra_tests/snippets/stdlib_math.py index 94d8c7347c..090de710ed 100644 --- a/extra_tests/snippets/stdlib_math.py +++ b/extra_tests/snippets/stdlib_math.py @@ -1,9 +1,9 @@ import math from testutils import assert_raises, skip_if_unsupported -NAN = float('nan') -INF = float('inf') -NINF = float('-inf') +NAN = float("nan") +INF = float("inf") +NINF = float("-inf") # assert(math.exp(2) == math.exp(2.0)) # assert(math.exp(True) == math.exp(1.0)) @@ -46,6 +46,7 @@ def float_ceil_exists(): assert isinstance(math.ceil(3.3), int) assert isinstance(math.floor(4.4), int) + class A(object): def __trunc__(self): return 2 @@ -56,10 +57,12 @@ def __ceil__(self): def __floor__(self): return 4 + assert math.trunc(A()) == 2 assert math.ceil(A()) == 3 assert math.floor(A()) == 4 + class A(object): def __trunc__(self): return 2.2 @@ -70,23 +73,26 @@ def __ceil__(self): def __floor__(self): return 4.4 + assert math.trunc(A()) == 2.2 assert math.ceil(A()) == 3.3 assert math.floor(A()) == 4.4 + class A(object): def __trunc__(self): - return 'trunc' + return "trunc" def __ceil__(self): - return 'ceil' + return "ceil" def __floor__(self): - return 'floor' + return "floor" + -assert math.trunc(A()) == 'trunc' -assert math.ceil(A()) == 'ceil' -assert math.floor(A()) == 'floor' +assert math.trunc(A()) == "trunc" +assert math.ceil(A()) == "ceil" +assert math.floor(A()) == "floor" with assert_raises(TypeError): math.trunc(object()) @@ -97,44 +103,54 @@ def __floor__(self): isclose = math.isclose + def assertIsClose(a, b, *args, **kwargs): assert isclose(a, b, *args, **kwargs) == True, "%s and %s should be close!" % (a, b) + def assertIsNotClose(a, b, *args, **kwargs): - assert isclose(a, b, *args, **kwargs) == False, "%s and %s should not be close!" % (a, b) + assert isclose(a, b, *args, **kwargs) == False, "%s and %s should not be close!" % ( + a, + b, + ) + def assertAllClose(examples, *args, **kwargs): for a, b in examples: assertIsClose(a, b, *args, **kwargs) + def assertAllNotClose(examples, *args, **kwargs): for a, b in examples: assertIsNotClose(a, b, *args, **kwargs) + # test_negative_tolerances: ValueError should be raised if either tolerance is less than zero assert_raises(ValueError, lambda: isclose(1, 1, rel_tol=-1e-100)) assert_raises(ValueError, lambda: isclose(1, 1, rel_tol=1e-100, abs_tol=-1e10)) # test_identical: identical values must test as close -identical_examples = [(2.0, 2.0), - (0.1e200, 0.1e200), - (1.123e-300, 1.123e-300), - (12345, 12345.0), - (0.0, -0.0), - (345678, 345678)] +identical_examples = [ + (2.0, 2.0), + (0.1e200, 0.1e200), + (1.123e-300, 1.123e-300), + (12345, 12345.0), + (0.0, -0.0), + (345678, 345678), +] assertAllClose(identical_examples, rel_tol=0.0, abs_tol=0.0) # test_eight_decimal_places: examples that are close to 1e-8, but not 1e-9 -eight_decimal_places_examples = [(1e8, 1e8 + 1), - (-1e-8, -1.000000009e-8), - (1.12345678, 1.12345679)] +eight_decimal_places_examples = [ + (1e8, 1e8 + 1), + (-1e-8, -1.000000009e-8), + (1.12345678, 1.12345679), +] assertAllClose(eight_decimal_places_examples, rel_tol=1e-08) assertAllNotClose(eight_decimal_places_examples, rel_tol=1e-09) # test_near_zero: values close to zero -near_zero_examples = [(1e-9, 0.0), - (-1e-9, 0.0), - (-1e-150, 0.0)] +near_zero_examples = [(1e-9, 0.0), (-1e-9, 0.0), (-1e-150, 0.0)] # these should not be close to any rel_tol assertAllNotClose(near_zero_examples, rel_tol=0.9) # these should be close to abs_tol=1e-8 @@ -147,35 +163,36 @@ def assertAllNotClose(examples, *args, **kwargs): assertIsClose(NINF, NINF, abs_tol=0.0) # test_inf_ninf_nan(self): these should never be close (following IEEE 754 rules for equality) -not_close_examples = [(NAN, NAN), - (NAN, 1e-100), - (1e-100, NAN), - (INF, NAN), - (NAN, INF), - (INF, NINF), - (INF, 1.0), - (1.0, INF), - (INF, 1e308), - (1e308, INF)] +not_close_examples = [ + (NAN, NAN), + (NAN, 1e-100), + (1e-100, NAN), + (INF, NAN), + (NAN, INF), + (INF, NINF), + (INF, 1.0), + (1.0, INF), + (INF, 1e308), + (1e308, INF), +] # use largest reasonable tolerance assertAllNotClose(not_close_examples, abs_tol=0.999999999999999) # test_zero_tolerance: test with zero tolerance -zero_tolerance_close_examples = [(1.0, 1.0), - (-3.4, -3.4), - (-1e-300, -1e-300)] +zero_tolerance_close_examples = [(1.0, 1.0), (-3.4, -3.4), (-1e-300, -1e-300)] assertAllClose(zero_tolerance_close_examples, rel_tol=0.0) -zero_tolerance_not_close_examples = [(1.0, 1.000000000000001), - (0.99999999999999, 1.0), - (1.0e200, .999999999999999e200)] +zero_tolerance_not_close_examples = [ + (1.0, 1.000000000000001), + (0.99999999999999, 1.0), + (1.0e200, 0.999999999999999e200), +] assertAllNotClose(zero_tolerance_not_close_examples, rel_tol=0.0) # test_asymmetry: test the asymmetry example from PEP 485 assertAllClose([(9, 10), (10, 9)], rel_tol=0.1) # test_integers: test with integer values -integer_examples = [(100000001, 100000000), - (123456789, 123456788)] +integer_examples = [(100000001, 100000000), (123456789, 123456788)] assertAllClose(integer_examples, rel_tol=1e-8) assertAllNotClose(integer_examples, rel_tol=1e-9) @@ -184,26 +201,26 @@ def assertAllNotClose(examples, *args, **kwargs): # test_fractions: test with Fraction values assert math.copysign(1, 42) == 1.0 -assert math.copysign(0., 42) == 0.0 -assert math.copysign(1., -42) == -1.0 -assert math.copysign(3, 0.) == 3.0 -assert math.copysign(4., -0.) == -4.0 +assert math.copysign(0.0, 42) == 0.0 +assert math.copysign(1.0, -42) == -1.0 +assert math.copysign(3, 0.0) == 3.0 +assert math.copysign(4.0, -0.0) == -4.0 assert_raises(TypeError, math.copysign) # copysign should let us distinguish signs of zeros -assert math.copysign(1., 0.) == 1. -assert math.copysign(1., -0.) == -1. -assert math.copysign(INF, 0.) == INF -assert math.copysign(INF, -0.) == NINF -assert math.copysign(NINF, 0.) == INF -assert math.copysign(NINF, -0.) == NINF +assert math.copysign(1.0, 0.0) == 1.0 +assert math.copysign(1.0, -0.0) == -1.0 +assert math.copysign(INF, 0.0) == INF +assert math.copysign(INF, -0.0) == NINF +assert math.copysign(NINF, 0.0) == INF +assert math.copysign(NINF, -0.0) == NINF # and of infinities -assert math.copysign(1., INF) == 1. -assert math.copysign(1., NINF) == -1. +assert math.copysign(1.0, INF) == 1.0 +assert math.copysign(1.0, NINF) == -1.0 assert math.copysign(INF, INF) == INF assert math.copysign(INF, NINF) == NINF assert math.copysign(NINF, INF) == INF assert math.copysign(NINF, NINF) == NINF -assert math.isnan(math.copysign(NAN, 1.)) +assert math.isnan(math.copysign(NAN, 1.0)) assert math.isnan(math.copysign(NAN, INF)) assert math.isnan(math.copysign(NAN, NINF)) assert math.isnan(math.copysign(NAN, NAN)) @@ -212,7 +229,7 @@ def assertAllNotClose(examples, *args, **kwargs): # given platform. assert math.isinf(math.copysign(INF, NAN)) # similarly, copysign(2., NAN) could be 2. or -2. -assert abs(math.copysign(2., NAN)) == 2. +assert abs(math.copysign(2.0, NAN)) == 2.0 assert str(math.frexp(0.0)) == str((+0.0, 0)) assert str(math.frexp(-0.0)) == str((-0.0, 0)) @@ -248,7 +265,7 @@ def assertAllNotClose(examples, *args, **kwargs): assert math.factorial(20) == 2432902008176640000 assert_raises(ValueError, lambda: math.factorial(-1)) -if hasattr(math, 'nextafter'): +if hasattr(math, "nextafter"): try: assert math.nextafter(4503599627370496.0, -INF) == 4503599627370495.5 assert math.nextafter(4503599627370496.0, INF) == 4503599627370497.0 @@ -278,13 +295,13 @@ def assertAllNotClose(examples, *args, **kwargs): assert math.fmod(-10, 1) == -0.0 assert math.fmod(-10, 0.5) == -0.0 assert math.fmod(-10, 1.5) == -1.0 -assert math.isnan(math.fmod(NAN, 1.)) == True -assert math.isnan(math.fmod(1., NAN)) == True +assert math.isnan(math.fmod(NAN, 1.0)) == True +assert math.isnan(math.fmod(1.0, NAN)) == True assert math.isnan(math.fmod(NAN, NAN)) == True -assert_raises(ValueError, lambda: math.fmod(1., 0.)) -assert_raises(ValueError, lambda: math.fmod(INF, 1.)) -assert_raises(ValueError, lambda: math.fmod(NINF, 1.)) -assert_raises(ValueError, lambda: math.fmod(INF, 0.)) +assert_raises(ValueError, lambda: math.fmod(1.0, 0.0)) +assert_raises(ValueError, lambda: math.fmod(INF, 1.0)) +assert_raises(ValueError, lambda: math.fmod(NINF, 1.0)) +assert_raises(ValueError, lambda: math.fmod(INF, 0.0)) assert math.fmod(3.0, INF) == 3.0 assert math.fmod(-3.0, INF) == -3.0 assert math.fmod(3.0, NINF) == 3.0 diff --git a/extra_tests/snippets/stdlib_os.py b/extra_tests/snippets/stdlib_os.py index ab40582fd8..f5d26030a4 100644 --- a/extra_tests/snippets/stdlib_os.py +++ b/extra_tests/snippets/stdlib_os.py @@ -5,25 +5,24 @@ from testutils import assert_raises -assert os.name == 'posix' or os.name == 'nt' +assert os.name == "posix" or os.name == "nt" -fd = os.open('README.md', os.O_RDONLY) +fd = os.open("README.md", os.O_RDONLY) assert fd > 0 os.close(fd) assert_raises(OSError, lambda: os.read(fd, 10)) -assert_raises(FileNotFoundError, - lambda: os.open('DOES_NOT_EXIST', os.O_RDONLY)) -assert_raises(FileNotFoundError, - lambda: os.open('DOES_NOT_EXIST', os.O_WRONLY)) -assert_raises(FileNotFoundError, - lambda: os.rename('DOES_NOT_EXIST', 'DOES_NOT_EXIST 2')) +assert_raises(FileNotFoundError, lambda: os.open("DOES_NOT_EXIST", os.O_RDONLY)) +assert_raises(FileNotFoundError, lambda: os.open("DOES_NOT_EXIST", os.O_WRONLY)) +assert_raises( + FileNotFoundError, lambda: os.rename("DOES_NOT_EXIST", "DOES_NOT_EXIST 2") +) # sendfile only supports in_fd as non-socket on linux and solaris if hasattr(os, "sendfile") and sys.platform.startswith("linux"): - src_fd = os.open('README.md', os.O_RDONLY) - dest_fd = os.open('destination.md', os.O_RDWR | os.O_CREAT) - src_len = os.stat('README.md').st_size + src_fd = os.open("README.md", os.O_RDONLY) + dest_fd = os.open("destination.md", os.O_RDWR | os.O_CREAT) + src_len = os.stat("README.md").st_size bytes_sent = os.sendfile(dest_fd, src_fd, 0, src_len) assert src_len == bytes_sent @@ -32,10 +31,10 @@ assert os.read(src_fd, src_len) == os.read(dest_fd, bytes_sent) os.close(src_fd) os.close(dest_fd) - os.remove('destination.md') + os.remove("destination.md") try: - os.open('DOES_NOT_EXIST', 0) + os.open("DOES_NOT_EXIST", 0) except OSError as err: assert err.errno == 2 @@ -81,15 +80,14 @@ assert_raises(TypeError, lambda: os.fspath([1, 2, 3])) -class TestWithTempDir(): +class TestWithTempDir: def __enter__(self): if os.name == "nt": base_folder = os.environ["TEMP"] else: base_folder = "/tmp" - name = os.path.join(base_folder, - "rustpython_test_os_" + str(int(time.time()))) + name = os.path.join(base_folder, "rustpython_test_os_" + str(int(time.time()))) while os.path.isdir(name): name = name + "_" @@ -102,7 +100,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): pass -class TestWithTempCurrentDir(): +class TestWithTempCurrentDir: def __enter__(self): self.prev_cwd = os.getcwd() @@ -130,8 +128,9 @@ def __exit__(self, exc_type, exc_val, exc_tb): assert os.write(fd, CONTENT3) == len(CONTENT3) os.close(fd) - assert_raises(FileExistsError, - lambda: os.open(fname, os.O_WRONLY | os.O_CREAT | os.O_EXCL)) + assert_raises( + FileExistsError, lambda: os.open(fname, os.O_WRONLY | os.O_CREAT | os.O_EXCL) + ) fd = os.open(fname, os.O_RDONLY) assert os.read(fd, len(CONTENT2)) == CONTENT2 @@ -150,7 +149,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): assert not os.isatty(fd) # TODO: get os.lseek working on windows - if os.name != 'nt': + if os.name != "nt": fd = os.open(fname3, 0) assert os.read(fd, len(CONTENT2)) == CONTENT2 assert os.read(fd, len(CONTENT3)) == CONTENT3 @@ -201,8 +200,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): if dir_entry.is_symlink(): symlinks.add(dir_entry.name) - assert names == set( - [FILE_NAME, FILE_NAME2, FOLDER, SYMLINK_FILE, SYMLINK_FOLDER]) + assert names == set([FILE_NAME, FILE_NAME2, FOLDER, SYMLINK_FILE, SYMLINK_FOLDER]) assert paths == set([fname, fname2, folder, symlink_file, symlink_folder]) assert dirs == set([FOLDER, SYMLINK_FOLDER]) assert dirs_no_symlink == set([FOLDER]) @@ -270,23 +268,26 @@ def __exit__(self, exc_type, exc_val, exc_tb): os.stat(fname).st_mode == os.stat(symlink_file).st_mode os.stat(fname, follow_symlinks=False).st_ino == os.stat( - symlink_file, follow_symlinks=False).st_ino + symlink_file, follow_symlinks=False + ).st_ino os.stat(fname, follow_symlinks=False).st_mode == os.stat( - symlink_file, follow_symlinks=False).st_mode + symlink_file, follow_symlinks=False + ).st_mode # os.chmod if os.name != "nt": os.chmod(fname, 0o666) - assert oct(os.stat(fname).st_mode) == '0o100666' + assert oct(os.stat(fname).st_mode) == "0o100666" -# os.chown + # os.chown if os.name != "nt": # setup root_in_posix = False - if hasattr(os, 'geteuid'): - root_in_posix = (os.geteuid() == 0) + if hasattr(os, "geteuid"): + root_in_posix = os.geteuid() == 0 try: import pwd + all_users = [u.pw_uid for u in pwd.getpwall()] except (ImportError, AttributeError): all_users = [] @@ -299,10 +300,8 @@ def __exit__(self, exc_type, exc_val, exc_tb): if not root_in_posix and len(all_users) > 1: uid_1, uid_2 = all_users[:2] gid = os.stat(fname1).st_gid - assert_raises(PermissionError, - lambda: os.chown(fname1, uid_1, gid)) - assert_raises(PermissionError, - lambda: os.chown(fname1, uid_2, gid)) + assert_raises(PermissionError, lambda: os.chown(fname1, uid_1, gid)) + assert_raises(PermissionError, lambda: os.chown(fname1, uid_2, gid)) # test chown with root perm and file name if root_in_posix and len(all_users) > 1: @@ -327,7 +326,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): assert uid == uid_2 # test gid change - if hasattr(os, 'getgroups'): + if hasattr(os, "getgroups"): groups = os.getgroups() if len(groups) > 1: gid_1, gid_2 = groups[:2] @@ -434,7 +433,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): os.close(wfd) # os.pipe2 -if sys.platform.startswith('linux') or sys.platform.startswith('freebsd'): +if sys.platform.startswith("linux") or sys.platform.startswith("freebsd"): rfd, wfd = os.pipe2(0) try: os.write(wfd, CONTENT2) @@ -460,11 +459,11 @@ def __exit__(self, exc_type, exc_val, exc_tb): with TestWithTempDir() as tmpdir: for i in range(0, 4): - file_name = os.path.join(tmpdir, 'file' + str(i)) - with open(file_name, 'w') as f: - f.write('test') + file_name = os.path.join(tmpdir, "file" + str(i)) + with open(file_name, "w") as f: + f.write("test") - expected_files = ['file0', 'file1', 'file2', 'file3'] + expected_files = ["file0", "file1", "file2", "file3"] dir_iter = os.scandir(tmpdir) collected_files = [dir_entry.name for dir_entry in dir_iter] @@ -476,13 +475,14 @@ def __exit__(self, exc_type, exc_val, exc_tb): dir_iter.close() - expected_files_bytes = [(file.encode(), os.path.join(tmpdir, - file).encode()) - for file in expected_files] + expected_files_bytes = [ + (file.encode(), os.path.join(tmpdir, file).encode()) for file in expected_files + ] dir_iter_bytes = os.scandir(tmpdir.encode()) - collected_files_bytes = [(dir_entry.name, dir_entry.path) - for dir_entry in dir_iter_bytes] + collected_files_bytes = [ + (dir_entry.name, dir_entry.path) for dir_entry in dir_iter_bytes + ] assert set(collected_files_bytes) == set(expected_files_bytes) @@ -492,8 +492,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): assert set(collected_files) == set(expected_files) collected_files = os.listdir(tmpdir.encode()) - assert set(collected_files) == set( - [file.encode() for file in expected_files]) + assert set(collected_files) == set([file.encode() for file in expected_files]) with TestWithTempCurrentDir(): os.chdir(tmpdir) @@ -502,20 +501,20 @@ def __exit__(self, exc_type, exc_val, exc_tb): assert set(collected_files) == set(expected_files) # system() -if os.name in ('posix', 'nt'): - assert os.system('echo test') == 0 - assert os.system('&') != 0 +if os.name in ("posix", "nt"): + assert os.system("echo test") == 0 + assert os.system("&") != 0 for arg in [None, 1, 1.0, TabError]: assert_raises(TypeError, os.system, arg) # Testing for os.pathconf_names -if not sys.platform.startswith('win'): +if not sys.platform.startswith("win"): assert len(os.pathconf_names) > 0 - assert 'PC_NAME_MAX' in os.pathconf_names + assert "PC_NAME_MAX" in os.pathconf_names for option, index in os.pathconf_names.items(): if sys.platform == "darwin": # TODO: check why it fails if option in ["PC_MAX_CANON", "PC_MAX_INPUT", "PC_VDISABLE"]: continue - assert os.pathconf('/', index) == os.pathconf('/', option) + assert os.pathconf("/", index) == os.pathconf("/", option) diff --git a/extra_tests/snippets/stdlib_pwd.py b/extra_tests/snippets/stdlib_pwd.py index 6ef3a64d02..2a44aed32c 100644 --- a/extra_tests/snippets/stdlib_pwd.py +++ b/extra_tests/snippets/stdlib_pwd.py @@ -1,4 +1,5 @@ import sys + # windows doesn't support pwd if sys.platform.startswith("win"): exit(0) @@ -7,6 +8,6 @@ import pwd with assert_raises(KeyError): - fake_name = 'fake_user' + fake_name = "fake_user" while pwd.getpwnam(fake_name): - fake_name += '1' + fake_name += "1" diff --git a/extra_tests/snippets/stdlib_random.py b/extra_tests/snippets/stdlib_random.py index 969b09d339..60fc9a3097 100644 --- a/extra_tests/snippets/stdlib_random.py +++ b/extra_tests/snippets/stdlib_random.py @@ -15,8 +15,8 @@ assert random.choice(left) == 5 # random.choices -expected = ['red', 'green', 'red', 'black', 'black', 'red'] -result = random.choices(['red', 'black', 'green'], [18, 18, 2], k=6) +expected = ["red", "green", "red", "black", "black", "red"] +result = random.choices(["red", "black", "green"], [18, 18, 2], k=6) assert expected == result # random.sample @@ -30,7 +30,7 @@ assert len(zero_size_buf) == 0 non_zero_buf = random.randbytes(4) assert type(non_zero_buf) is bytes -assert list(non_zero_buf) == list(b'\xb9\x7fi\xf7') +assert list(non_zero_buf) == list(b"\xb9\x7fi\xf7") # TODO : random.random(), random.uniform(), random.triangular(), # random.betavariate, random.expovariate, random.gammavariate, diff --git a/extra_tests/snippets/stdlib_re.py b/extra_tests/snippets/stdlib_re.py index 17ecdba7f6..89d729f2b2 100644 --- a/extra_tests/snippets/stdlib_re.py +++ b/extra_tests/snippets/stdlib_re.py @@ -1,8 +1,7 @@ - import re haystack = "Hello world" -needle = 'ello' +needle = "ello" mo = re.search(needle, haystack) print(mo) @@ -12,62 +11,67 @@ assert mo.start() == 1 assert mo.end() == 5 -assert re.escape('python.exe') == 'python\\.exe' +assert re.escape("python.exe") == "python\\.exe" -p = re.compile('ab') -s = p.sub('x', 'abcabca') +p = re.compile("ab") +s = p.sub("x", "abcabca") # print(s) -assert s == 'xcxca' +assert s == "xcxca" -idpattern = r'([_a-z][_a-z0-9]*)' +idpattern = r"([_a-z][_a-z0-9]*)" -mo = re.search(idpattern, '7382 _boe0+2') -assert mo.group(0) == '_boe0' +mo = re.search(idpattern, "7382 _boe0+2") +assert mo.group(0) == "_boe0" # tes op range -assert re.compile('[a-z]').match('a').span() == (0, 1) -assert re.compile('[a-z]').fullmatch('z').span() == (0, 1) +assert re.compile("[a-z]").match("a").span() == (0, 1) +assert re.compile("[a-z]").fullmatch("z").span() == (0, 1) # test op charset -assert re.compile('[_a-z0-9]*').match('_09az').group() == '_09az' +assert re.compile("[_a-z0-9]*").match("_09az").group() == "_09az" # test op bigcharset -assert re.compile('[你好a-z]*').match('a好z你?').group() == 'a好z你' -assert re.compile('[你好a-z]+').search('1232321 a好z你 !!?').group() == 'a好z你' +assert re.compile("[你好a-z]*").match("a好z你?").group() == "a好z你" +assert re.compile("[你好a-z]+").search("1232321 a好z你 !!?").group() == "a好z你" # test op repeat one -assert re.compile('a*').match('aaa').span() == (0, 3) -assert re.compile('abcd*').match('abcdddd').group() == 'abcdddd' -assert re.compile('abcd*').match('abc').group() == 'abc' -assert re.compile('abcd*e').match('abce').group() == 'abce' -assert re.compile('abcd*e+').match('abcddeee').group() == 'abcddeee' -assert re.compile('abcd+').match('abcddd').group() == 'abcddd' +assert re.compile("a*").match("aaa").span() == (0, 3) +assert re.compile("abcd*").match("abcdddd").group() == "abcdddd" +assert re.compile("abcd*").match("abc").group() == "abc" +assert re.compile("abcd*e").match("abce").group() == "abce" +assert re.compile("abcd*e+").match("abcddeee").group() == "abcddeee" +assert re.compile("abcd+").match("abcddd").group() == "abcddd" # test op mark -assert re.compile('(a)b').match('ab').group(0, 1) == ('ab', 'a') -assert re.compile('a(b)(cd)').match('abcd').group(0, 1, 2) == ('abcd', 'b', 'cd') +assert re.compile("(a)b").match("ab").group(0, 1) == ("ab", "a") +assert re.compile("a(b)(cd)").match("abcd").group(0, 1, 2) == ("abcd", "b", "cd") # test op repeat -assert re.compile('(ab)+').match('abab') -assert re.compile('(a)(b)(cd)*').match('abcdcdcd').group(0, 1, 2, 3) == ('abcdcdcd', 'a', 'b', 'cd') -assert re.compile('ab()+cd').match('abcd').group() == 'abcd' -assert re.compile('(a)+').match('aaa').groups() == ('a',) -assert re.compile('(a+)').match('aaa').groups() == ('aaa',) +assert re.compile("(ab)+").match("abab") +assert re.compile("(a)(b)(cd)*").match("abcdcdcd").group(0, 1, 2, 3) == ( + "abcdcdcd", + "a", + "b", + "cd", +) +assert re.compile("ab()+cd").match("abcd").group() == "abcd" +assert re.compile("(a)+").match("aaa").groups() == ("a",) +assert re.compile("(a+)").match("aaa").groups() == ("aaa",) # test Match object method -assert re.compile('(a)(bc)').match('abc')[1] == 'a' -assert re.compile('a(b)(?Pc)d').match('abcd').groupdict() == {'a': 'c'} +assert re.compile("(a)(bc)").match("abc")[1] == "a" +assert re.compile("a(b)(?Pc)d").match("abcd").groupdict() == {"a": "c"} # test op branch -assert re.compile(r'((?=\d|\.\d)(?P\d*)|a)').match('123.2132').group() == '123' +assert re.compile(r"((?=\d|\.\d)(?P\d*)|a)").match("123.2132").group() == "123" -assert re.sub(r'^\s*', 'X', 'test') == 'Xtest' +assert re.sub(r"^\s*", "X", "test") == "Xtest" -assert re.match(r'\babc\b', 'abc').group() == 'abc' +assert re.match(r"\babc\b", "abc").group() == "abc" -urlpattern = re.compile('//([^/#?]*)(.*)', re.DOTALL) -url = '//www.example.org:80/foo/bar/baz.html' -assert urlpattern.match(url).group(1) == 'www.example.org:80' +urlpattern = re.compile("//([^/#?]*)(.*)", re.DOTALL) +url = "//www.example.org:80/foo/bar/baz.html" +assert urlpattern.match(url).group(1) == "www.example.org:80" -assert re.compile('(?:\w+(?:\s|/(?!>))*)*').match('a /bb />ccc').group() == 'a /bb ' -assert re.compile('(?:(1)?)*').match('111').group() == '111' \ No newline at end of file +assert re.compile("(?:\w+(?:\s|/(?!>))*)*").match("a /bb />ccc").group() == "a /bb " +assert re.compile("(?:(1)?)*").match("111").group() == "111" diff --git a/extra_tests/snippets/stdlib_signal.py b/extra_tests/snippets/stdlib_signal.py index eb4a25f90d..0abfd7cb71 100644 --- a/extra_tests/snippets/stdlib_signal.py +++ b/extra_tests/snippets/stdlib_signal.py @@ -7,11 +7,12 @@ signals = [] + def handler(signum, frame): - signals.append(signum) + signals.append(signum) -signal.signal(signal.SIGILL, signal.SIG_IGN); +signal.signal(signal.SIGILL, signal.SIG_IGN) assert signal.getsignal(signal.SIGILL) is signal.SIG_IGN old_signal = signal.signal(signal.SIGILL, signal.SIG_DFL) @@ -21,24 +22,21 @@ def handler(signum, frame): # unix if "win" not in sys.platform: - signal.signal(signal.SIGALRM, handler) - assert signal.getsignal(signal.SIGALRM) is handler - - signal.alarm(1) - time.sleep(2.0) - assert signals == [signal.SIGALRM] - - signal.signal(signal.SIGALRM, signal.SIG_IGN) - signal.alarm(1) - time.sleep(2.0) - - assert signals == [signal.SIGALRM] + signal.signal(signal.SIGALRM, handler) + assert signal.getsignal(signal.SIGALRM) is handler - signal.signal(signal.SIGALRM, handler) - signal.alarm(1) - time.sleep(2.0) + signal.alarm(1) + time.sleep(2.0) + assert signals == [signal.SIGALRM] - assert signals == [signal.SIGALRM, signal.SIGALRM] + signal.signal(signal.SIGALRM, signal.SIG_IGN) + signal.alarm(1) + time.sleep(2.0) + assert signals == [signal.SIGALRM] + signal.signal(signal.SIGALRM, handler) + signal.alarm(1) + time.sleep(2.0) + assert signals == [signal.SIGALRM, signal.SIGALRM] diff --git a/extra_tests/snippets/stdlib_socket.py b/extra_tests/snippets/stdlib_socket.py index bbedb794ba..199ff9fe47 100644 --- a/extra_tests/snippets/stdlib_socket.py +++ b/extra_tests/snippets/stdlib_socket.py @@ -5,8 +5,8 @@ assert _socket.socket == _socket.SocketType -MESSAGE_A = b'aaaa' -MESSAGE_B= b'bbbbb' +MESSAGE_A = b"aaaa" +MESSAGE_B = b"bbbbb" # TCP @@ -26,9 +26,9 @@ assert recv_a == MESSAGE_A assert recv_b == MESSAGE_B -fd = open('README.md', 'rb') +fd = open("README.md", "rb") connector.sendfile(fd) -recv_readme = connection.recv(os.stat('README.md').st_size) +recv_readme = connection.recv(os.stat("README.md").st_size) # need this because sendfile leaves the cursor at the end of the file fd.seek(0) assert recv_readme == fd.read() @@ -36,14 +36,14 @@ # fileno if os.name == "posix": - connector_fd = connector.fileno() - connection_fd = connection.fileno() - os.write(connector_fd, MESSAGE_A) - connection.send(MESSAGE_B) - recv_a = connection.recv(len(MESSAGE_A)) - recv_b = os.read(connector_fd, (len(MESSAGE_B))) - assert recv_a == MESSAGE_A - assert recv_b == MESSAGE_B + connector_fd = connector.fileno() + connection_fd = connection.fileno() + os.write(connector_fd, MESSAGE_A) + connection.send(MESSAGE_B) + recv_a = connection.recv(len(MESSAGE_A)) + recv_b = os.read(connector_fd, (len(MESSAGE_B))) + assert recv_a == MESSAGE_A + assert recv_b == MESSAGE_B connection.close() connector.close() @@ -51,30 +51,30 @@ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) with assert_raises(TypeError): - s.connect(("127.0.0.1", 8888, 8888)) + s.connect(("127.0.0.1", 8888, 8888)) with assert_raises(OSError): - # Lets hope nobody is listening on port 1 - s.connect(("127.0.0.1", 1)) + # Lets hope nobody is listening on port 1 + s.connect(("127.0.0.1", 1)) with assert_raises(TypeError): - s.bind(("127.0.0.1", 8888, 8888)) + s.bind(("127.0.0.1", 8888, 8888)) with assert_raises(OSError): - # Lets hope nobody run this test on machine with ip 1.2.3.4 - s.bind(("1.2.3.4", 8888)) + # Lets hope nobody run this test on machine with ip 1.2.3.4 + s.bind(("1.2.3.4", 8888)) with assert_raises(TypeError): - s.bind((888, 8888)) + s.bind((888, 8888)) s.close() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("127.0.0.1", 0)) with assert_raises(OSError): - s.recv(100) + s.recv(100) with assert_raises(OSError): - s.send(MESSAGE_A) + s.send(MESSAGE_A) s.close() @@ -117,48 +117,48 @@ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) with assert_raises(OSError): - s.bind(("1.2.3.4", 888)) + s.bind(("1.2.3.4", 888)) s.close() ### Errors with assert_raises(OSError): - socket.socket(100, socket.SOCK_STREAM) + socket.socket(100, socket.SOCK_STREAM) with assert_raises(OSError): - socket.socket(socket.AF_INET, 1000) + socket.socket(socket.AF_INET, 1000) with assert_raises(OSError): - socket.inet_aton("test") + socket.inet_aton("test") with assert_raises(OverflowError): - socket.htonl(-1) + socket.htonl(-1) -assert socket.htonl(0)==0 -assert socket.htonl(10)==167772160 +assert socket.htonl(0) == 0 +assert socket.htonl(10) == 167772160 -assert socket.inet_aton("127.0.0.1")==b"\x7f\x00\x00\x01" -assert socket.inet_aton("255.255.255.255")==b"\xff\xff\xff\xff" +assert socket.inet_aton("127.0.0.1") == b"\x7f\x00\x00\x01" +assert socket.inet_aton("255.255.255.255") == b"\xff\xff\xff\xff" -assert socket.inet_ntoa(b"\x7f\x00\x00\x01")=="127.0.0.1" -assert socket.inet_ntoa(b"\xff\xff\xff\xff")=="255.255.255.255" +assert socket.inet_ntoa(b"\x7f\x00\x00\x01") == "127.0.0.1" +assert socket.inet_ntoa(b"\xff\xff\xff\xff") == "255.255.255.255" with assert_raises(OSError): - socket.inet_ntoa(b"\xff\xff\xff\xff\xff") + socket.inet_ntoa(b"\xff\xff\xff\xff\xff") with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: - pass + pass with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener: - listener.bind(("127.0.0.1", 0)) - listener.listen(1) - connector = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - connector.connect(("127.0.0.1", listener.getsockname()[1])) - (connection, addr) = listener.accept() - connection.settimeout(1.0) - with assert_raises(OSError): # TODO: check that it raises a socket.timeout - # testing that it doesn't work with the timeout; that it stops blocking eventually - connection.recv(len(MESSAGE_A)) + listener.bind(("127.0.0.1", 0)) + listener.listen(1) + connector = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + connector.connect(("127.0.0.1", listener.getsockname()[1])) + (connection, addr) = listener.accept() + connection.settimeout(1.0) + with assert_raises(OSError): # TODO: check that it raises a socket.timeout + # testing that it doesn't work with the timeout; that it stops blocking eventually + connection.recv(len(MESSAGE_A)) for exc, expected_name in [ (socket.gaierror, "gaierror"), diff --git a/extra_tests/snippets/stdlib_sqlite.py b/extra_tests/snippets/stdlib_sqlite.py index 8ec5416fe2..f2e02b48cf 100644 --- a/extra_tests/snippets/stdlib_sqlite.py +++ b/extra_tests/snippets/stdlib_sqlite.py @@ -18,6 +18,7 @@ INSERT INTO foo(key) VALUES (11); """) + class AggrSum: def __init__(self): self.val = 0.0 @@ -28,6 +29,7 @@ def step(self, val): def finalize(self): return self.val + cx.create_aggregate("mysum", 1, AggrSum) cur.execute("select mysum(key) from foo") assert cur.fetchone()[0] == 28.0 @@ -35,15 +37,19 @@ def finalize(self): # toobig = 2**64 # cur.execute("insert into foo(key) values (?)", (toobig,)) + class AggrText: def __init__(self): self.txt = "" + def step(self, txt): txt = str(txt) self.txt = self.txt + txt + def finalize(self): return self.txt + cx.create_aggregate("aggtxt", 1, AggrText) cur.execute("select aggtxt(key) from foo") -assert cur.fetchone()[0] == '341011' \ No newline at end of file +assert cur.fetchone()[0] == "341011" diff --git a/extra_tests/snippets/stdlib_string.py b/extra_tests/snippets/stdlib_string.py index 9151d2f593..ae544f3289 100644 --- a/extra_tests/snippets/stdlib_string.py +++ b/extra_tests/snippets/stdlib_string.py @@ -1,22 +1,26 @@ import string -assert string.ascii_letters == 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' -assert string.ascii_lowercase == 'abcdefghijklmnopqrstuvwxyz' -assert string.ascii_uppercase == 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' -assert string.digits == '0123456789' -assert string.hexdigits == '0123456789abcdefABCDEF' -assert string.octdigits == '01234567' -assert string.punctuation == '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' -assert string.whitespace == ' \t\n\r\x0b\x0c', string.whitespace -assert string.printable == '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' +assert string.ascii_letters == "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" +assert string.ascii_lowercase == "abcdefghijklmnopqrstuvwxyz" +assert string.ascii_uppercase == "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +assert string.digits == "0123456789" +assert string.hexdigits == "0123456789abcdefABCDEF" +assert string.octdigits == "01234567" +assert string.punctuation == "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" +assert string.whitespace == " \t\n\r\x0b\x0c", string.whitespace +assert ( + string.printable + == "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c" +) -assert string.capwords('bla bla', ' ') == 'Bla Bla' +assert string.capwords("bla bla", " ") == "Bla Bla" from string import Template -s = Template('$who likes $what') -r = s.substitute(who='tim', what='kung pow') -assert r == 'tim likes kung pow' + +s = Template("$who likes $what") +r = s.substitute(who="tim", what="kung pow") +assert r == "tim likes kung pow" from string import Formatter diff --git a/extra_tests/snippets/stdlib_struct.py b/extra_tests/snippets/stdlib_struct.py index 83154c8100..1e08d0a223 100644 --- a/extra_tests/snippets/stdlib_struct.py +++ b/extra_tests/snippets/stdlib_struct.py @@ -1,51 +1,51 @@ - from testutils import assert_raises import struct -data = struct.pack('IH', 14, 12) +data = struct.pack("IH", 14, 12) assert data == bytes([14, 0, 0, 0, 12, 0]) -v1, v2 = struct.unpack('IH', data) +v1, v2 = struct.unpack("IH", data) assert v1 == 14 assert v2 == 12 -data = struct.pack('IH', 14, 12) +data = struct.pack(">IH", 14, 12) assert data == bytes([0, 0, 0, 14, 0, 12]) -v1, v2 = struct.unpack('>IH', data) +v1, v2 = struct.unpack(">IH", data) assert v1 == 14 assert v2 == 12 -data = struct.pack('3B', 65, 66, 67) +data = struct.pack("3B", 65, 66, 67) assert data == bytes([65, 66, 67]) -v1, v2, v3 = struct.unpack('3B', data) +v1, v2, v3 = struct.unpack("3B", data) assert v1 == 65 assert v2 == 66 assert v3 == 67 with assert_raises(Exception): - data = struct.pack('B0B', 65, 66) + data = struct.pack("B0B", 65, 66) with assert_raises(Exception): - data = struct.pack('B2B', 65, 66) + data = struct.pack("B2B", 65, 66) -data = struct.pack('B1B', 65, 66) +data = struct.pack("B1B", 65, 66) with assert_raises(Exception): - struct.pack(' 0: demo(x - 1) + sys.settrace(trc) demo(5) sys.settrace(None) @@ -53,7 +61,7 @@ def demo(x): assert sys.exc_info() == (None, None, None) try: - 1/0 + 1 / 0 except ZeroDivisionError as exc: exc_info = sys.exc_info() assert exc_info[0] == type(exc) == ZeroDivisionError @@ -62,10 +70,12 @@ def demo(x): # Recursion: + def recursive_call(n): if n > 0: recursive_call(n - 1) + sys.setrecursionlimit(200) assert sys.getrecursionlimit() == 200 @@ -74,11 +84,25 @@ def recursive_call(n): if sys.platform.startswith("win"): winver = sys.getwindowsversion() - print(f'winver: {winver} {winver.platform_version}') + print(f"winver: {winver} {winver.platform_version}") # the biggest value of wSuiteMask (https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-osversioninfoexa#members). - all_masks = 0x00000004 | 0x00000400 | 0x00004000 | 0x00000080 | 0x00000002 | 0x00000040 | 0x00000200 | \ - 0x00000100 | 0x00000001 | 0x00000020 | 0x00002000 | 0x00000010 | 0x00008000 | 0x00020000 + all_masks = ( + 0x00000004 + | 0x00000400 + | 0x00004000 + | 0x00000080 + | 0x00000002 + | 0x00000040 + | 0x00000200 + | 0x00000100 + | 0x00000001 + | 0x00000020 + | 0x00002000 + | 0x00000010 + | 0x00008000 + | 0x00020000 + ) # We really can't test if the results are correct, so it just checks for meaningful value assert winver.major > 6 @@ -112,18 +136,14 @@ def recursive_call(n): # Test the PYTHONSAFEPATH environment variable code = "import sys; print(sys.flags.safe_path)" env = dict(os.environ) -env.pop('PYTHONSAFEPATH', None) -args = (sys.executable, '-P', '-c', code) +env.pop("PYTHONSAFEPATH", None) +args = (sys.executable, "-P", "-c", code) -proc = subprocess.run( - args, stdout=subprocess.PIPE, - universal_newlines=True, env=env) -assert proc.stdout.rstrip() == 'True', proc +proc = subprocess.run(args, stdout=subprocess.PIPE, universal_newlines=True, env=env) +assert proc.stdout.rstrip() == "True", proc assert proc.returncode == 0, proc -env['PYTHONSAFEPATH'] = '1' -proc = subprocess.run( - args, stdout=subprocess.PIPE, - universal_newlines=True, env=env) -assert proc.stdout.rstrip() == 'True' +env["PYTHONSAFEPATH"] = "1" +proc = subprocess.run(args, stdout=subprocess.PIPE, universal_newlines=True, env=env) +assert proc.stdout.rstrip() == "True" assert proc.returncode == 0, proc diff --git a/extra_tests/snippets/stdlib_sys_getframe.py b/extra_tests/snippets/stdlib_sys_getframe.py index d4328286aa..50447ce882 100644 --- a/extra_tests/snippets/stdlib_sys_getframe.py +++ b/extra_tests/snippets/stdlib_sys_getframe.py @@ -2,20 +2,24 @@ value = 189 locals_dict = sys._getframe().f_locals -assert locals_dict['value'] == 189 -foo = 'bar' -assert locals_dict['foo'] == foo +assert locals_dict["value"] == 189 +foo = "bar" +assert locals_dict["foo"] == foo + def test_function(): x = 17 assert sys._getframe().f_locals is not locals_dict - assert sys._getframe().f_locals['x'] == 17 - assert sys._getframe(1).f_locals['foo'] == 'bar' + assert sys._getframe().f_locals["x"] == 17 + assert sys._getframe(1).f_locals["foo"] == "bar" + test_function() -class TestClass(): + +class TestClass: def __init__(self): - assert sys._getframe().f_locals['self'] == self + assert sys._getframe().f_locals["self"] == self + TestClass() diff --git a/extra_tests/snippets/stdlib_time.py b/extra_tests/snippets/stdlib_time.py index baf6755306..9a92969f5f 100644 --- a/extra_tests/snippets/stdlib_time.py +++ b/extra_tests/snippets/stdlib_time.py @@ -1,5 +1,3 @@ - - import time x = time.gmtime(1000) @@ -9,14 +7,13 @@ assert x.tm_sec == 40 assert x.tm_isdst == 0 -s = time.strftime('%Y-%m-%d-%H-%M-%S', x) +s = time.strftime("%Y-%m-%d-%H-%M-%S", x) # print(s) -assert s == '1970-01-01-00-16-40' +assert s == "1970-01-01-00-16-40" -x2 = time.strptime(s, '%Y-%m-%d-%H-%M-%S') +x2 = time.strptime(s, "%Y-%m-%d-%H-%M-%S") assert x2.tm_min == 16 s = time.asctime(x) # print(s) -assert s == 'Thu Jan 1 00:16:40 1970' - +assert s == "Thu Jan 1 00:16:40 1970" diff --git a/extra_tests/snippets/stdlib_traceback.py b/extra_tests/snippets/stdlib_traceback.py index 689f36e027..7e42e70fb7 100644 --- a/extra_tests/snippets/stdlib_traceback.py +++ b/extra_tests/snippets/stdlib_traceback.py @@ -1,27 +1,27 @@ import traceback try: - 1/0 + 1 / 0 except ZeroDivisionError as ex: - tb = traceback.extract_tb(ex.__traceback__) - assert len(tb) == 1 + tb = traceback.extract_tb(ex.__traceback__) + assert len(tb) == 1 try: - try: - 1/0 - except ZeroDivisionError as ex: - raise KeyError().with_traceback(ex.__traceback__) + try: + 1 / 0 + except ZeroDivisionError as ex: + raise KeyError().with_traceback(ex.__traceback__) except KeyError as ex2: - tb = traceback.extract_tb(ex2.__traceback__) - assert tb[1].line == "1/0" + tb = traceback.extract_tb(ex2.__traceback__) + assert tb[1].line == "1/0" try: - try: - 1/0 - except ZeroDivisionError as ex: - raise ex.with_traceback(None) + try: + 1 / 0 + except ZeroDivisionError as ex: + raise ex.with_traceback(None) except ZeroDivisionError as ex2: - tb = traceback.extract_tb(ex2.__traceback__) - assert len(tb) == 1 + tb = traceback.extract_tb(ex2.__traceback__) + assert len(tb) == 1 diff --git a/extra_tests/snippets/stdlib_types.py b/extra_tests/snippets/stdlib_types.py index 479004b6cf..3a3872d2f4 100644 --- a/extra_tests/snippets/stdlib_types.py +++ b/extra_tests/snippets/stdlib_types.py @@ -2,7 +2,7 @@ from testutils import assert_raises -ns = types.SimpleNamespace(a=2, b='Rust') +ns = types.SimpleNamespace(a=2, b="Rust") assert ns.a == 2 assert ns.b == "Rust" diff --git a/extra_tests/snippets/test_threading.py b/extra_tests/snippets/test_threading.py index 41024b360e..4d7c29f509 100644 --- a/extra_tests/snippets/test_threading.py +++ b/extra_tests/snippets/test_threading.py @@ -11,7 +11,7 @@ def thread_function(name): output.append((0, 0)) -x = threading.Thread(target=thread_function, args=(1, )) +x = threading.Thread(target=thread_function, args=(1,)) output.append((0, 1)) x.start() output.append((0, 2)) diff --git a/extra_tests/snippets/testutils.py b/extra_tests/snippets/testutils.py index 437fa06ae3..aac153441e 100644 --- a/extra_tests/snippets/testutils.py +++ b/extra_tests/snippets/testutils.py @@ -1,6 +1,7 @@ import platform import sys + def assert_raises(expected, *args, _msg=None, **kw): if args: f, f_args = args[0], args[1:] @@ -22,8 +23,7 @@ def __enter__(self): def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is None: - failmsg = self.failmsg or \ - '{} was not raised'.format(self.expected.__name__) + failmsg = self.failmsg or "{} was not raised".format(self.expected.__name__) assert False, failmsg if not issubclass(exc_type, self.expected): return False @@ -36,6 +36,7 @@ class TestFailingBool: def __bool__(self): raise RuntimeError + class TestFailingIter: def __iter__(self): raise RuntimeError @@ -48,47 +49,64 @@ def _assert_print(f, args): raised = False finally: if raised: - print('Assertion Failure:', *args) + print("Assertion Failure:", *args) + def _typed(obj): - return '{}({})'.format(type(obj), obj) + return "{}({})".format(type(obj), obj) def assert_equal(a, b): - _assert_print(lambda: a == b, [_typed(a), '==', _typed(b)]) + _assert_print(lambda: a == b, [_typed(a), "==", _typed(b)]) def assert_true(e): - _assert_print(lambda: e is True, [_typed(e), 'is True']) + _assert_print(lambda: e is True, [_typed(e), "is True"]) def assert_false(e): - _assert_print(lambda: e is False, [_typed(e), 'is False']) + _assert_print(lambda: e is False, [_typed(e), "is False"]) + def assert_isinstance(obj, klass): - _assert_print(lambda: isinstance(obj, klass), ['isisntance(', _typed(obj), ',', klass, ')']) + _assert_print( + lambda: isinstance(obj, klass), ["isisntance(", _typed(obj), ",", klass, ")"] + ) + def assert_in(a, b): - _assert_print(lambda: a in b, [a, 'in', b]) + _assert_print(lambda: a in b, [a, "in", b]) + def skip_if_unsupported(req_maj_vers, req_min_vers, test_fct): def exec(): test_fct() - if platform.python_implementation() == 'RustPython': + if platform.python_implementation() == "RustPython": exec() - elif sys.version_info.major>=req_maj_vers and sys.version_info.minor>=req_min_vers: + elif ( + sys.version_info.major >= req_maj_vers + and sys.version_info.minor >= req_min_vers + ): exec() else: - print(f'Skipping test as a higher python version is required. Using {platform.python_implementation()} {platform.python_version()}') + print( + f"Skipping test as a higher python version is required. Using {platform.python_implementation()} {platform.python_version()}" + ) + def fail_if_unsupported(req_maj_vers, req_min_vers, test_fct): def exec(): test_fct() - if platform.python_implementation() == 'RustPython': + if platform.python_implementation() == "RustPython": exec() - elif sys.version_info.major>=req_maj_vers and sys.version_info.minor>=req_min_vers: + elif ( + sys.version_info.major >= req_maj_vers + and sys.version_info.minor >= req_min_vers + ): exec() else: - assert False, f'Test cannot performed on this python version. {platform.python_implementation()} {platform.python_version()}' + assert False, ( + f"Test cannot performed on this python version. {platform.python_implementation()} {platform.python_version()}" + ) diff --git a/extra_tests/test_snippets.py b/extra_tests/test_snippets.py index c191c1e638..5ff944c772 100644 --- a/extra_tests/test_snippets.py +++ b/extra_tests/test_snippets.py @@ -42,23 +42,27 @@ def perform_test(filename, method, test_type): def run_via_cpython(filename): - """ Simply invoke python itself on the script """ + """Simply invoke python itself on the script""" env = os.environ.copy() subprocess.check_call([sys.executable, filename], env=env) -RUSTPYTHON_BINARY = os.environ.get("RUSTPYTHON") or os.path.join(ROOT_DIR, "target/release/rustpython") + +RUSTPYTHON_BINARY = os.environ.get("RUSTPYTHON") or os.path.join( + ROOT_DIR, "target/release/rustpython" +) RUSTPYTHON_BINARY = os.path.abspath(RUSTPYTHON_BINARY) + def run_via_rustpython(filename, test_type): env = os.environ.copy() - env['RUST_LOG'] = 'info,cargo=error,jobserver=error' - env['RUST_BACKTRACE'] = '1' + env["RUST_LOG"] = "info,cargo=error,jobserver=error" + env["RUST_BACKTRACE"] = "1" subprocess.check_call([RUSTPYTHON_BINARY, filename], env=env) def create_test_function(cls, filename, method, test_type): - """ Create a test function for a single snippet """ + """Create a test function for a single snippet""" core_test_directory, snippet_filename = os.path.split(filename) test_function_name = "test_{}_".format(method) + os.path.splitext(snippet_filename)[ 0 @@ -74,7 +78,7 @@ def test_function(self): def populate(method): def wrapper(cls): - """ Decorator function which can populate a unittest.TestCase class """ + """Decorator function which can populate a unittest.TestCase class""" for test_type, filename in get_test_files(): create_test_function(cls, filename, method, test_type) return cls @@ -83,7 +87,7 @@ def wrapper(cls): def get_test_files(): - """ Retrieve test files """ + """Retrieve test files""" for test_type, test_dir in TEST_DIRS.items(): for filepath in sorted(glob.iglob(os.path.join(test_dir, "*.py"))): filename = os.path.split(filepath)[1] @@ -122,7 +126,9 @@ class SampleTestCase(unittest.TestCase): @classmethod def setUpClass(cls): # Here add resource files - cls.slices_resource_path = Path(TEST_DIRS[_TestType.functional]) / "cpython_generated_slices.py" + cls.slices_resource_path = ( + Path(TEST_DIRS[_TestType.functional]) / "cpython_generated_slices.py" + ) if cls.slices_resource_path.exists(): cls.slices_resource_path.unlink() diff --git a/ruff.toml b/ruff.toml index 5e2fb8c4f5..15aaa07c8a 100644 --- a/ruff.toml +++ b/ruff.toml @@ -9,6 +9,8 @@ exclude = [ "Lib", "vm/Lib", "benches", + "syntax_*.py", # Do not format files that are specifically testing for syntax + "badsyntax_*.py", ] [lint] diff --git a/wasm/demo/snippets/asyncbrowser.py b/wasm/demo/snippets/asyncbrowser.py index 5cd2f7b0a0..d3a9dca85f 100644 --- a/wasm/demo/snippets/asyncbrowser.py +++ b/wasm/demo/snippets/asyncbrowser.py @@ -1,6 +1,7 @@ import browser import asyncweb + async def main(delay): url = f"https://httpbin.org/delay/{delay}" print(f"fetching {url}...") diff --git a/wasm/demo/snippets/fetch.py b/wasm/demo/snippets/fetch.py index f507057b22..80e1775c76 100644 --- a/wasm/demo/snippets/fetch.py +++ b/wasm/demo/snippets/fetch.py @@ -1,12 +1,12 @@ from browser import fetch + def fetch_handler(res): print(f"headers: {res['headers']}") + fetch( "https://httpbin.org/get", response_format="json", - headers={ - "X-Header-Thing": "rustpython is neat!" - }, + headers={"X-Header-Thing": "rustpython is neat!"}, ).then(fetch_handler, lambda err: print(f"error: {err}")) diff --git a/wasm/demo/snippets/import_pypi.py b/wasm/demo/snippets/import_pypi.py index a7c8a8e7fd..e3325d56f4 100644 --- a/wasm/demo/snippets/import_pypi.py +++ b/wasm/demo/snippets/import_pypi.py @@ -8,12 +8,14 @@ whlimport.setup() + @asyncweb.main async def main(): await whlimport.load_package("pygments") import pygments import pygments.lexers import pygments.formatters.html + lexer = pygments.lexers.get_lexer_by_name("python") fmter = pygments.formatters.html.HtmlFormatter(noclasses=True, style="default") print(pygments.highlight("print('hi, mom!')", lexer, fmter)) diff --git a/wasm/demo/snippets/mandelbrot.py b/wasm/demo/snippets/mandelbrot.py index b4010c7539..ea4fade56d 100644 --- a/wasm/demo/snippets/mandelbrot.py +++ b/wasm/demo/snippets/mandelbrot.py @@ -1,6 +1,7 @@ w = 50.0 h = 50.0 + def mandel(): """Print a mandelbrot fractal to the console, yielding after each character is printed""" y = 0.0 @@ -20,9 +21,9 @@ def mandel(): i += 1 if Tr + Ti <= 4: - print('*', end='') + print("*", end="") else: - print('·', end='') + print("·", end="") x += 1 yield @@ -31,14 +32,24 @@ def mandel(): y += 1 yield + # run the mandelbrot -try: from browser import request_animation_frame -except: request_animation_frame = None +try: + from browser import request_animation_frame +except: + request_animation_frame = None gen = mandel() + + def gen_cb(_time=None): - for _ in range(4): gen.__next__() + for _ in range(4): + gen.__next__() request_animation_frame(gen_cb) -if request_animation_frame: gen_cb() -else: any(gen) + + +if request_animation_frame: + gen_cb() +else: + any(gen) diff --git a/wasm/example/src/main.py b/wasm/example/src/main.py index 5447d078af..b5a1bda7c0 100644 --- a/wasm/example/src/main.py +++ b/wasm/example/src/main.py @@ -1,12 +1,14 @@ from browser import fetch, alert + def fetch_handler(repos): star_sum = 0 for repo in repos: - star_sum += repo['stars'] - alert(f'Average github trending star count: {star_sum / len(repos)}') + star_sum += repo["stars"] + alert(f"Average github trending star count: {star_sum / len(repos)}") + fetch( - 'https://github-trending-api.now.sh/repositories', - response_format='json', -).then(fetch_handler, lambda err: alert(f"Error: {err}")) \ No newline at end of file + "https://github-trending-api.now.sh/repositories", + response_format="json", +).then(fetch_handler, lambda err: alert(f"Error: {err}")) From 6fa12b0739343446357a21532152a9061313daca Mon Sep 17 00:00:00 2001 From: Rex Ledesma Date: Sun, 11 May 2025 11:01:53 -0400 Subject: [PATCH 2/2] fix tests --- extra_tests/snippets/example_interactive.py | 2 +- extra_tests/snippets/stdlib_traceback.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/extra_tests/snippets/example_interactive.py b/extra_tests/snippets/example_interactive.py index bbaf7b88af..f9484f15dc 100644 --- a/extra_tests/snippets/example_interactive.py +++ b/extra_tests/snippets/example_interactive.py @@ -21,7 +21,7 @@ def f(x, y, *args, power=1, **kwargs): print(c2.co_consts) assert 2 in c2.co_consts, c2.co_consts assert "example_interactive.py" in c2.co_filename -assert c2.co_firstlineno == 5, str(c2.co_firstlineno) +assert c2.co_firstlineno == 6, str(c2.co_firstlineno) # assert isinstance(c2.co_flags, int) # 'OPTIMIZED, NEWLOCALS, NOFREE' # assert c2.co_freevars == (), str(c2.co_freevars) assert c2.co_kwonlyargcount == 1, c2.co_kwonlyargcount diff --git a/extra_tests/snippets/stdlib_traceback.py b/extra_tests/snippets/stdlib_traceback.py index 7e42e70fb7..c2cc5773db 100644 --- a/extra_tests/snippets/stdlib_traceback.py +++ b/extra_tests/snippets/stdlib_traceback.py @@ -14,7 +14,7 @@ raise KeyError().with_traceback(ex.__traceback__) except KeyError as ex2: tb = traceback.extract_tb(ex2.__traceback__) - assert tb[1].line == "1/0" + assert tb[1].line == "1 / 0" try: