Skip to content

Commit

Permalink
refactor: use with to open files
Browse files Browse the repository at this point in the history
  • Loading branch information
nedbat committed Nov 24, 2023
1 parent 55a8165 commit dca3f2c
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 17 deletions.
3 changes: 2 additions & 1 deletion cogapp/cogapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -650,7 +650,8 @@ def replaceFile(self, sOldPath, sNewText):
if self.options.sMakeWritableCmd:
# Use an external command to make the file writable.
cmd = self.options.sMakeWritableCmd.replace('%s', sOldPath)
self.stdout.write(os.popen(cmd).read())
with os.popen(cmd) as cmdout:
self.stdout.write(cmdout.read())
if not os.access(sOldPath, os.W_OK):
raise CogError(f"Couldn't make {sOldPath} writable")
else:
Expand Down
19 changes: 9 additions & 10 deletions cogapp/test_cogapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -782,18 +782,17 @@ def tearDown(self):
shutil.rmtree(self.tempdir)

def assertFilesSame(self, sFName1, sFName2):
text1 = open(os.path.join(self.tempdir, sFName1), 'rb').read()
text2 = open(os.path.join(self.tempdir, sFName2), 'rb').read()
with open(os.path.join(self.tempdir, sFName1), 'rb') as f1:
text1 = f1.read()
with open(os.path.join(self.tempdir, sFName2), 'rb') as f2:
text2 = f2.read()
self.assertEqual(text1, text2)

def assertFileContent(self, sFName, sContent):
sAbsName = os.path.join(self.tempdir, sFName)
f = open(sAbsName, 'rb')
try:
sFileContent = f.read()
finally:
f.close()
self.assertEqual(sFileContent, sContent.encode("utf-8"))
def assertFileContent(self, fname, content):
absname = os.path.join(self.tempdir, fname)
with open(absname, 'rb') as f:
file_content = f.read()
self.assertEqual(file_content, content.encode("utf-8"))


class ArgumentHandlingTests(TestCaseWithTempDir):
Expand Down
10 changes: 4 additions & 6 deletions cogapp/test_makefiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,8 @@ def testContents(self):
cont0 = "I am bar.txt"
d = { fname: cont0 }
makefiles.makeFiles(d, self.tempdir)
fcont1 = open(os.path.join(self.tempdir, fname))
assert(fcont1.read() == cont0)
fcont1.close()
with open(os.path.join(self.tempdir, fname)) as fcont1:
assert(fcont1.read() == cont0)

def testDedent(self):
fname = 'dedent.txt'
Expand All @@ -112,6 +111,5 @@ def testDedent(self):
""",
}
makefiles.makeFiles(d, self.tempdir)
fcont = open(os.path.join(self.tempdir, fname))
assert(fcont.read() == "This is dedent.txt\n\tTabbed in.\n spaced in.\nOK.\n")
fcont.close()
with open(os.path.join(self.tempdir, fname)) as fcont:
assert(fcont.read() == "This is dedent.txt\n\tTabbed in.\n spaced in.\nOK.\n")

0 comments on commit dca3f2c

Please sign in to comment.