Skip to content

Commit e09e90b

Browse files
committed
Perform code optimization
1 parent 180902f commit e09e90b

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

47 files changed

+4042
-2572
lines changed

docs/prepare.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def process_file(file_name):
5050
content = content.replace("(" + md_path + ")", normalize_path(path))
5151

5252
for url in urls:
53-
path = url[len(GITHUB_URL):]
53+
path = url[len(GITHUB_URL) :] # noqa: E203
5454
paths.add(path)
5555
content = content.replace(
5656
url, normalize_path(os.path.relpath(path, directory))
@@ -83,9 +83,9 @@ def main(*args, **kwargs):
8383
process_file(file_)
8484

8585
readme_file = "./docs/README.md"
86-
with open(readme_file, 'r', encoding='utf-8') as f:
86+
with open(readme_file, "r", encoding="utf-8") as f:
8787
all_code = f.read()
88-
code_lines = all_code.split('\n')
88+
code_lines = all_code.split("\n")
8989

9090
changed = False
9191
seleniumbase_lines = []
@@ -99,24 +99,27 @@ def main(*args, **kwargs):
9999
r'<p align="center"><div align="center">'
100100
r'<a href="https://github.com/seleniumbase/SeleniumBase">'
101101
r'<img src="https://img.shields.io/badge/'
102-
r'✅%20💛%20View%20Code-on%20GitHub%20🌎%20🚀'
102+
r"✅%20💛%20View%20Code-on%20GitHub%20🌎%20🚀"
103103
r'-02A79E.svg" alt="SeleniumBase on GitHub" />'
104-
r'</a></div></p>')
104+
r"</a></div></p>"
105+
)
105106
if "<!-- SeleniumBase Header1 -->" in line:
106107
changed = True
107108
line = (
108109
'<section align="center"><div align="center">'
109-
'<h2>✅ Reliable Browser Testing</h2>'
110-
'</div></section>')
110+
"<h2>✅ Reliable Browser Testing</h2>"
111+
"</div></section>"
112+
)
111113
if "<!-- SeleniumBase Docs -->" in line:
112114
changed = True
113115
line = (
114116
'<h2><img src="https://seleniumbase.io/img/sb_icon.png" '
115117
'title="SeleniumBase" width="20" /> SeleniumBase Docs '
116118
'<img src="https://seleniumbase.io/img/sb_icon.png" '
117-
'title="SeleniumBase" width="20" /></h2>')
119+
'title="SeleniumBase" width="20" /></h2>'
120+
)
118121
seleniumbase_lines.append(line)
119122
if changed:
120-
out_file = codecs.open(readme_file, "w+", encoding='utf-8')
123+
out_file = codecs.open(readme_file, "w+", encoding="utf-8")
121124
out_file.writelines("\r\n".join(seleniumbase_lines))
122125
out_file.close()

integrations/brython/index.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22

33

44
def setup_page():
5-
document['topHeader'].textContent = "Brython Examples:"
5+
document["topHeader"].textContent = "Brython Examples:"

integrations/node_js/my_first_test.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33

44
class MyTestClass(BaseCase):
5-
65
def test_basics(self):
76
url = "https://store.xkcd.com/collections/posters"
87
self.open(url)

integrations/node_js/test_demo_site.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33

44
class MyTestClass(BaseCase):
5-
65
def test_demo_site(self):
76
self.open("https://seleniumbase.io/demo_page")
87

seleniumbase/common/decorators.py

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,14 @@
99

1010

