Skip to main content

Merge pull request #8 from alexwlchan/add-more-tests

ID
64e2d6c
date
2024-08-17 18:51:10+00:00
author
Alex Chan <alex@alexwlchan.net>
parents
656f1e2, 81a9818
message
Merge pull request #8 from alexwlchan/add-more-tests

Only replace a `const` declaration at the start of the file
changed files
3 files, 28 additions, 4 deletions

Changed files

pyproject.toml (1193) → pyproject.toml (1189)

diff --git a/pyproject.toml b/pyproject.toml
index c88084c..19b123b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -6,9 +6,8 @@ build-backend = "setuptools.build_meta"
 
 [project]
 name = "alexwlchan-python-js-files"
-description = "Manipulate JavaScript data files from Python"
+description = "Work with JSON which is stored as a value in a JavaScript file"
 readme = "README.md"
-keywords = ["flickr"]
 authors = [
   {name = "Alex Chan", email = "alex@alexwlchan.net"},
 ]

src/javascript/__init__.py (2393) → src/javascript/__init__.py (2413)

diff --git a/src/javascript/__init__.py b/src/javascript/__init__.py
index 9e41dd6..f37c2ea 100644
--- a/src/javascript/__init__.py
+++ b/src/javascript/__init__.py
@@ -1,6 +1,7 @@
 import json
 import os
 import pathlib
+import re
 import typing
 
 
@@ -24,12 +25,14 @@ def read_js(p: pathlib.Path | str, *, varname: str) -> typing.Any:
     with open(p) as in_file:
         contents = in_file.read()
 
-    if not contents.startswith(f"const {varname} = "):
+    m = re.compile(r"^const %s = " % varname)
+
+    if not m.match(contents):
         raise ValueError(
             f"File {p} does not start with JavaScript `const` declaration!"
         )
 
-    json_string = contents.replace(f"const {varname} = ", "").rstrip().rstrip(";")
+    json_string = m.sub(repl="", string=contents).rstrip().rstrip(";")
 
     return json.loads(json_string)
 

tests/test_javascript.py (3796) → tests/test_javascript.py (4431)

diff --git a/tests/test_javascript.py b/tests/test_javascript.py
index d9b35cf..e6639a0 100644
--- a/tests/test_javascript.py
+++ b/tests/test_javascript.py
@@ -1,4 +1,5 @@
 import pathlib
+import typing
 
 import pytest
 
@@ -98,6 +99,27 @@ class TestAppendToArray:
 
 
 class TestRoundTrip:
+    @pytest.mark.parametrize(
+        "value",
+        [
+            "hello world",
+            5,
+            None,
+            ["1", "2", "3"],
+            {"colour": "red", "sides": 5},
+            'a string with "double quotes"',
+            "this is const myTestVariable",
+            "const myTestVariable = ",
+        ],
+    )
+    def test_can_read_and_write_value(
+        self, tmp_path: pathlib.Path, value: typing.Any
+    ) -> None:
+        js_path = tmp_path / "testdata.js"
+
+        write_js(js_path, value=value, varname="myTestVariable")
+        assert read_js(js_path, varname="myTestVariable") == value
+
     def test_can_append_to_file(self, tmp_path: pathlib.Path) -> None:
         js_path = tmp_path / "food.js"