Files
EOS/tests/test_cache.py
Bobby Noelte b397b5d43e fix: automatic optimization (#596)
This fix implements the long term goal to have the EOS server run optimization (or
energy management) on regular intervals automatically. Thus clients can request
the current energy management plan at any time and it is updated on regular
intervals without interaction by the client.

This fix started out to "only" make automatic optimization (or energy management)
runs working. It turned out there are several endpoints that in some way
update predictions or run the optimization. To lock against such concurrent attempts
the code had to be refactored to allow control of execution. During refactoring it
became clear that some classes and files are named without a proper reference
to their usage. Thus not only refactoring but also renaming became necessary.
The names are still not the best, but I hope they are more intuitive.

The fix includes several bug fixes that are not directly related to the automatic optimization
but are necessary to keep EOS running properly to do the automatic optimization and
to test and document the changes.

This is a breaking change as the configuration structure changed once again and
the server API was also enhanced and streamlined. The server API that is used by
Andreas and Jörg in their videos has not changed.

* fix: automatic optimization

  Allow optimization to automatically run on configured intervals gathering all
  optimization parameters from configuration and predictions. The automatic run
  can be configured to only run prediction updates skipping the optimization.
  Extend documentaion to also cover automatic optimization. Lock automatic runs
  against runs initiated by the /optimize or other endpoints. Provide new
  endpoints to retrieve the energy management plan and the genetic solution
  of the latest automatic optimization run. Offload energy management to thread
  pool executor to keep the app more responsive during the CPU heavy optimization
  run.

* fix: EOS servers recognize environment variables on startup

  Force initialisation of EOS configuration on server startup to assure
  all sources of EOS configuration are properly set up and read. Adapt
  server tests and configuration tests to also test for environment
  variable configuration.

* fix: Remove 0.0.0.0 to localhost translation under Windows

  EOS imposed a 0.0.0.0 to localhost translation under Windows for
  convenience. This caused some trouble in user configurations. Now, as the
  default IP address configuration is 127.0.0.1, the user is responsible
  for to set up the correct Windows compliant IP address.

* fix: allow names for hosts additional to IP addresses

* fix: access pydantic model fields by class

  Access by instance is deprecated.

* fix: down sampling key_to_array

* fix: make cache clear endpoint clear all cache files

  Make /v1/admin/cache/clear clear all cache files. Before it only cleared
  expired cache files by default. Add new endpoint /v1/admin/clear-expired
  to only clear expired cache files.

* fix: timezonefinder returns Europe/Paris instead of Europe/Berlin

  timezonefinder 8.10 got more inaccurate for timezones in europe as there is
  a common timezone. Use new package tzfpy instead which is still returning
  Europe/Berlin if you are in Germany. tzfpy also claims to be faster than
  timezonefinder.

* fix: provider settings configuration

  Provider configuration used to be a union holding the settings for several
  providers. Pydantic union handling does not always find the correct type
  for a provider setting. This led to exceptions in specific configurations.
  Now provider settings are explicit comfiguration items for each possible
  provider. This is a breaking change as the configuration structure was
  changed.

* fix: ClearOutside weather prediction irradiance calculation

  Pvlib needs a pandas time index. Convert time index.

* fix: test config file priority

  Do not use config_eos fixture as this fixture already creates a config file.

* fix: optimization sample request documentation

  Provide all data in documentation of optimization sample request.

* fix: gitlint blocking pip dependency resolution

  Replace gitlint by commitizen. Gitlint is not actively maintained anymore.
  Gitlint dependencies blocked pip from dependency resolution.

* fix: sync pre-commit config to actual dependency requirements

  .pre-commit-config.yaml was out of sync, also requirements-dev.txt.

* fix: missing babel in requirements.txt

  Add babel to requirements.txt

* feat: setup default device configuration for automatic optimization

  In case the parameters for automatic optimization are not fully defined a
  default configuration is setup to allow the automatic energy management
  run. The default configuration may help the user to correctly define
  the device configuration.

* feat: allow configuration of genetic algorithm parameters

  The genetic algorithm parameters for number of individuals, number of
  generations, the seed and penalty function parameters are now avaliable
  as configuration options.

* feat: allow configuration of home appliance time windows

  The time windows a home appliance is allowed to run are now configurable
  by the configuration (for /v1 API) and also by the home appliance parameters
  (for the classic /optimize API). If there is no such configuration the
  time window defaults to optimization hours, which was the standard before
  the change. Documentation on how to configure time windows is added.

* feat: standardize mesaurement keys for battery/ ev SoC measurements

  The standardized measurement keys to report battery SoC to the device
  simulations can now be retrieved from the device configuration as a
  read-only config option.

* feat: feed in tariff prediction

  Add feed in tarif predictions needed for automatic optimization. The feed in
  tariff can be retrieved as fixed feed in tarif or can be imported. Also add
  tests for the different feed in tariff providers. Extend documentation to
  cover the feed in tariff providers.

* feat: add energy management plan based on S2 standard instructions

  EOS can generate an energy management plan as a list of simple instructions.
  May be retrieved by the /v1/energy-management/plan endpoint. The instructions
  loosely follow the S2 energy management standard.

* feat: make measurement keys configurable by EOS configuration.

  The fixed measurement keys are replaced by configurable measurement keys.

* feat: make pendulum DateTime, Date, Duration types usable for pydantic models

  Use pydantic_extra_types.pendulum_dt to get pydantic pendulum types. Types are
  added to the datetimeutil utility. Remove custom made pendulum adaptations
  from EOS pydantic module. Make EOS modules use the pydantic pendulum types
  managed by the datetimeutil module instead of the core pendulum types.

* feat: Add Time, TimeWindow, TimeWindowSequence and to_time to datetimeutil.

  The time windows are are added to support home appliance time window
  configuration. All time classes are also pydantic models. Time is the base
  class for time definition derived from pendulum.Time.

* feat: Extend DataRecord by configurable field like data.

  Configurable field like data was added to support the configuration of
  measurement records.

* feat: Add additional information to health information

  Version information is added to the health endpoints of eos and eosDash.
  The start time of the last optimization and the latest run time of the energy
  management is added to the EOS health information.

* feat: add pydantic merge model tests

* feat: add plan tab to EOSdash

  The plan tab displays the current energy management instructions.

* feat: add predictions tab to EOSdash

  The predictions tab displays the current predictions.

* feat: add cache management to EOSdash admin tab

  The admin tab is extended by a section for cache management. It allows to
  clear the cache.

* feat: add about tab to EOSdash

  The about tab resembles the former hello tab and provides extra information.

* feat: Adapt changelog and prepare for release management

  Release management using commitizen is added. The changelog file is adapted and
  teh changelog and a description for release management is added in the
  documentation.

* feat(doc): Improve install and devlopment documentation

  Provide a more concise installation description in Readme.md and add extra
  installation page and development page to documentation.

* chore: Use memory cache for interpolation instead of dict in inverter

  Decorate calculate_self_consumption() with @cachemethod_until_update to cache
  results in memory during an energy management/ optimization run. Replacement
  of dict type caching in inverter is now possible because all optimization
  runs are properly locked and the memory cache CacheUntilUpdateStore is properly
  cleared at the start of any energy management/ optimization operation.

* chore: refactor genetic

  Refactor the genetic algorithm modules for enhanced module structure and better
  readability. Removed unnecessary and overcomplex devices singleton. Also
  split devices configuration from genetic algorithm parameters to allow further
  development independently from genetic algorithm parameter format. Move
  charge rates configuration for electric vehicles from optimization to devices
  configuration to allow to have different charge rates for different cars in
  the future.

* chore: Rename memory cache to CacheEnergyManagementStore

  The name better resembles the task of the cache to chache function and method
  results for an energy management run. Also the decorator functions are renamed
  accordingly: cachemethod_energy_management, cache_energy_management

* chore: use class properties for config/ems/prediction mixin classes

* chore: skip debug logs from mathplotlib

  Mathplotlib is very noisy in debug mode.

* chore: automatically sync bokeh js to bokeh python package

  bokeh was updated to 3.8.0, make JS CDN automatically follow the package version.

* chore: rename hello.py to about.py

  Make hello.py the adapted EOSdash about page.

* chore: remove demo page from EOSdash

  As no the plan and prediction pages are working without configuration, the demo
  page is no longer necessary

* chore: split test_server.py for system test

  Split test_server.py to create explicit test_system.py for system tests.

* chore: move doc utils to generate_config_md.py

  The doc utils are only used in scripts/generate_config_md.py. Move it there to
  attribute for strong cohesion.

* chore: improve pydantic merge model documentation

* chore: remove pendulum warning from readme

* chore: remove GitHub discussions from contributing documentation

  Github discussions is to be replaced by Akkudoktor.net.

* chore(release): bump version to 0.1.0+dev for development

* build(deps): bump fastapi[standard] from 0.115.14 to 0.117.1

  bump fastapi and make coverage version (for pytest-cov) explicit to avoid pip break.

* build(deps): bump uvicorn from 0.36.0 to 0.37.0

BREAKING CHANGE: EOS configuration changed. V1 API changed.

  - The available_charge_rates_percent configuration is removed from optimization.
    Use the new charge_rate configuration for the electric vehicle
  - Optimization configuration parameter hours renamed to horizon_hours
  - Device configuration now has to provide the number of devices and device
    properties per device.
  - Specific prediction provider configuration to be provided by explicit
    configuration item (no union for all providers).
  - Measurement keys to be provided as a list.
  - New feed in tariff providers have to be configured.
  - /v1/measurement/loadxxx endpoints are removed. Use generic mesaurement endpoints.
  - /v1/admin/cache/clear now clears all cache files. Use
    /v1/admin/cache/clear-expired to only clear all expired cache files.

Signed-off-by: Bobby Noelte <b0661n0e17e@gmail.com>
2025-10-28 02:50:31 +01:00

695 lines
28 KiB
Python

import io
import json
import pickle
import tempfile
from datetime import date, datetime, timedelta
from pathlib import Path
from time import sleep
from unittest.mock import MagicMock, patch
import cachebox
import pytest
from akkudoktoreos.core.cache import (
CacheEnergyManagementStore,
CacheFileRecord,
CacheFileStore,
cache_energy_management,
cache_in_file,
cachemethod_energy_management,
)
from akkudoktoreos.utils.datetimeutil import compare_datetimes, to_datetime, to_duration
# ---------------------------------
# In-Memory Caching Functionality
# ---------------------------------
# Fixtures for testing
@pytest.fixture
def cache_energy_management_store():
"""Ensures CacheEnergyManagementStore is reset between tests."""
cache = CacheEnergyManagementStore()
CacheEnergyManagementStore().clear()
assert len(cache) == 0
return cache
class TestCacheEnergyManagementStore:
def test_cache_initialization(self, cache_energy_management_store):
"""Test that CacheEnergyManagementStore initializes with the correct properties."""
cache = CacheEnergyManagementStore()
assert isinstance(cache.cache, cachebox.LRUCache)
assert cache.maxsize == 100
assert len(cache) == 0
def test_singleton_behavior(self, cache_energy_management_store):
"""Test that CacheEnergyManagementStore is a singleton."""
cache1 = CacheEnergyManagementStore()
cache2 = CacheEnergyManagementStore()
assert cache1 is cache2
def test_cache_storage(self, cache_energy_management_store):
"""Test that items can be added and retrieved from the cache."""
cache = CacheEnergyManagementStore()
cache["key1"] = "value1"
assert cache["key1"] == "value1"
assert len(cache) == 1
def test_cache_getattr_invalid_method(self, cache_energy_management_store):
"""Test that accessing an invalid method raises an AttributeError."""
with pytest.raises(AttributeError):
CacheEnergyManagementStore().non_existent_method() # This should raise AttributeError
class TestCacheUntilUpdateDecorators:
def test_cachemethod_energy_management(self, cache_energy_management_store):
"""Test that cachemethod_energy_management caches method results."""
class MyClass:
@cachemethod_energy_management
def compute(self, value: int) -> int:
return value * 2
obj = MyClass()
# Call method and assert caching
assert CacheEnergyManagementStore.miss_count == 0
assert CacheEnergyManagementStore.hit_count == 0
result1 = obj.compute(5)
assert CacheEnergyManagementStore.miss_count == 1
assert CacheEnergyManagementStore.hit_count == 0
result2 = obj.compute(5)
assert CacheEnergyManagementStore.miss_count == 1
assert CacheEnergyManagementStore.hit_count == 1
assert result1 == result2
def test_cache_energy_management(self, cache_energy_management_store):
"""Test that cache_energy_management caches function results."""
@cache_energy_management
def compute(value: int) -> int:
return value * 3
# Call function and assert caching
result1 = compute(4)
assert CacheEnergyManagementStore.last_event == cachebox.EVENT_MISS
result2 = compute(4)
assert CacheEnergyManagementStore.last_event == cachebox.EVENT_HIT
assert result1 == result2
def test_cache_with_different_arguments(self, cache_energy_management_store):
"""Test that caching works for different arguments."""
class MyClass:
@cachemethod_energy_management
def compute(self, value: int) -> int:
return value * 2
obj = MyClass()
assert CacheEnergyManagementStore.miss_count == 0
result1 = obj.compute(3)
assert CacheEnergyManagementStore.last_event == cachebox.EVENT_MISS
assert CacheEnergyManagementStore.miss_count == 1
result2 = obj.compute(5)
assert CacheEnergyManagementStore.last_event == cachebox.EVENT_MISS
assert CacheEnergyManagementStore.miss_count == 2
assert result1 == 6
assert result2 == 10
def test_cache_clearing(self, cache_energy_management_store):
"""Test that cache is cleared between EMS update cycles."""
class MyClass:
@cachemethod_energy_management
def compute(self, value: int) -> int:
return value * 2
obj = MyClass()
obj.compute(5)
# Clear cache
CacheEnergyManagementStore().clear()
with pytest.raises(KeyError):
_ = CacheEnergyManagementStore()["<invalid>"]
def test_decorator_works_for_standalone_function(self, cache_energy_management_store):
"""Test that cache_energy_management works with standalone functions."""
@cache_energy_management
def add(a: int, b: int) -> int:
return a + b
assert CacheEnergyManagementStore.miss_count == 0
assert CacheEnergyManagementStore.hit_count == 0
result1 = add(1, 2)
assert CacheEnergyManagementStore.miss_count == 1
assert CacheEnergyManagementStore.hit_count == 0
result2 = add(1, 2)
assert CacheEnergyManagementStore.miss_count == 1
assert CacheEnergyManagementStore.hit_count == 1
assert result1 == result2
# -----------------------------
# CacheFileStore
# -----------------------------
@pytest.fixture
def temp_store_file():
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
yield Path(temp_file.file.name)
# temp_file.unlink()
@pytest.fixture
def cache_file_store(temp_store_file):
"""A pytest fixture that creates a new CacheFileStore instance for testing."""
cache = CacheFileStore()
cache._store_file = temp_store_file
cache.clear(clear_all=True)
assert len(cache._store) == 0
return cache
class TestCacheFileStore:
def test_generate_cache_file_key(self, cache_file_store):
"""Test cache file key generation based on URL and date."""
key = "http://example.com"
# Provide until date - assure until_dt is used.
until_dt = to_datetime("2024-10-01")
cache_file_key, cache_file_until_dt, ttl_duration = (
cache_file_store._generate_cache_file_key(key=key, until_datetime=until_dt)
)
assert cache_file_key is not None
assert compare_datetimes(cache_file_until_dt, until_dt).equal
# Provide until date again - assure same key is generated.
cache_file_key1, cache_file_until_dt1, ttl_duration1 = (
cache_file_store._generate_cache_file_key(key=key, until_datetime=until_dt)
)
assert cache_file_key1 == cache_file_key
assert compare_datetimes(cache_file_until_dt1, until_dt).equal
# Provide no until date - assure today EOD is used.
no_until_dt = to_datetime().end_of("day")
cache_file_key, cache_file_until_dt, ttl_duration = (
cache_file_store._generate_cache_file_key(key)
)
assert cache_file_key is not None
assert compare_datetimes(cache_file_until_dt, no_until_dt).equal
# Provide with_ttl - assure until_dt is used.
until_dt = to_datetime().add(hours=1)
cache_file_key, cache_file_until_dt, ttl_duration = (
cache_file_store._generate_cache_file_key(key, with_ttl="1 hour")
)
assert cache_file_key is not None
assert compare_datetimes(cache_file_until_dt, until_dt).approximately_equal
assert ttl_duration == to_duration("1 hour")
# Provide with_ttl again - assure same key is generated.
until_dt = to_datetime().add(hours=1)
cache_file_key1, cache_file_until_dt1, ttl_duration1 = (
cache_file_store._generate_cache_file_key(key=key, with_ttl="1 hour")
)
assert cache_file_key1 == cache_file_key
assert compare_datetimes(cache_file_until_dt1, until_dt).approximately_equal
assert ttl_duration1 == to_duration("1 hour")
# Provide different with_ttl - assure different key is generated.
until_dt = to_datetime().add(hours=1, minutes=1)
cache_file_key2, cache_file_until_dt2, ttl_duration2 = (
cache_file_store._generate_cache_file_key(key=key, with_ttl="1 hour 1 minute")
)
assert cache_file_key2 != cache_file_key
assert compare_datetimes(cache_file_until_dt2, until_dt).approximately_equal
assert ttl_duration2 == to_duration("1 hour 1 minute")
def test_get_file_path(self, cache_file_store):
"""Test get file path from cache file object."""
cache_file = cache_file_store.create("test_file", mode="w+", suffix=".txt")
file_path = cache_file_store._get_file_path(cache_file)
assert file_path is not None
def test_until_datetime_by_options(self, cache_file_store):
"""Test until datetime calculation based on options."""
now = to_datetime()
# Test with until_datetime
result, ttl_duration = cache_file_store._until_datetime_by_options(until_datetime=now)
assert result == now
assert ttl_duration is None
# -- From now on we expect a until_datetime in one hour
ttl_duration_expected = to_duration("1 hour")
# Test with with_ttl as timedelta
until_datetime_expected = to_datetime().add(hours=1)
ttl = timedelta(hours=1)
result, ttl_duration = cache_file_store._until_datetime_by_options(with_ttl=ttl)
assert compare_datetimes(result, until_datetime_expected).approximately_equal
assert ttl_duration == ttl_duration_expected
# Test with with_ttl as int (seconds)
until_datetime_expected = to_datetime().add(hours=1)
ttl_seconds = 3600
result, ttl_duration = cache_file_store._until_datetime_by_options(with_ttl=ttl_seconds)
assert compare_datetimes(result, until_datetime_expected).approximately_equal
assert ttl_duration == ttl_duration_expected
# Test with with_ttl as string ("1 hour")
until_datetime_expected = to_datetime().add(hours=1)
ttl_string = "1 hour"
result, ttl_duration = cache_file_store._until_datetime_by_options(with_ttl=ttl_string)
assert compare_datetimes(result, until_datetime_expected).approximately_equal
assert ttl_duration == ttl_duration_expected
# -- From now on we expect a until_datetime today at end of day
until_datetime_expected = to_datetime().end_of("day")
ttl_duration_expected = None
# Test default case (end of today)
result, ttl_duration = cache_file_store._until_datetime_by_options()
assert compare_datetimes(result, until_datetime_expected).equal
assert ttl_duration == ttl_duration_expected
# -- From now on we expect a until_datetime in one day at end of day
until_datetime_expected = to_datetime().add(days=1).end_of("day")
assert ttl_duration == ttl_duration_expected
# Test with until_date as date
until_date = date.today() + timedelta(days=1)
result, ttl_duration = cache_file_store._until_datetime_by_options(until_date=until_date)
assert compare_datetimes(result, until_datetime_expected).equal
assert ttl_duration == ttl_duration_expected
# -- Test with multiple options (until_datetime takes precedence)
specific_datetime = to_datetime().add(days=2)
result, ttl_duration = cache_file_store._until_datetime_by_options(
until_date=to_datetime().add(days=1).date(),
until_datetime=specific_datetime,
with_ttl=ttl,
)
assert compare_datetimes(result, specific_datetime).equal
assert ttl_duration is None
# Test with invalid inputs
with pytest.raises(ValueError):
cache_file_store._until_datetime_by_options(until_date="invalid-date")
with pytest.raises(ValueError):
cache_file_store._until_datetime_by_options(with_ttl="invalid-ttl")
with pytest.raises(ValueError):
cache_file_store._until_datetime_by_options(until_datetime="invalid-datetime")
def test_create_cache_file(self, cache_file_store):
"""Test the creation of a cache file and ensure it is stored correctly."""
# Create a cache file for today's date
cache_file = cache_file_store.create("test_file", mode="w+", suffix=".txt")
# Check that the file exists in the store and is a file-like object
assert cache_file is not None
assert hasattr(cache_file, "name")
assert cache_file.name.endswith(".txt")
# Write some data to the file
cache_file.seek(0)
cache_file.write("Test data")
cache_file.seek(0) # Reset file pointer
assert cache_file.read() == "Test data"
def test_get_cache_file(self, cache_file_store):
"""Test retrieving an existing cache file by key."""
# Create a cache file and write data to it
cache_file = cache_file_store.create("test_file", mode="w+")
cache_file.seek(0)
cache_file.write("Test data")
cache_file.seek(0)
# Retrieve the cache file and verify the data
retrieved_file = cache_file_store.get("test_file")
assert retrieved_file is not None
retrieved_file.seek(0)
assert retrieved_file.read() == "Test data"
def test_set_custom_file_object(self, cache_file_store):
"""Test setting a custom file-like object (BytesIO or StringIO) in the store."""
# Create a BytesIO object and set it into the cache
file_obj = io.BytesIO(b"Binary data")
cache_file_store.set("binary_file", file_obj)
# Retrieve the file from the store
retrieved_file = cache_file_store.get("binary_file")
assert isinstance(retrieved_file, io.BytesIO)
retrieved_file.seek(0)
assert retrieved_file.read() == b"Binary data"
def test_delete_cache_file(self, cache_file_store):
"""Test deleting a cache file from the store."""
# Create multiple cache files
cache_file1 = cache_file_store.create("file1")
assert hasattr(cache_file1, "name")
cache_file2 = cache_file_store.create("file2")
assert hasattr(cache_file2, "name")
# Ensure the files are in the store
assert cache_file_store.get("file1") is cache_file1
assert cache_file_store.get("file2") is cache_file2
# Delete cache files
cache_file_store.delete("file1")
cache_file_store.delete("file2")
# Ensure the store is empty
assert cache_file_store.get("file1") is None
assert cache_file_store.get("file2") is None
def test_clear_all_cache_files(self, cache_file_store):
"""Test clearing all cache files from the store."""
# Create multiple cache files
cache_file1 = cache_file_store.create("file1")
assert hasattr(cache_file1, "name")
cache_file2 = cache_file_store.create("file2")
assert hasattr(cache_file2, "name")
# Ensure the files are in the store
assert cache_file_store.get("file1") is cache_file1
assert cache_file_store.get("file2") is cache_file2
current_store = cache_file_store.current_store()
assert current_store != {}
# Clear all cache files
cache_file_store.clear(clear_all=True)
# Ensure the store is empty
assert cache_file_store.get("file1") is None
assert cache_file_store.get("file2") is None
current_store = cache_file_store.current_store()
assert current_store == {}
def test_clear_cache_files_by_date(self, cache_file_store):
"""Test clearing cache files from the store by date."""
# Create multiple cache files
cache_file1 = cache_file_store.create("file1")
assert hasattr(cache_file1, "name")
cache_file2 = cache_file_store.create("file2")
assert hasattr(cache_file2, "name")
# Ensure the files are in the store
assert cache_file_store.get("file1") is cache_file1
assert cache_file_store.get("file2") is cache_file2
# Clear cache files that are older than today
cache_file_store.clear(before_datetime=to_datetime().start_of("day"))
# Ensure the files are in the store
assert cache_file_store.get("file1") is cache_file1
assert cache_file_store.get("file2") is cache_file2
# Clear cache files that are older than tomorrow
cache_file_store.clear(before_datetime=datetime.now() + timedelta(days=1))
# Ensure the store is empty
assert cache_file_store.get("file1") is None
assert cache_file_store.get("file2") is None
def test_cache_file_with_date(self, cache_file_store):
"""Test creating and retrieving cache files with a specific date."""
# Use a specific date for cache file creation
specific_date = datetime(2023, 10, 10)
cache_file = cache_file_store.create("dated_file", mode="w+", until_date=specific_date)
# Write data to the cache file
cache_file.write("Dated data")
cache_file.seek(0)
# Retrieve the cache file with the specific date
retrieved_file = cache_file_store.get("dated_file", until_date=specific_date)
assert retrieved_file is not None
retrieved_file.seek(0)
assert retrieved_file.read() == "Dated data"
def test_recreate_existing_cache_file(self, cache_file_store):
"""Test creating a cache file with an existing key does not overwrite the existing file."""
# Create a cache file
cache_file = cache_file_store.create("test_file", mode="w+")
cache_file.write("Original data")
cache_file.seek(0)
# Attempt to recreate the same file (should return the existing one)
new_file = cache_file_store.create("test_file")
assert new_file is cache_file # Should be the same object
new_file.seek(0)
assert new_file.read() == "Original data" # Data should be preserved
# Assure cache file store is a singleton
cache_file_store2 = CacheFileStore()
new_file = cache_file_store2.get("test_file")
assert new_file is cache_file # Should be the same object
def test_cache_file_store_is_singleton(self, cache_file_store):
"""Test re-creating a cache store provides the same store."""
# Create a cache file
cache_file = cache_file_store.create("test_file", mode="w+")
cache_file.write("Original data")
cache_file.seek(0)
# Assure cache file store is a singleton
cache_file_store2 = CacheFileStore()
new_file = cache_file_store2.get("test_file")
assert new_file is cache_file # Should be the same object
def test_cache_file_store_save_store(self, cache_file_store):
# Creating a sample cache record
cache_file = MagicMock()
cache_file.name = "cache_file_path"
cache_file.mode = "wb+"
cache_record = CacheFileRecord(
cache_file=cache_file, until_datetime=to_datetime(), ttl_duration=None
)
cache_file_store._store = {"test_key": cache_record}
# Save the store to the file
cache_file_store.save_store()
# Verify the file content
with cache_file_store._store_file.open("r", encoding="utf-8", newline=None) as f:
store_loaded = json.load(f)
assert "test_key" in store_loaded
assert store_loaded["test_key"]["cache_file"] == "cache_file_path"
assert store_loaded["test_key"]["mode"] == "wb+"
assert store_loaded["test_key"]["until_datetime"] == to_datetime(
cache_record.until_datetime, as_string=True
)
assert store_loaded["test_key"]["ttl_duration"] is None
def test_cache_file_store_load_store(self, cache_file_store):
# Creating a sample cache record and save it to the file
cache_record = {
"test_key": {
"cache_file": "cache_file_path",
"mode": "wb+",
"until_datetime": to_datetime(as_string=True),
"ttl_duration": None,
}
}
with cache_file_store._store_file.open("w", encoding="utf-8", newline="\n") as f:
json.dump(cache_record, f, indent=4)
# Mock the open function to return a MagicMock for the cache file
with patch("builtins.open", new_callable=MagicMock) as mock_open:
mock_open.return_value.name = "cache_file_path"
mock_open.return_value.mode = "wb+"
# Load the store from the file
cache_file_store.load_store()
# Verify the loaded store
assert "test_key" in cache_file_store._store
loaded_record = cache_file_store._store["test_key"]
assert loaded_record.cache_file.name == "cache_file_path"
assert loaded_record.cache_file.mode == "wb+"
assert loaded_record.until_datetime == to_datetime(
cache_record["test_key"]["until_datetime"]
)
assert loaded_record.ttl_duration is None
class TestCacheFileDecorators:
def test_cache_in_file_decorator_caches_function_result(self, cache_file_store):
"""Test that the cache_in_file decorator caches a function result."""
# Clear store to assure it is empty
cache_file_store.clear(clear_all=True)
assert len(cache_file_store._store) == 0
# Define a simple function to decorate
@cache_in_file(mode="w+")
def my_function(until_date=None):
return "Some expensive computation result"
# Call the decorated function (should store result in cache)
result = my_function(until_date=datetime.now() + timedelta(days=1))
assert result == "Some expensive computation result"
# Assert that the create method was called to store the result
assert len(cache_file_store._store) == 1
# Check if the result was written to the cache file
key = next(iter(cache_file_store._store))
cache_file = cache_file_store._store[key].cache_file
assert cache_file is not None
# Assert correct content was written to the file
cache_file.seek(0) # Move to the start of the file
assert cache_file.read() == "Some expensive computation result"
def test_cache_in_file_decorator_uses_cache(self, cache_file_store):
"""Test that the cache_in_file decorator reuses cached file on subsequent calls."""
# Clear store to assure it is empty
cache_file_store.clear(clear_all=True)
assert len(cache_file_store._store) == 0
# Define a simple function to decorate
@cache_in_file(mode="w+")
def my_function(until_date=None):
return "New result"
# Call the decorated function (should store result in cache)
result = my_function(until_date=to_datetime().add(days=1))
assert result == "New result"
# Assert result was written to cache file
key = next(iter(cache_file_store._store))
cache_file = cache_file_store._store[key].cache_file
assert cache_file is not None
cache_file.seek(0) # Move to the start of the file
assert cache_file.read() == result
# Modify cache file
result2 = "Cached result"
cache_file.seek(0)
cache_file.write(result2)
# Call the decorated function again (should get result from cache)
result = my_function(until_date=to_datetime().add(days=1))
assert result == result2
def test_cache_in_file_decorator_forces_update_data(self, cache_file_store):
"""Test that the cache_in_file decorator reuses cached file on subsequent calls."""
# Clear store to assure it is empty
cache_file_store.clear(clear_all=True)
assert len(cache_file_store._store) == 0
# Define a simple function to decorate
@cache_in_file(mode="w+")
def my_function(until_date=None):
return "New result"
until_date = to_datetime().add(days=1).date()
# Call the decorated function (should store result in cache)
result1 = "New result"
result = my_function(until_date=until_date)
assert result == result1
# Assert result was written to cache file
key = next(iter(cache_file_store._store))
cache_file = cache_file_store._store[key].cache_file
assert cache_file is not None
cache_file.seek(0) # Move to the start of the file
assert cache_file.read() == result
# Modify cache file
result2 = "Cached result"
cache_file.seek(0)
cache_file.write(result2)
cache_file.seek(0) # Move to the start of the file
assert cache_file.read() == result2
# Call the decorated function again with force update (should get result from function)
result = my_function(until_date=until_date, force_update=True) # type: ignore[call-arg]
assert result == result1
# Assure result was written to the same cache file
cache_file.seek(0) # Move to the start of the file
assert cache_file.read() == result1
def test_cache_in_file_handles_ttl(self, cache_file_store):
"""Test that the cache_infile decorator handles the with_ttl parameter."""
# Define a simple function to decorate
@cache_in_file(mode="w+")
def my_function():
return "New result"
# Call the decorated function
result1 = my_function(with_ttl="1 second") # type: ignore[call-arg]
assert result1 == "New result"
assert len(cache_file_store._store) == 1
key = list(cache_file_store._store.keys())[0]
# Assert result was written to cache file
key = next(iter(cache_file_store._store))
cache_file = cache_file_store._store[key].cache_file
assert cache_file is not None
cache_file.seek(0) # Move to the start of the file
assert cache_file.read() == result1
# Modify cache file
result2 = "Cached result"
cache_file.seek(0)
cache_file.write(result2)
cache_file.seek(0) # Move to the start of the file
assert cache_file.read() == result2
# Call the decorated function again
result = my_function(with_ttl="1 second") # type: ignore[call-arg]
cache_file.seek(0) # Move to the start of the file
assert cache_file.read() == result2
assert result == result2
# Wait one second to let the cache time out
sleep(2)
# Call again - cache should be timed out
result = my_function(with_ttl="1 second") # type: ignore[call-arg]
assert result == result1
def test_cache_in_file_handles_bytes_return(self, cache_file_store):
"""Test that the cache_infile decorator handles bytes returned from the function."""
# Clear store to assure it is empty
cache_file_store.clear(clear_all=True)
assert len(cache_file_store._store) == 0
# Define a function that returns bytes
@cache_in_file()
def my_function(until_date=None) -> bytes:
return b"Some binary data"
# Call the decorated function
result = my_function(until_date=datetime.now() + timedelta(days=1))
# Check if the binary data was written to the cache file
key = next(iter(cache_file_store._store))
cache_file = cache_file_store._store[key].cache_file
assert len(cache_file_store._store) == 1
assert cache_file is not None
cache_file.seek(0)
result1 = pickle.load(cache_file)
assert result1 == result
# Access cache
result = my_function(until_date=datetime.now() + timedelta(days=1))
assert len(cache_file_store._store) == 1
assert cache_file_store._store[key].cache_file is not None
assert result1 == result