Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Python unittests and apply Python standard #394

Merged
merged 2 commits into from
Oct 1, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion getgauge/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 6 additions & 8 deletions getgauge/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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__()
Expand All @@ -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__()
Expand Down
23 changes: 13 additions & 10 deletions getgauge/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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():
Expand Down Expand Up @@ -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')
return os.getenv('gauge_screenshots_dir')
23 changes: 11 additions & 12 deletions getgauge/static_loader.py
Original file line number Diff line number Diff line change
@@ -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):
Expand All @@ -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:
chadlwilson marked this conversation as resolved.
Show resolved Hide resolved
load_steps(pf)
12 changes: 6 additions & 6 deletions getgauge/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)
38 changes: 20 additions & 18 deletions tests/test_python.py
Original file line number Diff line number Diff line change
@@ -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:
Expand Down Expand Up @@ -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()
Expand All @@ -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))
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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|
|------|-----------|
Expand All @@ -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|
|----|-----------|""")
Expand Down Expand Up @@ -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):
Expand Down
20 changes: 9 additions & 11 deletions tests/test_refactor.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import os
import sys
import tempfile
import unittest

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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()

Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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 <vowels> <bsdfdsf>.")
def assert_default_vowels(arg0, arg1):
Expand Down Expand Up @@ -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)
Expand All @@ -345,4 +344,3 @@ def getActualText(self):
_file.write(RefactorTests.data)
_file.close()
return actual_data

Loading