def test_complex_object(self): self.maxDiff = None json = """{ "ref": {"@ref":{"collection":{"@ref":{"id":"collections"}},"id":"widget"}}, "set_ref": {"@set":{"match":{"@ref":{"collection":{"@ref":{"id":"collections"}},"id":"widget"}},"terms":"Laptop"}}, "date": {"@date":"1970-01-01"}, "time": {"@ts":"1970-01-01T00:00:00.123456789Z"}, "object": {"@obj":{"key":"value"}}, "array": [1, 2], "string": "a string", "number": 1 }""" self.assertJson( json, { "ref": Ref("widget", Native.COLLECTIONS), "set_ref": SetRef({ "match": Ref("widget", Native.COLLECTIONS), "terms": "Laptop" }), "date": parse_date("1970-01-01").date(), "time": FaunaTime("1970-01-01T00:00:00.123456789Z"), "object": { "key": "value" }, "array": [1, 2], "string": "a string", "number": 1 })
def setUpClass(cls): super(ObjectsTest, cls).setUpClass() cls.ref = Ref("123", Ref("frogs", Native.COLLECTIONS)) cls.json_ref = ( '{"@ref":{' '"collection":{"@ref":{"collection":{"@ref":{"id":"collections"}},"id":"frogs"}},' '"id":"123"' '}}')
def test_equality(self): self.assertEqual(query.var("x"), _Expr({"var": "x"})) self.assertEqual( query.match(Ref("widgets_by_name", Native.INDEXES), "computer"), _Expr({ "match": Ref("widgets_by_name", Native.INDEXES), "terms": "computer" }))
def test_login_logout(self): instance_ref = self.client.query( query.create(self.collection_ref, {"credentials": {"password": "******"}}))["ref"] secret = self.client.query( query.login(instance_ref, {"password": "******"}))["secret"] instance_client = self.client.new_session_client(secret=secret) self.assertEqual(instance_client.query( query.select("ref", query.get(Ref("self", Ref("widgets", Native.COLLECTIONS))))), instance_ref) self.assertTrue(instance_client.query(query.logout(True)))
def _parse_json_hook(dct): #pylint: disable=too-many-return-statements """ Looks for FaunaDB types in a JSON object and converts to them if possible. """ if "@ref" in dct: ref = dct["@ref"] if (not "collection" in ref) and (not "database" in ref): return Native.from_name(ref["id"]) return Ref(ref["id"], ref.get("collection"), ref.get("database")) if "@obj" in dct: return dct["@obj"] if "@set" in dct: return SetRef(dct["@set"]) if "@query" in dct: return Query(dct["@query"]) if "@ts" in dct: return FaunaTime(dct["@ts"]) if "@date" in dct: return parse_date(dct["@date"]).date() if "@bytes" in dct: return bytearray(urlsafe_b64decode(dct["@bytes"].encode())) return dct
def fauna_paginate_database(self) -> Tuple[bool, Any, str]: """Fauna paginate database.""" client = self.get_fauna_connection() # database: str = kwargs["database"] try: return client.query(q.paginate(Ref("databases"))) except (BadRequest) as _error: # pragma: no cover raise ValueError("Fauna error.") from _error
def test_repr(self): self.assertRegexCompat(repr(query.var("x")), r"Expr\({u?'var': u?'x'}\)") self.assertRegexCompat(repr(Ref("collections")), r"Ref\(id=collections\)") self.assertRegexCompat( repr(SetRef(query.match(query.index("widgets")))), r"SetRef\({u?'match': Expr\({u?'index': u?'widgets'}\)}\)")
def test_set_ref(self): self.assertJson(SetRef({"match": Ref("widgets", Native.INDEXES), "terms": "Laptop"}), ('{' '"@set":{' '"match":{"@ref":{"collection":{"@ref":{"id":"indexes"}},"id":"widgets"}},' '"terms":"Laptop"' '}' '}'))
def get(event, context): # fetch todo from the database ref = Ref(TODOS, event['pathParameters']['id']) fetched = client.query(query.get(ref)) # create a response response = {"statusCode": 200, "body": json.dumps(make_result(fetched))} return response
def test_array(self): self.assertJson('[1, "a string"]', [1, "a string"]) self.assertJson( """[ {"@ref":{"id":"widgets","collection":{"@ref":{"id":"collections"}}}}, {"@date":"1970-01-01"} ]""", [ Ref("widgets", Native.COLLECTIONS), parse_date("1970-01-01").date() ])
def delete(event, context): # delete the todo from the database client.query(query.delete(Ref(TODOS, event['pathParameters']['id']))) # create a response response = { "statusCode": 200 } return response
def test_nested_references(self): client1 = self.create_new_database(self.admin_client, "parent-database") client2 = self.create_new_database(client1, "child-database") client2.query(query.create_collection({"name": "a_collection"})) client2.query( query.create_role({ "name": "a_role", "privileges": { "resource": query.collections(), "actions": { "read": True } } })) nested_database_ref = query.database("child-database", query.database("parent-database")) nested_collection_ref = query.collection("a_collection", nested_database_ref) nested_role_ref = query.role("a_role", nested_database_ref) self.assertEqual( self.admin_client.query(query.exists(nested_collection_ref)), True) self.assertEqual( self.admin_client.query(query.exists(nested_role_ref)), True) parent_db_ref = Ref("parent-database", Native.DATABASES) child_db_ref = Ref("child-database", Native.DATABASES, parent_db_ref) self.assertEqual( self.admin_client.query( query.paginate( query.collections(nested_database_ref)))["data"], [Ref("a_collection", Native.COLLECTIONS, child_db_ref)]) self.assertEqual( self.admin_client.query( query.paginate(query.roles(nested_database_ref)))["data"], [Ref("a_role", Native.ROLES, child_db_ref)])
def test_ref(self): self.assertJson('{"@ref":{"id":"collections"}}', Native.COLLECTIONS) self.assertJson( '{"@ref":{"id":"widgets","collection":{"@ref":{"id":"collections"}}}}', Ref("widgets", Native.COLLECTIONS)) self.assertJson( """{ "@ref":{ "id":"widgets", "collection":{"@ref":{"id":"collections"}}, "database":{ "@ref":{ "id":"db", "collection":{"@ref":{"id":"databases"}} } } } }""", Ref("widgets", Native.COLLECTIONS, Ref("db", Native.DATABASES)))
def test_set_ref(self): self.assertJson( """{ "@set":{ "match":{"@ref":{"id":"widgets","collection":{"@ref":{"id":"collections"}}}}, "terms":"Laptop" } }""", SetRef({ "match": Ref("widgets", Native.COLLECTIONS), "terms": "Laptop" }))
def test_set(self): index = Ref("frogs_by_size", Native.INDEXES) json_index = '{"@ref":{"collection":{"@ref":{"id":"indexes"}},"id":"frogs_by_size"}}' match = SetRef(query.match(index, self.ref)) json_match = '{"@set":{"match":%s,"terms":%s}}' % (json_index, self.json_ref) self.assertJson(match, json_match) self.assertNotEqual( match, SetRef( query.match(index, query.ref(query.collection("frogs"), "456"))))
def test_ref(self): self.assertJson(self.ref, self.json_ref) self.assertRaises(ValueError, lambda: Ref(None)) ref = Ref("123", Native.KEYS) self.assertEqual(ref.id(), "123") self.assertEqual(ref.collection(), Native.KEYS) self.assertEqual(ref.database(), None) self.assertRegexCompat(repr(ref), r"Ref\(id=123, collection=Ref\(id=keys\)\)")
def update(event, context): data = json.loads(event['body']) if 'text' not in data or 'checked' not in data: logging.error("Validation Failed") raise Exception("Couldn't update the todo item.") data = { 'text': data['text'], 'checked': data['checked'], 'updatedAt': query.time('now') } # update the todo in the database ref = Ref(TODOS, event['pathParameters']['id']) updated = client.query(query.update(ref, {'data': data})) # create a response response = {"statusCode": 200, "body": json.dumps(make_result(updated))} return response
def test_nested_keys(self): client = self.create_new_database(self.admin_client, "db-for-keys") client.query(query.create_database({"name": "db-test"})) server_key = client.query(query.create_key({ "database": query.database("db-test"), "role": "server" })) admin_key = client.query(query.create_key({ "database": query.database("db-test"), "role": "admin" })) server_key_ref = Ref(server_key["ref"].id(), cls=Ref("keys", db=Ref("db-for-keys", cls=Native.DATABASES))) admin_key_ref = Ref(admin_key["ref"].id(), cls=Ref( "keys", db=Ref("db-for-keys", cls=Native.DATABASES))) self.assertEqual( self.admin_client.query(query.paginate(query.keys(query.database("db-for-keys"))))["data"], [server_key_ref, admin_key_ref] )
def test_ref(self): self.assertJson(Ref("collections"), '{"@ref":{"id":"collections"}}') self.assertJson( Ref("widgets", Native.COLLECTIONS), '{"@ref":{"collection":{"@ref":{"id":"collections"}},"id":"widgets"}}' )
def test_role(self): self.assertEqual(self._q(query.role("role-name")), Ref("role-name", Native.ROLES))
def test_access_provider(self): self.assertEqual(self._q(query.access_provider("pvd-name")), Ref("pvd-name", Native.ACCESS_PROVIDERS))
def test_function(self): self.assertEqual(self._q(query.function("fn-name")), Ref("fn-name", Native.FUNCTIONS))
def test_collection(self): self.assertEqual(self._q(query.collection("cls-name")), Ref("cls-name", Native.COLLECTIONS))
def test_index(self): self.assertEqual(self._q(query.index("idx-name")), Ref("idx-name", Native.INDEXES))
def test_database(self): self.assertEqual(self._q(query.database("db-name")), Ref("db-name", Native.DATABASES))
import json import logging import os from faunadb.client import FaunaClient from faunadb.objects import Ref from faunadb import query client = FaunaClient(secret=os.environ['FAUNADB_SECRET']) TODOS = Ref('classes/todos') ALL_TODOS = query.index('all_todos')