Coverage for src/paperap/tests/utils.py: 100%
30 statements
« prev ^ index » next coverage.py v7.6.12, created at 2025-03-12 23:40 -0400
« prev ^ index » next coverage.py v7.6.12, created at 2025-03-12 23:40 -0400
1"""
6 ----------------------------------------------------------------------------
8 METADATA:
10 File: utils.py
11 Project: paperap
12 Created: 2025-03-12
13 Version: 0.0.6
14 Author: Jess Mann
15 Email: jess@jmann.me
16 Copyright (c) 2025 Jess Mann
18 ----------------------------------------------------------------------------
20 LAST MODIFIED:
22 2025-03-12 By Jess Mann
24"""
25from __future__ import annotations
26import json
27import os
28from pathlib import Path
29import random
30import string
31from typing import Any, TYPE_CHECKING
32from typing_extensions import TypeVar
33from unittest.mock import patch
34from paperap.client import PaperlessClient
36if TYPE_CHECKING:
37 from paperap.resources import BaseResource
39_BaseResource = TypeVar("_BaseResource", bound="BaseResource")
41def defaults(defaults : dict[str, Any], **kwargs : Any) -> dict[str, Any]:
42 """
43 Merge default fields with overrides for hypothesis @example
45 This avoids ugly double unpacking. The following two examples are equivalent:
46 - @example(**defaults(v, field1="value1", field2="value2"))
47 - @example(**{**v, "field1": "value1", "field2": "value2"})
49 Examples:
50 >>> from paperap.tests.utils import default as d
51 >>> note = { "title": "Sample Title", "created": datetime.datetime.now() }
52 >>> @example(**d(note, title="Note Title", content="Note Content"))
53 >>> def test_create_note(note: dict[str, Any]): ...
54 """
55 return {**defaults, **kwargs}
57def load_sample_data(filename : str) -> dict[str, Any]:
58 """
59 Load sample data from a JSON file.
61 Args:
62 filename: The name of the file to load.
64 Returns:
65 A dictionary containing the sample data.
66 """
67 # Load sample response from tests/sample_data/{model}_{endpoint}.json
68 sample_data_filepath = Path(__file__).parent.parent.parent.parent / "tests" / "sample_data" / filename
69 with open(sample_data_filepath, "r", encoding="utf-8") as f:
70 text = f.read()
71 sample_data = json.loads(text)
72 return sample_data
75def random_string(length=10):
76 """Generate a random string with mixed characters."""
77 return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
79def random_json():
80 """Generate random JSON-like data."""
81 return json.dumps({
82 "id": random.randint(1, 10**9),
83 "value": random.choice([None, random_string(15), 123, 3.14, True, {}, []])
84 })
86def create_client() -> PaperlessClient:
87 # patch env
88 env_data = {'PAPERLESS_BASE_URL': 'http://localhost:8000', 'PAPERLESS_TOKEN': 'abc123'}
89 with patch.dict(os.environ, env_data, clear=True):
90 return PaperlessClient()
92def create_resource(resource : type[_BaseResource]) -> _BaseResource:
93 client = create_client()
94 return resource(client=client)