1111
def retry_on_exception(tries=6, delay=1, backoff=2, max_delay=32):
12-
'''
12+
"""
1313
Decorator for implementing exponential backoff for retrying on failures.
1414
1515
tries: Max number of tries to execute the wrapped function before failing.
1616
delay: Delay time in seconds before the FIRST retry.
1717
backoff: Multiplier to extend the initial delay by for each retry.
1818
max_delay: Max time in seconds to wait between retries.
19-
'''
19+
"""
2020
tries = math.floor(tries)
2121
if tries < 1:
2222
raise ValueError('"tries" must be greater than or equal to 1.')
@@ -37,21 +37,24 @@ def function_to_retry(*args, **kwargs):
3737
except Exception as e:
3838
if local_delay > max_delay:
3939
local_delay = max_delay
40-
logging.exception('%s: Retrying in %d seconds...'
41-
% (str(e), local_delay))
40+
logging.exception(
41+
"%s: Retrying in %d seconds..." % (str(e), local_delay)
42+
)
4243
time.sleep(local_delay)
4344
local_tries -= 1
4445
local_delay *= backoff
4546
return func(*args, **kwargs)
47+
4648
return function_to_retry
49+
4750
return decorated_function_with_retry
4851

4952

5053
def rate_limited(max_per_second):
51-
""" This decorator limits how often a method can get called in a second.
52-
If the limit is exceeded, the call will be held in a queue until
53-
enough time has passed.
54-
Useful when trying to avoid overloading a system with rapid calls. """
54+
"""This decorator limits how often a method can get called in a second.
55+
If the limit is exceeded, the call will be held in a queue until
56+
enough time has passed.
57+
Useful when trying to avoid overloading a system with rapid calls."""
5558
min_interval = 1.0 / float(max_per_second)
5659

5760
def decorate(func):
@@ -76,33 +79,37 @@ def rate_limited_function(*args, **kargs):
7679
finally:
7780
rate_lock.release()
7881
return func(*args, **kargs)
82+
7983
return rate_limited_function
84+
8085
return decorate
8186

8287

8388
def deprecated(message=None):
84-
""" This decorator marks methods as deprecated.
85-
A warning is displayed if the method is called. """
89+
"""This decorator marks methods as deprecated.
90+
A warning is displayed if the method is called."""
8691

8792
def decorated_method_to_deprecate(func):
8893
if inspect.isclass(func):
8994
# Handle a deprecated class differently from a deprecated method
9095
msg = "Class {}() is DEPRECATED! *** ".format(func.__name__)
9196
if message:
9297
msg += "<> %s <>" % message
93-
warnings.simplefilter('always', DeprecationWarning) # See Warnings
98+
warnings.simplefilter("always", DeprecationWarning) # See Warnings
9499
warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
95-
warnings.simplefilter('default', DeprecationWarning) # Set Default
100+
warnings.simplefilter("default", DeprecationWarning) # Set Default
96101
return func
97102

98103
@wraps(func)
99104
def new_func(*args, **kwargs):
100105
msg = "Method {}() is DEPRECATED! *** ".format(func.__name__)
101106
if message:
102107
msg += "<> %s <>" % message
103-
warnings.simplefilter('always', DeprecationWarning) # See Warnings
108+
warnings.simplefilter("always", DeprecationWarning) # See Warnings
104109
warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
105-
warnings.simplefilter('default', DeprecationWarning) # Set Default
110+
warnings.simplefilter("default", DeprecationWarning) # Set Default
106111
return func(*args, **kwargs)
112+
107113
return new_func
114+
108115
return decorated_method_to_deprecate

seleniumbase/common/encryption.py

Lines changed: 42 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# -\*- coding: utf-8 -\*-
22

3-
''' This is mainly for string obfuscation. '''
3+
""" This is mainly for string obfuscation. """
44

55
import base64
66
import codecs
@@ -13,16 +13,17 @@ def str_xor(string, key):
1313
raise Exception("2nd arg of str_xor() must be a string of length > 0!")
1414
if len(string) > len(key):
1515
difference = len(string) - len(key)
16-
key = key + (
17-
((difference / len(key)) * key) + key)
16+
key = key + (((difference / len(key)) * key) + key)
1817
result = None
1918
try:
2019
result = "".join(
21-
[chr(ord(c1) ^ ord(c2)) for (c1, c2) in zip(string, key)])
20+
[chr(ord(c1) ^ ord(c2)) for (c1, c2) in zip(string, key)]
21+
)
2222
except Exception:
23-
string = string.decode('utf-8')
23+
string = string.decode("utf-8")
2424
result = "".join(
25-
[chr(ord(c1) ^ ord(c2)) for (c1, c2) in zip(string, key)])
25+
[chr(ord(c1) ^ ord(c2)) for (c1, c2) in zip(string, key)]
26+
)
2627
return result
2728

2829

@@ -31,22 +32,22 @@ def is_obfuscated(string):
3132
# Obfuscated strings have a common predefined start token and end token.
3233
start_token = settings.OBFUSCATION_START_TOKEN
3334
end_token = settings.OBFUSCATION_END_TOKEN
34-
return (string.startswith(start_token) and string.endswith(end_token))
35+
return string.startswith(start_token) and string.endswith(end_token)
3536

3637

3738
def shuffle_string(string):
3839
if len(string) < 2:
3940
return string
40-
return (string[1::2] + string[::2])
41+
return string[1::2] + string[::2]
4142

4243

4344
def reverse_shuffle_string(string):
4445
if len(string) < 2:
4546
return string
4647
new_string = ""
47-
odd = (len(string) % 2 == 1)
48-
part1 = string[:int(len(string) / 2):1]
49-
part2 = string[int(len(string) / 2)::1]
48+
odd = len(string) % 2 == 1
49+
part1 = string[: int(len(string) / 2) : 1] # noqa: E203
50+
part2 = string[int(len(string) / 2) :: 1] # noqa: E203
5051
for c in range(len(part1)):
5152
new_string += part2[c]
5253
new_string += part1[c]
@@ -81,7 +82,7 @@ def ord_string_sum(string):
8182
for c in string:
8283
count += ord(c)
8384
except Exception:
84-
string = string.decode('utf-8')
85+
string = string.decode("utf-8")
8586
for c in string:
8687
count += ord(c)
8788
return count
@@ -97,14 +98,18 @@ def decrypt(string):
9798
already_encrypted = False
9899
if is_obfuscated(string):
99100
already_encrypted = True
100-
string = string[len(start_token):-len(end_token)]
101+
string = string[len(start_token) : -len(end_token)] # noqa: E203
101102
string = base64.b64decode(codecs.encode(string))
102103
# Obfuscate the key used for string obfuscation
103-
hd1 = hashlib.sha256(str(encryption_key).encode('utf-8')).hexdigest()
104-
hd2 = hashlib.sha256(str(encryption_key[::-1]).encode('utf-8')).hexdigest()
104+
hd1 = hashlib.sha256(str(encryption_key).encode("utf-8")).hexdigest()
105+
hd2 = hashlib.sha256(str(encryption_key[::-1]).encode("utf-8")).hexdigest()
105106
b64_key = base64.b64encode(codecs.encode(encryption_key * 8))
106-
xor_key = "".join([chr(ord(str(c3)) - int(c1, 16) - int(c2, 16)) for (
107-
c1, c2, c3) in zip(hd1, hd2, b64_key.decode("utf-8"))])
107+
xor_key = "".join(
108+
[
109+
chr(ord(str(c3)) - int(c1, 16) - int(c2, 16))
110+
for (c1, c2, c3) in zip(hd1, hd2, b64_key.decode("utf-8"))
111+
]
112+
)
108113
xor_key = blend_strings(xor_key, encryption_key)
109114
if len(xor_key) % 7 == 0:
110115
xor_key = xor_key + encryption_key[-1]
@@ -118,18 +123,30 @@ def decrypt(string):
118123
rem4 = (len(string) + ord_string_sum(string)) % 2
119124
if len(string) % 2 != 0:
120125
if rem3 == 1:
121-
string = (chr(ord(string[-1]) - 5 - rem1) + string + ''
122-
'' + chr(ord(string[-1]) - 13 - rem1))
126+
string = (
127+
chr(ord(string[-1]) - 5 - rem1)
128+
+ string
129+
+ chr(ord(string[-1]) - 13 - rem1)
130+
)
123131
else:
124-
string = (chr(ord(string[-1]) - 11 - rem1) + string + ''
125-
'' + chr(ord(string[-1]) - 23 - rem1))
132+
string = (
133+
chr(ord(string[-1]) - 11 - rem1)
134+
+ string
135+
+ chr(ord(string[-1]) - 23 - rem1)
136+
)
126137
elif len(string) > 1:
127138
if rem4 == 1:
128-
string = (chr(ord(string[0]) - 19 + rem2) + string + ''
129-
'' + chr(ord(string[0]) - 7 - rem2))
139+
string = (
140+
chr(ord(string[0]) - 19 + rem2)
141+
+ string
142+
+ chr(ord(string[0]) - 7 - rem2)
143+
)
130144
else:
131-
string = (chr(ord(string[0]) - 26 + rem2) + string + ''
132-
'' + chr(ord(string[0]) - 12 - rem2))
145+
string = (
146+
chr(ord(string[0]) - 26 + rem2)
147+
+ string
148+
+ chr(ord(string[0]) - 12 - rem2)
149+
)
133150
rem5 = (len(string) + ord_string_sum(string)) % 23
134151
string = rotate(string, rem5)
135152
result = str_xor(shuffle_string(string)[::-1], xor_key)

seleniumbase/common/obfuscate.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
def main():
1616
try:
17-
while(1):
17+
while 1:
1818
print("\nEnter password to obfuscate: (CTRL+C to exit)")
1919
password = getpass.getpass()
2020
print("Verify password:")

seleniumbase/common/unobfuscate.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,10 @@ def main():
2020
# Python 2 has the raw_input() method. Python 3 does not.
2121
input_method = raw_input # noqa: ignore=F821
2222
try:
23-
while(1):
23+
while 1:
2424
code = input_method(
25-
'\nEnter obfuscated/encrypted string: (CTRL+C to exit):\n')
25+
"\nEnter obfuscated/encrypted string: (CTRL+C to exit):\n"
26+
)
2627
print("\nHere is the unobfuscated string/password:")
2728
time.sleep(0.07)
2829
print(encryption.decrypt(code))

seleniumbase/console_scripts/logo_helper.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,13 @@
44

55
import colorama
66

7-
r'''
7+
r"""
88
______ __ _ ____
99
/ ____/__ / /__ ____ (_)_ ______ ___ / _ \____ ________
1010
\__ \/ _ \/ / _ \/ __ \/ / / / / __ `__ \/ /_) / __ \/ ___/ _ \
1111
___/ / __/ / __/ / / / / /_/ / / / / / / /_) / (_/ /__ / __/
1212
/____/\___/_/\___/_/ /_/_/\__,_/_/ /_/ /_/_____/\__,_/____/\___/
13-
'''
13+
"""
1414

1515

1616
def get_seleniumbase_logo():

0 commit comments

Comments
 (0)