Skip to content

Commit

Permalink
test: Add tests for python and JS with pytest and jest. Update some g…
Browse files Browse the repository at this point in the history
…h actions versions
  • Loading branch information
vemonet committed Mar 3, 2024
1 parent 2840850 commit fdca2f7
Show file tree
Hide file tree
Showing 14 changed files with 237 additions and 38 deletions.
28 changes: 22 additions & 6 deletions .github/workflows/test.yml
Expand Up @@ -24,8 +24,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
submodules: true
- run: |
rustup update
cargo install cargo-tarpaulin
Expand All @@ -34,6 +32,24 @@ jobs:
env:
RUST_BACKTRACE: 1

test-js:
name: 🟨 Tests JavaScript
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: |
rustup update
./scripts/test-js.sh
test-python:
name: 🐍 Tests Python
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: |
rustup update
./scripts/test-python.sh
cov:
name: ☂️ Coverage
runs-on: ubuntu-latest
Expand All @@ -47,7 +63,7 @@ jobs:
cargo tarpaulin -p nanopub --out xml --exclude-files lib/src/error.rs --verbose --timeout 120
- name: Upload to codecov.io
uses: codecov/codecov-action@v2
uses: codecov/codecov-action@v4
with:
fail_ci_if_error: true
token: ${{secrets.CODECOV_TOKEN}}
Expand Down Expand Up @@ -78,10 +94,10 @@ jobs:
- run: bash ./scripts/docs-build.sh

- name: Setup Pages
uses: actions/configure-pages@v3
uses: actions/configure-pages@v4

- name: Upload artifact
uses: actions/upload-pages-artifact@v1
uses: actions/upload-pages-artifact@v3
with:
path: './target/doc'

Expand All @@ -103,7 +119,7 @@ jobs:
with:
python-version: ${{ env.STABLE_PYTHON_VERSION }}

- uses: actions/setup-java@v3
- uses: actions/setup-java@v4
with:
distribution: 'temurin' # See 'Supported distributions' for available options
java-version: '21'
Expand Down
8 changes: 7 additions & 1 deletion .gitignore
@@ -1,4 +1,3 @@
.venv
target/
Cargo.lock
tarpaulin-report.html
Expand All @@ -7,9 +6,16 @@ tarpaulin-report.html
node_modules/
pkg*/
package-lock.json
yarn.lock
pnpm-lock.yaml
*.lock
js/LICENSE.txt

# Python
.venv
__pycache__/
.pytest_cache

# HTML docs generated by mdbook
lib/docs/docs
/theme/
Expand Down
9 changes: 9 additions & 0 deletions js/jest.config.ts
@@ -0,0 +1,9 @@
import type {Config} from 'jest';

const config: Config = {
preset: 'ts-jest',
verbose: true,
// testEnvironment: 'node',
};

