diff options
| author | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-10-01 16:01:20 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-10-01 16:01:20 +0000 |
| commit | e8fe116ef4a996a8281bf0b43bed5e9d39c766c8 (patch) | |
| tree | 00170767d45e96ff4c53538201e50321265df38d | |
| parent | 457a463286c2feb1e6d90460acb65927177fcc09 (diff) | |
| download | genenetwork4-e8fe116ef4a996a8281bf0b43bed5e9d39c766c8.tar.gz | |
Add /version endpoint, extract shared python test helper.
* .gitignore: Add __pycache__. * src/lib.rs (app): Add /version route. (VersionInfo, version): New struct and handler, returning name, short_name, version, release, date, and git as a JSON record. * build.rs: New file. Embeds GN4_GIT_HASH and GN4_COMMIT_DATE via cargo:rustc-env, read from git rev-parse and git show of HEAD. * Cargo.toml (dependencies): Add serde with derive feature. [dev-dependencies]: Add serde_json. * tests/version.rs: New file. * test/python/server_test_case.py: New file. ServerTestCase, wait_for_port, BINARY, HOST, PORT moved here from test/python/test_hello_world.py. * test/python/test_hello_world.py: Use server_test_case.ServerTestCase instead of duplicating setUpClass and tearDownClass. * test/python/test_version.py: New file. * guix.scm: Add (gnu packages version-control) to use-modules. (genenetwork4-git)[native-inputs]: Add git-minimal. (genenetwork4-git)[arguments]<#:phases>[python-rest-test]: Run test/python with python3 -m unittest discover instead of invoking test_hello_world.py directly, so test_version.py also runs.
| -rw-r--r-- | .gitignore | 1 | ||||
| -rw-r--r-- | Cargo.lock | 3 | ||||
| -rw-r--r-- | Cargo.toml | 2 | ||||
| -rw-r--r-- | build.rs | 30 | ||||
| -rw-r--r-- | guix.scm | 15 | ||||
| -rw-r--r-- | src/lib.rs | 28 | ||||
| -rw-r--r-- | test/python/server_test_case.py | 42 | ||||
| -rw-r--r-- | test/python/test_hello_world.py | 40 | ||||
| -rw-r--r-- | test/python/test_version.py | 32 | ||||
| -rw-r--r-- | tests/version.rs | 30 |
10 files changed, 178 insertions, 45 deletions
diff --git a/.gitignore b/.gitignore index ea8c4bf..e653f36 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /target +__pycache__ diff --git a/Cargo.lock b/Cargo.lock index b610eb4..9d21872 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -114,6 +114,8 @@ version = "0.1.0" dependencies = [ "axum", "http-body-util", + "serde", + "serde_json", "tokio", "tower", ] @@ -294,6 +296,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", + "serde_derive", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 27eea0f..069bcd5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,8 +5,10 @@ edition = "2024" [dependencies] axum = "0.8.9" +serde = { version = "1.0.229", features = ["derive"] } tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros"] } [dev-dependencies] http-body-util = "0.1.5" +serde_json = "1.0.151" tower = { version = "0.5.3", features = ["util"] } diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..087f52e --- /dev/null +++ b/build.rs @@ -0,0 +1,30 @@ +use std::process::Command; + +// Embeds the short git hash and the HEAD commit's date into the binary via +// env!() in src/lib.rs. Using the commit date (not the wall-clock build +// time) keeps this a pure function of the git commit being built, so the +// build stays reproducible. + +fn main() { + let git_hash = Command::new("git") + .args(["rev-parse", "--short", "HEAD"]) + .output() + .ok() + .filter(|output| output.status.success()) + .and_then(|output| String::from_utf8(output.stdout).ok()) + .map(|s| s.trim().to_string()) + .unwrap_or_else(|| "unknown".to_string()); + println!("cargo:rustc-env=GN4_GIT_HASH={git_hash}"); + + let commit_date = Command::new("git") + .args(["show", "-s", "--format=%cd", "--date=format:%Y%m%d", "HEAD"]) + .output() + .ok() + .filter(|output| output.status.success()) + .and_then(|output| String::from_utf8(output.stdout).ok()) + .map(|s| s.trim().to_string()) + .unwrap_or_else(|| "unknown".to_string()); + println!("cargo:rustc-env=GN4_COMMIT_DATE={commit_date}"); + + println!("cargo:rerun-if-changed=.git/HEAD"); +} diff --git a/guix.scm b/guix.scm index 3d848e0..ce8c23b 100644 --- a/guix.scm +++ b/guix.scm @@ -13,6 +13,7 @@ (guix packages) (guix build-system cargo) (gnu packages python) + (gnu packages version-control) (rust-package)) (define %source-dir (dirname (current-filename))) @@ -29,9 +30,9 @@ (list #:install-source? #f #:phases #~(modify-phases %standard-phases - ;; tests/hello_world.rs (Rust) and test/python/test_hello_world.py - ;; exercise the same endpoint; the Python version mirrors the - ;; Rust one over real HTTP since Python can only reach the + ;; tests/*.rs (Rust) and test/python/test_*.py mirror each + ;; other endpoint for endpoint; the Python side exercises the + ;; REST API over real HTTP since Python can only reach the ;; server that way (clients of the REST API are not all Rust). (add-after 'install 'python-rest-test (lambda* (#:key inputs outputs #:allow-other-keys) @@ -40,10 +41,12 @@ (setenv "GENENETWORK4_BINARY" (string-append out "/bin/genenetwork4")) (setenv "GENENETWORK4_PORT" "3737") - (invoke (string-append python "/bin/python3") - "test/python/test_hello_world.py"))))))) + (with-directory-excursion "test/python" + (invoke (string-append python "/bin/python3") + "-m" "unittest" "discover" "-v")))))))) (native-inputs - (list python + (list git-minimal + python rust-atomic-waker-1.1.2 rust-axum-0.8.9 rust-axum-core-0.5.6 diff --git a/src/lib.rs b/src/lib.rs index d5bbaec..230b878 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,11 +1,35 @@ -use axum::{routing::get, Router}; +use axum::{routing::get, Json, Router}; +use serde::Serialize; /// Build the application router. Public so integration tests (tests/) and /// the binary (src/main.rs) can both use it without binding a real socket. pub fn app() -> Router { - Router::new().route("/", get(hello_world)) + Router::new() + .route("/", get(hello_world)) + .route("/version", get(version)) } async fn hello_world() -> &'static str { "Hello, world!" } + +#[derive(Serialize)] +struct VersionInfo { + name: &'static str, + short_name: &'static str, + version: f64, + release: u32, + date: &'static str, + git: &'static str, +} + +async fn version() -> Json<VersionInfo> { + Json(VersionInfo { + name: "GeneNetwork4", + short_name: "GN4AI", + version: 4.0, + release: 1, + date: env!("GN4_COMMIT_DATE"), + git: env!("GN4_GIT_HASH"), + }) +} diff --git a/test/python/server_test_case.py b/test/python/server_test_case.py new file mode 100644 index 0000000..0025c4b --- /dev/null +++ b/test/python/server_test_case.py @@ -0,0 +1,42 @@ +"""Shared helper for tests that exercise a running genenetwork4 server over +real HTTP (Python can only reach the server this way, unlike the Rust +integration tests under tests/, which call the router in-process). +""" + +import os +import socket +import subprocess +import time +import unittest + +BINARY = os.environ.get("GENENETWORK4_BINARY", "genenetwork4") +HOST = "127.0.0.1" +PORT = os.environ.get("GENENETWORK4_PORT", "3000") + + +def wait_for_port(host, port, timeout=10): + deadline = time.time() + timeout + while time.time() < deadline: + try: + with socket.create_connection((host, int(port)), timeout=0.5): + return True + except OSError: + time.sleep(0.1) + return False + + +class ServerTestCase(unittest.TestCase): + """Spawns the genenetwork4 binary for the duration of the test class.""" + + @classmethod + def setUpClass(cls): + env = dict(os.environ, GENENETWORK4_PORT=PORT) + cls.proc = subprocess.Popen([BINARY], env=env) + if not wait_for_port(HOST, PORT): + cls.proc.terminate() + raise RuntimeError(f"server did not start listening on {HOST}:{PORT}") + + @classmethod + def tearDownClass(cls): + cls.proc.terminate() + cls.proc.wait(timeout=5) diff --git a/test/python/test_hello_world.py b/test/python/test_hello_world.py index d146b89..989fc85 100644 --- a/test/python/test_hello_world.py +++ b/test/python/test_hello_world.py @@ -1,46 +1,12 @@ -"""Mirrors tests/hello_world.rs: exercises the REST API over real HTTP, -rather than in-process, since Python can only reach the server this way. - -Usage: GENENETWORK4_BINARY=/path/to/genenetwork4 python3 test_hello_world.py -""" +"""Mirrors tests/hello_world.rs.""" import http.client -import os -import socket -import subprocess -import time import unittest -BINARY = os.environ.get("GENENETWORK4_BINARY", "genenetwork4") -HOST = "127.0.0.1" -PORT = os.environ.get("GENENETWORK4_PORT", "3000") - - -def wait_for_port(host, port, timeout=10): - deadline = time.time() + timeout - while time.time() < deadline: - try: - with socket.create_connection((host, int(port)), timeout=0.5): - return True - except OSError: - time.sleep(0.1) - return False - - -class HelloWorldTest(unittest.TestCase): - @classmethod - def setUpClass(cls): - env = dict(os.environ, GENENETWORK4_PORT=PORT) - cls.proc = subprocess.Popen([BINARY], env=env) - if not wait_for_port(HOST, PORT): - cls.proc.terminate() - raise RuntimeError(f"server did not start listening on {HOST}:{PORT}") +from server_test_case import HOST, PORT, ServerTestCase - @classmethod - def tearDownClass(cls): - cls.proc.terminate() - cls.proc.wait(timeout=5) +class HelloWorldTest(ServerTestCase): def test_hello_world_returns_ok_with_greeting(self): conn = http.client.HTTPConnection(HOST, int(PORT), timeout=5) try: diff --git a/test/python/test_version.py b/test/python/test_version.py new file mode 100644 index 0000000..2fb46e9 --- /dev/null +++ b/test/python/test_version.py @@ -0,0 +1,32 @@ +"""Mirrors tests/version.rs.""" + +import http.client +import json +import unittest + +from server_test_case import HOST, PORT, ServerTestCase + + +class VersionTest(ServerTestCase): + def test_version_returns_ok_with_json_record(self): + conn = http.client.HTTPConnection(HOST, int(PORT), timeout=5) + try: + conn.request("GET", "/version") + response = conn.getresponse() + body = response.read() + finally: + conn.close() + self.assertEqual(response.status, 200) + + record = json.loads(body) + self.assertEqual(record["name"], "GeneNetwork4") + self.assertEqual(record["short_name"], "GN4AI") + self.assertEqual(record["version"], 4.0) + self.assertEqual(record["release"], 1) + # date and git are set at build time (see build.rs); just check shape. + self.assertEqual(len(record["date"]), 8) + self.assertTrue(record["git"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/version.rs b/tests/version.rs new file mode 100644 index 0000000..9797555 --- /dev/null +++ b/tests/version.rs @@ -0,0 +1,30 @@ +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use http_body_util::BodyExt; +use serde_json::Value; +use tower::ServiceExt; + +#[tokio::test] +async fn version_returns_ok_with_json_record() { + let response = genenetwork4::app() + .oneshot(Request::builder().uri("/version").body(Body::empty()).unwrap()) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + response.headers().get("content-type").unwrap(), + "application/json" + ); + + let body = response.into_body().collect().await.unwrap().to_bytes(); + let record: Value = serde_json::from_slice(&body).unwrap(); + + assert_eq!(record["name"], "GeneNetwork4"); + assert_eq!(record["short_name"], "GN4AI"); + assert_eq!(record["version"], 4.0); + assert_eq!(record["release"], 1); + // date and git are set at build time (see build.rs); just check shape. + assert_eq!(record["date"].as_str().unwrap().len(), 8); + assert!(!record["git"].as_str().unwrap().is_empty()); +} |
