From 97093f64da8890548f62b17bfeec4efd36b73bae Mon Sep 17 00:00:00 2001 From: Sebastian <89982771+sschulz92@users.noreply.github.com> Date: Tue, 1 Oct 2024 07:57:47 +0200 Subject: [PATCH] Update Python unittests and apply Python standard (#394) Signed-off-by: sschulz92 Co-authored-by: Chad Wilson --- getgauge/parser.py | 2 +- getgauge/python.py | 14 ++++++-------- getgauge/registry.py | 23 +++++++++++++---------- getgauge/static_loader.py | 23 +++++++++++------------ getgauge/util.py | 12 ++++++------ tests/test_python.py | 38 ++++++++++++++++++++------------------ tests/test_refactor.py | 20 +++++++++----------- 7 files changed, 66 insertions(+), 66 deletions(-) diff --git a/getgauge/parser.py b/getgauge/parser.py index 11b7953..cacd6f7 100644 --- a/getgauge/parser.py +++ b/getgauge/parser.py @@ -93,7 +93,7 @@ def _find_step_node(self, step_text): arg_node = decorator.call.value[0].value if step == step_text: return arg_node, func - elif isinstance(step, list) and step_text in step: + if isinstance(step, list) and step_text in step: step_node = arg_node[step.index(step_text)] return step_node, func return None, None diff --git a/getgauge/python.py b/getgauge/python.py index 688dc0b..8de1f1e 100644 --- a/getgauge/python.py +++ b/getgauge/python.py @@ -66,10 +66,12 @@ def custom_screen_grabber(func): registry.set_screenshot_provider(func, False) return func + def custom_screenshot_writer(func): registry.set_screenshot_provider(func, True) return func + def _warn_screenshot_deprecation(old_function, new_function): warnings.warn( "'{0}' is deprecated in favour of '{1}'".format(old_function, new_function), @@ -172,12 +174,8 @@ def tags(self): return self.__tags def __str__(self): - return "Specification: {{ name: {}, is_failing: {}, tags: {}, file_name: {} }}".format(self.name, - str( - self.is_failing), - ", ".join( - self.tags), - self.file_name) + s = "Specification: {{ name: {}, is_failing: {}, tags: {}, file_name: {} }}" + return s.format(self.name, str(self.is_failing), ", ".join(self.tags), self.file_name) def __eq__(self, other): return self.__str__() == other.__str__() @@ -202,8 +200,8 @@ def tags(self): return self.__tags def __str__(self): - return "Scenario: {{ name: {}, is_failing: {}, tags: {} }}".format(self.name, str(self.is_failing), - ", ".join(self.tags)) + s = "Scenario: {{ name: {}, is_failing: {}, tags: {} }}" + return s.format(self.name, str(self.is_failing), ", ".join(self.tags)) def __eq__(self, other): return self.__str__() == other.__str__() diff --git a/getgauge/registry.py b/getgauge/registry.py index 7317611..16b413e 100644 --- a/getgauge/registry.py +++ b/getgauge/registry.py @@ -2,8 +2,8 @@ import os import re import sys -from uuid import uuid1 from subprocess import call +from uuid import uuid1 from getgauge import logger @@ -218,13 +218,13 @@ def _filter_hooks(tags, hooks): continue for tag in tags: hook_tags = hook_tags.replace('<{}>'.format(tag), 'True') - if eval(re.sub('<[^<]+?>', 'False', hook_tags)): + if eval(re.sub(r'<[^<]+?>', 'False', hook_tags)): filtered_hooks.append(hook) return filtered_hooks def _get_step_value(step_text): - return re.sub('(<.*?>)', '{}', step_text) + return re.sub(r'(<.*?>)', '{}', step_text) def _take_screenshot(): @@ -263,23 +263,26 @@ def capture_to_file(): if not registry.is_screenshot_writer: screenshot_file = _uniqe_screenshot_file() content = registry.screenshot_provider()() - file = open(screenshot_file, "wb") - file.write(content) - file.close() + with open(screenshot_file, "wb") as file: + file.write(content) + file.close() return os.path.basename(screenshot_file) screenshot_file = registry.screenshot_provider()() - if(not os.path.isabs(screenshot_file)): + if not os.path.isabs(screenshot_file): screenshot_file = os.path.join(_screenshots_dir(), screenshot_file) - if(not os.path.exists(screenshot_file)): - logger.warning("Screenshot file {0} does not exists.".format(screenshot_file)) + if not os.path.exists(screenshot_file): + logger.warning( + "Screenshot file {0} does not exists.".format(screenshot_file)) return os.path.basename(screenshot_file) @staticmethod def clear(): ScreenshotsStore.__screenshots = [] + def _uniqe_screenshot_file(): return os.path.join(_screenshots_dir(), "screenshot-{0}.png".format(uuid1().int)) + def _screenshots_dir(): - return os.getenv('gauge_screenshots_dir') \ No newline at end of file + return os.getenv('gauge_screenshots_dir') diff --git a/getgauge/static_loader.py b/getgauge/static_loader.py index 0984bce..5261763 100644 --- a/getgauge/static_loader.py +++ b/getgauge/static_loader.py @@ -1,12 +1,13 @@ -import os -from getgauge.registry import registry +import glob + from getgauge.parser import Parser +from getgauge.registry import registry -def load_steps(python_file): - for funcStep in python_file.iter_steps(): - registry.add_step(funcStep[0], funcStep[1], - python_file.file_path, funcStep[2]) +def load_steps(python_file: Parser): + for func_step in python_file.iter_steps(): + registry.add_step(func_step[0], func_step[1], + python_file.file_path, func_step[2]) def reload_steps(file_path, content=None): @@ -18,9 +19,7 @@ def reload_steps(file_path, content=None): def load_files(step_impl_dirs): for step_impl_dir in step_impl_dirs: - for dirpath, _, files in os.walk(step_impl_dir): - py_files = (os.path.join(dirpath, f) for f in files if f.endswith('.py')) - for file_path in py_files: - pf = Parser.parse(file_path) - if pf: - load_steps(pf) + for file_path in glob.glob(f"{step_impl_dir}/**/*.py", recursive=True): + pf = Parser.parse(file_path) + if pf: + load_steps(pf) diff --git a/getgauge/util.py b/getgauge/util.py index 79f0377..eeb8f52 100644 --- a/getgauge/util.py +++ b/getgauge/util.py @@ -34,9 +34,9 @@ def get_impl_files(): def read_file_contents(file_name): if os.path.isfile(file_name): - f = open(file_name) - content = f.read().replace('\r\n', '\n') - f.close() + with open(file_name, "r", encoding="utf-8") as f: + content = f.read().replace('\r\n', '\n') + f.close() return content return None @@ -46,6 +46,6 @@ def get_file_name(prefix='', counter=0): file_name = os.path.join(get_step_impl_dirs()[0], name) if not os.path.exists(file_name): return file_name - else: - counter = counter + 1 - return get_file_name('_{}'.format(counter), counter) + + counter = counter + 1 + return get_file_name('_{}'.format(counter), counter) diff --git a/tests/test_python.py b/tests/test_python.py index c36c163..a073f90 100644 --- a/tests/test_python.py +++ b/tests/test_python.py @@ -1,14 +1,15 @@ +import os +import tempfile from unittest import TestCase, main +from uuid import uuid1 from getgauge.messages.messages_pb2 import Message -from getgauge.registry import registry, MessagesStore, ScreenshotsStore -from getgauge.python import (Messages, DataStore, DictObject, - DataStoreContainer, data_store, Table, Specification, - Scenario, Step, ExecutionContext, - create_execution_context_from) -from uuid import uuid1 -import os -import tempfile +from getgauge.python import (DataStore, DataStoreContainer, DictObject, + ExecutionContext, Messages, Scenario, + Specification, Step, Table, + create_execution_context_from, data_store) +from getgauge.registry import MessagesStore, ScreenshotsStore, registry + try: from collections.abc import MutableMapping except ImportError: @@ -64,11 +65,11 @@ def test_data_store(self): for value in values: store.put(value, value) - for value in values: - store.put(value, values[value]) + for key, value in values.items(): + store.put(key, value) - for value in values: - self.assertEqual(store.get(value), values[value]) + for key, value in values.items(): + self.assertEqual(store.get(key), value) def test_data_store_clear(self): store = DataStore() @@ -80,8 +81,8 @@ def test_data_store_clear(self): for value in values: store.put(value, value) - for value in values: - store.put(value, values[value]) + for key, value in values.items(): + store.put(key, value) for value in values: self.assertTrue(store.is_present(value)) @@ -140,6 +141,7 @@ def test_data_store_as_proxy(self): self.assertFalse(proxy2.is_present('c')) self.assertFalse(proxy2.is_present('d')) + class DictObjectTests(TestCase): def test_attribute_access(self): store = DictObject() @@ -241,7 +243,7 @@ def test_Table_with_index_access(self): self.assertEqual(row, table[expected_rows.index(row)]) for row in table: - self.assertTrue(expected_rows.__contains__(row)) + self.assertIn(row, expected_rows) with self.assertRaises(IndexError): table.get_row(5) @@ -270,7 +272,7 @@ def test_Table__str__(self): proto_table = ProtoTable({'headers': {'cells': headers}, 'rows': rows}) - table = Table(proto_table).__str__() + table = str(Table(proto_table)) self.assertEqual(table, """|Word |Vowel Count| |------|-----------| @@ -286,7 +288,7 @@ def test_Table__str__without_rows(self): proto_table = ProtoTable({'headers': {'cells': headers}, 'rows': rows}) - table = Table(proto_table).__str__() + table = str(Table(proto_table)) self.assertEqual(table, """|Word|Vowel Count| |----|-----------|""") @@ -481,7 +483,7 @@ def test_screenshot_decorator(self): class ScreenshotsTests(TestCase): def setUp(self): self.__old_screenshot_provider = registry.screenshot_provider() - self.__is_screenshot_writer = registry.is_screenshot_writer + self.__is_screenshot_writer = registry.is_screenshot_writer os.environ["gauge_screenshots_dir"] = tempfile.mkdtemp() def test_pending_screenshots(self): diff --git a/tests/test_refactor.py b/tests/test_refactor.py index 8dadae0..83d5596 100644 --- a/tests/test_refactor.py +++ b/tests/test_refactor.py @@ -1,5 +1,4 @@ import os -import sys import tempfile import unittest @@ -49,7 +48,7 @@ def test_Processor_refactor_request_with_add_param(self): param_position.newPosition = 1 request.refactorRequest.paramPositions.extend([position, param_position]) - processor.refactor_step(request.refactorRequest, response, None) + processor.refactor_step(request.refactorRequest, response) actual_data = self.getActualText() self.assertEqual(Message.RefactorResponse, response.messageType) @@ -83,7 +82,7 @@ def test_Processor_refactor_request_with_add_param_and_invalid_identifier(self): param_position.newPosition = 1 request.refactorRequest.paramPositions.extend([position, param_position]) - processor.refactor_step(request.refactorRequest, response, None) + processor.refactor_step(request.refactorRequest, response) actual_data = self.getActualText() self.assertEqual(Message.RefactorResponse, response.messageType) @@ -117,7 +116,7 @@ def test_Processor_refactor_request_with_add_param_and_only_invalid_identifier(s param_position.newPosition = 1 request.refactorRequest.paramPositions.extend([position, param_position]) - processor.refactor_step(request.refactorRequest, response, None) + processor.refactor_step(request.refactorRequest, response) actual_data = self.getActualText() self.assertEqual(Message.RefactorResponse, response.messageType) @@ -142,7 +141,7 @@ def test_Processor_refactor_request_with_remove_param(self): request.refactorRequest.newStepValue.parameterizedStepValue = 'Vowels in English language is.' request.refactorRequest.newStepValue.stepValue = 'Vowels in English language is.' - processor.refactor_step(request.refactorRequest, response, None) + processor.refactor_step(request.refactorRequest, response) actual_data = self.getActualText() @@ -173,7 +172,7 @@ def test_Processor_refactor_request(self): position.newPosition = 0 request.refactorRequest.paramPositions.extend([position]) - processor.refactor_step(request.refactorRequest, response, None) + processor.refactor_step(request.refactorRequest, response) actual_data = self.getActualText() @@ -204,7 +203,7 @@ def test_Processor_refactor_request_with_add_and_remove_param(self): param_position.newPosition = 0 request.refactorRequest.paramPositions.extend([param_position]) - processor.refactor_step(request.refactorRequest, response, None) + processor.refactor_step(request.refactorRequest, response) actual_data = self.getActualText() @@ -242,7 +241,7 @@ def test_processor_refactor_request_with_insert_param(self): param2_position.newPosition = 1 request.refactorRequest.paramPositions.extend([param1_position, param2_position]) - processor.refactor_step(request.refactorRequest, response, None) + processor.refactor_step(request.refactorRequest, response) actual_data = self.getActualText() @@ -280,7 +279,7 @@ def test_Processor_refactor_request_without_save_change_with_add_param(self): old_content = self.getActualText() - processor.refactor_step(request.refactorRequest, response, None) + processor.refactor_step(request.refactorRequest, response) expected = """@step("Vowels in English language is .") def assert_default_vowels(arg0, arg1): @@ -319,7 +318,7 @@ def test_Processor_refactor_request_without_save_changes_add_param_and_invalid_i old_content = self.getActualText() - processor.refactor_step(request.refactorRequest, response, None) + processor.refactor_step(request.refactorRequest, response) self.assertEqual(Message.RefactorResponse, response.messageType) self.assertTrue(response.refactorResponse.success, response.refactorResponse.error) @@ -345,4 +344,3 @@ def getActualText(self): _file.write(RefactorTests.data) _file.close() return actual_data -