Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions misc/abandoned_roman_numerals_example/rome.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
ROMAN_NUMERALS = ('I', 'V', 'X')
def add(augend, addend):
if not isinstance(augend, basestring) or not isinstance(addend, basestring):
if not (isinstance(augend, basestring) and isinstance(addend, basestring)):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function add refactored with the following changes:

  • Inline variable that is only used once
  • Simplify logical expression

raise ValueError

simple_augend = augend.replace('IV', 'IIII')
Expand All @@ -13,6 +13,10 @@ def add(augend, addend):

ordered_sum = ''.join(reversed(sorted(simple_sum)))

canonicalised_sum = ordered_sum.replace('IIIII', 'V').replace('IIII', 'IV').replace('VV', 'X').replace('VIV', 'IX')
return canonicalised_sum
return (
ordered_sum.replace('IIIII', 'V')
.replace('IIII', 'IV')
.replace('VV', 'X')
.replace('VIV', 'IX')
)

20 changes: 11 additions & 9 deletions misc/get_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def main():
for commit in commits:
checkout_commit(commit.hash)
all_wordcounts[commit] = get_wordcounts()
filenames.update(set(wc.filename for wc in all_wordcounts[commit]))
filenames.update({wc.filename for wc in all_wordcounts[commit]})
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:

  • Merge dictionary assignment with declaration
  • Replace list(), dict() or set() with comprehension


with open(os.path.join(BOOK_ROOT, 'wordcounts.tsv'), 'w') as csvfile:
fieldnames = ['date.{}'.format(thing) for thing in ['year', 'month', 'day', 'hour']]
Expand All @@ -58,14 +58,16 @@ def main():
writer = csv.DictWriter(csvfile, fieldnames, dialect="excel-tab")
writer.writeheader()
for commit, wordcounts in all_wordcounts.items():
row = {}
row['hash'] = commit.hash
row['subject'] = commit.subject
row['date'] = ''
row['date.year'] = commit.date.year
row['date.month'] = commit.date.month
row['date.day'] = commit.date.day
row['date.hour'] = commit.date.hour
row = {
'hash': commit.hash,
'subject': commit.subject,
'date': '',
'date.year': commit.date.year,
'date.month': commit.date.month,
'date.day': commit.date.day,
'date.hour': commit.date.hour,
}

for wordcount in wordcounts:
row[wordcount.filename + " (words)"] = wordcount.words
row[wordcount.filename + " (lines)"] = wordcount.lines
Expand Down
5 changes: 1 addition & 4 deletions misc/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@ def get_data_from_csv():
for field in reader.fieldnames:
if 'words' in field:
val = row[field]
if val:
fixed_row[field] = val
else:
fixed_row[field] = 0
fixed_row[field] = val if val else 0
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_data_from_csv refactored with the following changes:

  • Replace if statement with if expression

date = datetime(int(row['date.year']), int(row['date.month']), int(row['date.day']), int(row['date.hour']),)
fixed_row['date'] = date
data.append(fixed_row)
Expand Down
6 changes: 1 addition & 5 deletions tests/book_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,7 @@ def parse_output(listing):

outputs = []
output_before = listing.text
if output_before:
output_before = fix_newlines(output_before.strip())
else:
output_before = ''

output_before = fix_newlines(output_before.strip()) if output_before else ''
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function parse_output refactored with the following changes:

  • Replace if statement with if expression

for command in commands:
if '$' in output_before and '\n' in output_before:
last_cr = output_before.rfind('\n')
Expand Down
45 changes: 16 additions & 29 deletions tests/book_tester.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@

def contains(inseq, subseq):
return any(
inseq[pos:pos + len(subseq)] == subseq
for pos in range(0, len(inseq) - len(subseq) + 1)
inseq[pos : pos + len(subseq)] == subseq
for pos in range(len(inseq) - len(subseq) + 1)
Comment on lines -45 to +46
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function contains refactored with the following changes:

  • Replace range(0, x) with range(x)

)