export default config;
12 changes: 9 additions & 3 deletions js/package.json
@@ -1,7 +1,7 @@
{
"version": "0.0.0",
"name": "@nanopub/sign",
"description": "JavaScript bindings for the Nanopub rust toolkit",
"description": "JavaScript bindings for the Nanopub toolkit writen in Rust",
"license": "MIT",
"homepage": "https://github.com/vemonet/nanopub-rs",
"module": "web.js",
Expand All @@ -21,7 +21,9 @@
],
"scripts": {
"fmt": "prettier \"**/*.{ts,tsx,js,cjs,json,md,html}\" --ignore-path .gitignore --write",
"test": "wasm-pack build --debug --target nodejs && mocha",
"old-test": "wasm-pack build --debug --target nodejs && mocha",
"jest" : "jest",
"test": "npm run build && jest",
"build": "rm -rf pkg pkg-web pkg-node && wasm-pack build --release --target web --out-name web && mv pkg pkg-web && wasm-pack build --release --target nodejs --out-name node && mv pkg pkg-node && node build_package.js && rm -r pkg-web pkg-node",
"start": "http-server ./",
"release": "npm run build && npm publish ./pkg --access public",
Expand All @@ -33,8 +35,12 @@
]
},
"devDependencies": {
"@jest/globals": "^29.7.0",
"http-server": "^14.1.1",
"prettier": "^3.1.0"
"jest": "^29.7.0",
"prettier": "^3.1.0",
"ts-jest": "^29.1.1",
"ts-node": "^10.9.2"
},
"prettier": {
"trailingComma": "none",
Expand Down
48 changes: 48 additions & 0 deletions js/tests/nanopub.test.ts
@@ -0,0 +1,48 @@
import {describe, expect, test} from '@jest/globals';
import {Nanopub, NpProfile} from "../pkg/node";

const privKey=`MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCjY1gsFxmak6SOCouJPuEzHNForkqFhgfHE3aAIAx+Y5q6UDEDM9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+4ABYp+foY+Cpcq2btLIeZhiWjsKIrw71+Q/vIe0YDb1PGf6DsoYhmWBpdHzR9HN+hGjvwlsYny2L9Qbfhgxxmsuf7zeFLpQLijjwKBgH7TD28k8IOk5VKec2CNjKd600OYaA3UfCpP/OhDl/RmVtYoHWDcrBrRvkvEEd2/DZ8qw165Zl7gJs3vK+FTYvYVcfIzGPWA1KU7nkntwewmf3i7V8lT8ZTwVRsmObWU60ySJ8qKuwoBQodki2VX12NpMN1wgWe3qUUlr6gLJU4xAoGAet6nD3QKwk6TTmcGVfSWOzvpaDEzGkXjCLaxLKh9GreM/OE+h5aN2gUoFeQapG5rUwI/7Qq0xiLbRXw+OmfAoV2XKv7iI8DjdIh0F06mlEAwQ/B0CpbqkuuxphIbchtdcz/5ra233r3BMNIqBl3VDDVoJlgHPg9msOTRy13lFqc=`;
const orcid="https://orcid.org/0000-0000-0000-0000";
const unsignedRdf = `@prefix : <http://purl.org/nanopub/temp/mynanopub#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix dc: <http://purl.org/dc/terms/> .
@prefix pav: <http://purl.org/pav/> .
@prefix prov: <http://www.w3.org/ns/prov#> .
@prefix np: <http://www.nanopub.org/nschema#> .
@prefix npx: <http://purl.org/nanopub/x/> .
@prefix ex: <http://example.org/> .
:Head {
: np:hasAssertion :assertion ;
np:hasProvenance :provenance ;
np:hasPublicationInfo :pubinfo ;
a np:Nanopublication .
}
:assertion {
ex:mosquito ex:transmits ex:malaria .
}
:provenance {
:assertion prov:hadPrimarySource <http://dx.doi.org/10.3233/ISU-2010-0613> .
}
:pubinfo {
: dc:created "2014-07-24T18:05:11+01:00"^^xsd:dateTime ;
pav:createdBy <http://orcid.org/0000-0002-1267-0234> ;
a npx:ExampleNanopub .
}`

describe('Tests for the curies npm package', () => {
// NOTE: `await init()` only needed in browser environment

test('publish np', async () => {
const profile = new NpProfile(privKey, orcid, "Your Name", "");
const np = await new Nanopub(unsignedRdf).publish(profile);

console.log("Published Nanopub:", np.info());
expect(np.info().published).toBeDefined();
// expect(np.info().trusty_hash).toBe("RAE9traVUygMTJ-k8E1_pVNy3gtf7uUvtHJtPeU64WpA4");
});

});
42 changes: 27 additions & 15 deletions lib/docs/contributing.md
Expand Up @@ -83,14 +83,16 @@ cd nanopub-rs
git checkout -b add-my-contribution
```

### 🧪 Run tests
### 🧪 Test Rust crate

Run tests for all packages:
Run tests for the rust crate:

```bash
cargo test
```

~~~admonish example title="Testing options"
Display prints:
```bash
Expand All @@ -109,25 +111,20 @@ If tests panic without telling on which test it failed:
cargo test -- --test-threads=1
```
~~~

Test the `nanopub` crate with code coverage:

```bash
cargo tarpaulin -p nanopub --out html
```

Test signing a nanopublication with the CLI:

```bash
cd cli
cargo run -- sign ../lib/tests/resources/nanopub_test_blank.trig
```

### 🐍 Run python
### 🐍 Test Python package

Build the pip package, and run the `python/try.py` script:
Build the pip package and run `pytest` tests:

```bash
./scripts/run-python.sh
./scripts/test-python.sh
```

Or just run the script:
Expand All @@ -137,12 +134,12 @@ source .venv/bin/activate
python python/try.py
```

### 🟨 Run JavaScript
### 🟨 Test JavaScript package

Build the npm package:
Build the npm package and run `jest` tests:

```bash
./scripts/run-js.py
./scripts/test-js.sh
```

Start a web server to access the dev webpage:
Expand All @@ -153,6 +150,21 @@ python -m http.server 3000 --directory ./js

Open [localhost:3000](http://localhost:3000) in your web browser.

### ⌨️ Test CLI

Test signing a nanopublication with the commandline interface:

```bash
cd cli
cargo run -- sign ../lib/tests/resources/nanopub_test_blank.trig
```

### 🌈 Run all tests

```bash
./scripts/test-all.sh
```

### ✨ Format

```bash
Expand Down
4 changes: 2 additions & 2 deletions lib/docs/use_python.md
Expand Up @@ -5,9 +5,9 @@
You can easily publish Nanopubs from Python.


```admonish info title="Build a Nanopublication"
~~~admonish info title="Build a Nanopublication"
This package takes an already prepared Nanopublication RDF string as input. If you want to build a Nanopublication programmatically, use the [`nanopub`](https://fair-workflows.github.io/nanopub) pip package. You can then feed the serialized RDF of the built Nanopub to this package functions.
```
~~~

## 📥️ Install

Expand Down
16 changes: 16 additions & 0 deletions lib/tests/nanopub_test.rs
Expand Up @@ -42,6 +42,22 @@ async fn publish_proteinatlas() -> Result<(), Box<dyn Error>> {
Ok(())
}

#[tokio::test]
async fn publish_already_signed() -> Result<(), Box<dyn Error>> {
let np_rdf = fs::read_to_string("./tests/resources/signed.simple1-rsa.trig")?;
let np = Nanopub::new(&np_rdf)?.publish(None, Some("")).await?;
assert!(np.info.published.is_some());
Ok(())
}

#[tokio::test]
async fn publish_unsigned_no_profile_error() -> Result<(), Box<dyn Error>> {
let np_rdf = fs::read_to_string("./tests/resources/simple1-rsa.trig")?;
let np = Nanopub::new(&np_rdf)?.publish(None, None).await;
assert!(np.is_err());
Ok(())
}

#[test]
fn sign_nanopub_blank() -> Result<(), Box<dyn Error>> {
let np_rdf = fs::read_to_string("./tests/resources/nanopub_test_blank.trig")?;
Expand Down
1 change: 1 addition & 0 deletions python/tests/__init__.py
@@ -0,0 +1 @@
"""Tests."""
70 changes: 70 additions & 0 deletions python/tests/test_nanopub.py
@@ -0,0 +1,70 @@
import pytest
from nanopub_sign import Nanopub, NpProfile, get_np_server

rdf_str = """@prefix : <http://purl.org/nanopub/temp/mynanopub#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix dc: <http://purl.org/dc/terms/> .
@prefix pav: <http://purl.org/pav/> .
@prefix prov: <http://www.w3.org/ns/prov#> .
@prefix np: <http://www.nanopub.org/nschema#> .
@prefix npx: <http://purl.org/nanopub/x/> .
@prefix ex: <http://example.org/> .
:Head {
: np:hasAssertion :assertion ;
np:hasProvenance :provenance ;
np:hasPublicationInfo :pubinfo ;
a np:Nanopublication .
}
:assertion {
ex:mosquito ex:transmits ex:malaria .
}
:provenance {
:assertion prov:hadPrimarySource <http://dx.doi.org/10.3233/ISU-2010-0613> .
}
:pubinfo {
: dc:created "2014-07-24T18:05:11+01:00"^^xsd:dateTime ;
pav:createdBy <http://orcid.org/0000-0002-1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Hciywo8qESiA7UYDkU6+hsmxaI01DsttMIdG4lSBbEjA7t4IQC5lyr7xiQKBgQCN87YGJ40Y5ZXCSgOZDepz9hqX2KGOIfnUv2HvXsIfiUwqTXs6HbD18xg3KL4myIBOvywSM+4ABYp+foY+Cpcq2btLIeZhiWjsKIrw71+Q/vIe0YDb1PGf6DsoYhmWBpdHzR9HN+hGjvwlsYny2L9Qbfhgxxmsuf7zeFLpQLijjwKBgH7TD28k8IOk5VKec2CNjKd600OYaA3UfCpP/OhDl/RmVtYoHWDcrBrRvkvEEd2/DZ8qw165Zl7gJs3vK+FTYvYVcfIzGPWA1KU7nkntwewmf3i7V8lT8ZTwVRsmObWU60ySJ8qKuwoBQodki2VX12NpMN1wgWe3qUUlr6gLJU4xAoGAet6nD3QKwk6TTmcGVfSWOzvpaDEzGkXjCLaxLKh9GreM/OE+h5aN2gUoFeQapG5rUwI/7Qq0xiLbRXw+OmfAoV2XKv7iI8DjdIh0F06mlEAwQ/B0CpbqkuuxphIbchtdcz/5ra233r3BMNIqBl3VDDVoJlgHPg9msOTRy13lFqc="""

# Instantiate nanopub profile
profile = NpProfile(
private_key=private_key,
orcid_id="https://orcid.org/0000-0000-0000-0000",
name="",
introduction_nanopub_uri=""
)

def test_check():
np = Nanopub.check(rdf_str)
assert not np.info()["trusty_hash"]
assert not np.info()["published"]

def test_sign():
np = Nanopub.sign(
rdf=rdf_str,
profile=profile,
)
assert np.info()["trusty_hash"]
assert not np.info()["published"]

def test_publish():
np = Nanopub.publish(
rdf=rdf_str,
profile=profile,
server_url=None,
)
# print("Published", np.info())
# print(np.get_rdf())
assert np.info()["trusty_hash"]
assert np.info()["published"]

def test_get_np_server():
print(f"Random server: {get_np_server()}")
assert len(get_np_server()) > 3
9 changes: 0 additions & 9 deletions scripts/run-python.sh

This file was deleted.

7 changes: 7 additions & 0 deletions scripts/test-all.sh
@@ -0,0 +1,7 @@
#!/usr/bin/env bash
set -e

cargo test

./scripts/test-js.sh
./scripts/test-python.sh

0 comments on commit fdca2f7

Please sign in to comment.