Skip to content

Commit 55d2d7e

Browse files
authored
Merge pull request #26 from abhijo89-to/v2
Removed few Unnecessary else after return
2 parents 6c0bbf1 + 8fda42e commit 55d2d7e

File tree

11 files changed

+133
-109
lines changed

11 files changed

+133
-109
lines changed

.coveragerc

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
# .coveragerc to control coverage.py
22
[run]
33
branch = True
4+
omit = py3resttest/runner.py
5+
46
command_line = --source py3resttest -m pytest tests/test_*.py
57
[paths]
68
source =

coverage.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@
22
# pip install coverage
33
coverage run --source py3resttest -m pytest tests/test_*.py
44
coverage html
5+
coverage report

py3resttest/binding.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
class Context(object):
1212
""" Manages binding of variables & generators, with both variable name and generator name being strings """
13-
13+
# variables = {}
1414
def __init__(self):
1515
self.variables = {} # Maps variable name to current value
1616
self.generators = {} # Maps generator name to generator function
@@ -21,6 +21,7 @@ def bind_variable(self, variable_name, variable_value):
2121
This allows for passing in variables in testing """
2222
str_name = str(variable_name)
2323
prev = self.variables.get(str_name)
24+
2425
if prev != variable_value:
2526
self.variables[str(variable_name)] = variable_value
2627
self.mod_count = self.mod_count + 1

py3resttest/generators.py

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -232,16 +232,8 @@ def parse_generator(configuration):
232232
elif gen_type == 'env_string':
233233
return factory_env_string(configuration['string'])()
234234
elif gen_type == 'number_sequence':
235-
start = configuration.get('start')
236-
increment = configuration.get('increment')
237-
if not start:
238-
start = 1
239-
else:
240-
start = int(start)
241-
if not increment:
242-
increment = 1
243-
else:
244-
increment = int(increment)
235+
start = int(configuration.get('start', 1))
236+
increment = int(configuration.get('increment', 1))
245237
return factory_generate_ids(start, increment)()
246238
elif gen_type == 'random_int':
247239
return generator_random_int32()

py3resttest/testcase.py

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ def __init__(self):
8686
def parse(self, base_url: str, testcase_list: List, test_file=None, working_directory=None, variable_dict=None):
8787

8888
if working_directory is None:
89-
working_directory = os.path.abspath(os.getcwd())
89+
working_directory = Path(os.path.abspath(os.getcwd()))
9090
else:
9191
working_directory = Path(working_directory)
9292
if variable_dict is None:
@@ -108,27 +108,24 @@ def parse(self, base_url: str, testcase_list: List, test_file=None, working_dire
108108
raise ValueError("include should be list not %s" % type(sub_testcase_node))
109109
for testcase_file_path in sub_testcase_node:
110110
testcase_file_path = testcase_file_path.replace('.', '/')
111-
testcase_file = working_directory.joinpath("%s.yaml" % testcase_file_path).resolve()
111+
testcase_file = str(working_directory.joinpath("%s.yaml" % testcase_file_path).resolve())
112112
if testcase_file not in self.__testcase_file:
113113
self.__testcase_file.add(testcase_file)
114114
import_testcase_list = read_testcase_file(testcase_file)
115115
with ChangeDir(working_directory):
116116
self.parse(base_url, import_testcase_list, variable_dict=variable_dict)
117117
elif key == YamlKeyWords.IMPORT:
118118
if sub_testcase_node not in self.__testcase_file:
119-
testcase_file_path = os.path.dirname(os.path.realpath(sub_testcase_node))
119+
testcase_file_path = sub_testcase_node
120120
logger.debug("Importing testcase from %s", testcase_file_path)
121+
testcase_file_path = str(working_directory.joinpath("%s" % testcase_file_path).resolve())
121122
self.__testcase_file.add(sub_testcase_node)
122123
import_testcase_list = read_testcase_file(testcase_file_path)
123-
with ChangeDir(testcase_file_path):
124+
with ChangeDir(working_directory):
124125
self.parse(base_url, import_testcase_list, variable_dict=variable_dict)
125126
elif key == YamlKeyWords.URL:
126127
__group_name = TestCaseGroup.DEFAULT_GROUP
127-
try:
128-
group_object = TestSet.test_group_list_dict[__group_name]
129-
except KeyError:
130-
group_object = TestCaseGroup(TestCaseGroup.DEFAULT_GROUP, config=testcase_config_object)
131-
TestSet.test_group_list_dict[__group_name] = group_object
128+
group_object = TestSet.__create_test(__group_name, testcase_config_object)
132129
testcase_object = TestCase(
133130
base_url=base_url, extract_binds=group_object.extract_binds,
134131
variable_binds=group_object.variable_binds, context=group_object.context,
@@ -153,11 +150,7 @@ def parse_test(base_url, sub_testcase_node, testcase_config_object):
153150
if __group_name is None:
154151
__group_name = node_dict.get(TestCaseKeywords.group)
155152
__group_name = __group_name if __group_name else TestCaseGroup.DEFAULT_GROUP
156-
try:
157-
group_object = TestSet.test_group_list_dict[__group_name]
158-
except KeyError:
159-
group_object = TestCaseGroup(TestCaseGroup.DEFAULT_GROUP, config=testcase_config_object)
160-
TestSet.test_group_list_dict[__group_name] = group_object
153+
group_object = TestSet.__create_test(__group_name, testcase_config_object)
161154
testcase_object = TestCase(
162155
base_url=base_url, extract_binds=group_object.extract_binds,
163156
variable_binds=group_object.variable_binds, context=group_object.context,
@@ -166,6 +159,15 @@ def parse_test(base_url, sub_testcase_node, testcase_config_object):
166159
testcase_object.parse(sub_testcase_node)
167160
group_object.testcase_list = testcase_object
168161

162+
@staticmethod
163+
def __create_test(__group_name, testcase_config_object):
164+
try:
165+
group_object = TestSet.test_group_list_dict[__group_name]
166+
except KeyError:
167+
group_object = TestCaseGroup(TestCaseGroup.DEFAULT_GROUP, config=testcase_config_object)
168+
TestSet.test_group_list_dict[__group_name] = group_object
169+
return group_object
170+
169171

170172
class TestCaseGroup:
171173
DEFAULT_GROUP = "NO GROUP"
@@ -367,6 +369,8 @@ def url(self):
367369
val = self.__url
368370
if not self.__abs_url:
369371
val = urljoin(self.__base_url, val)
372+
if isinstance(val, dict):
373+
logger.warning("URL is not applied template values.")
370374
return val
371375

372376
@url.setter
@@ -489,8 +493,10 @@ def body(self, value):
489493
if value:
490494
if isinstance(value, bytes):
491495
self.__body = ContentHandler.parse_content(value.decode())
492-
else:
496+
elif isinstance(value, str):
493497
self.__body = ContentHandler.parse_content(value)
498+
else:
499+
self.__body = value
494500
else:
495501
self.__body = value
496502

@@ -499,7 +505,7 @@ def failures(self):
499505
return self.__failure_list
500506

501507
def realize_template(self, variable_name, context):
502-
if context is None or self.templates is None or variable_name not in self.templates:
508+
if (context or self.templates) is None or (variable_name not in self.templates):
503509
return None
504510
if not context.get_values():
505511
return None

py3resttest/validators.py

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,6 @@ def __str__(self):
6060
@abstractmethod
6161
def extract_internal(self, query=None, body=None, headers=None, args=None):
6262
""" Do extraction, query should be pre-templated """
63-
pass
6463

6564
def extract(self, body=None, headers=None, context=None):
6665
""" Extract data """
@@ -165,8 +164,8 @@ def extract_internal(self, query=None, args=None, body=None, headers=None):
165164
# Fix #19
166165
if len(extracted) == 1:
167166
return extracted[0]
168-
else:
169-
return extracted
167+
168+
return extracted
170169

171170
@classmethod
172171
def parse(cls, config):
@@ -198,9 +197,8 @@ def _get_extractor(config_dict):
198197
for key, value in config_dict.items():
199198
if key in EXTRACTORS:
200199
return parse_extractor(key, value)
201-
else: # No valid extractor
202-
raise Exception(
203-
'No valid extractor name to use in input: {0}'.format(config_dict))
200+
raise Exception(
201+
'No valid extractor name to use in input: {0}'.format(config_dict))
204202

205203

206204
class AbstractValidator(metaclass=ABCMeta):
@@ -218,7 +216,6 @@ def __init__(self):
218216
@abstractmethod
219217
def validate(self, body=None, headers=None, context=None):
220218
""" Run the validation function, return true or a Failure """
221-
pass
222219

223220

224221
class ComparatorValidator(AbstractValidator):
@@ -322,7 +319,7 @@ def parse(config):
322319
# Expected value can be another extractor query, or a single value, or
323320
# a templated value
324321

325-
if isinstance(expected, str) or isinstance(expected, (int, float, complex)):
322+
if isinstance(expected, (str, int, float, complex)):
326323
output.expected = expected
327324
elif isinstance(expected, dict):
328325

@@ -457,13 +454,13 @@ def register_extractor(extractor_name, parse_function):
457454
if extractor_name.lower() == 'comparator':
458455
raise ValueError(
459456
"Cannot register extractors called 'comparator', that is a reserved name")
460-
elif extractor_name.lower() == 'test':
457+
if extractor_name.lower() == 'test':
461458
raise ValueError(
462459
"Cannot register extractors called 'test', that is a reserved name")
463-
elif extractor_name.lower() == 'expected':
460+
if extractor_name.lower() == 'expected':
464461
raise ValueError(
465462
"Cannot register extractors called 'expected', that is a reserved name")
466-
elif extractor_name in EXTRACTORS:
463+
if extractor_name in EXTRACTORS:
467464
raise ValueError(
468465
"Cannot register an extractor name that already exists: {0}".format(extractor_name))
469466
EXTRACTORS[extractor_name] = parse_function
@@ -473,7 +470,7 @@ def register_test(test_name, test_function):
473470
""" Register a new one-argument test function """
474471
if not isinstance(test_name, str):
475472
raise TypeError("Cannot register a non-string test name")
476-
elif test_name in VALIDATOR_TESTS:
473+
if test_name in VALIDATOR_TESTS:
477474
raise ValueError(
478475
"Cannot register a test name that already exists: {0}".format(test_name))
479476
VALIDATOR_TESTS[test_name] = test_function

tests/content-test-include.yaml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
- include:
2+
- tests.content-test

tests/test_binding.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ def test_variables(self):
1919
""" Test bind/return of variables """
2020

2121
context = Context()
22+
context.variables = {}
2223
self.assertTrue(context.get_value('foo') is None)
2324
self.assertEqual(0, context.mod_count)
2425

tests/test_generators.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import types
44
import unittest
55

6+
import pytest
7+
68
from py3resttest import generators
79
from py3resttest.binding import Context
810

@@ -140,6 +142,8 @@ def test_parse_fixed_sequence(self):
140142
'values': vals}
141143
gen = generators.parse_generator(config)
142144
self.generator_basic_test(gen, lambda x: x in vals)
145+
self.assertRaises(ValueError, generators.parse_generator, {'type': 'fixed_sequence', 'values': []})
146+
self.assertRaises(ValueError, generators.parse_generator, {'type': 'fixed_sequence', 'values': {'x': 1}})
143147

144148
def test_factory_choice(self):
145149
""" Tests linear sequences """
@@ -155,6 +159,17 @@ def test_factory_choice(self):
155159
gen = generators.factory_choice_generator(vals)()
156160
self.generator_basic_test(gen, lambda x: x in vals)
157161

162+
with pytest.raises(ValueError) as e:
163+
gen = generators.parse_choice_generator({'values': []})()
164+
165+
def test_register_generator(self):
166+
167+
with pytest.raises(TypeError) as e:
168+
gen = generators.register_generator(1, lambda x: x)
169+
170+
with pytest.raises(ValueError) as e:
171+
gen = generators.register_generator('env_string', lambda x: x)
172+
158173
def test_parse_choice_generatpr(self):
159174
vals = ['moobie', 'moby', 'moo']
160175
config = {'type': 'choice',

tests/test_testcase.py

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,31 @@ def test_config(self):
115115
}
116116
]
117117
self.assertRaises(TypeError, config_object.parse, config_list)
118+
test_case = TestCase('https://api.github.com', None, None)
119+
testcase_list = [
120+
{'name': 'Get github user abihijo89-to'},
121+
{'url': '/search/users?q=abhijo89-to'},
122+
{'method': 'GET'},
123+
{'headers': {'Content-Type': 'application/json'}},
124+
125+
]
126+
127+
test_case.parse(testcase_list)
128+
test_case.run()
129+
self.assertTrue(test_case.is_passed)
130+
131+
def test_include(self):
132+
with open("%s/content-test-include.yaml" % current_module_path.parent, 'r') as f:
133+
test_dict_list = yaml.safe_load(f.read())
134+
135+
ts = TestSet()
136+
ts.parse('', test_dict_list)
137+
self.assertEqual(1, len(ts.test_group_list_dict))
138+
ts.parse('', [{'url': 'http://google.com'}])
139+
self.assertEqual(1, len(ts.test_group_list_dict))
140+
ts.parse('', [{'import': 'tests/content-test.yaml'}])
141+
self.assertEqual(1, len(ts.test_group_list_dict))
142+
118143

119-
if __name__ == '__main__':
120-
unittest.main()
144+
if __name__ == '__main__':
145+
unittest.main()

0 commit comments

Comments
 (0)