Expand Down Expand Up @@ -73,12 +73,11 @@ def strip_mock_ids(output):
r"Mock name='\1' id='XX'>",
output,
)
strip_all_mocks = re.sub(
return re.sub(
r"Mock id='(\d+)'>",
r"Mock id='XX'>",
strip_mocks_with_names,
)
return strip_all_mocks
Comment on lines -76 to -81
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function strip_mock_ids refactored with the following changes:

  • Inline variable that is only used once


def strip_object_ids(output):
return re.sub('0x([0-9a-f]+)>', '0xXX>', output)
Expand Down Expand Up @@ -106,13 +105,12 @@ def strip_git_hashes(output):
r"index XXXXXXX\.\.XXXXXXX 100644",
output,
)
fixed_commit_numbers = re.sub(
return re.sub(
r"^[a-f0-9]{7} ",
r"XXXXXXX ",
fixed_indexes,
flags=re.MULTILINE,
)
return fixed_commit_numbers
Comment on lines -109 to -115
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function strip_git_hashes refactored with the following changes:

  • Inline variable that is only used once



def strip_callouts(output):
Expand All @@ -122,13 +120,12 @@ def strip_callouts(output):
output,
flags=re.MULTILINE,
)
minus_new_callouts = re.sub(
return re.sub(
r"^(.+) \(\d+\)$",
r"\1",
minus_old_callouts,
flags=re.MULTILINE,
)
return minus_new_callouts
Comment on lines -125 to -131
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function strip_callouts refactored with the following changes:

  • Inline variable that is only used once



def standardise_library_paths(output):
Expand Down Expand Up @@ -527,9 +524,12 @@ def assert_console_output_correct(self, actual, expected, ls=False):
else:
self.assertLineIn(line, [l.strip() for l in actual_lines])

if len(expected_lines) > 4 and '[...' not in expected_fixed:
if expected.type != 'qunit output':
self.assertMultiLineEqual(actual_fixed.strip(), expected_fixed.strip())
if (
len(expected_lines) > 4
and '[...' not in expected_fixed
and expected.type != 'qunit output'
):
self.assertMultiLineEqual(actual_fixed.strip(), expected_fixed.strip())
Comment on lines -530 to +532
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ChapterTest.assert_console_output_correct refactored with the following changes:

  • Merge nested if conditions


expected.was_checked = True

Expand Down Expand Up @@ -614,10 +614,6 @@ def unset_PYTHONDONTWRITEBYTECODE(self):

def _strip_out_any_pycs(self):
return
self.sourcetree.run_command(
r"find . -name __pycache__ -exec rm -rf {} \;",
ignore_errors=True
)
Comment on lines -617 to -620
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ChapterTest._strip_out_any_pycs refactored with the following changes:

  • Remove unreachable code



def run_test_and_check_result(self, bdd=False):
Expand Down Expand Up @@ -654,12 +650,6 @@ def run_js_tests(self, tests_path):
print('fixed phantomjs output', output)
return output

os.chmod(SLIMERJS_BINARY, os.stat(SLIMERJS_BINARY).st_mode | stat.S_IXUSR)
os.environ['SLIMERJSLAUNCHER'] = '/usr/bin/firefox'
return subprocess.check_output(
['xvfb-run', '--auto-servernum', SLIMERJS_BINARY, PHANTOMJS_RUNNER, tests_path]
).decode()
Comment on lines 652 to -661
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ChapterTest.run_js_tests refactored with the following changes:

  • Remove unreachable code



def check_qunit_output(self, expected_output):
lists_tests = os.path.join(
Expand Down Expand Up @@ -735,9 +725,10 @@ def check_diff_or_status(self, pos):
'diff' in self.listings[pos] or 'status' in self.listings[pos]
)
git_output = self.run_command(self.listings[pos])
if not any('/' + l in git_output for l in LIKELY_FILES):
if not any(f in git_output for f in ('lists/', 'functional_tests.py')):
self.fail('no likely files in diff output %s' % (git_output,))
if all('/' + l not in git_output for l in LIKELY_FILES) and all(
f not in git_output for f in ('lists/', 'functional_tests.py')
):
self.fail('no likely files in diff output %s' % (git_output,))
Comment on lines -738 to +731
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ChapterTest.check_diff_or_status refactored with the following changes:

  • Merge nested if conditions
  • Simplify inverted any() and all() calls

self.pos += 1
comment = self.listings[pos + 1]
if comment.skip:
Expand Down Expand Up @@ -823,11 +814,7 @@ def run_interactive_manage_py(self, listing):
expected_output = output_before
output_after = None
next_output = None
if user_input == '2':
ignore_errors = True
else:
ignore_errors = False

ignore_errors = True if user_input == '2' else False
Comment on lines -826 to +817
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ChapterTest.run_interactive_manage_py refactored with the following changes:

  • Replace if statement with if expression

else:
user_input = None
expected_output = output_before
Expand Down
13 changes: 8 additions & 5 deletions tests/slimerjs-0.9.0/slimerjs.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def which(program):
if SLIMERJSLAUNCHER == "":
POSSIBLE_PATH = []

if sys.platform == "linux" or sys.platform == "linux2" or sys.platform == "darwin":
if sys.platform in ["linux", "linux2", "darwin"]:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 42-42 refactored with the following changes:

  • Replace multiple comparisons of same variable with in operator

POSSIBLE_PATH.append(os.path.join(SLIMERJS_PATH, "xulrunner", "xulrunner"))
path = which('firefox')
if path != None:
Expand Down Expand Up @@ -139,7 +139,7 @@ def showHelp():
"--reset-profile","--profile","--p","--createprofile","--profilemanager",
]
for arg in SYS_ARGS:
if arg == '--help' or arg == "-h":
if arg in ['--help', "-h"]:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 142-193 refactored with the following changes:

  • Merge extend into list assignment
  • Replace multiple comparisons of same variable with in operator

