Esempio n. 1
0
def test_query(mocked_requests, mocked_requests2):
    woql_client = WOQLClient("http://localhost:6363")
    woql_client.connect(user="******",
                        account="admin",
                        key="root",
                        db="myDBName")

    # WoqlStar is the query in json-ld

    woql_client.query(WoqlStar)

    requests.post.assert_called_once_with(
        "http://localhost:6363/api/woql/admin/myDBName/local/branch/main",
        headers={"Authorization": "Basic YWRtaW46cm9vdA=="},
        verify=False,
        json={
            "commit_info": {
                "author": "admin",
                "message": f"Commit via python client {__version__}",
            },
            "query": WoqlStar,
        },
    )
Esempio n. 2
0
def test_create_database_with_schema(
    mocked_requests, mocked_requests2, create_schema_obj
):
    woql_client = WOQLClient(
        "http://localhost:6363", user="******", account="admin", key="root"
    )
    woql_client.connect()
    assert woql_client.basic_auth() == "admin:root"

    woql_client.create_database(
        "myFirstTerminusDB",
        "admin",
        label="my first db",
        description="my first db comment",
        include_schema=True,
    )

    requests.post.assert_called_once_with(
        "http://localhost:6363/api/db/admin/myFirstTerminusDB",
        headers={"Authorization": "Basic YWRtaW46cm9vdA=="},
        verify=False,
        json={"label": "my first db", "comment": "my first db comment", "schema": True},
    )
def test_csv_handeling(docker_url):
    client = WOQLClient(docker_url)
    assert not client._connected
    # test connect
    client.connect()
    assert client._connected
    # test create db
    client.create_database("test_csv")
    client._get_current_commit()
    assert client._db == "test_csv"
    assert "test_csv" in client.list_databases()
    csv_file_path = _generate_csv(1)  # create testing csv
    try:
        client.insert_csv(csv_file_path)
        client.get_csv(csv_file_path, csv_output_name="new_" + csv_file_path)
        assert filecmp.cmp(csv_file_path, "new_" + csv_file_path)
        csv_file_path = _generate_csv(2)
        client.update_csv(csv_file_path)
        client.get_csv(csv_file_path, csv_output_name="update_" + csv_file_path)
        assert not filecmp.cmp("new_" + csv_file_path, "update_" + csv_file_path)
    finally:
        _file_clean_up(csv_file_path)
        _file_clean_up("new_" + csv_file_path)
        _file_clean_up("update_" + csv_file_path)
def test_create_schema(docker_url, test_schema):
    my_schema = test_schema
    client = WOQLClient(docker_url)
    client.connect()
    client.create_database("test_docapi")
    client.insert_document(my_schema,
                           commit_msg="I am checking in the schema",
                           graph_type="schema")
    result = client.get_all_documents(graph_type="schema")
    for item in result:
        if "@id" in item:
            assert item["@id"] in [
                "Employee",
                "Person",
                "Address",
                "Team",
                "Country",
                "Coordinate",
                "Role",
            ]
        elif "@type" in item:
            assert item["@type"] == "@context"
        else:
            raise AssertionError()
Esempio n. 5
0
from terminusdb_client.woqlquery.woql_query import WOQLQuery as WQ
from terminusdb_client.woqlclient.woqlClient import WOQLClient

server_url = "https://127.0.0.1:6363"
user = "******"
account = "admin"
key = "root"
dbid = "unwarbled_widgets"
repository = "local"
label = "Unwarbled Widgets"
description = "The database for storage of the unwarbled widgets"
result_csv = '/app/local_files/unwarbled_widgets.csv'
widgets_url = 'http://terminusdb.github.io/terminusdb-web-assets/tutorials/episode_1/items.csv'

client = WOQLClient(server_url)
client.connect(user=user,account=account,key=key,db=dbid)

try:
    client.create_database(dbid,user,label=label, description=description)
except Exception as E:
    error_obj = E.errorObj
    if "api:DatabaseAlreadyExists" == error_obj.get("api:error",{}).get("@type",None):
        print(f'Warning: Database "{dbid}" already exists!\n')
    else:
        raise(E)

