Skip to content

Commit e2a3ae7

Browse files
authored
Enable test coverage report according to README (#399)
Signed-off-by: sschulz92 <[email protected]>
1 parent 46e0873 commit e2a3ae7

File tree

7 files changed

+43
-35
lines changed

7 files changed

+43
-35
lines changed

build.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -102,13 +102,17 @@ def copy(src, dest):
102102
"""
103103

104104

105-
def run_tests():
105+
def run_tests() -> int:
106106
pp = "PYTHONPATH"
107107
os.environ[pp] = str(ROOT_DIR)
108108
exit_code = 0
109-
for file_name_path in glob.glob(f"{ROOT_DIR}/tests/**/test_*.py", recursive=True):
110-
exit_code = call([sys.executable, file_name_path]
111-
) if exit_code == 0 else exit_code
109+
all_python_test_files = glob.glob(f"{ROOT_DIR}/tests/**/test_*.py", recursive=True)
110+
for i, file_name_path in enumerate(all_python_test_files):
111+
command = ["coverage", "run", file_name_path]
112+
exit_code = call(command) if exit_code == 0 else exit_code
113+
# Keep coverage files
114+
os.rename(".coverage", f".coverage.{i}")
115+
call(["coverage", "combine"])
112116
return exit_code
113117

114118

getgauge/exceptions.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
class MultipleImplementationFoundException(Exception):
2+
def __init__(self, message):
3+
super().__init__(message)
4+
self.message = message

getgauge/impl_loader.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
import importlib
22
import inspect
33
import json
4+
import os
45
import re
56
import shutil
67
import sys
78
import traceback
8-
from os import path
99
from contextlib import contextmanager
10+
from os import path
1011

1112
from getgauge import logger
1213
from getgauge.registry import registry
13-
from getgauge.util import *
14+
from getgauge.util import get_project_root, get_step_impl_dirs
1415

1516
project_root = get_project_root()
1617
impl_dirs = get_step_impl_dirs()
@@ -50,9 +51,8 @@ def copy_skel_files():
5051
shutil.copytree(os.path.join(SKEL,path.basename(impl_dirs[0]) ), impl_dirs[0])
5152
logger.info('create {}'.format(os.path.join(env_dir, PYTHON_PROPERTIES)))
5253
shutil.copy(os.path.join(SKEL, PYTHON_PROPERTIES), env_dir)
53-
f = open(requirements_file, 'w')
54-
f.write('getgauge==' + _get_version())
55-
f.close()
54+
with open(requirements_file, 'w', encoding="utf-8") as f:
55+
f.write('getgauge==' + _get_version())
5656
except:
5757
logger.fatal('Exception occurred while copying skel files.\n{}.'.format(traceback.format_exc()))
5858

@@ -95,10 +95,10 @@ def _import_file(base_dir, file_path):
9595
except:
9696
logger.fatal('Exception occurred while loading step implementations from file: {}.\n{}'.format(rel_path, traceback.format_exc()))
9797

98-
# Inject instace in each class method (hook/step)
98+
# Inject instance in each class method (hook/step)
9999
def update_step_registry_with_class(instance, file_path):
100100
# Resolve the absolute path from relative path
101-
file_path = os.path.abspath(file_path) if '..' in file_path else file_path
101+
file_path = os.path.abspath(file_path) if str(file_path).startswith("..") else file_path
102102
method_list = registry.get_all_methods_in(file_path)
103103
for info in method_list:
104104
class_methods = [x[0] for x in inspect.getmembers(instance, inspect.ismethod)]
@@ -107,13 +107,14 @@ def update_step_registry_with_class(instance, file_path):
107107
return method_list
108108

109109
def _get_version():
110-
json_data = open(PLUGIN_JSON).read()
111-
data = json.loads(json_data)
110+
with open(PLUGIN_JSON, "r", encoding="utf-8") as json_data:
111+
data = json.loads(json_data.read())
112112
return data[VERSION]
113113

114-
def _has_methods_with_gauge_decoratores(klass):
115-
foo = r"@(step|before_suite|after_suite|before_scenario|after_scenario|before_spec|after_spec|before_step|after_step|screenshot|custom_screen_grabber)"
114+
def _has_methods_with_gauge_decoratores(klass) -> bool:
115+
gauge_decorator_pattern = r"@(step|before_suite|after_suite|before_scenario|after_scenario|before_spec|after_spec|before_step|after_step|screenshot|custom_screen_grabber)"
116116
sourcelines = inspect.getsourcelines(klass)[0]
117-
for i,line in enumerate(sourcelines):
118-
if re.match(foo, line.strip()) != None:
117+
for line in sourcelines:
118+
if re.match(gauge_decorator_pattern, line.strip()) is not None:
119119
return True
120+
return False

getgauge/processor.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
1-
import os
2-
import traceback
3-
from os import environ, path
4-
from threading import Timer
1+
from os import path
52

6-
from getgauge import logger
73
from getgauge.executor import (create_execution_status_response,
84
execute_method, run_hook)
95
from getgauge.impl_loader import load_impls
@@ -17,6 +13,7 @@
1713
read_file_contents)
1814
from getgauge.validator import validate_step
1915

16+
2017
def process_validate_step_request(request):
2118
return validate_step(request)
2219

@@ -47,7 +44,7 @@ def process_refactor_request(request):
4744
refactor_step(request, response)
4845
except Exception as e:
4946
response.success = False
50-
response.error = 'Reason: {}'.format(e.__str__())
47+
response.error = f"Reason: {e}"
5148
return response
5249

5350

@@ -175,7 +172,7 @@ def _load_from_disk(file_path):
175172
def process_cache_file_request(request):
176173
file = request.filePath
177174
status = request.status
178-
if status == CacheFileRequest.CHANGED or status == CacheFileRequest.OPENED:
175+
if status in [CacheFileRequest.CHANGED, CacheFileRequest.OPENED]:
179176
reload_steps(file, request.content)
180177
elif status == CacheFileRequest.CREATED:
181178
if not registry.is_file_cached(file):
@@ -225,15 +222,15 @@ def process_stub_impl_request(request):
225222
prefix = "from getgauge.python import step\n"
226223
span = Span(**{'start': 0, 'startChar': 0, 'end': 0, 'endChar': 0})
227224
codes = [prefix] + codes[:]
228-
textDiffs = [TextDiff(**{'span': span, 'content': '\n'.join(codes)})]
225+
text_diffs = [TextDiff(**{'span': span, 'content': '\n'.join(codes)})]
229226
response.filePath = file_name
230-
response.textDiffs.extend(textDiffs)
227+
response.textDiffs.extend(text_diffs)
231228
return response
232229

233230

234231
def process_glob_pattern_request(request):
235232
res = ImplementationFileGlobPatternResponse()
236-
globPatterns = [["{}/**/*.py".format(d)] for d in get_step_impl_dirs()]
233+
glob_patterns = [[f"{d}/**/*.py"] for d in get_step_impl_dirs()]
237234
res.globPatterns.extend(
238-
[item for sublist in globPatterns for item in sublist])
235+
[item for sublist in glob_patterns for item in sublist])
239236
return res

getgauge/refactor.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
1-
from getgauge.messages.messages_pb2 import RefactorResponse, TextDiff
1+
from getgauge.exceptions import MultipleImplementationFoundException
2+
from getgauge.messages.messages_pb2 import TextDiff
23
from getgauge.messages.spec_pb2 import Span
34
from getgauge.parser import Parser
45
from getgauge.registry import registry
56

67

78
def refactor_step(request, response):
89
if registry.has_multiple_impls(request.oldStepValue.stepValue):
9-
raise Exception('Multiple Implementation found for `{}`'.format(
10+
raise MultipleImplementationFoundException('Multiple Implementation found for `{}`'.format(
1011
request.oldStepValue.parameterizedStepValue
1112
))
1213
info = registry.get_info_for(request.oldStepValue.stepValue)
@@ -18,7 +19,7 @@ def refactor_step(request, response):
1819
)
1920
content = impl_file.get_code()
2021
if request.saveChanges:
21-
with open(info.file_name, 'w') as f:
22+
with open(info.file_name, 'w', encoding="utf-8") as f:
2223
f.write(content)
2324
response.success = True
2425
response.filesChanged.append(info.file_name)
@@ -31,6 +32,6 @@ def refactor_step(request, response):
3132

3233
def _new_parameter_positions(request):
3334
moved_pos = list(range(len(request.paramPositions)))
34-
for index, position in enumerate(request.paramPositions):
35+
for position in request.paramPositions:
3536
moved_pos[position.newPosition] = position.oldPosition
3637
return moved_pos

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,4 @@ twine==5.1.1
3131
urllib3==2.2.3
3232
webencodings==0.5.1
3333
zipp==3.20.2
34+
coverage==7.6.1

tests/test_impl_loader.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
import os
22
import unittest
33

4-
from test_relative_import.relative_import_class import Sample
54
from getgauge.impl_loader import update_step_registry_with_class
5+
from test_relative_import.relative_import_class import Sample
66

77

88
class ImplLoaderTest(unittest.TestCase):
99
def setUp(self):
1010
self.relative_file_path = os.path.join('..', 'test_relative_import', 'relative_import_class.py')
1111

12-
def test_update_step_resgistry_with_class(self):
12+
def test_update_step_registry_with_class(self):
1313
curr_dir = os.getcwd()
1414
os.chdir('tests')
1515
method_list = update_step_registry_with_class(Sample(), self.relative_file_path)
@@ -18,6 +18,6 @@ def test_update_step_resgistry_with_class(self):
1818
"Greet <name> from outside the class"],
1919
[method.step_text for method in method_list])
2020

21-
21+
2222
if __name__ == '__main__':
2323
unittest.main()

0 commit comments

Comments
 (0)