showHelp()
sys.exit(0)

Expand All @@ -165,8 +165,11 @@ def showHelp():
os.environ.data['__SLIMER_ARGS'] = string.join(SYS_ARGS,' ')

# launch slimerjs with firefox/xulrunner
SLCMD = [ SLIMERJSLAUNCHER ]
SLCMD.extend(["-app", os.path.join(SLIMERJS_PATH, "application.ini"), "-no-remote"])
SLCMD = [
SLIMERJSLAUNCHER,
*["-app", os.path.join(SLIMERJS_PATH, "application.ini"), "-no-remote"],
]

if sys.platform == "win32":
SLCMD.extend(["-attach-console"])
SLCMD.extend(PROFILE)
Expand All @@ -190,5 +193,5 @@ def showHelp():

if CREATE_TEMP:
shutil.rmtree(PROFILE_DIR)

sys.exit(exitCode)
9 changes: 4 additions & 5 deletions tests/source_updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,11 +174,10 @@ def find_first_nonimport_line(self):
except StopIteration:
return len(self.lines)
pos = self.lines.index(first_nonimport)
if self._import_nodes:
if pos < max(n.lineno for n in self._import_nodes):
raise SourceUpdateError('first nonimport (%s) was before end of imports (%s)' % (
first_nonimport, max(n.lineno for n in self._import_nodes))
)
if self._import_nodes and pos < max(n.lineno for n in self._import_nodes):
raise SourceUpdateError('first nonimport (%s) was before end of imports (%s)' % (
first_nonimport, max(n.lineno for n in self._import_nodes))
)
Comment on lines -177 to +180
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Source.find_first_nonimport_line refactored with the following changes:

  • Merge nested if conditions

return pos


Expand Down
17 changes: 8 additions & 9 deletions tests/sourcetree.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,17 @@ def from_diff(commit_info):
commit.all_lines = commit.info.split('\n')

commit.lines_to_add = [
l[1:] for l in commit.all_lines
if l.startswith('+') and
l[1:].strip() and
not l[1] == '+'
l[1:]
for l in commit.all_lines
if l.startswith('+') and l[1:].strip() and l[1] != '+'
]

commit.lines_to_remove = [
l[1:] for l in commit.all_lines
if l.startswith('-') and
l[1:].strip() and
not l[1] == '-'
l[1:]
for l in commit.all_lines
if l.startswith('-') and l[1:].strip() and l[1] != '-'
]

Comment on lines -33 to +43
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Commit.from_diff refactored with the following changes:

  • Simplify logical expression

