Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,9 @@ jobs:
env:
# Fail instead of silently skipping if the schema files above are missing (see test_helpers.py).
REQUIRE_SCHEMA_TESTS: "1"
# A CouchDB service container is always started for this job (see `services:` above), so a
# missing or misconfigured CouchDB should fail the build, not silently skip the CouchDB tests.
REQUIRE_COUCHDB_INTEGRATION_TESTS: "1"
run: |
python -m coverage run --source=basyx -m unittest
- name: Report test coverage
Expand Down
25 changes: 16 additions & 9 deletions sdk/test/_helper/setup_testdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,20 @@

setup_testdb.py -u admin -p admin_password

If no CouchDB server at the configured URL, the script will exit with exit code 1. To avoid the error exit code (for use
in CI), provide the ``--failsafe`` option.
If no CouchDB server is reachable at the configured URL, or the test database already exists, the script exits with

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The docstring presents --failsafe as safe for idempotent re-runs, but it has two side effects that should be mentioned:

  • It also exits 0 when the server is unreachable.
  • If the database already exists, the script exits before it creates the test user and the _security entry. If an earlier run failed after creating the DB, re-running with --failsafe leaves the user missing, the probe gets a 401, and the tests skip or fail.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Note that deleting only the database isn't enough, the script then fails with 409 because the user exists, so the docstring says to delete both.

exit code 1, so that CI fails fast if the CouchDB service container isn't healthy. With ``--failsafe``, it exits with
exit code 0 in both cases instead.

In both cases, the script exits before it creates the test user and adds it to the ``_security`` object of the test
database. If an earlier run created the database but not the user, the tests cannot log in (``401``): they are
skipped, or fail if ``REQUIRE_COUCHDB_INTEGRATION_TESTS`` is set. To set up the server again, delete both the test
database and the test user; the script fails if the user already exists.
"""

import argparse
import base64
import configparser
import http.client
import json
import os.path
import sys
Expand Down Expand Up @@ -68,8 +75,8 @@
TEST_CONFIG["couchdb"]["url"], headers=default_headers, method="HEAD"
)
try:
urllib.request.urlopen(request)
except urllib.error.URLError as e:
urllib.request.urlopen(request, timeout=5)
except (OSError, http.client.HTTPException) as e:
print(
"Could not reach CouchDB server at {}: {}".format(
TEST_CONFIG["couchdb"]["url"], e
Expand All @@ -85,7 +92,7 @@
method="HEAD",
)
try:
urllib.request.urlopen(request)
urllib.request.urlopen(request, timeout=5)
except urllib.error.HTTPError as e:
if e.code != 404:
raise
Expand All @@ -95,7 +102,7 @@
headers=default_headers,
method="PUT",
)
urllib.request.urlopen(request)
urllib.request.urlopen(request, timeout=5)


# Create the database if not existing
Expand All @@ -105,7 +112,7 @@
method="PUT",
)
try:
urllib.request.urlopen(request)
urllib.request.urlopen(request, timeout=5)
except urllib.error.HTTPError as e:
if e.code == 412:
# TODO make more failsafe: Delete and recreate database if it exists already
Expand Down Expand Up @@ -136,7 +143,7 @@
).encode(),
)
# TODO make more failsafe: Set password of user if they exist already
urllib.request.urlopen(request)
urllib.request.urlopen(request, timeout=5)


# Add user as member of database
Expand All @@ -154,4 +161,4 @@
}
).encode(),
)
urllib.request.urlopen(request)
urllib.request.urlopen(request, timeout=5)
43 changes: 35 additions & 8 deletions sdk/test/_helper/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@

import base64
import configparser
import http.client
import os
import os.path
import urllib.error
import unittest
import urllib.request
from typing import Final, Optional

TEST_CONFIG = configparser.ConfigParser()
TEST_CONFIG.read(
Expand All @@ -21,13 +23,25 @@
)


def env_flag(name: str) -> bool:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice helper. server/test/_helper/test_helpers.py still parses REQUIRE_SERVER_INTEGRATION_TESTS with the same inline expression, though. Should it use the same accepted values, so the two flags don't drift apart?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It already accepts the same values. It can't import env_flag because the server tests don't depend on sdk/test, so I'd leave it.

"""Return whether the environment variable ``name`` is set to "1", "true" or "yes" (case-insensitive)."""
return os.environ.get(name, "false").lower() in {"1", "true", "yes"}


# By default, the schema validation tests are skipped when the AAS schema files are missing, so that a plain local
# `python -m unittest` run doesn't require downloading them first. Set this environment variable to "1"/"true"
# (e.g. in CI) to instead make those tests fail if the files are missing, so a broken download can't silently cause
# the tests to be skipped without anyone noticing.
REQUIRE_SCHEMAS = os.environ.get("REQUIRE_SCHEMA_TESTS", "false").lower() in {"1", "true", "yes"}
REQUIRE_SCHEMAS: Final[bool] = env_flag("REQUIRE_SCHEMA_TESTS")

# Likewise, the CouchDB tests are skipped when no CouchDB is reachable. Set this environment variable to fail them
# instead (see require_couchdb()).
REQUIRE_COUCHDB_INTEGRATION_TESTS: Final[bool] = env_flag("REQUIRE_COUCHDB_INTEGRATION_TESTS")

# Check if CouchDB database is available. Otherwise, skip tests.
# Check if the CouchDB test database is reachable. The timeout keeps an unresponsive server from stalling the test run.
# OSError covers HTTP errors (urllib's URLError) as well as refused connections and timeouts. HTTPException covers
# malformed responses, e.g. from a service on the port that does not speak HTTP.
COUCHDB_ERROR: Optional[Exception] = None
try:
request = urllib.request.Request(
"{}/{}".format(
Expand All @@ -47,9 +61,22 @@
},
method="HEAD",
)
urllib.request.urlopen(request)
COUCHDB_OKAY = True
COUCHDB_ERROR = None
except urllib.error.URLError as e:
COUCHDB_OKAY = False
urllib.request.urlopen(request, timeout=5).close()
except (OSError, http.client.HTTPException) as e:
COUCHDB_ERROR = e


def require_couchdb() -> None:
"""
Skip the calling test if no CouchDB is reachable, or fail it if ``REQUIRE_COUCHDB_INTEGRATION_TESTS`` is set.

