Last active
June 3, 2019 18:23
-
-
Save cueo/da1ca49e92679ac49f808c7ef594e75b to your computer and use it in GitHub Desktop.
Remove unnecessary stubbing UnnecessaryStubbingException automatically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
# Before running the script, we need to generate the list of unnecessary stubs. | |
# For this, run mvn clean install and copy paste the output here: https://regexr.com/4etmi | |
# This will extract all the stubs that should be removed. | |
# Create a file called: unnecessary-stubbings.txt in the same folder as this script. | |
# Paste the output from regexr into this file and run the below script. | |
''' | |
import json | |
import os | |
import sys | |
from collections import defaultdict | |
# file with list of unnecessary stubbings | |
raw_file_name = 'unnecessary-stubbings.txt' | |
json_file_name = 'unnecessary-stubbings.json' | |
if not os.path.exists(json_file_name): | |
unnecessary_stubs_dict = defaultdict(list) | |
print('Stubbings json not found. Generating the json.') | |
with open(raw_file_name, 'r') as f: | |
for line in f.readlines(): | |
classname, line = line.strip().split(':') | |
# using negative to sort in descending order | |
unnecessary_stubs_dict[classname].append(int(line)) | |
print('Writing json to file=' + json_file_name, 'length=' + str(len(unnecessary_stubs_dict))) | |
with open(json_file_name, 'w') as f: | |
json.dump(unnecessary_stubs_dict, f, indent=2) | |
with open(json_file_name, 'r') as f: | |
unnecessary_stubs_dict = json.load(f) | |
# change this value | |
test_dir = '/path/to/application/src/test/java/com/cueo' | |
for r, d, files in os.walk(test_dir): | |
for f in files: | |
if f in unnecessary_stubs_dict: | |
print('Class=' + f, 'has total=' + str(len(unnecessary_stubs_dict[f])), 'unnecessary stubbings!') | |
text = '' | |
filepath = os.path.join(r, f) | |
with open(filepath, 'r') as fp: | |
i = 0 | |
for line in fp.readlines(): | |
i += 1 | |
if i not in unnecessary_stubs_dict[f]: | |
text += line | |
else: | |
if not line.strip().endswith(';'): | |
# print(line) | |
unnecessary_stubs_dict[f].append(i+1) | |
text += '\n' | |
with open(filepath, 'w') as fp: | |
fp.write(text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment