Skip to content

Commit

Permalink
fix: Do not send logout request if token is not set
Browse files Browse the repository at this point in the history
  • Loading branch information
subotic committed Oct 11, 2019
1 parent 2eeaeb8 commit 9cfd484
Show file tree
Hide file tree
Showing 18 changed files with 331 additions and 171 deletions.
72 changes: 64 additions & 8 deletions BUILD
@@ -1,41 +1,97 @@
load("@rules_python//python:defs.bzl", "py_binary")
load("@rules_python//python:defs.bzl", "py_library")
load("@rules_python//python:defs.bzl", "py_test")

load("@knora_py_deps//:requirements.bzl", "requirement")

py_library(
name = "knora",
srcs = glob(["knora/knora.py"]),
deps = [
requirement("rdflib"),
requirement("lxml"),
requirement("validators"),
requirement("requests"),
requirement("jsonschema"),
requirement("click"),
requirement("rfc3987"),
requirement("pprint"),
]
)

py_binary(
name = "knora_create_ontology",
srcs = ["knora/create_ontology.py"],
deps = ["knora"]
deps = [
"knora",
requirement("jsonschema"),
requirement("pprint"),
]
)

py_binary(
name = "knora-xml-import",
name = "knora_xml_import",
srcs = ["knora/xml2knora.py"],
deps = ["knora"]
deps = [
"knora",
requirement("lxml"),
requirement("pprint"),
],
)

py_binary(
name = "knora-reset-triplestore",
name = "knora_reset_triplestore",
srcs = ["knora/reset_triplestore.py"],
deps = ["knora"]
deps = [":knora"],
)

py_binary(
name = "knoractl",
srcs = ["knora/knoractl.py"],
deps = ["knora"]
deps = [":knora"],
)

py_test(
name = "test_create_ontology",
srcs = ["test/test_create_ontology.py"],
deps = [":knora"],
)

py_test(
name = "test_create_resource",
srcs = ["test/test_create_resource.py"],
deps = [
":knora",
requirement("pprint"),
],
)

py_test(
name = "test_knora",
srcs = ["tests/test_knora.py"],
deps = ["knora"],
srcs = ["test/test_knora.py"],
deps = [":knora"],
)

test_suite(
name = "all_tests",
tests = [
"test_create_ontology",
"test_create_resource",
"test_knora",
],
)

py_library(
name = "test_lib",
srcs = glob(["test/*.py"]),
deps = [
":knora",
],
)

py_binary(
name = "run_tests",
main = "test/run.py",
srcs = ["test/run.py"],
deps = ["test_lib"],
)
7 changes: 6 additions & 1 deletion Makefile
Expand Up @@ -16,8 +16,13 @@ serve-docs: ## serve docs for local viewing
publish-docs: ## build and publish docs to Github Pages
mkdocs gh-deploy

.PHONY: install-requirements
install-requirements: ## install requirements
pip3 install -r requirements.txt

.PHONY: test
test: ## runs all tests
python3 -m pytest
cd test && python3 -m unittest

clean: ## cleans the project directory
rm -rf dist/ build/ knora.egg-info/ .pytest_cache/ site/
Expand Down
17 changes: 8 additions & 9 deletions README.md
Expand Up @@ -33,6 +33,13 @@ $ python3 setup.py install
The project contains a Makefile defining management tasks. Please use
`make help` to see what is available.

## Testing

```bash
$ make install-requirements
$ make test
```

## Publishing to PyPi

Generate distribution package. Make sure you have the latest versions of `setuptools` and `wheel` installed:
Expand Down Expand Up @@ -70,15 +77,7 @@ $ python3 -m twine upload dist/*
For local development:

```bash
$ python3 setup.py develop
```

## Testing

```bash
$ pip3 install pytest
$ pip3 install --editable .
$ pytest
$ python3 setup.py --editable .
```

## Requirements
Expand Down
42 changes: 42 additions & 0 deletions WORKSPACE
@@ -0,0 +1,42 @@
workspace(name = "knora_py")

# use bazel federation (set of rule versions known to work well together)
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "bazel_federation",
url = "https://github.com/bazelbuild/bazel-federation/releases/download/0.0.1/bazel_federation-0.0.1.tar.gz",
sha256 = "506dfbfd74ade486ac077113f48d16835fdf6e343e1d4741552b450cfc2efb53",
)

# load the initializer methods for all the rules we want to use in this workspace
load("@bazel_federation//:repositories.bzl",
"rules_python",
)

# run any rule specific setups
rules_python()
load("@bazel_federation//setup:rules_python.bzl", "rules_python_setup")
rules_python_setup()

# load py_repositories from rules_python
load("@rules_python//python:repositories.bzl", "py_repositories")
py_repositories()

# load pip_repositories from rules_python
load("@rules_python//python:pip.bzl", "pip_repositories")
pip_repositories()

# allows to use requirements.txt for loading the dependencies
load("@rules_python//python:pip.bzl", "pip_import")

# This rule translates the specified requirements.txt into
# @knora_py_deps//:requirements.bzl, which itself exposes a pip_install method.
pip_import(
name = "knora_py_deps",
requirements = "//:requirements.txt",
)

# Load the pip_install symbol for knora_py_deps, and create the dependencies'
# repositories.
load("@knora_py_deps//:requirements.bzl", "pip_install")
pip_install()
16 changes: 9 additions & 7 deletions knora/knora.py
Expand Up @@ -116,6 +116,7 @@ def __init__(self, server: str, prefixes: Dict[str, str] = None):
"""
self.server = server
self.prefixes = prefixes
self.token = None

def login(self, email: str, password: str):
"""
Expand All @@ -142,12 +143,13 @@ def get_token(self):
return self.token

def logout(self):
req = requests.delete(
self.server + '/v2/authentication',
headers={'Authorization': 'Bearer ' + self.token}
)
self.on_api_error(req)
self.token = None
if self.token is not None:
req = requests.delete(
self.server + '/v2/authentication',
headers={'Authorization': 'Bearer ' + self.token}
)
self.on_api_error(req)
self.token = None

def __del__(self):
self.logout()
Expand Down Expand Up @@ -245,7 +247,7 @@ def create_project(
project['logo'] = logo

jsondata = json.dumps(project)
print(jsondata)
# print(jsondata)

req = requests.post(self.server + "/admin/projects",
headers={'Content-Type': 'application/json; charset=UTF-8',
Expand Down
8 changes: 8 additions & 0 deletions requirements.txt
Expand Up @@ -6,3 +6,11 @@ twine
pytest
mkdocs==1.0.4
mkdocs-material
rdflib
lxml
validators
requests
jsonschema
click
rfc3987
pprint
6 changes: 3 additions & 3 deletions setup.py
Expand Up @@ -27,16 +27,16 @@
'jsonschema',
'click',
'rfc3987',
'pprint'
'pprint',
],
entry_points={
'console_scripts': [
'knora-create-ontology=knora.create_ontology:main',
'knora-xml-import=knora.xml2knora:main',
'knora-reset-triplestore=knora.reset_triplestore:main',
'knoractl=knoractl:main'
'knoractl=knoractl:main',
],
},
include_package_data=True,
zip_safe=False
zip_safe=False,
)
File renamed without changes.
55 changes: 55 additions & 0 deletions test/run.py
@@ -0,0 +1,55 @@
"""Universal launcher for unit tests"""

import argparse
import logging
import os
import sys
import unittest


def main():
"""Parse args, collect tests and run them"""
# Disable *.pyc files
sys.dont_write_bytecode = True

# Add ".." to module search path
cur_dir = os.path.dirname(os.path.realpath(__file__))
top_dir = os.path.abspath(os.path.join(cur_dir, os.pardir))
sys.path.append(top_dir)

# Parse command line arguments
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("-v", "--verbose", action="count", default=0,
help="verbosity level, use: [-v | -vv | -vvv]")
parser.add_argument("-s", "--start-directory", default=None,
help="directory to start discovery")
parser.add_argument("-p", "--pattern", default="test*.py",
help="pattern to match test files ('test*.py' default)")
parser.add_argument("test", nargs="*",
help="test specs (e.g. module.TestCase.test_func)")
args = parser.parse_args()

if not args.start_directory:
args.start_directory = cur_dir

if args.verbose > 2:
logging.basicConfig(level=logging.DEBUG, format="DEBUG: %(message)s")

loader = unittest.TestLoader()
if args.test:
# Add particular tests
for test in args.test:
suite = unittest.TestSuite()
suite.addTests(loader.loadTestsFromName(test))
else:
# Find all tests
suite = loader.discover(args.start_directory, args.pattern)

runner = unittest.TextTestRunner(verbosity=args.verbose)
result = runner.run(suite)
return result.wasSuccessful()


if __name__ == "__main__":
# NOTE: True(success) -> 0, False(fail) -> 1
exit(not main())
File renamed without changes.
File renamed without changes.
12 changes: 12 additions & 0 deletions test/test_create_ontology.py
@@ -0,0 +1,12 @@
import unittest


class TestCreateOntology(unittest.TestCase):

@unittest.skip("not implemented")
def test_create_ontology(self):
pass


if __name__ == "__main__":
unittest.main()
52 changes: 52 additions & 0 deletions test/test_create_resource.py
@@ -0,0 +1,52 @@
import unittest
from pprint import pprint
from knora import Knora, Sipi


class TestCreateResource(unittest.TestCase):

@unittest.skip("not implemented")
def test_create_resource(self):
server = "http://0.0.0.0:3333"
sipi = "http://0.0.0.0:1024"
email = "root@example.com"
password = "test"
projectcode = "00FE"
ontoname = "KPT"

con = Knora(server)
con.login(email, password)
graph = con.get_ontology_graph('00FE', 'kpt')
# print(graph)
# exit(0)
schema = con.create_schema(projectcode, ontoname)
# pprint(schema)
# exit(0)

inst1_info = con.create_resource(schema, "object1", "obj1_inst1", {
"textprop": "Dies ist ein Text!",
"intprop": 7,
"listprop": "options:opt2",
"dateprop": "1966:CE:1967-05-21",
"decimalprop": {'value': "3.14159", 'comment': "Die Zahl PI"},
"geonameprop": "2661604",
"richtextprop": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<text><p><strong>this is</strong> text</p> with standoff</text>",
"intervalprop": "13.57:15.88"
})
pprint(inst1_info)

# first upload image to SIPI
sipi = Sipi(sipi, con.get_token())
res = sipi.upload_image('test.tif')
pprint(res)

fileref = res['uploadedFiles'][0]['internalFilename']
inst2_info = con.create_resource(schema, "object2", "obj2_inst1", {
"titleprop": "Stained glass",
"linkprop": inst1_info['iri']
}, fileref)
pprint(inst2_info)


if __name__ == "__main__":
unittest.main()

0 comments on commit 9cfd484

Please sign in to comment.