Call it in ``setUpClass()`` of a test class or at the beginning of a test method.
"""
if COUCHDB_ERROR is None:
return
location = "{}/{}".format(TEST_CONFIG["couchdb"]["url"], TEST_CONFIG["couchdb"]["database"])
if REQUIRE_COUCHDB_INTEGRATION_TESTS:
raise RuntimeError(
f"REQUIRE_COUCHDB_INTEGRATION_TESTS is set, but no CouchDB is reachable at {location}: {COUCHDB_ERROR}"
)
raise unittest.SkipTest(f"No CouchDB is reachable at {location}: {COUCHDB_ERROR}, skipping test")
24 changes: 7 additions & 17 deletions sdk/test/backend/test_couchdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,14 @@
from basyx.aas.backend import couchdb
from basyx.aas.examples.data.example_aas import *

from test._helper.test_helpers import COUCHDB_ERROR, COUCHDB_OKAY, TEST_CONFIG

source_core: str = (
"couchdb://"
+ TEST_CONFIG["couchdb"]["url"].lstrip("http://")
+ "/"
+ TEST_CONFIG["couchdb"]["database"]
+ "/"
)


@unittest.skipUnless(
COUCHDB_OKAY,
"No CouchDB is reachable at {}/{}: {}".format(
TEST_CONFIG["couchdb"]["url"], TEST_CONFIG["couchdb"]["database"], COUCHDB_ERROR
),
)
from test._helper.test_helpers import TEST_CONFIG, require_couchdb


class CouchDBBackendTest(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
require_couchdb()

def setUp(self) -> None:
self.couch_identifiable_store = couchdb.CouchDBIdentifiableStore(
TEST_CONFIG["couchdb"]["url"], TEST_CONFIG["couchdb"]["database"]
Expand Down
15 changes: 4 additions & 11 deletions sdk/test/examples/test_tutorials.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

from basyx.aas import model

from .._helper.test_helpers import COUCHDB_ERROR, COUCHDB_OKAY, TEST_CONFIG
from .._helper.test_helpers import require_couchdb


class TutorialTest(unittest.TestCase):
Expand All @@ -35,17 +35,10 @@ def test_tutorial_storage(self):
pass
# The tutorial already includes assert statements for the relevant points. So no further checks are required.

@unittest.skipUnless(
COUCHDB_OKAY,
"No CouchDB is reachable at {}/{}: {}".format(
TEST_CONFIG["couchdb"]["url"],
TEST_CONFIG["couchdb"]["database"],
COUCHDB_ERROR,
),
)
def test_tutorial_backend_couchdb(self):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test_tutorial_backend_couchdb still has only pass as its body. It never imports basyx.aas.examples.tutorial_backend_couchdb, so with REQUIRE_COUCHDB_INTEGRATION_TESTS=1 it passes even if the tutorial is broken. Requiring CouchDB here adds no coverage. The import was probably removed by ruff's unused-import fix. Could you import the tutorial inside the test body (with a # noqa: F401 if needed)? The other tutorial tests in this file are empty the same way.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. The other empty tutorial tests are tracked in #634, so I kept them out of this PR.

pass
# The tutorial already includes assert statements for the relevant points. So no further checks are required.
require_couchdb()
# Importing the tutorial runs it. It raises an error if storing or deleting its objects in the CouchDB fails.
from basyx.aas.examples import tutorial_backend_couchdb # noqa: F401

def test_tutorial_serialization_deserialization_json(self):
with temporary_workingdirectory():
Expand Down