commit.moved_lines = [
l for l in commit.lines_to_add if l in commit.lines_to_remove
]
Expand Down Expand Up @@ -130,7 +130,6 @@ def run_command(self, command, cwd=None, user_input=None, ignore_errors=False, s
print(output)
except io.BlockingIOError as e:
print(e)
pass
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function SourceTree.run_command refactored with the following changes:

  • Remove redundant pass statement

return output


Expand Down
4 changes: 2 additions & 2 deletions tests/test_book_tester.py
Original file line number Diff line number Diff line change
Expand Up @@ -641,8 +641,8 @@ def test_ignores_3_5_x_AssertionError_None_thing(self):
actual = "AssertionError"
expected = Output("AssertionError: None")
self.assert_console_output_correct(actual, expected)
actual2 = "AssertionError: something"
with self.assertRaises(AssertionError):
actual2 = "AssertionError: something"
Comment on lines -644 to +645
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AssertConsoleOutputCorrectTest.test_ignores_3_5_x_AssertionError_None_thing refactored with the following changes:

  • Move assignments closer to their usage

self.assert_console_output_correct(actual2, expected)


Expand All @@ -662,9 +662,9 @@ def test_ignores_localhost_server_port_5_digits(self):


def test_only_ignores_exactly_32_char_strings_no_whitespace(self):
actual = "qnslckvp2aga7tm6xuivyb0ob1akzzwl"
expected = Output("jvhzc8kj2mkh06xooqq9iciptead20qq")
with self.assertRaises(AssertionError):
actual = "qnslckvp2aga7tm6xuivyb0ob1akzzwl"
Comment on lines -665 to +667
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AssertConsoleOutputCorrectTest.test_only_ignores_exactly_32_char_strings_no_whitespace refactored with the following changes:

  • Move assignments closer to their usage

self.assert_console_output_correct(actual[:-1], expected[:-1])
self.assert_console_output_correct(actual + '1', expected + 'a')
self.assert_console_output_correct(' ' + actual, ' ' + expected)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_chapter_automate_deployment_with_fabric.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ def test_listings_and_commands_and_output(self):

self.start_with_checkout()

vm_restore = 'MAKING_END'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Chapter9cTest.test_listings_and_commands_and_output refactored with the following changes:

  • Move assignments closer to their usage

# hack fast-forward
skip = False
if skip:
Expand All @@ -31,6 +30,7 @@ def test_listings_and_commands_and_output(self):
))

if DO_SERVER_COMMANDS:
vm_restore = 'MAKING_END'
subprocess.check_call(['vagrant', 'snapshot', 'restore', vm_restore])

self.current_server_cd = '~/sites/superlists-staging.ottg.eu'
Expand Down
4 changes: 2 additions & 2 deletions tests/test_chapter_making_deployment_production_ready.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@ def test_listings_and_commands_and_output(self):
' && git reset --hard origin/chapter_making_deployment_production_ready',
)

vm_restore = 'MANUAL_END'

Comment on lines -43 to -44
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Chapter9bTest.test_listings_and_commands_and_output refactored with the following changes:

  • Move assignments closer to their usage

# hack fast-forward
skip = False
if skip:
Expand All @@ -51,6 +49,8 @@ def test_listings_and_commands_and_output(self):
))

if DO_SERVER_COMMANDS:
vm_restore = 'MANUAL_END'

subprocess.check_call(['vagrant', 'snapshot', 'restore', vm_restore])

self.current_server_cd = '~/sites/$SITENAME'
Expand Down
4 changes: 2 additions & 2 deletions tests/test_chapter_server_side_debugging.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ def test_listings_and_commands_and_output(self):
self.start_with_checkout()
self.prep_database()

vm_restore = 'FABRIC_END'

Comment on lines -38 to -39
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Chapter18Test.test_listings_and_commands_and_output refactored with the following changes:

  • Move assignments closer to their usage

# hack fast-forward
skip = False
if skip:
Expand All @@ -46,6 +44,8 @@ def test_listings_and_commands_and_output(self):
))

if DO_SERVER_COMMANDS:
vm_restore = 'FABRIC_END'

subprocess.check_call(['vagrant', 'snapshot', 'restore', vm_restore])

while self.pos < len(self.listings):
Expand Down
6 changes: 3 additions & 3 deletions tests/test_source_updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -644,7 +644,7 @@ def test_finding_start_line(self):
assert source.find_start_line(['bla bla', 'whatever']) == 3
assert source.find_start_line(['indented', 'whatever']) == 4
assert source.find_start_line([' indented', 'whatever']) == 4
assert source.find_start_line(['no such line', 'whatever']) == None
assert source.find_start_line(['no such line', 'whatever']) is None
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function LineFindingTests.test_finding_start_line refactored with the following changes:

  • Use x is None rather than x == None

with self.assertRaises(SourceUpdateError):
source.find_start_line([''])
with self.assertRaises(SourceUpdateError):
Expand All @@ -666,8 +666,8 @@ def test_finding_end_line(self):

assert source.find_end_line(['stuff', 'things']) == 1
assert source.find_end_line(['bla bla', 'whatever', 'more']) == 5
assert source.find_end_line(['bla bla', 'whatever']) == None
assert source.find_end_line(['no such line', 'whatever']) == None
assert source.find_end_line(['bla bla', 'whatever']) is None
assert source.find_end_line(['no such line', 'whatever']) is None
Comment on lines -669 to +670
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function LineFindingTests.test_finding_end_line refactored with the following changes:

  • Use x is None rather than x == None

with self.assertRaises(SourceUpdateError):
source.find_end_line([])
with self.assertRaises(SourceUpdateError):
Expand Down
Loading