From 49668a4f4fc7bb20547a5221a8ad354f3fb0e1c9 Mon Sep 17 00:00:00 2001 From: Cayo Puigdefabregas Date: Fri, 9 Oct 2020 20:54:12 +0200 Subject: [PATCH] open files using with statement --- ereuse_devicehub/resources/action/views.py | 6 +++--- tests/test_snapshot.py | 12 ++++++------ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/ereuse_devicehub/resources/action/views.py b/ereuse_devicehub/resources/action/views.py index 6c5fc77a..58f59627 100644 --- a/ereuse_devicehub/resources/action/views.py +++ b/ereuse_devicehub/resources/action/views.py @@ -35,9 +35,9 @@ def save_json(req_json): if not os.path.isdir(TMP_SNAPSHOTS): os.system('mkdir -p {}'.format(TMP_SNAPSHOTS)) - snapshot_file = open(path_name, 'w') - snapshot_file.write(json.dumps(req_json)) - snapshot_file.close() + with open(path_name, 'w') as snapshot_file: + snapshot_file.write(json.dumps(req_json)) + return path_name diff --git a/tests/test_snapshot.py b/tests/test_snapshot.py index 193604ae..60667da1 100644 --- a/tests/test_snapshot.py +++ b/tests/test_snapshot.py @@ -492,9 +492,9 @@ def test_save_snapshot_in_file(): snapshot = {'software': '', 'version': '', 'uuid': ''} if files: path_snapshot = os.path.join(TMP_SNAPSHOTS, files[0]) - file_snapshot = open(path_snapshot) - snapshot = json.loads(file_snapshot.read()) - file_snapshot.close() + with open(path_snapshot) as file_snapshot: + snapshot = json.loads(file_snapshot.read()) + os.remove(path_snapshot) assert snapshot['software'] == snapshot_no_hid['software'] @@ -515,9 +515,9 @@ def test_backup_snapshot_with_errors(user: UserClient): files = [x for x in os.listdir(TMP_SNAPSHOTS) if uuid in x] if files: path_snapshot = os.path.join(TMP_SNAPSHOTS, files[0]) - file_snapshot = open(path_snapshot) - snapshot = json.loads(file_snapshot.read()) - file_snapshot.close() + with open(path_snapshot) as file_snapshot: + snapshot = json.loads(file_snapshot.read()) + os.remove(path_snapshot) assert snapshot['software'] == snapshot_no_hid['software']