Skip to content

Commit

Permalink
Attempt to backup archive before saving
Browse files Browse the repository at this point in the history
After saving clean up the backup file if it exists.
  • Loading branch information
smarlowucf committed Jan 12, 2024
1 parent 72c2171 commit 99bd483
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
16 changes: 15 additions & 1 deletion csp_billing_adapter_local/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import logging
import urllib.request
import urllib.error
import shutil

from json.decoder import JSONDecodeError
from pathlib import Path
Expand Down Expand Up @@ -100,9 +101,22 @@ def update_cache(config: Config, cache: dict, replace: bool):
@csp_billing_adapter.hookimpl(trylast=True)
def save_metering_archive(config: Config, archive_data: list):
"""Update local storage archive with new content"""
with open(get_local_path(ARCHIVE_FILE), 'w', encoding='utf-8') as f:
archive_path = get_local_path(ARCHIVE_FILE)
archive_bak = Path(str(archive_path) + '.bak')

try:
shutil.copy(archive_path, archive_bak)
except FileNotFoundError:
pass

with open(archive_path, 'w', encoding='utf-8') as f:
json.dump(archive_data, f)

try:
archive_bak.unlink()
except FileNotFoundError:
pass


@csp_billing_adapter.hookimpl(trylast=True)
def get_metering_archive(config: Config):
Expand Down
8 changes: 5 additions & 3 deletions tests/unit/test_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
import json
import logging
from pathlib import Path
from tempfile import NamedTemporaryFile
from tempfile import NamedTemporaryFile, TemporaryDirectory
from unittest.mock import patch
from pytest import raises

Expand Down Expand Up @@ -477,8 +477,10 @@ def test_local_get_metering_archive_file_not_found_exception(
def test_local_save_metering_archive(self, mock_get_local_path):
"""Test save_metering_archive() in local plugin"""

with NamedTemporaryFile() as temp_file:
mock_get_local_path.return_value = Path(temp_file.name)
with TemporaryDirectory() as temp_dir:
mock_get_local_path.return_value = Path(
temp_dir
).joinpath('archive.json')
archive = [{
'billing_time': '2024-02-09T18:11:59.527064+00:00',
'billing_status': {
Expand Down

0 comments on commit 99bd483

Please sign in to comment.