Skip to content

Commit 97093f6

Browse files
Update Python unittests and apply Python standard (#394)
Signed-off-by: sschulz92 <[email protected]> Co-authored-by: Chad Wilson <[email protected]>
1 parent 52e1ade commit 97093f6

File tree

7 files changed

+66
-66
lines changed

7 files changed

+66
-66
lines changed

getgauge/parser.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ def _find_step_node(self, step_text):
9393
arg_node = decorator.call.value[0].value
9494
if step == step_text:
9595
return arg_node, func
96-
elif isinstance(step, list) and step_text in step:
96+
if isinstance(step, list) and step_text in step:
9797
step_node = arg_node[step.index(step_text)]
9898
return step_node, func
9999
return None, None

getgauge/python.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -66,10 +66,12 @@ def custom_screen_grabber(func):
6666
registry.set_screenshot_provider(func, False)
6767
return func
6868

69+
6970
def custom_screenshot_writer(func):
7071
registry.set_screenshot_provider(func, True)
7172
return func
7273

74+
7375
def _warn_screenshot_deprecation(old_function, new_function):
7476
warnings.warn(
7577
"'{0}' is deprecated in favour of '{1}'".format(old_function, new_function),
@@ -172,12 +174,8 @@ def tags(self):
172174
return self.__tags
173175

174176
def __str__(self):
175-
return "Specification: {{ name: {}, is_failing: {}, tags: {}, file_name: {} }}".format(self.name,
176-
str(
177-
self.is_failing),
178-
", ".join(
179-
self.tags),
180-
self.file_name)
177+
s = "Specification: {{ name: {}, is_failing: {}, tags: {}, file_name: {} }}"
178+
return s.format(self.name, str(self.is_failing), ", ".join(self.tags), self.file_name)
181179

182180
def __eq__(self, other):
183181
return self.__str__() == other.__str__()
@@ -202,8 +200,8 @@ def tags(self):
202200
return self.__tags
203201

204202
def __str__(self):
205-
return "Scenario: {{ name: {}, is_failing: {}, tags: {} }}".format(self.name, str(self.is_failing),
206-
", ".join(self.tags))
203+
s = "Scenario: {{ name: {}, is_failing: {}, tags: {} }}"
204+
return s.format(self.name, str(self.is_failing), ", ".join(self.tags))
207205

208206
def __eq__(self, other):
209207
return self.__str__() == other.__str__()

getgauge/registry.py

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22
import os
33
import re
44
import sys
5-
from uuid import uuid1
65
from subprocess import call
6+
from uuid import uuid1
77

88
from getgauge import logger
99

@@ -218,13 +218,13 @@ def _filter_hooks(tags, hooks):
218218
continue
219219
for tag in tags:
220220
hook_tags = hook_tags.replace('<{}>'.format(tag), 'True')
221-
if eval(re.sub('<[^<]+?>', 'False', hook_tags)):
221+
if eval(re.sub(r'<[^<]+?>', 'False', hook_tags)):
222222
filtered_hooks.append(hook)
223223
return filtered_hooks
224224

225225

226226
def _get_step_value(step_text):
227-
return re.sub('(<.*?>)', '{}', step_text)
227+
return re.sub(r'(<.*?>)', '{}', step_text)
228228

229229

230230
def _take_screenshot():
@@ -263,23 +263,26 @@ def capture_to_file():
263263
if not registry.is_screenshot_writer:
264264
screenshot_file = _uniqe_screenshot_file()
265265
content = registry.screenshot_provider()()
266-
file = open(screenshot_file, "wb")
267-
file.write(content)
268-
file.close()
266+
with open(screenshot_file, "wb") as file:
267+
file.write(content)
268+
file.close()
269269
return os.path.basename(screenshot_file)
270270
screenshot_file = registry.screenshot_provider()()
271-
if(not os.path.isabs(screenshot_file)):
271+
if not os.path.isabs(screenshot_file):
272272
screenshot_file = os.path.join(_screenshots_dir(), screenshot_file)
273-
if(not os.path.exists(screenshot_file)):
274-
logger.warning("Screenshot file {0} does not exists.".format(screenshot_file))
273+
if not os.path.exists(screenshot_file):
274+
logger.warning(
275+
"Screenshot file {0} does not exists.".format(screenshot_file))
275276
return os.path.basename(screenshot_file)
276277

277278
@staticmethod
278279
def clear():
279280
ScreenshotsStore.__screenshots = []
280281

282+
281283
def _uniqe_screenshot_file():
282284
return os.path.join(_screenshots_dir(), "screenshot-{0}.png".format(uuid1().int))
283285

286+
284287
def _screenshots_dir():
285-
return os.getenv('gauge_screenshots_dir')
288+
return os.getenv('gauge_screenshots_dir')

getgauge/static_loader.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
1-
import os
2-
from getgauge.registry import registry
1+
import glob
2+
33
from getgauge.parser import Parser
4+
from getgauge.registry import registry
45

56

6-
def load_steps(python_file):
7-
for funcStep in python_file.iter_steps():
8-
registry.add_step(funcStep[0], funcStep[1],
9-
python_file.file_path, funcStep[2])
7+
def load_steps(python_file: Parser):
8+
for func_step in python_file.iter_steps():
9+
registry.add_step(func_step[0], func_step[1],
10+
python_file.file_path, func_step[2])
1011

1112

1213
def reload_steps(file_path, content=None):
@@ -18,9 +19,7 @@ def reload_steps(file_path, content=None):
1819

1920
def load_files(step_impl_dirs):
2021
for step_impl_dir in step_impl_dirs:
21-
for dirpath, _, files in os.walk(step_impl_dir):
22-
py_files = (os.path.join(dirpath, f) for f in files if f.endswith('.py'))
23-
for file_path in py_files:
24-
pf = Parser.parse(file_path)
25-
if pf:
26-
load_steps(pf)
22+
for file_path in glob.glob(f"{step_impl_dir}/**/*.py", recursive=True):
23+
pf = Parser.parse(file_path)
24+
if pf:
25+
load_steps(pf)

getgauge/util.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,9 @@ def get_impl_files():
3434

3535
def read_file_contents(file_name):
3636
if os.path.isfile(file_name):
37-
f = open(file_name)
38-
content = f.read().replace('\r\n', '\n')
39-
f.close()
37+
with open(file_name, "r", encoding="utf-8") as f:
38+
content = f.read().replace('\r\n', '\n')
39+
f.close()
4040
return content
4141
return None
4242

@@ -46,6 +46,6 @@ def get_file_name(prefix='', counter=0):
4646
file_name = os.path.join(get_step_impl_dirs()[0], name)
4747
if not os.path.exists(file_name):
4848
return file_name
49-
else:
50-
counter = counter + 1
51-
return get_file_name('_{}'.format(counter), counter)
49+
50+
counter = counter + 1
51+
return get_file_name('_{}'.format(counter), counter)

tests/test_python.py

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
1+
import os
2+
import tempfile
13
from unittest import TestCase, main
4+
from uuid import uuid1
25

36
from getgauge.messages.messages_pb2 import Message
4-
from getgauge.registry import registry, MessagesStore, ScreenshotsStore
5-
from getgauge.python import (Messages, DataStore, DictObject,
6-
DataStoreContainer, data_store, Table, Specification,
7-
Scenario, Step, ExecutionContext,
8-
create_execution_context_from)
9-
from uuid import uuid1
10-
import os
11-
import tempfile
7+
from getgauge.python import (DataStore, DataStoreContainer, DictObject,
8+
ExecutionContext, Messages, Scenario,
9+
Specification, Step, Table,
10+
create_execution_context_from, data_store)
11+
from getgauge.registry import MessagesStore, ScreenshotsStore, registry
12+
1213
try:
1314
from collections.abc import MutableMapping
1415
except ImportError:
@@ -64,11 +65,11 @@ def test_data_store(self):
6465
for value in values:
6566
store.put(value, value)
6667

67-
for value in values:
68-
store.put(value, values[value])
68+
for key, value in values.items():
69+
store.put(key, value)
6970

70-
for value in values:
71-
self.assertEqual(store.get(value), values[value])
71+
for key, value in values.items():
72+
self.assertEqual(store.get(key), value)
7273

7374
def test_data_store_clear(self):
7475
store = DataStore()
@@ -80,8 +81,8 @@ def test_data_store_clear(self):
8081
for value in values:
8182
store.put(value, value)
8283

83-
for value in values:
84-
store.put(value, values[value])
84+
for key, value in values.items():
85+
store.put(key, value)
8586

8687
for value in values:
8788
self.assertTrue(store.is_present(value))
@@ -140,6 +141,7 @@ def test_data_store_as_proxy(self):
140141
self.assertFalse(proxy2.is_present('c'))
141142
self.assertFalse(proxy2.is_present('d'))
142143

144+
143145
class DictObjectTests(TestCase):
144146
def test_attribute_access(self):
145147
store = DictObject()
@@ -241,7 +243,7 @@ def test_Table_with_index_access(self):
241243
self.assertEqual(row, table[expected_rows.index(row)])
242244

243245
for row in table:
244-
self.assertTrue(expected_rows.__contains__(row))
246+
self.assertIn(row, expected_rows)
245247

246248
with self.assertRaises(IndexError):
247249
table.get_row(5)
@@ -270,7 +272,7 @@ def test_Table__str__(self):
270272

271273
proto_table = ProtoTable({'headers': {'cells': headers}, 'rows': rows})
272274

273-
table = Table(proto_table).__str__()
275+
table = str(Table(proto_table))
274276

275277
self.assertEqual(table, """|Word |Vowel Count|
276278
|------|-----------|
@@ -286,7 +288,7 @@ def test_Table__str__without_rows(self):
286288

287289
proto_table = ProtoTable({'headers': {'cells': headers}, 'rows': rows})
288290

289-
table = Table(proto_table).__str__()
291+
table = str(Table(proto_table))
290292

291293
self.assertEqual(table, """|Word|Vowel Count|
292294
|----|-----------|""")
@@ -481,7 +483,7 @@ def test_screenshot_decorator(self):
481483
class ScreenshotsTests(TestCase):
482484
def setUp(self):
483485
self.__old_screenshot_provider = registry.screenshot_provider()
484-
self.__is_screenshot_writer = registry.is_screenshot_writer
486+
self.__is_screenshot_writer = registry.is_screenshot_writer
485487
os.environ["gauge_screenshots_dir"] = tempfile.mkdtemp()
486488

487489
def test_pending_screenshots(self):

tests/test_refactor.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import os
2-
import sys
32
import tempfile
43
import unittest
54

@@ -49,7 +48,7 @@ def test_Processor_refactor_request_with_add_param(self):
4948
param_position.newPosition = 1
5049
request.refactorRequest.paramPositions.extend([position, param_position])
5150

52-
processor.refactor_step(request.refactorRequest, response, None)
51+
processor.refactor_step(request.refactorRequest, response)
5352
actual_data = self.getActualText()
5453

5554
self.assertEqual(Message.RefactorResponse, response.messageType)
@@ -83,7 +82,7 @@ def test_Processor_refactor_request_with_add_param_and_invalid_identifier(self):
8382
param_position.newPosition = 1
8483
request.refactorRequest.paramPositions.extend([position, param_position])
8584

86-
processor.refactor_step(request.refactorRequest, response, None)
85+
processor.refactor_step(request.refactorRequest, response)
8786
actual_data = self.getActualText()
8887

8988
self.assertEqual(Message.RefactorResponse, response.messageType)
@@ -117,7 +116,7 @@ def test_Processor_refactor_request_with_add_param_and_only_invalid_identifier(s
117116
param_position.newPosition = 1
118117
request.refactorRequest.paramPositions.extend([position, param_position])
119118

120-
processor.refactor_step(request.refactorRequest, response, None)
119+
processor.refactor_step(request.refactorRequest, response)
121120
actual_data = self.getActualText()
122121

123122
self.assertEqual(Message.RefactorResponse, response.messageType)
@@ -142,7 +141,7 @@ def test_Processor_refactor_request_with_remove_param(self):
142141
request.refactorRequest.newStepValue.parameterizedStepValue = 'Vowels in English language is.'
143142
request.refactorRequest.newStepValue.stepValue = 'Vowels in English language is.'
144143

145-
processor.refactor_step(request.refactorRequest, response, None)
144+
processor.refactor_step(request.refactorRequest, response)
146145

147146
actual_data = self.getActualText()
148147

@@ -173,7 +172,7 @@ def test_Processor_refactor_request(self):
173172
position.newPosition = 0
174173
request.refactorRequest.paramPositions.extend([position])
175174

176-
processor.refactor_step(request.refactorRequest, response, None)
175+
processor.refactor_step(request.refactorRequest, response)
177176

178177
actual_data = self.getActualText()
179178

@@ -204,7 +203,7 @@ def test_Processor_refactor_request_with_add_and_remove_param(self):
204203
param_position.newPosition = 0
205204
request.refactorRequest.paramPositions.extend([param_position])
206205

207-
processor.refactor_step(request.refactorRequest, response, None)
206+
processor.refactor_step(request.refactorRequest, response)
208207

209208
actual_data = self.getActualText()
210209

@@ -242,7 +241,7 @@ def test_processor_refactor_request_with_insert_param(self):
242241
param2_position.newPosition = 1
243242
request.refactorRequest.paramPositions.extend([param1_position, param2_position])
244243

245-
processor.refactor_step(request.refactorRequest, response, None)
244+
processor.refactor_step(request.refactorRequest, response)
246245

247246
actual_data = self.getActualText()
248247

@@ -280,7 +279,7 @@ def test_Processor_refactor_request_without_save_change_with_add_param(self):
280279

281280
old_content = self.getActualText()
282281

283-
processor.refactor_step(request.refactorRequest, response, None)
282+
processor.refactor_step(request.refactorRequest, response)
284283

285284
expected = """@step("Vowels in English language is <vowels> <bsdfdsf>.")
286285
def assert_default_vowels(arg0, arg1):
@@ -319,7 +318,7 @@ def test_Processor_refactor_request_without_save_changes_add_param_and_invalid_i
319318

320319
old_content = self.getActualText()
321320

322-
processor.refactor_step(request.refactorRequest, response, None)
321+
processor.refactor_step(request.refactorRequest, response)
323322

324323
self.assertEqual(Message.RefactorResponse, response.messageType)
325324
self.assertTrue(response.refactorResponse.success, response.refactorResponse.error)
@@ -345,4 +344,3 @@ def getActualText(self):
345344
_file.write(RefactorTests.data)
346345
_file.close()
347346
return actual_data
348-

0 commit comments

Comments
 (0)