# Add the schema (there is no harm in adding repeatedly as it is idempotent)
WQ().woql_and(
    WQ().doctype("scm:Widget")
        .label("Widget")
Esempio n. 6
0
def test_copy_client():
    woql_client = WOQLClient("http://localhost:6363")
    copy_client = woql_client.copy()
    assert id(woql_client) != copy_client
Esempio n. 7
0
def test_rollback(mocked_requests):
    woql_client = WOQLClient("http://localhost:6363")
    woql_client.connect(user="******", account="admin", key="root")
    with pytest.raises(NotImplementedError):
        woql_client.rollback()
Esempio n. 8
0
def test_query_nodb(mocked_requests):
    woql_client = WOQLClient("http://localhost:6363")
    woql_client.connect(user="******", account="admin", key="root")
    with pytest.raises(InterfaceError):
        woql_client.query(WoqlStar)
Esempio n. 9
0
def test_wrong_graph_type(mocked_requests, mocked_requests2):
    woql_client = WOQLClient("http://localhost:6363")
    woql_client.connect(user="******", account="admin", key="root", db="myDBName")

    with pytest.raises(ValueError):
        woql_client.create_graph("wrong_graph_name", "mygraph", "add a new graph")
Esempio n. 10
0
def test_bank_tutorial(docker_url):

    user = "******"
    account = "admin"
    key = "root"
    dbid = "bank_balance_example"
    repository = "local"
    label = "Bank Balance Example"
    description = "An example database for playing with bank accounts"

    client = WOQLClient(docker_url)
    client.connect(user=user, account=account, key=key)
    client.create_database(dbid, user, label=label, description=description)

    # Add the schema (there is no harm in adding repeatedly as it is idempotent)
    WOQLQuery().woql_and(WOQLQuery().doctype("scm:BankAccount").label(
        "Bank Account").description("A bank account").property(
            "scm:owner", "xsd:string").label("owner").cardinality(1).property(
                "scm:balance",
                "xsd:nonNegativeInteger").label("owner")).execute(
                    client, "Adding bank account object to schema")

    # Fix bug in schema
    WOQLQuery().woql_and(
        WOQLQuery().delete_quad("scm:balance", "label", "owner",
                                "schema/main"),
        WOQLQuery().add_quad("scm:balance", "label", "balance", "schema/main"),
    ).execute(client, "Label for balance was wrong")

    # Add the data from csv to the main branch (again idempotent as widget ids are chosen from sku)
    WOQLQuery().woql_and(WOQLQuery().insert(
        "doc:mike", "scm:BankAccount").property("scm:owner", "mike").property(
            "scm:balance", 123)).execute(client, "Add mike")

    # try to make mike go below zero
    balance, new_balance = WOQLQuery().vars("Balance", "New Balance")
    with pytest.raises(DatabaseError):
        WOQLQuery().woql_and(
            WOQLQuery().triple("doc:mike", "scm:balance", balance),
            WOQLQuery().delete_triple("doc:mike", "scm:balance", balance),
            WOQLQuery().eval(WOQLQuery().minus(balance, 130), new_balance),
            WOQLQuery().add_triple("doc:mike", "scm:balance", new_balance),
        ).execute(client, "Update mike")

    # Subtract less
    WOQLQuery().woql_and(
        WOQLQuery().triple("doc:mike", "scm:balance", balance),
        WOQLQuery().delete_triple("doc:mike", "scm:balance", balance),
        WOQLQuery().eval(WOQLQuery().minus(balance, 110), new_balance),
        WOQLQuery().add_triple("doc:mike", "scm:balance", new_balance),
    ).execute(client, "Update mike")

    # Make the "branch_office" branch
    branch = "branch_office"
    client.branch(branch)

    # Add some data to the branch
    client.checkout(branch)
    WOQLQuery().woql_and(WOQLQuery().insert(
        "doc:jim", "scm:BankAccount").property("owner", "jim").property(
            "balance", 8)).execute(client, "Adding Jim")

    # Return to the 'main' branch and add Jane
    client.checkout("main")
    WOQLQuery().woql_and(WOQLQuery().insert(
        "doc:jane", "scm:BankAccount").property("owner", "jane").property(
            "balance", 887)).execute(client, "Adding Jane")

    client.rebase(
        rebase_source=f"{user}/{dbid}/{repository}/branch/{branch}",
        author=user,
        message="Merging jim in from branch_office",
    )
    result = WOQLQuery().triple("doc:jim", "scm:balance", 8).execute(client)
    assert (
        len(result.get("bindings")) == 1
    )  # if jim is there, the length of the binding should be 1, if not it will be 0
def test_insert_cheuk(docker_url, test_schema):
    my_schema = test_schema
    Country = my_schema.object.get("Country")
    Address = my_schema.object.get("Address")
    Employee = my_schema.object.get("Employee")
    Role = my_schema.object.get("Role")
    Team = my_schema.object.get("Team")

    uk = Country()
    uk.name = "United Kingdom"
    uk.perimeter = []

    home = Address()
    home.street = "123 Abc Street"
    home.country = uk
    home.postal_code = "A12 345"

    cheuk = Employee()
    cheuk.permisstion = {Role.Admin, Role.Read}
    cheuk.address_of = home
    cheuk.contact_number = "07777123456"
    cheuk.age = 21
    cheuk.name = "Cheuk"
    cheuk.managed_by = cheuk
    cheuk.friend_of = {cheuk}
    cheuk.member_of = Team.IT

    client = WOQLClient(docker_url)
    client.connect(db="test_docapi")
    # client.create_database("test_docapi")
    # print(cheuk._obj_to_dict())
    with pytest.raises(ValueError) as error:
        client.insert_document(home)
        assert str(error.value) == "Subdocument cannot be added directly"
    with pytest.raises(ValueError) as error:
        client.insert_document([cheuk])
        assert (
            str(error.value) ==
            f"{str(id(uk))} is referenced but not captured. Seems you forgot to submit one or more object(s)."
        )
    with pytest.raises(ValueError) as error:
        client.insert_document(cheuk)
        assert (
            str(error.value) ==
            "There are uncaptured references. Seems you forgot to submit one or more object(s)."
        )
    assert cheuk._id is None and uk._id is None
    client.insert_document([uk, cheuk], commit_msg="Adding cheuk")
    assert cheuk._backend_id and cheuk._id
    assert uk._backend_id and uk._id
    result = client.get_all_documents()
    for item in result:
        if item.get("@type") == "Country":
            assert item["name"] == "United Kingdom"
        elif item.get("@type") == "Employee":
            assert item["address_of"]["postal_code"] == "A12 345"
            assert item["address_of"]["street"] == "123 Abc Street"
            assert item["name"] == "Cheuk"
            assert item["age"] == 21
            assert item["contact_number"] == "07777123456"
            assert item["managed_by"] == item["@id"]
        else:
            raise AssertionError()
def test_insert_cheuk_again(docker_url, test_schema):
    client = WOQLClient(docker_url)
    client.connect(db="test_docapi")
    new_schema = WOQLSchema()
    new_schema.from_db(client)
    uk = new_schema.import_objects(
        client.get_document("Country/United%20Kingdom"))

    Address = new_schema.object.get("Address")
    Employee = new_schema.object.get("Employee")
    Role = new_schema.object.get("Role")
    Team = new_schema.object.get("Team")
    Coordinate = new_schema.object.get("Coordinate")

    home = Address()
    home.street = "123 Abc Street"
    home.country = uk
    home.postal_code = "A12 345"

    location = Coordinate(x=0.7, y=51.3)
    uk.perimeter = [location]
    with pytest.raises(ValueError) as error:
        uk.name = "United Kingdom of Great Britain and Northern Ireland"
        assert (str(error.value) ==
                "name has been used to generated id hance cannot be changed.")

    cheuk = Employee()
    cheuk.permisstion = {Role.admin, Role.read}
    cheuk.address_of = home
    cheuk.contact_number = "07777123456"
    cheuk.age = 21
    cheuk.name = "Cheuk"
    cheuk.managed_by = cheuk
    cheuk.friend_of = {cheuk}
    cheuk.member_of = Team.information_technology
    cheuk._id = "Cheuk is back"

    with pytest.raises(ValueError) as error:
        client.update_document([uk])
        assert (
            str(error.value) ==
            f"{str(id(location))} is referenced but not captured. Seems you forgot to submit one or more object(s)."
        )
    with pytest.raises(ValueError) as error:
        client.insert_document(uk)
        assert (
            str(error.value) ==
            "There are uncaptured references. Seems you forgot to submit one or more object(s)."
        )

    client.update_document([location, uk, cheuk],
                           commit_msg="Adding cheuk again")
    assert location._backend_id and location._id
    location.x = -0.7
    result = client.replace_document([location], commit_msg="Fixing location")
    assert len(result) == 1
    result = client.get_all_documents()
    for item in result:
        if item.get("@type") == "Country":
            assert item["name"] == "United Kingdom"
            assert item["perimeter"]
        elif item.get("@type") == "Employee":
            assert item["@id"] == "Employee/Cheuk%20is%20back"
            assert item["address_of"]["postal_code"] == "A12 345"
            assert item["address_of"]["street"] == "123 Abc Street"
            assert item["name"] == "Cheuk"
            assert item["age"] == 21
            assert item["contact_number"] == "07777123456"
            assert item["managed_by"] == item["@id"]
        elif item.get("@type") == "Coordinate":
            assert item["x"] == -0.7
            assert item["y"] == 51.3
        else:
            raise AssertionError()