diff options
author | Sam Thursfield <sam.thursfield@codethink.co.uk> | 2023-02-13 14:13:03 +0100 |
---|---|---|
committer | Sam Thursfield <sam.thursfield@codethink.co.uk> | 2023-02-13 14:55:16 +0100 |
commit | 9d829ace3e5f4e215a32dbd5fc1939abea2a64fa (patch) | |
tree | fd1ddd11755b8141b9b792e1dc28085b2179ec2c /tests | |
parent | 39856ca30aae7c21d01c778196286ca6c67484d2 (diff) | |
download | tracker-9d829ace3e5f4e215a32dbd5fc1939abea2a64fa.tar.gz |
functional-tests: Reformat code using Black formatter
The Python community are mostly using a standard code style defined by
`black` tool these days, let's do the same.
Diffstat (limited to 'tests')
-rw-r--r-- | tests/functional-tests/configuration.py | 34 | ||||
-rw-r--r-- | tests/functional-tests/fixtures.py | 157 | ||||
-rw-r--r-- | tests/functional-tests/test_cli.py | 95 | ||||
-rw-r--r-- | tests/functional-tests/test_coalesce.py | 12 | ||||
-rw-r--r-- | tests/functional-tests/test_collation.py | 45 | ||||
-rw-r--r-- | tests/functional-tests/test_concurrent_query.py | 14 | ||||
-rw-r--r-- | tests/functional-tests/test_distance.py | 24 | ||||
-rw-r--r-- | tests/functional-tests/test_fts_functions.py | 12 | ||||
-rw-r--r-- | tests/functional-tests/test_graph.py | 4 | ||||
-rw-r--r-- | tests/functional-tests/test_group_concat.py | 28 | ||||
-rw-r--r-- | tests/functional-tests/test_insertion.py | 343 | ||||
-rw-r--r-- | tests/functional-tests/test_notifier.py | 42 | ||||
-rw-r--r-- | tests/functional-tests/test_ontology_changes.py | 407 | ||||
-rw-r--r-- | tests/functional-tests/test_ontology_rollback.py | 116 | ||||
-rw-r--r-- | tests/functional-tests/test_portal.py | 438 | ||||
-rw-r--r-- | tests/functional-tests/test_query.py | 14 | ||||
-rw-r--r-- | tests/functional-tests/test_sparql_bugs.py | 25 |
17 files changed, 1111 insertions, 699 deletions
diff --git a/tests/functional-tests/configuration.py b/tests/functional-tests/configuration.py index 649959888..f99fdd526 100644 --- a/tests/functional-tests/configuration.py +++ b/tests/functional-tests/configuration.py @@ -30,39 +30,45 @@ import sys DEFAULT_TIMEOUT = 10 -if 'TRACKER_FUNCTIONAL_TEST_CONFIG' not in os.environ: - raise RuntimeError("The TRACKER_FUNCTIONAL_TEST_CONFIG environment " - "variable must be set to point to the location of " - "the generated configuration.json file.") - -with open(os.environ['TRACKER_FUNCTIONAL_TEST_CONFIG']) as f: +if "TRACKER_FUNCTIONAL_TEST_CONFIG" not in os.environ: + raise RuntimeError( + "The TRACKER_FUNCTIONAL_TEST_CONFIG environment " + "variable must be set to point to the location of " + "the generated configuration.json file." + ) + +with open(os.environ["TRACKER_FUNCTIONAL_TEST_CONFIG"]) as f: config = json.load(f) -TEST_DBUS_DAEMON_CONFIG_FILE = config['TEST_DBUS_DAEMON_CONFIG_FILE'] -TEST_PORTAL_FLATPAK_INFO = config['TEST_PORTAL_FLATPAK_INFO'] +TEST_DBUS_DAEMON_CONFIG_FILE = config["TEST_DBUS_DAEMON_CONFIG_FILE"] +TEST_PORTAL_FLATPAK_INFO = config["TEST_PORTAL_FLATPAK_INFO"] + def cli_dir(): - return config['TEST_CLI_DIR'] + return config["TEST_CLI_DIR"] def ontologies_dir(): - return config['TEST_ONTOLOGIES_DIR'] + return config["TEST_ONTOLOGIES_DIR"] def tracker_version(): - return config['TRACKER_VERSION'] + return config["TRACKER_VERSION"] def tap_protocol_enabled(): - return config['TEST_TAP_ENABLED'] + return config["TEST_TAP_ENABLED"] TRACKER_DEBUG_TESTS = 1 + def tests_verbose(): tracker_debug_tests = GLib.DebugKey() tracker_debug_tests.key = "tests" tracker_debug_tests.value = TRACKER_DEBUG_TESTS - flags = GLib.parse_debug_string (os.environ.get('TRACKER_DEBUG', ''), [tracker_debug_tests]) - return (flags & TRACKER_DEBUG_TESTS) + flags = GLib.parse_debug_string( + os.environ.get("TRACKER_DEBUG", ""), [tracker_debug_tests] + ) + return flags & TRACKER_DEBUG_TESTS diff --git a/tests/functional-tests/fixtures.py b/tests/functional-tests/fixtures.py index 1cab229b8..1a8bd036f 100644 --- a/tests/functional-tests/fixtures.py +++ b/tests/functional-tests/fixtures.py @@ -23,7 +23,8 @@ Fixtures used by the Tracker functional-tests. """ import gi -gi.require_version('Tracker', '3.0') + +gi.require_version("Tracker", "3.0") from gi.repository import Gio, GLib from gi.repository import Tracker @@ -56,22 +57,25 @@ def tracker_test_main(): # only errors and warnings should be output here unless the environment # contains G_MESSAGES_DEBUG=. handler_stderr = logging.StreamHandler(stream=sys.stderr) - handler_stderr.addFilter(logging.Filter('sandbox-session-bus.stderr')) + handler_stderr.addFilter(logging.Filter("sandbox-session-bus.stderr")) handler_stdout = logging.StreamHandler(stream=sys.stderr) - handler_stdout.addFilter(logging.Filter('sandbox-session-bus.stdout')) - logging.basicConfig(level=logging.INFO, - handlers=[handler_stderr, handler_stdout], - format='%(message)s') + handler_stdout.addFilter(logging.Filter("sandbox-session-bus.stdout")) + logging.basicConfig( + level=logging.INFO, + handlers=[handler_stderr, handler_stdout], + format="%(message)s", + ) runner = None if cfg.tap_protocol_enabled(): try: from tap import TAPTestRunner + runner = TAPTestRunner() runner.set_stream(True) except ImportError as e: - log.error('No TAP test runner found: %s', e) + log.error("No TAP test runner found: %s", e) raise ut.main(testRunner=runner, verbosity=2) @@ -84,14 +88,15 @@ class TrackerSparqlDirectTest(ut.TestCase): @classmethod def setUpClass(self): - self.tmpdir = tempfile.mkdtemp(prefix='tracker-test-') + self.tmpdir = tempfile.mkdtemp(prefix="tracker-test-") try: self.conn = Tracker.SparqlConnection.new( Tracker.SparqlConnectionFlags.NONE, Gio.File.new_for_path(self.tmpdir), Gio.File.new_for_path(cfg.ontologies_dir()), - None) + None, + ) self.tracker = trackertestutils.helpers.StoreHelper(self.conn) except Exception: @@ -104,7 +109,7 @@ class TrackerSparqlDirectTest(ut.TestCase): shutil.rmtree(self.tmpdir, ignore_errors=True) -class TrackerSparqlBusTest (ut.TestCase): +class TrackerSparqlBusTest(ut.TestCase): """ Fixture for tests using a D-Bus connection to a Tracker database. @@ -124,7 +129,8 @@ class TrackerSparqlBusTest (ut.TestCase): Tracker.SparqlConnectionFlags.NONE, Gio.File.new_for_path(tmpdir), Gio.File.new_for_path(cfg.ontologies_dir()), - None) + None, + ) endpoint = Tracker.EndpointDBus.new(conn, bus, None, None) @@ -135,11 +141,16 @@ class TrackerSparqlBusTest (ut.TestCase): @classmethod def setUpClass(self): - self.tmpdir = tempfile.mkdtemp(prefix='tracker-test-') + self.tmpdir = tempfile.mkdtemp(prefix="tracker-test-") message_queue = multiprocessing.Queue() - self.process = multiprocessing.Process(target=self.database_process_fn, - args=(self.tmpdir, message_queue,)) + self.process = multiprocessing.Process( + target=self.database_process_fn, + args=( + self.tmpdir, + message_queue, + ), + ) try: self.process.start() service_name = message_queue.get() @@ -170,24 +181,32 @@ class TrackerPortalTest(ut.TestCase): bus = Gio.DBusConnection.new_for_address_sync( dbus_address, - Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT | - Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION, None, None) + Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT + | Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION, + None, + None, + ) conn = Tracker.SparqlConnection.new( Tracker.SparqlConnectionFlags.NONE, None, Gio.File.new_for_path(cfg.ontologies_dir()), - None) + None, + ) endpoint = Tracker.EndpointDBus.new(conn, bus, None, None) bus.call_sync( - 'org.freedesktop.DBus', - '/org/freedesktop/DBus', - 'org.freedesktop.DBus', - 'RequestName', - GLib.Variant('(su)', (service_name, 0x4)), - None, 0, -1, None) + "org.freedesktop.DBus", + "/org/freedesktop/DBus", + "org.freedesktop.DBus", + "RequestName", + GLib.Variant("(su)", (service_name, 0x4)), + None, + 0, + -1, + None, + ) loop = GLib.MainLoop.new(None, False) @@ -202,7 +221,7 @@ class TrackerPortalTest(ut.TestCase): pass return GLib.SOURCE_CONTINUE - GLib.timeout_add (50, pop_update, in_queue) + GLib.timeout_add(50, pop_update, in_queue) out_queue.put(None) loop.run() @@ -210,29 +229,33 @@ class TrackerPortalTest(ut.TestCase): def setUp(self): extra_env = {} - extra_env['TRACKER_TEST_PORTAL_FLATPAK_INFO'] = cfg.TEST_PORTAL_FLATPAK_INFO + extra_env["TRACKER_TEST_PORTAL_FLATPAK_INFO"] = cfg.TEST_PORTAL_FLATPAK_INFO self.loop = trackertestutils.mainloop.MainLoop() self.message_queues = {} self.connections = {} self.sandbox = trackertestutils.helpers.TrackerDBusSandbox( - session_bus_config_file=cfg.TEST_DBUS_DAEMON_CONFIG_FILE, extra_env=extra_env) + session_bus_config_file=cfg.TEST_DBUS_DAEMON_CONFIG_FILE, + extra_env=extra_env, + ) self.sandbox.start() self.bus = self.sandbox.get_session_bus_connection() self.dbus_address = self.sandbox.get_session_bus_address() - os.environ['DBUS_SESSION_BUS_ADDRESS'] = self.dbus_address + os.environ["DBUS_SESSION_BUS_ADDRESS"] = self.dbus_address try: log.info("Starting portal") self._portal_proxy = Gio.DBusProxy.new_sync( self.bus, - Gio.DBusProxyFlags.NONE, None, - 'org.freedesktop.portal.Tracker', - '/org/freedesktop/portal/Tracker', - 'org.freedesktop.portal.Tracker', - None) + Gio.DBusProxyFlags.NONE, + None, + "org.freedesktop.portal.Tracker", + "/org/freedesktop/portal/Tracker", + "org.freedesktop.portal.Tracker", + None, + ) except Exception: self.sandbox.stop() @@ -248,10 +271,11 @@ class TrackerPortalTest(ut.TestCase): out_queue = multiprocessing.Queue() thread = threading.Thread( target=self.database_process_fn, - args=(service_name, out_queue, in_queue, self.dbus_address)) + args=(service_name, out_queue, in_queue, self.dbus_address), + ) thread.start() in_queue.get() - self.message_queues[service_name] = [ in_queue, out_queue ] + self.message_queues[service_name] = [in_queue, out_queue] def stop_service(self, service_name): queues = self.message_queues[service_name] @@ -281,7 +305,8 @@ class TrackerPortalTest(ut.TestCase): Tracker.SparqlConnectionFlags.NONE, None, Gio.File.new_for_path(cfg.ontologies_dir()), - None) + None, + ) class CliError(Exception): @@ -292,9 +317,11 @@ class TrackerCommandLineTestCase(ut.TestCase): def setUp(self): self.env = os.environ.copy() - path = self.env.get('PATH', []).split(':') - self.env['PATH'] = ':'.join([cfg.cli_dir()] + path) - self.env['TRACKER_CLI_SUBCOMMANDS_DIR'] = os.path.join(cfg.cli_dir(), 'subcommands') + path = self.env.get("PATH", []).split(":") + self.env["PATH"] = ":".join([cfg.cli_dir()] + path) + self.env["TRACKER_CLI_SUBCOMMANDS_DIR"] = os.path.join( + cfg.cli_dir(), "subcommands" + ) self.bg_processes = [] def tearDown(self): @@ -311,14 +338,15 @@ class TrackerCommandLineTestCase(ut.TestCase): shutil.rmtree(dirpath, ignore_errors=True) def data_path(self, filename): - test_data = pathlib.Path(__file__).parent.joinpath('data') + test_data = pathlib.Path(__file__).parent.joinpath("data") return test_data.joinpath(filename) def run_cli(self, command): command = [str(c) for c in command] - log.info("Running: %s", ' '.join(command)) - result = subprocess.run(command, stdout=subprocess.PIPE, - stderr=subprocess.PIPE, env=self.env) + log.info("Running: %s", " ".join(command)) + result = subprocess.run( + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=self.env + ) if len(result.stdout) > 0: log.debug("stdout: %s", result.stdout) @@ -326,32 +354,45 @@ class TrackerCommandLineTestCase(ut.TestCase): log.debug("stderr: %s", result.stderr) if result.returncode != 0: - raise CliError('\n'.join([ - "CLI command failed.", - "Command: %s" % ' '.join(command), - "Error: %s" % result.stderr.decode('utf-8')])) - - return result.stdout.decode('utf-8') + raise CliError( + "\n".join( + [ + "CLI command failed.", + "Command: %s" % " ".join(command), + "Error: %s" % result.stderr.decode("utf-8"), + ] + ) + ) + + return result.stdout.decode("utf-8") def run_background(self, command, init_string=None): command = [str(c) for c in command] - log.info("Running in background: %s", ' '.join(command)) + log.info("Running in background: %s", " ".join(command)) result = subprocess.Popen( - command, stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL, env=self.env, - encoding='UTF-8') + command, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + env=self.env, + encoding="UTF-8", + ) initialized = False if result.returncode != None: - raise CliError('\n'.join([ - "CLI command failed.", - "Command: %s" % ' '.join(command), - "Error: %s" % result.stderr.decode('utf-8')])) + raise CliError( + "\n".join( + [ + "CLI command failed.", + "Command: %s" % " ".join(command), + "Error: %s" % result.stderr.decode("utf-8"), + ] + ) + ) # Wait for the specified output while init_string and not initialized: - txt = result.stdout.readline(); + txt = result.stdout.readline() initialized = txt.find(init_string) >= 0 result.stdout.close() - self.bg_processes.append(result); + self.bg_processes.append(result) diff --git a/tests/functional-tests/test_cli.py b/tests/functional-tests/test_cli.py index 050984a35..b4f1c2536 100644 --- a/tests/functional-tests/test_cli.py +++ b/tests/functional-tests/test_cli.py @@ -30,11 +30,10 @@ import random class TestCli(fixtures.TrackerCommandLineTestCase): def test_version(self): """Check we're testing the correct version of the CLI""" - output = self.run_cli( - ['tracker3', '--version']) + output = self.run_cli(["tracker3", "--version"]) version_line = output.splitlines()[0] - expected_version_line = 'Tracker %s' % configuration.tracker_version() + expected_version_line = "Tracker %s" % configuration.tracker_version() self.assertEqual(version_line, expected_version_line) def test_create_local_database(self): @@ -45,13 +44,27 @@ class TestCli(fixtures.TrackerCommandLineTestCase): # Create the database self.run_cli( - ['tracker3', 'endpoint', '--database', tmpdir, - '--ontology-path', ontology_path]) + [ + "tracker3", + "endpoint", + "--database", + tmpdir, + "--ontology-path", + ontology_path, + ] + ) # Sanity check that it works. self.run_cli( - ['tracker3', 'sparql', '--database', tmpdir, - '--query', 'ASK { ?u a rdfs:Resource }']) + [ + "tracker3", + "sparql", + "--database", + tmpdir, + "--query", + "ASK { ?u a rdfs:Resource }", + ] + ) def test_export(self): """Export contents of a Tracker database.""" @@ -62,26 +75,37 @@ class TestCli(fixtures.TrackerCommandLineTestCase): # Create a database and export it as Turtle. # We don't validate the output in this test, but we should. self.run_cli( - ['tracker3', 'endpoint', '--database', tmpdir, - '--ontology-path', ontology_path]) - self.run_cli( - ['tracker3', 'export', '--database', tmpdir]); - self.run_cli( - ['tracker3', 'export', '--database', tmpdir, '--show-graphs']); + [ + "tracker3", + "endpoint", + "--database", + tmpdir, + "--ontology-path", + ontology_path, + ] + ) + self.run_cli(["tracker3", "export", "--database", tmpdir]) + self.run_cli(["tracker3", "export", "--database", tmpdir, "--show-graphs"]) def test_import(self): """Import a Turtle file into a Tracker database.""" - testdata = str(self.data_path('serialized/test-movie.ttl')) + testdata = str(self.data_path("serialized/test-movie.ttl")) with self.tmpdir() as tmpdir: ontology_path = configuration.ontologies_dir() self.run_cli( - ['tracker3', 'endpoint', '--database', tmpdir, - '--ontology-path', ontology_path]) - self.run_cli( - ['tracker3', 'import', '--database', tmpdir, testdata]); + [ + "tracker3", + "endpoint", + "--database", + tmpdir, + "--ontology-path", + ontology_path, + ] + ) + self.run_cli(["tracker3", "import", "--database", tmpdir, testdata]) def test_http_endpoint(self): """Create a HTTP endpoint for local testing""" @@ -89,20 +113,35 @@ class TestCli(fixtures.TrackerCommandLineTestCase): with self.tmpdir() as tmpdir: ontology_path = configuration.ontologies_dir() port = random.randint(32000, 65000) - address = 'http://127.0.0.1:%d/sparql' % port + address = "http://127.0.0.1:%d/sparql" % port # Create the database self.run_background( - ['tracker3', 'endpoint', '--database', tmpdir, - '--ontology-path', ontology_path, '--http-port', port], - 'Listening') + [ + "tracker3", + "endpoint", + "--database", + tmpdir, + "--ontology-path", + ontology_path, + "--http-port", + port, + ], + "Listening", + ) # Sanity check that it works. self.run_cli( - ['tracker3', 'sparql', - '--remote-service', address, - '--query', 'ASK { ?u a rdfs:Resource }']) - - -if __name__ == '__main__': + [ + "tracker3", + "sparql", + "--remote-service", + address, + "--query", + "ASK { ?u a rdfs:Resource }", + ] + ) + + +if __name__ == "__main__": fixtures.tracker_test_main() diff --git a/tests/functional-tests/test_coalesce.py b/tests/functional-tests/test_coalesce.py index f8961edf7..a2860dd71 100644 --- a/tests/functional-tests/test_coalesce.py +++ b/tests/functional-tests/test_coalesce.py @@ -25,7 +25,7 @@ import unittest as ut import fixtures -class TestCoalesce (fixtures.TrackerSparqlDirectTest): +class TestCoalesce(fixtures.TrackerSparqlDirectTest): """ Insert and instance with some values, and tracker coalesce of some of them with different combinations (first NULL, none NULL, all NULL...) @@ -42,13 +42,17 @@ class TestCoalesce (fixtures.TrackerSparqlDirectTest): nco:fullname \"full name\" ; nco:nameFamily \"family name\" . } - """ % (self.resource_uri) + """ % ( + self.resource_uri + ) self.tracker.update(insert) def tearDown(self): delete = """ DELETE { <%s> a rdfs:Resource. } - """ % (self.resource_uri) + """ % ( + self.resource_uri + ) self.tracker.update(delete) def test_coalesce_first_fine(self): @@ -115,5 +119,5 @@ class TestCoalesce (fixtures.TrackerSparqlDirectTest): assert results[0][0] == "test_coalesce" -if __name__ == '__main__': +if __name__ == "__main__": fixtures.tracker_test_main() diff --git a/tests/functional-tests/test_collation.py b/tests/functional-tests/test_collation.py index 733d4243f..28ed2e1a4 100644 --- a/tests/functional-tests/test_collation.py +++ b/tests/functional-tests/test_collation.py @@ -31,7 +31,7 @@ import unittest as ut import fixtures -class TrackerStoreCollationTests (fixtures.TrackerSparqlDirectTest): +class TrackerStoreCollationTests(fixtures.TrackerSparqlDirectTest): """ Insert few instances with a text field containing collation-problematic words. Ask for those instances order by the field and check the results. @@ -52,26 +52,31 @@ class TrackerStoreCollationTests (fixtures.TrackerSparqlDirectTest): def __insert_text(self, text): uri = "test://collation-01-%d" % (random.randint(1, 1000)) # There is a remote chance to get a duplicate int - while (uri in self.clean_up_instances): + while uri in self.clean_up_instances: uri = "test://collation-01-%d" % (random.randint(1, 1000)) self.clean_up_instances.append(uri) - self.tracker.update (""" + self.tracker.update( + """ INSERT { <%s> a nie:InformationElement ; nie:title "%s" ; nie:description "tracker-collation-test-instance" . } - """ % (uri, text)) + """ + % (uri, text) + ) def get_text_sorted_by_collation(self): - return self.tracker.query (""" + return self.tracker.query( + """ SELECT ?title WHERE { ?u a nie:InformationElement ; nie:title ?title ; nie:description 'tracker-collation-test-instance' . } ORDER BY ?title - """) + """ + ) def __collation_test(self, input_list, expected_list): @@ -82,22 +87,28 @@ class TrackerStoreCollationTests (fixtures.TrackerSparqlDirectTest): self.assertEqual(len(results), len(expected_list)) for r in range(0, len(results)): - self.assertEqual(results[r], expected_list[r], - """Error: + self.assertEqual( + results[r], + expected_list[r], + """Error: Expected : *** %s Result : *** %s Using locale (%s, %s) - """ % (expected_list, - results, - locale.getdefaultlocale()[0], - locale.getdefaultlocale()[1])) + """ + % ( + expected_list, + results, + locale.getdefaultlocale()[0], + locale.getdefaultlocale()[1], + ), + ) def test_collation_01(self): """ Behaves as case-insensitive """ - input_dt = ["abb", "bb", "Abc", "Ba"] - expected = ["abb", "Abc", "Ba", "bb"] + input_dt = ["abb", "bb", "Abc", "Ba"] + expected = ["abb", "Abc", "Ba", "bb"] self.__collation_test(input_dt, expected) def test_collation_02(self): @@ -127,9 +138,11 @@ class TrackerStoreCollationTests (fixtures.TrackerSparqlDirectTest): if __name__ == "__main__": - print(""" + print( + """ # TODO: # * Check what happens in non-english encoding # * Dynamic change of collation - """) + """ + ) fixtures.tracker_test_main() diff --git a/tests/functional-tests/test_concurrent_query.py b/tests/functional-tests/test_concurrent_query.py index 1ef8d69bc..0c080db7a 100644 --- a/tests/functional-tests/test_concurrent_query.py +++ b/tests/functional-tests/test_concurrent_query.py @@ -31,11 +31,12 @@ AMOUNT_OF_TEST_INSTANCES = 100 AMOUNT_OF_QUERIES = 10 -class ConcurrentQueryTests(): +class ConcurrentQueryTests: """ Send a bunch of queries to the daemon asynchronously, to test the queue holding those queries """ + def test_setup(self): self.main_loop = GLib.MainLoop() @@ -45,8 +46,10 @@ class ConcurrentQueryTests(): def mock_data_insert(self): query = "INSERT {\n" for i in range(0, AMOUNT_OF_TEST_INSTANCES): - query += "<test-09:instance-%d> a nco:PersonContact ; nco:fullname 'moe %d'.\n" % ( - i, i) + query += ( + "<test-09:instance-%d> a nco:PersonContact ; nco:fullname 'moe %d'.\n" + % (i, i) + ) query += "}" self.tracker.update(query) @@ -78,11 +81,12 @@ class ConcurrentQueryTests(): cursor = self.conn.query_finish(result) rows = 0 - while cursor.next(): rows += 1 + while cursor.next(): + rows += 1 self.assertEqual(rows, AMOUNT_OF_TEST_INSTANCES) self.finish_counter += 1 - if (self.finish_counter >= AMOUNT_OF_QUERIES): + if self.finish_counter >= AMOUNT_OF_QUERIES: self.timeout_cb() def update_cb(self, obj, result): diff --git a/tests/functional-tests/test_distance.py b/tests/functional-tests/test_distance.py index 9ad6ddd6b..6c1525b10 100644 --- a/tests/functional-tests/test_distance.py +++ b/tests/functional-tests/test_distance.py @@ -24,12 +24,10 @@ Test the distance-calculation functions in SPARQL. import unittest as ut import fixtures -POINT_COORDS = [ - (0, 0), (1, 1), (2, 2), (3, 3), (4, 4) -] +POINT_COORDS = [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] -class TestDistanceFunctions (fixtures.TrackerSparqlDirectTest): +class TestDistanceFunctions(fixtures.TrackerSparqlDirectTest): """ Insert some points and get the distance between them. """ @@ -43,7 +41,11 @@ class TestDistanceFunctions (fixtures.TrackerSparqlDirectTest): slo:longitude %d ; slo:latitude %d . } - """ % ("point://test/point/" + str(self.counter), log, lat) + """ % ( + "point://test/point/" + str(self.counter), + log, + lat, + ) self.tracker.update(insert) self.counter += 1 @@ -53,7 +55,9 @@ class TestDistanceFunctions (fixtures.TrackerSparqlDirectTest): DELETE { <%s> a rdfs:Resource. } - """ % ("point://test/point/" + str (i)) + """ % ( + "point://test/point/" + str(i) + ) self.tracker.update(delete) def get_distance_between_points(self, sum_func, id1, id2): @@ -73,7 +77,11 @@ class TestDistanceFunctions (fixtures.TrackerSparqlDirectTest): slo:latitude ?lat2 ; slo:longitude ?lon2 . } - """ % (sum_func, id1, id2) + """ % ( + sum_func, + id1, + id2, + ) result = self.tracker.query(query_1_to_2) return int(result[0][0]) @@ -125,5 +133,5 @@ class TestDistanceFunctions (fixtures.TrackerSparqlDirectTest): assert d_2_to_3h < d_2_to_3c -if __name__ == '__main__': +if __name__ == "__main__": fixtures.tracker_test_main() diff --git a/tests/functional-tests/test_fts_functions.py b/tests/functional-tests/test_fts_functions.py index e1b33bc1c..761d857ba 100644 --- a/tests/functional-tests/test_fts_functions.py +++ b/tests/functional-tests/test_fts_functions.py @@ -25,10 +25,11 @@ import unittest as ut import fixtures -class TestFTSFunctions (fixtures.TrackerSparqlDirectTest): +class TestFTSFunctions(fixtures.TrackerSparqlDirectTest): """ Insert data with text and check the fts:xxxx functions are returning the expected results """ + @ut.skip("Test currently fails.") def test_fts_rank(self): """ @@ -111,10 +112,9 @@ class TestFTSFunctions (fixtures.TrackerSparqlDirectTest): results = self.tracker.query(query) self.assertEqual(len(results), 3) - self.assertEqual(results[0][0], 'nco:fullname,0,nco:nickname,0') - self.assertEqual(results[1][0], 'nco:fullname,0') - self.assertEqual( - results[2][0], 'nco:fullname,0,nco:nickname,0,nco:nickname,10') + self.assertEqual(results[0][0], "nco:fullname,0,nco:nickname,0") + self.assertEqual(results[1][0], "nco:fullname,0") + self.assertEqual(results[2][0], "nco:fullname,0,nco:nickname,0,nco:nickname,10") delete_sparql = """ DELETE { @@ -126,5 +126,5 @@ class TestFTSFunctions (fixtures.TrackerSparqlDirectTest): self.tracker.update(delete_sparql) -if __name__ == '__main__': +if __name__ == "__main__": fixtures.tracker_test_main() diff --git a/tests/functional-tests/test_graph.py b/tests/functional-tests/test_graph.py index 1b93df467..9a3bcc186 100644 --- a/tests/functional-tests/test_graph.py +++ b/tests/functional-tests/test_graph.py @@ -24,7 +24,7 @@ import unittest as ut import fixtures -class TestGraphs (fixtures.TrackerSparqlDirectTest): +class TestGraphs(fixtures.TrackerSparqlDirectTest): """ Insert triplets in different graphs and check the query results asking in one specific graph, in all of them and so on. @@ -145,5 +145,5 @@ class TestGraphs (fixtures.TrackerSparqlDirectTest): """ -if __name__ == '__main__': +if __name__ == "__main__": fixtures.tracker_test_main() diff --git a/tests/functional-tests/test_group_concat.py b/tests/functional-tests/test_group_concat.py index 5e3f11d26..14c4e799d 100644 --- a/tests/functional-tests/test_group_concat.py +++ b/tests/functional-tests/test_group_concat.py @@ -25,7 +25,7 @@ import unittest as ut import fixtures -class TestGroupConcat (fixtures.TrackerSparqlDirectTest): +class TestGroupConcat(fixtures.TrackerSparqlDirectTest): """ Insert a multivalued property and request the results in GROUP_CONCAT """ @@ -47,7 +47,9 @@ class TestGroupConcat (fixtures.TrackerSparqlDirectTest): nco:imCapability nco:im-capability-media-calls ; nco:imCapability nco:im-capability-file-transfers . } - """ % (uri) + """ % ( + uri + ) self.tracker.update(insert) query = """ @@ -70,23 +72,31 @@ class TestGroupConcat (fixtures.TrackerSparqlDirectTest): results = self.tracker.query(group_concat_query) assert len(results) == 1 - instances = results[0][1].split('|') + instances = results[0][1].split("|") assert len(instances) == 3 - TEXT_CHAT = "http://tracker.api.gnome.org/ontology/v3/nco#im-capability-text-chat" - MEDIA_CALLS = "http://tracker.api.gnome.org/ontology/v3/nco#im-capability-media-calls" - FILE_TRANSFERS = "http://tracker.api.gnome.org/ontology/v3/nco#im-capability-file-transfers" + TEXT_CHAT = ( + "http://tracker.api.gnome.org/ontology/v3/nco#im-capability-text-chat" + ) + MEDIA_CALLS = ( + "http://tracker.api.gnome.org/ontology/v3/nco#im-capability-media-calls" + ) + FILE_TRANSFERS = ( + "http://tracker.api.gnome.org/ontology/v3/nco#im-capability-file-transfers" + ) assert TEXT_CHAT in instances assert MEDIA_CALLS in instances assert FILE_TRANSFERS in instances - #self.assertEquals (str(results[0][0]), "test_insertion_1") + # self.assertEquals (str(results[0][0]), "test_insertion_1") delete = """ DELETE { <%s> a rdfs:Resource. } - """ % (uri) + """ % ( + uri + ) self.tracker.update(delete) -if __name__ == '__main__': +if __name__ == "__main__": fixtures.tracker_test_main() diff --git a/tests/functional-tests/test_insertion.py b/tests/functional-tests/test_insertion.py index 769aec7ae..ab194bba8 100644 --- a/tests/functional-tests/test_insertion.py +++ b/tests/functional-tests/test_insertion.py @@ -27,7 +27,7 @@ import unittest as ut import fixtures -class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): +class TrackerStoreInsertionTests(fixtures.TrackerSparqlDirectTest): """ Insert single and multiple-valued properties, dates (ok and broken) and check the results @@ -46,7 +46,9 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): insert = """ INSERT { <%s> a nie:InformationElement; nie:title \"test_insert_01\". } - """ % (uri) + """ % ( + uri + ) self.tracker.update(insert) """ verify the inserted item """ @@ -55,7 +57,9 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): <%s> a nie:InformationElement ; nie:title ?t . } - """ % (uri) + """ % ( + uri + ) results = self.tracker.query(query) self.assertEqual(str(results[0][0]), "test_insert_01") @@ -63,7 +67,9 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): """ delete the inserted item """ delete = """ DELETE { <%s> a rdfs:Resource. } - """ % (uri) + """ % ( + uri + ) self.tracker.update(delete) def test_insert_02(self): @@ -71,7 +77,8 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): Insert of a bigger set of triplets (linking two objects) """ - self.tracker.update(""" + self.tracker.update( + """ INSERT { <urn:uuid:bob-dylan> a nmm:Artist; nmm:artistName 'Bob Dylan'. @@ -85,7 +92,8 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): nie:title 'Subterranean homesick blues'; nmm:performer <urn:uuid:bob-dylan>. } - """) + """ + ) QUERY = """ SELECT ?uri ?title ?length WHERE { @@ -103,19 +111,22 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): self.assertEqual(result[0][1], "Subterranean homesick blues") self.assertEqual(result[0][2], "219252") - self.tracker.update (""" + self.tracker.update( + """ DELETE { <urn:uuid:bob-dylan> a rdfs:Resource. <file:///a/b/c/10_song3.mp3> a rdfs:Resource. } - """) + """ + ) def test_insert_03(self): """ Checking all the values are inserted """ - self.tracker.update(""" + self.tracker.update( + """ INSERT { <urn:uuid:7646004> a nmm:Artist; nmm:artistName 'John Lennon' . @@ -134,7 +145,8 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): nmm:performer <urn:uuid:7646004>. } - """) + """ + ) QUERY = """ SELECT ?artist ?length ?trackN ?album ?size ?flm ?fc ?filename WHERE { @@ -162,11 +174,12 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): self.assertEqual(result[0][3], "Imagine") self.assertEqual(result[0][4], "17630") # FIXME Tracker returns this translated to the current timezone - #self.assertEquals (result[0][5], "2008-12-23T11:47:02Z") - #self.assertEquals (result[0][6], "2008-12-16T10:41:20Z") + # self.assertEquals (result[0][5], "2008-12-23T11:47:02Z") + # self.assertEquals (result[0][6], "2008-12-16T10:41:20Z") self.assertEqual(result[0][7], "imagine.mp3") - self.tracker.update (""" + self.tracker.update( + """ DELETE { <urn:uuid:123123123> a rdfs:Resource . } @@ -174,7 +187,8 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): DELETE { <file:///a/b/c/imagine.mp3> a rdfs:Resource. } - """) + """ + ) def test_insert_04(self): """ @@ -182,7 +196,8 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): """ for i in range(0, 3): # Delete single valued properties of music file. - self.tracker.update(""" + self.tracker.update( + """ DELETE { <test://instance-1> nie:usageCounter ?v } WHERE { @@ -193,33 +208,41 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): } WHERE { <test://instance-1> nie:contentAccessed ?w . } - """) + """ + ) # Insert the same single valued properties of music file. - self.tracker.update(""" + self.tracker.update( + """ INSERT { <test://instance-1> a nmm:MusicPiece, nfo:FileDataObject; nie:usageCounter '%d'; nie:contentAccessed '2000-01-01T00:4%d:47Z' . - }""" % (i, i)) + }""" + % (i, i) + ) # Query for the property values and verify whether the last change # is applied. - result = self.tracker.query (""" + result = self.tracker.query( + """ SELECT ?playcount ?date WHERE { <test://instance-1> a nmm:MusicPiece ; nie:usageCounter ?playcount ; nie:contentAccessed ?date. - }""") + }""" + ) self.assertEqual(len(result), 1) self.assertEqual(len(result[0]), 2) self.assertEqual(int(result[0][0]), i) self.assertEqual(result[0][1], "2000-01-01T00:4%d:47Z" % (i)) - self.tracker.update (""" + self.tracker.update( + """ DELETE { <test://instance-1> a rdfs:Resource. } - """) + """ + ) def test_insert_05(self): """ @@ -227,30 +250,37 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): """ for i in range(0, 3): # Insert the same single valued properties of music file. - self.tracker.update(""" + self.tracker.update( + """ INSERT OR REPLACE { <test://instance-1> a nmm:MusicPiece, nfo:FileDataObject; nie:usageCounter '%d'; nie:contentAccessed '2000-01-01T00:4%d:47Z' . - }""" % (i, i)) + }""" + % (i, i) + ) # Query for the property values and verify whether the last change # is applied. - result = self.tracker.query (""" + result = self.tracker.query( + """ SELECT ?playcount ?date WHERE { <test://instance-1> a nmm:MusicPiece ; nie:usageCounter ?playcount ; nie:contentAccessed ?date. - }""") + }""" + ) self.assertEqual(len(result), 1) self.assertEqual(len(result[0]), 2) self.assertEqual(int(result[0][0]), i) self.assertEqual(result[0][1], "2000-01-01T00:4%d:47Z" % (i)) - self.tracker.update (""" + self.tracker.update( + """ DELETE { <test://instance-1> a rdfs:Resource. } - """) + """ + ) def test_insert_06(self): """ @@ -259,20 +289,25 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): for i in range(0, 3): # Insert the same single valued properties and insert multi valued # properties at the same time - self.tracker.update(""" + self.tracker.update( + """ INSERT OR REPLACE { <test://instance-2> a nie:InformationElement; nie:title '%d'; nie:keyword '%d' - }""" % (i, i)) + }""" + % (i, i) + ) # Query for the property values and verify whether the last change # is applied. - result = self.tracker.query (""" + result = self.tracker.query( + """ SELECT ?t ?k WHERE { <test://instance-2> nie:title ?t ; nie:keyword ?k - }""") + }""" + ) self.assertEqual(len(result), 3) self.assertEqual(len(result[0]), 2) @@ -285,9 +320,11 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): self.assertEqual(result[2][0], "%d" % i) self.assertEqual(result[2][1], "2") - self.tracker.update (""" + self.tracker.update( + """ DELETE { <test://instance-2> a rdfs:Resource. } - """) + """ + ) def test_insert_07(self): """ @@ -295,7 +332,9 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): """ try: - INSERT_SPARQL = """INSERT OR REPLACE { <test://instance-3> nie:title 'test' }""" + INSERT_SPARQL = ( + """INSERT OR REPLACE { <test://instance-3> nie:title 'test' }""" + ) self.tracker.update(INSERT_SPARQL) except: pass @@ -312,13 +351,17 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): INSERT_SPARQL = """INSERT OR REPLACE { <test://instance-5> a nie:InformationElement ; nie:rootElementOf <test://instance-4> }""" self.tracker.update(INSERT_SPARQL) - self.tracker.update (""" + self.tracker.update( + """ DELETE { <test://instance-4> a rdfs:Resource. } - """) + """ + ) - self.tracker.update (""" + self.tracker.update( + """ DELETE { <test://instance-5> a rdfs:Resource. } - """) + """ + ) def test_insert_08(self): """ @@ -331,10 +374,12 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): INSERT_SPARQL = """INSERT { GRAPH <test://graph-2> { <test://instance-6> a nie:InformationElement ; nie:title 'title 2' } }""" self.tracker.update(INSERT_SPARQL) - result = self.tracker.query (""" + result = self.tracker.query( + """ SELECT ?g ?t WHERE { GRAPH ?g { <test://instance-6> nie:title ?t - } } ORDER BY ?g""") + } } ORDER BY ?g""" + ) self.assertEqual(len(result), 2) self.assertEqual(len(result[0]), 2) @@ -346,10 +391,12 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): INSERT_SPARQL = """INSERT OR REPLACE { GRAPH <test://graph-2> { <test://instance-6> nie:title 'title 1' } }""" self.tracker.update(INSERT_SPARQL) - result = self.tracker.query (""" + result = self.tracker.query( + """ SELECT ?g ?t WHERE { GRAPH ?g { <test://instance-6> nie:title ?t - } } ORDER BY ?g""") + } } ORDER BY ?g""" + ) self.assertEqual(len(result), 2) self.assertEqual(len(result[0]), 2) @@ -361,10 +408,12 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): INSERT_SPARQL = """INSERT OR REPLACE { GRAPH <test://graph-3> { <test://instance-6> a nie:InformationElement ; nie:title 'title 2' } }""" self.tracker.update(INSERT_SPARQL) - result = self.tracker.query (""" + result = self.tracker.query( + """ SELECT ?g ?t WHERE { GRAPH ?g { <test://instance-6> nie:title ?t - } } ORDER BY ?g""") + } } ORDER BY ?g""" + ) self.assertEqual(len(result), 3) self.assertEqual(len(result[0]), 2) @@ -375,24 +424,32 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): self.assertEqual(result[2][0], "test://graph-3") self.assertEqual(result[2][1], "title 2") - self.tracker.update (""" + self.tracker.update( + """ DELETE { <test://instance-6> a rdfs:Resource. } - """) + """ + ) - def __insert_valid_date_test(self, datestring, year, month, day, hours, minutes, seconds, timezone): + def __insert_valid_date_test( + self, datestring, year, month, day, hours, minutes, seconds, timezone + ): """ Insert a property with datestring value, retrieve its components and validate against the expected results (all the other parameters) """ testId = random.randint(10, 1000) - self.tracker.update (""" + self.tracker.update( + """ INSERT { <test://instance-insert-date-%d> a nie:InformationElement; nie:informationElementDate '%s'. } - """ % (testId, datestring)) + """ + % (testId, datestring) + ) - result = self.tracker.query (""" + result = self.tracker.query( + """ SELECT fn:year-from-dateTime (?v) fn:month-from-dateTime (?v) fn:day-from-dateTime (?v) @@ -404,7 +461,9 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): <test://instance-insert-date-%d> a nie:InformationElement; nie:informationElementDate ?v . } - """ % (testId)) + """ + % (testId) + ) try: self.assertEqual(len(result), 1) self.assertEqual(len(result[0]), 7) @@ -417,9 +476,12 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): # FIXME To validate this we need to take into account the locale # self.assertEquals (result[0][7], timezone) finally: - self.tracker.update (""" + self.tracker.update( + """ DELETE { <test://instance-insert-date-%d> a rdfs:Resource. } - """ % (testId)) + """ + % (testId) + ) """Date-Time storage testing """ @@ -428,53 +490,63 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): 1. Insert a InformationElement with date having local timezone info. 2. TEST: Query and verify the various componentes of date """ - self.__insert_valid_date_test("2004-05-06T13:14:15+0400", - "2004", "05", "06", "13", "14", "15", "14400") + self.__insert_valid_date_test( + "2004-05-06T13:14:15+0400", "2004", "05", "06", "13", "14", "15", "14400" + ) def test_insert_date_02(self): """ 1. Insert a InformationElement with date ending with "Z" in TZD. 2. TEST: Query and verify the various componentes of date """ - self.__insert_valid_date_test("2004-05-06T13:14:15Z", - "2004", "05", "06", "13", "14", "15", "0") + self.__insert_valid_date_test( + "2004-05-06T13:14:15Z", "2004", "05", "06", "13", "14", "15", "0" + ) def test_insert_date_03(self): """ 1. Insert a InformationElement with date ending with no TZD. 2. TEST: Query and verify the various componentes of date """ - self.__insert_valid_date_test("2004-05-06T13:14:15", - "2004", "05", "06", "13", "14", "15", "10800") # HEL timezone? + self.__insert_valid_date_test( + "2004-05-06T13:14:15", "2004", "05", "06", "13", "14", "15", "10800" + ) # HEL timezone? - #@ut.skipIf (1, "It times out in the daemon. Investigate") + # @ut.skipIf (1, "It times out in the daemon. Investigate") def test_insert_date_04(self): """ 1. Insert a InformationElement with date having local timezone info with some minutes in it. 2. TEST: Query and verify the various componentes of date """ - self.__insert_valid_date_test("2004-05-06T13:14:15+0230", - "2004", "05", "06", "13", "14", "15", "9000") + self.__insert_valid_date_test( + "2004-05-06T13:14:15+0230", "2004", "05", "06", "13", "14", "15", "9000" + ) - #@ut.skipIf (1, "It times out in the daemon. Investigate") + # @ut.skipIf (1, "It times out in the daemon. Investigate") def __test_insert_date_05(self): """ - 1. Insert a InformationElement with date having local timezone info in negative. - 2. TEST: Query and verify the various componentes of date - """ - self.__insert_valid_date_test("2004-05-06T13:14:15-0230", - "2004", "05", "06", "13", "14", "15", "-9000") + 1. Insert a InformationElement with date having local timezone info in negative. + 2. TEST: Query and verify the various componentes of date + """ + self.__insert_valid_date_test( + "2004-05-06T13:14:15-0230", "2004", "05", "06", "13", "14", "15", "-9000" + ) def __insert_invalid_date_test(self, datestring): - self.assertRaises (Exception, self.tracker.update, """ + self.assertRaises( + Exception, + self.tracker.update, + """ INSERT { <test://instance-insert-invalid-date-01> a nie:InformationElement; nie:informationElementDate '204-05-06T13:14:15+0400'. } - """) + """, + ) - result = self.tracker.query (""" + result = self.tracker.query( + """ SELECT fn:year-from-dateTime (?v) fn:month-from-dateTime (?v) fn:day-from-dateTime (?v) @@ -486,10 +558,12 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): <test://instances-insert-invalid-date-01> a nie:InformationElement ; nie:informationElementDate ?v . } - """) + """ + ) self.assertEqual(len(result), 0) - #@ut.skipIf (1, "It times out in the daemon. Investigate") + # @ut.skipIf (1, "It times out in the daemon. Investigate") + def test_insert_invalid_date_01(self): """ 1. Insert a InformationElement with invalid year in date. @@ -497,7 +571,8 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): """ self.__insert_invalid_date_test("204-05-06T13:14:15+0400") - #@ut.skipIf (1, "It times out in the daemon. Investigate") + # @ut.skipIf (1, "It times out in the daemon. Investigate") + def test_insert_invalid_date_02(self): """ 1. Insert a InformationElement with date without time. @@ -505,14 +580,16 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): """ self.__insert_invalid_date_test("2004-05-06") - #@ut.skipIf (1, "It times out in the daemon. Investigate") + # @ut.skipIf (1, "It times out in the daemon. Investigate") + def test_insert_invalid_date_03(self): """ 1. Insert a InformationElement with date without time but only the "T" separator. """ self.__insert_invalid_date_test("2004-05-06T") - #@ut.skipIf (1, "It times out in the daemon. Investigate") + # @ut.skipIf (1, "It times out in the daemon. Investigate") + def test_insert_invalid_date_04(self): """ 1. Insert a InformationElement with date without time but only the "T" separator. @@ -531,7 +608,9 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): _:tag a nfo:FileDataObject; nie:url '%s'. } - """ % (url) + """ % ( + url + ) # First insert should go ok self.tracker.update(insert) @@ -544,13 +623,18 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): # Only 1 element must be available with the given nie:url select = """ SELECT ?u WHERE { ?u nie:url \"%s\" } - """ % (url) + """ % ( + url + ) self.assertEqual(len(self.tracker.query(select)), 1) # Cleanup - self.tracker.update (""" + self.tracker.update( + """ DELETE { ?u a rdfs:Resource } WHERE { ?u a rdfs:Resource ; nie:url '%s' } - """ % (url)) + """ + % (url) + ) def test_insert_replace_null(self): """ @@ -558,21 +642,22 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): """ self.tracker.update( - """INSERT { <test://instance-null> a nie:DataObject, nie:InformationElement }""") + """INSERT { <test://instance-null> a nie:DataObject, nie:InformationElement }""" + ) + self.tracker.update("""INSERT { <test://instance-ds1> a nie:DataSource }""") + self.tracker.update("""INSERT { <test://instance-ds2> a nie:DataSource }""") + self.tracker.update("""INSERT { <test://instance-ds3> a nie:DataSource }""") self.tracker.update( - """INSERT { <test://instance-ds1> a nie:DataSource }""") - self.tracker.update( - """INSERT { <test://instance-ds2> a nie:DataSource }""") - self.tracker.update( - """INSERT { <test://instance-ds3> a nie:DataSource }""") - self.tracker.update( - """INSERT { <test://instance-null> nie:dataSource <test://instance-ds1>, <test://instance-ds2>, <test://instance-ds3> }""") + """INSERT { <test://instance-null> nie:dataSource <test://instance-ds1>, <test://instance-ds2>, <test://instance-ds3> }""" + ) # null upfront, reset of list, rewrite of new list self.tracker.update( - """INSERT OR REPLACE { <test://instance-null> nie:dataSource null, <test://instance-ds1>, <test://instance-ds2> }""") + """INSERT OR REPLACE { <test://instance-null> nie:dataSource null, <test://instance-ds1>, <test://instance-ds2> }""" + ) result = self.tracker.query( - """SELECT ?ds WHERE { <test://instance-null> nie:dataSource ?ds }""") + """SELECT ?ds WHERE { <test://instance-null> nie:dataSource ?ds }""" + ) self.assertEqual(len(result), 2) self.assertEqual(len(result[0]), 1) self.assertEqual(len(result[1]), 1) @@ -581,9 +666,11 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): # null upfront, reset of list, rewrite of new list, second test self.tracker.update( - """INSERT OR REPLACE { <test://instance-null> nie:dataSource null, <test://instance-ds1>, <test://instance-ds2>, <test://instance-ds3> }""") + """INSERT OR REPLACE { <test://instance-null> nie:dataSource null, <test://instance-ds1>, <test://instance-ds2>, <test://instance-ds3> }""" + ) result = self.tracker.query( - """SELECT ?ds WHERE { <test://instance-null> nie:dataSource ?ds }""") + """SELECT ?ds WHERE { <test://instance-null> nie:dataSource ?ds }""" + ) self.assertEqual(len(result), 3) self.assertEqual(len(result[0]), 1) self.assertEqual(len(result[1]), 1) @@ -594,9 +681,11 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): # null in the middle, rewrite of new list self.tracker.update( - """INSERT OR REPLACE { <test://instance-null> nie:dataSource <test://instance-ds1>, null, <test://instance-ds2>, <test://instance-ds3> }""") + """INSERT OR REPLACE { <test://instance-null> nie:dataSource <test://instance-ds1>, null, <test://instance-ds2>, <test://instance-ds3> }""" + ) result = self.tracker.query( - """SELECT ?ds WHERE { <test://instance-null> nie:dataSource ?ds }""") + """SELECT ?ds WHERE { <test://instance-null> nie:dataSource ?ds }""" + ) self.assertEqual(len(result), 2) self.assertEqual(len(result[0]), 1) self.assertEqual(len(result[1]), 1) @@ -605,33 +694,33 @@ class TrackerStoreInsertionTests (fixtures.TrackerSparqlDirectTest): # null at the end self.tracker.update( - """INSERT OR REPLACE { <test://instance-null> nie:dataSource <test://instance-ds1>, <test://instance-ds2>, <test://instance-ds3>, null }""") + """INSERT OR REPLACE { <test://instance-null> nie:dataSource <test://instance-ds1>, <test://instance-ds2>, <test://instance-ds3>, null }""" + ) result = self.tracker.query( - """SELECT ?ds WHERE { <test://instance-null> nie:dataSource ?ds }""") + """SELECT ?ds WHERE { <test://instance-null> nie:dataSource ?ds }""" + ) self.assertEqual(len(result), 0) # Multiple nulls self.tracker.update( - """INSERT OR REPLACE { <test://instance-null> nie:dataSource null, <test://instance-ds1>, null, <test://instance-ds2>, <test://instance-ds3> }""") + """INSERT OR REPLACE { <test://instance-null> nie:dataSource null, <test://instance-ds1>, null, <test://instance-ds2>, <test://instance-ds3> }""" + ) result = self.tracker.query( - """SELECT ?ds WHERE { <test://instance-null> nie:dataSource ?ds }""") - #self.assertEqual(len(result), 2) + """SELECT ?ds WHERE { <test://instance-null> nie:dataSource ?ds }""" + ) + # self.assertEqual(len(result), 2) self.assertEqual(len(result[0]), 1) self.assertEqual(len(result[1]), 1) self.assertEqual(result[0][0], "test://instance-ds2") self.assertEqual(result[1][0], "test://instance-ds3") - self.tracker.update( - """DELETE { <test://instance-null> a rdfs:Resource. }""") - self.tracker.update( - """DELETE { <test://instance-ds1> a rdfs:Resource. }""") - self.tracker.update( - """DELETE { <test://instance-ds2> a rdfs:Resource. }""") - self.tracker.update( - """DELETE { <test://instance-ds3> a rdfs:Resource. }""") + self.tracker.update("""DELETE { <test://instance-null> a rdfs:Resource. }""") + self.tracker.update("""DELETE { <test://instance-ds1> a rdfs:Resource. }""") + self.tracker.update("""DELETE { <test://instance-ds2> a rdfs:Resource. }""") + self.tracker.update("""DELETE { <test://instance-ds3> a rdfs:Resource. }""") -class TrackerStoreDeleteTests (fixtures.TrackerSparqlDirectTest): +class TrackerStoreDeleteTests(fixtures.TrackerSparqlDirectTest): """ Use DELETE in Sparql and check the information is actually removed """ @@ -642,7 +731,8 @@ class TrackerStoreDeleteTests (fixtures.TrackerSparqlDirectTest): """ # first insert - self.tracker.update (""" + self.tracker.update( + """ INSERT { <urn:uuid:7646001> a nco:Contact; nco:fullname 'Artist_1_delete'. @@ -652,33 +742,40 @@ class TrackerStoreDeleteTests (fixtures.TrackerSparqlDirectTest): nmm:musicAlbum <test://1_Album_delete>; nmm:performer <urn:uuid:7646001>. } - """) + """ + ) # verify the insertion - result = self.tracker.query (""" + result = self.tracker.query( + """ SELECT ?u WHERE { ?u a nmm:MusicPiece ; nfo:genre 'Classic delete' . } - """) + """ + ) self.assertEqual(len(result), 1) self.assertEqual(len(result[0]), 1) self.assertEqual(result[0][0], "test://instance-test-delete-01") # now delete - self.tracker.update(""" + self.tracker.update( + """ DELETE { <test://instance-test-delete-01> a rdfs:Resource. } - """) + """ + ) # Check the instance is not there - result = self.tracker.query (""" + result = self.tracker.query( + """ SELECT ?u WHERE { ?u a nmm:MusicPiece ; nfo:genre 'Classic delete' . } - """) + """ + ) self.assertEqual(len(result), 0) def test_delete_02(self): @@ -694,22 +791,26 @@ class TrackerStoreDeleteTests (fixtures.TrackerSparqlDirectTest): initial = self.tracker.count_instances("nmm:MusicAlbum") """Add a music album """ - self.tracker.update (""" + self.tracker.update( + """ INSERT { <test://instance-delete-02> a nmm:MusicAlbum; nie:title '06_Album_delete'. } - """) + """ + ) after_insert = self.tracker.count_instances("nmm:MusicAlbum") self.assertEqual(initial + 1, after_insert) """Delete the added music album """ - self.tracker.update(""" + self.tracker.update( + """ DELETE { <test://instance-delete-02> a nmm:MusicAlbum. } - """) + """ + ) """get the count of music albums""" after_removal = self.tracker.count_instances("nmm:MusicAlbum") diff --git a/tests/functional-tests/test_notifier.py b/tests/functional-tests/test_notifier.py index e98512458..7e83ce1c0 100644 --- a/tests/functional-tests/test_notifier.py +++ b/tests/functional-tests/test_notifier.py @@ -22,7 +22,8 @@ Test change notifications using TrackerNotifier. """ import gi -gi.require_version('Tracker', '3.0') + +gi.require_version("Tracker", "3.0") from gi.repository import GLib from gi.repository import Tracker @@ -34,7 +35,7 @@ import fixtures import trackertestutils.mainloop -class TrackerNotifierTests(): +class TrackerNotifierTests: """ Test cases for TrackerNotifier. @@ -51,19 +52,23 @@ class TrackerNotifierTests(): self.results_updates = [] self.notifier = self.conn.create_notifier() - self.notifier.connect('events', self.__signal_received_cb) + self.notifier.connect("events", self.__signal_received_cb) def __wait_for_signal(self): """ In the callback of the signals, there should be a self.loop.quit () """ self.timeout_id = GLib.timeout_add_seconds( - configuration.DEFAULT_TIMEOUT, self.__timeout_on_idle) + configuration.DEFAULT_TIMEOUT, self.__timeout_on_idle + ) self.loop.run_checked() def __timeout_on_idle(self): self.loop.quit() - self.fail("Timeout, the signal never came after %i seconds!" % configuration.DEFAULT_TIMEOUT) + self.fail( + "Timeout, the signal never came after %i seconds!" + % configuration.DEFAULT_TIMEOUT + ) def __signal_received_cb(self, notifier, service, graph, events): """ @@ -100,7 +105,7 @@ class TrackerNotifierTests(): self.assertEqual(len(self.results_deletes), 0) self.assertEqual(len(self.results_inserts), 1) self.assertEqual(len(self.results_updates), 0) - assert self.results_inserts[0].get_urn() == 'test://signals-contact-add' + assert self.results_inserts[0].get_urn() == "test://signals-contact-add" def test_02_remove_contact(self): CONTACT = """ @@ -113,9 +118,11 @@ class TrackerNotifierTests(): self.tracker.update(CONTACT) self.__wait_for_signal() - self.tracker.update (""" + self.tracker.update( + """ DELETE { <test://signals-contact-remove> a rdfs:Resource } - """) + """ + ) self.__wait_for_signal() # Validate results: @@ -125,11 +132,13 @@ class TrackerNotifierTests(): def test_03_update_contact(self): self.tracker.update( - "INSERT { <test://signals-contact-update> a nco:PersonContact }") + "INSERT { <test://signals-contact-update> a nco:PersonContact }" + ) self.__wait_for_signal() self.tracker.update( - "INSERT { <test://signals-contact-update> nco:fullname 'wohoo'}") + "INSERT { <test://signals-contact-update> nco:fullname 'wohoo'}" + ) self.__wait_for_signal() self.assertEqual(len(self.results_updates), 1) @@ -138,15 +147,18 @@ class TrackerNotifierTests(): def test_04_fullupdate_contact(self): self.tracker.update( - "INSERT { <test://signals-contact-fullupdate> a nco:PersonContact; nco:fullname 'first value' }") + "INSERT { <test://signals-contact-fullupdate> a nco:PersonContact; nco:fullname 'first value' }" + ) self.__wait_for_signal() - self.tracker.update (""" + self.tracker.update( + """ DELETE { <test://signals-contact-fullupdate> nco:fullname ?x } WHERE { <test://signals-contact-fullupdate> a nco:PersonContact; nco:fullname ?x } INSERT { <test://signals-contact-fullupdate> nco:fullname 'second value'} - """) + """ + ) self.__wait_for_signal() self.assertEqual(len(self.results_deletes), 0) @@ -154,7 +166,7 @@ class TrackerNotifierTests(): self.assertEqual(len(self.results_updates), 1) -class TrackerLocalNotifierTest (fixtures.TrackerSparqlDirectTest, TrackerNotifierTests): +class TrackerLocalNotifierTest(fixtures.TrackerSparqlDirectTest, TrackerNotifierTests): """ Insert/update/remove instances from nco:PersonContact and check that the signals are emitted. @@ -164,7 +176,7 @@ class TrackerLocalNotifierTest (fixtures.TrackerSparqlDirectTest, TrackerNotifie self.base_setup() -class TrackerBusNotifierTest (fixtures.TrackerSparqlBusTest, TrackerNotifierTests): +class TrackerBusNotifierTest(fixtures.TrackerSparqlBusTest, TrackerNotifierTests): """ Insert/update/remove instances from nco:PersonContact and check that the signals are emitted. diff --git a/tests/functional-tests/test_ontology_changes.py b/tests/functional-tests/test_ontology_changes.py index 6ed01bfbf..f2630ba69 100644 --- a/tests/functional-tests/test_ontology_changes.py +++ b/tests/functional-tests/test_ontology_changes.py @@ -22,7 +22,8 @@ Test how the database handles various kinds of schema updates. """ import gi -gi.require_version('Tracker', '3.0') + +gi.require_version("Tracker", "3.0") from gi.repository import GLib from gi.repository import Gio from gi.repository import Tracker @@ -50,7 +51,7 @@ XSD_INTEGER = "http://www.w3.org/2001/XMLSchema#integer" TEST_PREFIX = "http://example.org/ns#" -class OntologyChangeTestTemplate (ut.TestCase): +class OntologyChangeTestTemplate(ut.TestCase): """ Template class for the ontology changes tests. The tests are subclasses of this, implementing these methods: @@ -65,13 +66,13 @@ class OntologyChangeTestTemplate (ut.TestCase): """ def setUp(self): - self.tmpdir = tempfile.mkdtemp(prefix='tracker-test-') + self.tmpdir = tempfile.mkdtemp(prefix="tracker-test-") def tearDown(self): shutil.rmtree(self.tmpdir, ignore_errors=True) def ontology_path(self, param): - return pathlib.Path(__file__).parent.joinpath('data', 'ontologies', param) + return pathlib.Path(__file__).parent.joinpath("data", "ontologies", param) def template_test_ontology_change(self): self.set_ontology_dirs() @@ -83,7 +84,8 @@ class OntologyChangeTestTemplate (ut.TestCase): Tracker.SparqlConnectionFlags.NONE, Gio.File.new_for_path(self.tmpdir), Gio.File.new_for_path(str(self.ontology_path(self.FIRST_ONTOLOGY_DIR))), - None) + None, + ) self.tracker = trackertestutils.helpers.StoreHelper(conn1) self.insert_data() @@ -95,7 +97,8 @@ class OntologyChangeTestTemplate (ut.TestCase): Tracker.SparqlConnectionFlags.NONE, Gio.File.new_for_path(self.tmpdir), Gio.File.new_for_path(str(self.ontology_path(self.SECOND_ONTOLOGY_DIR))), - None) + None, + ) self.tracker = trackertestutils.helpers.StoreHelper(conn2) self.validate_status() @@ -141,8 +144,7 @@ class OntologyChangeTestTemplate (ut.TestCase): for row in dbus_result: if member == str(row[column]): # This is going to fail with pretty printing - self.fail("'%s' wasn't supposed to be in '%s'" % - (member, dbus_result)) + self.fail("'%s' wasn't supposed to be in '%s'" % (member, dbus_result)) return def __assert_ontology_dates(self, first, second): @@ -153,14 +155,15 @@ class OntologyChangeTestTemplate (ut.TestCase): ISO9601_REGEX = "(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)" def get_ontology_date(ontology): - with open(ontology, 'r') as f: + with open(ontology, "r") as f: for line in f: if "nrl:lastModified" in line: getmodtime = re.compile( - 'nrl:lastModified\ \"' + ISO9601_REGEX + '\"') + 'nrl:lastModified\ "' + ISO9601_REGEX + '"' + ) modtime_match = getmodtime.search(line) - if (modtime_match): + if modtime_match: nao_date = modtime_match.group(1) return time.strptime(nao_date, "%Y-%m-%dT%H:%M:%SZ") else: @@ -168,15 +171,19 @@ class OntologyChangeTestTemplate (ut.TestCase): break first_date = get_ontology_date( - self.ontology_path(first).joinpath("91-test.ontology")) + self.ontology_path(first).joinpath("91-test.ontology") + ) second_date = get_ontology_date( - self.ontology_path(second).joinpath("91-test.ontology")) + self.ontology_path(second).joinpath("91-test.ontology") + ) if first_date >= second_date: - self.fail("nrl:lastModified in '%s' is not more recent in the second ontology" % ( - "91-test.ontology")) + self.fail( + "nrl:lastModified in '%s' is not more recent in the second ontology" + % ("91-test.ontology") + ) -class PropertyRangeStringToDate (OntologyChangeTestTemplate): +class PropertyRangeStringToDate(OntologyChangeTestTemplate): """ Change the range of a property from string to date. There shouldn't be any data loss. """ @@ -192,22 +199,24 @@ class PropertyRangeStringToDate (OntologyChangeTestTemplate): def insert_data(self): self.instance = "test://ontology-change/property-range/string-to-date" - self.tracker.update("INSERT { <%s> a test:A ; test:a_string '2010-10-12T13:30:00Z' }" - % (self.instance)) + self.tracker.update( + "INSERT { <%s> a test:A ; test:a_string '2010-10-12T13:30:00Z' }" + % (self.instance) + ) def validate_status(self): # Query the ontology itself - result = self.tracker.query( - "SELECT ?o WHERE { test:a_string rdfs:range ?o }") + result = self.tracker.query("SELECT ?o WHERE { test:a_string rdfs:range ?o }") self.assertEqual(result[0][0], XSD_DATETIME) # Check the value is there result = self.tracker.query( - "SELECT ?o WHERE { <%s> test:a_string ?o . }" % (self.instance)) + "SELECT ?o WHERE { <%s> test:a_string ?o . }" % (self.instance) + ) self.assertEqual(result[0][0], "2010-10-12T13:30:00Z") -class PropertyRangeDateToString (OntologyChangeTestTemplate): +class PropertyRangeDateToString(OntologyChangeTestTemplate): """ Change the range of a property from date to string. There shouldn't be any data loss. """ @@ -223,26 +232,28 @@ class PropertyRangeDateToString (OntologyChangeTestTemplate): def insert_data(self): self.instance = "test://ontology-change/property-range/date-to-string" - self.tracker.update("INSERT { <%s> a test:A ; test:a_string '2010-10-12T13:30:00Z' }" - % (self.instance)) + self.tracker.update( + "INSERT { <%s> a test:A ; test:a_string '2010-10-12T13:30:00Z' }" + % (self.instance) + ) def validate_status(self): # Query the ontology itself - result = self.tracker.query( - "SELECT ?o WHERE { test:a_string rdfs:range ?o }") + result = self.tracker.query("SELECT ?o WHERE { test:a_string rdfs:range ?o }") self.assertEqual(result[0][0], XSD_STRING) # Check the value is there result = self.tracker.query( - "SELECT ?o WHERE { <%s> test:a_string ?o . }" % (self.instance)) + "SELECT ?o WHERE { <%s> test:a_string ?o . }" % (self.instance) + ) self.assertEqual(result[0][0], "2010-10-12T13:30:00Z") -class PropertyRangeIntToString (OntologyChangeTestTemplate): +class PropertyRangeIntToString(OntologyChangeTestTemplate): """ Change the range of a property from int to string. There shouldn't be any data loss. """ - + def test_property_range_int_to_str(self): self.template_test_ontology_change() @@ -253,20 +264,21 @@ class PropertyRangeIntToString (OntologyChangeTestTemplate): def insert_data(self): self.instance = "test://ontology-change/property-range/int-to-string" self.tracker.update( - "INSERT { <%s> a test:A; test:a_int 12. }" % (self.instance)) + "INSERT { <%s> a test:A; test:a_int 12. }" % (self.instance) + ) def validate_status(self): - result = self.tracker.query( - "SELECT ?o WHERE { test:a_int rdfs:range ?o. }") + result = self.tracker.query("SELECT ?o WHERE { test:a_int rdfs:range ?o. }") self.assertEqual(str(result[0][0]), XSD_STRING) # Check the value is there result = self.tracker.query( - "SELECT ?o WHERE { <%s> test:a_int ?o .}" % (self.instance)) + "SELECT ?o WHERE { <%s> test:a_int ?o .}" % (self.instance) + ) self.assertEqual(result[0][0], "12") -class PropertyRangeStringToInt (OntologyChangeTestTemplate): +class PropertyRangeStringToInt(OntologyChangeTestTemplate): """ Change the range of a property from string to int. There shouldn't be any data loss. """ @@ -281,20 +293,21 @@ class PropertyRangeStringToInt (OntologyChangeTestTemplate): def insert_data(self): self.instance = "test://ontology-change/property-range/string-to-int" self.tracker.update( - "INSERT { <%s> a test:A; test:a_int '12'. }" % (self.instance)) + "INSERT { <%s> a test:A; test:a_int '12'. }" % (self.instance) + ) def validate_status(self): - result = self.tracker.query( - "SELECT ?o WHERE { test:a_int rdfs:range ?o. }") + result = self.tracker.query("SELECT ?o WHERE { test:a_int rdfs:range ?o. }") self.assertEqual(str(result[0][0]), XSD_INTEGER) # Check the value is there result = self.tracker.query( - "SELECT ?o WHERE { <%s> test:a_int ?o .}" % (self.instance)) + "SELECT ?o WHERE { <%s> test:a_int ?o .}" % (self.instance) + ) self.assertEqual(result[0][0], "12") -class PropertyMaxCardinality1toN (OntologyChangeTestTemplate): +class PropertyMaxCardinality1toN(OntologyChangeTestTemplate): """ Change cardinality of a property from 1 to N. There shouldn't be any data loss """ @@ -303,8 +316,8 @@ class PropertyMaxCardinality1toN (OntologyChangeTestTemplate): self.template_test_ontology_change() def set_ontology_dirs(self): - #self.FIRST_ONTOLOGY_DIR = "basic" - #self.SECOND_ONTOLOGY_DIR = "cardinality" + # self.FIRST_ONTOLOGY_DIR = "basic" + # self.SECOND_ONTOLOGY_DIR = "cardinality" self.FIRST_ONTOLOGY_DIR = "cardinality" self.SECOND_ONTOLOGY_DIR = "basic-future" @@ -312,24 +325,29 @@ class PropertyMaxCardinality1toN (OntologyChangeTestTemplate): def insert_data(self): self.instance = "test://ontology-change/cardinality/1-to-n" self.tracker.update( - "INSERT { <%s> a test:A; test:a_n_cardinality 'some text'. }" % (self.instance)) + "INSERT { <%s> a test:A; test:a_n_cardinality 'some text'. }" + % (self.instance) + ) result = self.tracker.query( - "SELECT ?o WHERE { test:a_n_cardinality nrl:maxCardinality ?o}") + "SELECT ?o WHERE { test:a_n_cardinality nrl:maxCardinality ?o}" + ) self.assertEqual(int(result[0][0]), 1) def validate_status(self): result = self.tracker.query( - "SELECT ?o WHERE { test:a_n_cardinality nrl:maxCardinality ?o}") + "SELECT ?o WHERE { test:a_n_cardinality nrl:maxCardinality ?o}" + ) self.assertEqual(len(result), 0, "Cardinality should be 0") # Check the value is there result = self.tracker.query( - "SELECT ?o WHERE { <%s> test:a_n_cardinality ?o .}" % (self.instance)) + "SELECT ?o WHERE { <%s> test:a_n_cardinality ?o .}" % (self.instance) + ) self.assertEqual(str(result[0][0]), "some text") -class PropertyMaxCardinalityNto1 (OntologyChangeTestTemplate): +class PropertyMaxCardinalityNto1(OntologyChangeTestTemplate): """ Change the cardinality of a property for N to 1. @@ -347,24 +365,29 @@ class PropertyMaxCardinalityNto1 (OntologyChangeTestTemplate): def insert_data(self): self.instance = "test://ontology-change/cardinality/1-to-n" self.tracker.update( - "INSERT { <%s> a test:A; test:a_n_cardinality 'some text'. }" % (self.instance)) + "INSERT { <%s> a test:A; test:a_n_cardinality 'some text'. }" + % (self.instance) + ) result = self.tracker.query( - "SELECT ?o WHERE { test:a_n_cardinality nrl:maxCardinality ?o}") + "SELECT ?o WHERE { test:a_n_cardinality nrl:maxCardinality ?o}" + ) self.assertEqual(len(result), 0, "Cardinality should be 0") def validate_status(self): result = self.tracker.query( - "SELECT ?o WHERE { test:a_n_cardinality nrl:maxCardinality ?o}") + "SELECT ?o WHERE { test:a_n_cardinality nrl:maxCardinality ?o}" + ) self.assertEqual(int(result[0][0]), 1, "Cardinality should be 1") # Check the value is there result = self.tracker.query( - "SELECT ?o WHERE { <%s> test:a_n_cardinality ?o .}" % (self.instance)) + "SELECT ?o WHERE { <%s> test:a_n_cardinality ?o .}" % (self.instance) + ) self.assertEqual(str(result[0][0]), "some text") -class ClassNotifySet (OntologyChangeTestTemplate): +class ClassNotifySet(OntologyChangeTestTemplate): """ Set nrl:notify to true in a class and check there is no data loss """ @@ -379,18 +402,18 @@ class ClassNotifySet (OntologyChangeTestTemplate): def insert_data(self): self.instance = "test://ontology-change/notify/true" self.tracker.update( - "INSERT { <%s> a test:A; test:a_string 'some text'. }" % (self.instance)) + "INSERT { <%s> a test:A; test:a_string 'some text'. }" % (self.instance) + ) def validate_status(self): - result = self.tracker.query( - "SELECT ?notify WHERE { test:A nrl:notify ?notify}") + result = self.tracker.query("SELECT ?notify WHERE { test:A nrl:notify ?notify}") self.assertEqual(str(result[0][0]), "true") result = self.tracker.query("SELECT ?u WHERE { ?u a test:A. }") self.assertEqual(str(result[0][0]), self.instance) -class ClassNotifyUnset (OntologyChangeTestTemplate): +class ClassNotifyUnset(OntologyChangeTestTemplate): """ Set nrl:notify to true in a class and check there is no data loss """ @@ -405,12 +428,12 @@ class ClassNotifyUnset (OntologyChangeTestTemplate): def insert_data(self): self.instance = "test://ontology-change/notify/true" self.tracker.update( - "INSERT { <%s> a test:A; test:a_string 'some text'. }" % (self.instance)) + "INSERT { <%s> a test:A; test:a_string 'some text'. }" % (self.instance) + ) def validate_status(self): - result = self.tracker.query( - "SELECT ?notify WHERE { test:A nrl:notify ?notify}") - if (len(result) == 1): + result = self.tracker.query("SELECT ?notify WHERE { test:A nrl:notify ?notify}") + if len(result) == 1: # Usually is (none) but it was "true" before so now has value. self.assertEqual(result[0][0], "false") else: @@ -420,7 +443,7 @@ class ClassNotifyUnset (OntologyChangeTestTemplate): self.assertEqual(str(result[0][0]), self.instance) -class PropertyIndexedSet (OntologyChangeTestTemplate): +class PropertyIndexedSet(OntologyChangeTestTemplate): """ Set nrl:indexed true to single and multiple valued properties. Check that instances and content of the property are still in the DB @@ -436,35 +459,45 @@ class PropertyIndexedSet (OntologyChangeTestTemplate): def insert_data(self): # Instance with value in the single valued property self.instance_single_valued = "test://ontology-change/indexed/single/true" - self.tracker.update("INSERT { <%s> a test:A ; test:a_string 'anything 1'. }" - % (self.instance_single_valued)) + self.tracker.update( + "INSERT { <%s> a test:A ; test:a_string 'anything 1'. }" + % (self.instance_single_valued) + ) # Instance with value in the n valued property self.instance_n_valued = "test://ontology-change/indexed/multiple/true" - self.tracker.update("INSERT { <%s> a test:A ; test:a_n_cardinality 'anything n'. }" - % (self.instance_n_valued)) + self.tracker.update( + "INSERT { <%s> a test:A ; test:a_n_cardinality 'anything n'. }" + % (self.instance_n_valued) + ) def validate_status(self): # Check ontology and instance for the single valued property result = self.tracker.query( - "SELECT ?indexed WHERE { test:a_string nrl:indexed ?indexed}") + "SELECT ?indexed WHERE { test:a_string nrl:indexed ?indexed}" + ) self.assertEqual(str(result[0][0]), "true") - result = self.tracker.query("SELECT ?content WHERE { <%s> a test:A; test:a_string ?content. }" - % (self.instance_single_valued)) + result = self.tracker.query( + "SELECT ?content WHERE { <%s> a test:A; test:a_string ?content. }" + % (self.instance_single_valued) + ) self.assertEqual(str(result[0][0]), "anything 1") # Check ontology and instance for the multiple valued property result = self.tracker.query( - "SELECT ?indexed WHERE { test:a_n_cardinality nrl:indexed ?indexed}") + "SELECT ?indexed WHERE { test:a_n_cardinality nrl:indexed ?indexed}" + ) self.assertEqual(str(result[0][0]), "true") - result = self.tracker.query("SELECT ?content WHERE { <%s> a test:A; test:a_n_cardinality ?content. }" - % (self.instance_n_valued)) + result = self.tracker.query( + "SELECT ?content WHERE { <%s> a test:A; test:a_n_cardinality ?content. }" + % (self.instance_n_valued) + ) self.assertEqual(str(result[0][0]), "anything n") -class PropertyIndexedUnset (OntologyChangeTestTemplate): +class PropertyIndexedUnset(OntologyChangeTestTemplate): """ nrl:indexed property from true to false in single and multiple valued properties. Check that instances and content of the property are still in the DB. @@ -480,13 +513,17 @@ class PropertyIndexedUnset (OntologyChangeTestTemplate): def insert_data(self): # Instance with value in the single valued property self.instance_single_valued = "test://ontology-change/indexed/single/true" - self.tracker.update("INSERT { <%s> a test:A ; test:a_string 'anything 1'. }" - % (self.instance_single_valued)) + self.tracker.update( + "INSERT { <%s> a test:A ; test:a_string 'anything 1'. }" + % (self.instance_single_valued) + ) # Instance with value in the n valued property self.instance_n_valued = "test://ontology-change/indexed/multiple/true" - self.tracker.update("INSERT { <%s> a test:A ; test:a_n_cardinality 'anything n'. }" - % (self.instance_n_valued)) + self.tracker.update( + "INSERT { <%s> a test:A ; test:a_n_cardinality 'anything n'. }" + % (self.instance_n_valued) + ) def validate_status(self): # @@ -495,24 +532,30 @@ class PropertyIndexedUnset (OntologyChangeTestTemplate): # Check ontology and instance for the single valued property result = self.tracker.query( - "SELECT ?indexed WHERE { test:a_string nrl:indexed ?indexed}") + "SELECT ?indexed WHERE { test:a_string nrl:indexed ?indexed}" + ) self.assertEqual(str(result[0][0]), "false") - result = self.tracker.query("SELECT ?content WHERE { <%s> a test:A; test:a_string ?content. }" - % (self.instance_single_valued)) + result = self.tracker.query( + "SELECT ?content WHERE { <%s> a test:A; test:a_string ?content. }" + % (self.instance_single_valued) + ) self.assertEqual(str(result[0][0]), "anything 1") # Check ontology and instance for the multiple valued property result = self.tracker.query( - "SELECT ?indexed WHERE { test:a_n_cardinality nrl:indexed ?indexed}") + "SELECT ?indexed WHERE { test:a_n_cardinality nrl:indexed ?indexed}" + ) self.assertEqual(str(result[0][0]), "false") - result = self.tracker.query("SELECT ?content WHERE { <%s> a test:A; test:a_n_cardinality ?content. }" - % (self.instance_n_valued)) + result = self.tracker.query( + "SELECT ?content WHERE { <%s> a test:A; test:a_n_cardinality ?content. }" + % (self.instance_n_valued) + ) self.assertEqual(str(result[0][0]), "anything n") -class OntologyAddClassTest (OntologyChangeTestTemplate): +class OntologyAddClassTest(OntologyChangeTestTemplate): """ Add a class in the ontology. """ @@ -537,7 +580,7 @@ class OntologyAddClassTest (OntologyChangeTestTemplate): self.assertInDbusResult(TEST_PREFIX + "E", result) -class OntologyRemoveClassTest (OntologyChangeTestTemplate): +class OntologyRemoveClassTest(OntologyChangeTestTemplate): """ Remove a class from the ontology. With and without superclasses. """ @@ -561,20 +604,20 @@ class OntologyRemoveClassTest (OntologyChangeTestTemplate): # The classes are not actually removed... so this assertions are not valid (yet?) # - #result = self.tracker.query ("SELECT ?k WHERE { ?k a rdfs:Class. }") - #self.assertNotInDbusResult (TEST_PREFIX + "E", result) - #self.assertNotInDbusResult (TEST_PREFIX + "D", result) + # result = self.tracker.query ("SELECT ?k WHERE { ?k a rdfs:Class. }") + # self.assertNotInDbusResult (TEST_PREFIX + "E", result) + # self.assertNotInDbusResult (TEST_PREFIX + "D", result) # D is a subclass of A, removing D should keep the A instances result = self.tracker.query("SELECT ?i WHERE { ?i a test:A. }") self.assertEqual(result[0][0], self.instance_e) -class OntologyAddPropertyTest (OntologyChangeTestTemplate): +class OntologyAddPropertyTest(OntologyChangeTestTemplate): """ Add new properties in the ontology, with/without super prop and different ranges and cardinalities """ - + def test_ontology_add_property(self): self.template_test_ontology_change() @@ -598,7 +641,7 @@ class OntologyAddPropertyTest (OntologyChangeTestTemplate): self.assertInDbusResult(TEST_PREFIX + "new_subprop_string_n", result) -class OntologyRemovePropertyTest (OntologyChangeTestTemplate): +class OntologyRemovePropertyTest(OntologyChangeTestTemplate): """ Remove properties from the ontology, with and without super props and different ranges and cardinalities """ @@ -612,7 +655,8 @@ class OntologyRemovePropertyTest (OntologyChangeTestTemplate): def insert_data(self): self.instance_a = "test://ontology-change/remove/properties/1" - self.tracker.update (""" + self.tracker.update( + """ INSERT { <%s> a test:A; test:a_string 'This is fine' ; test:new_prop_int 7; @@ -620,17 +664,24 @@ class OntologyRemovePropertyTest (OntologyChangeTestTemplate): test:new_prop_string 'this is going to disappear' ; test:new_prop_string_n 'same with this' . } - """ % (self.instance_a)) + """ + % (self.instance_a) + ) self.instance_b = "test://ontology-change/remove/properties/2" - self.tracker.update (""" + self.tracker.update( + """ INSERT { <%s> a test:B; test:new_subprop_string 'super-prop keeps this value'; test:new_subprop_string_n 'super-prop also keeps this value'. } - """ % (self.instance_b)) - self.assertTrue(self.tracker.ask("ASK { <%s> a test:A}" % ( - self.instance_a)), "The instance is not there") + """ + % (self.instance_b) + ) + self.assertTrue( + self.tracker.ask("ASK { <%s> a test:A}" % (self.instance_a)), + "The instance is not there", + ) def validate_status(self): # @@ -651,25 +702,27 @@ class OntologyRemovePropertyTest (OntologyChangeTestTemplate): ## self.assertNotInDbusResult (TEST_PREFIX + "new_subprop_string_n", result) # The instances are still there - self.assertTrue(self.tracker.ask( - "ASK { <%s> a test:A}" % (self.instance_a))) - self.assertTrue(self.tracker.ask( - "ASK { <%s> a test:B}" % (self.instance_b))) + self.assertTrue(self.tracker.ask("ASK { <%s> a test:A}" % (self.instance_a))) + self.assertTrue(self.tracker.ask("ASK { <%s> a test:B}" % (self.instance_b))) check = self.tracker.ask( - "ASK { <%s> test:a_superprop 'super-prop keeps this value' }" % (self.instance_b)) + "ASK { <%s> test:a_superprop 'super-prop keeps this value' }" + % (self.instance_b) + ) self.assertTrue(check, "This property and value should exist") check = self.tracker.ask( - "ASK { <%s> test:a_superprop_n 'super-prop also keeps this value' }" % (self.instance_b)) + "ASK { <%s> test:a_superprop_n 'super-prop also keeps this value' }" + % (self.instance_b) + ) self.assertTrue(check, "This property and value should exist") -class DomainIndexAddTest (OntologyChangeTestTemplate): +class DomainIndexAddTest(OntologyChangeTestTemplate): """ Add nrl:domainIndex to a class and check there is no data loss. """ - + def test_domain_index_add(self): self.template_test_ontology_change() @@ -679,38 +732,44 @@ class DomainIndexAddTest (OntologyChangeTestTemplate): def insert_data(self): self.instance_a = "test://ontology-changes/properties/add-domain-index/a" - self.tracker.update (""" + self.tracker.update( + """ INSERT { <%s> a test:B ; test:a_string 'test-value' ; - test:a_int 5. }""" % (self.instance_a)) + test:a_int 5. }""" + % (self.instance_a) + ) self.instance_b = "test://ontology-changes/properties/add-domain-index/b" - self.tracker.update (""" + self.tracker.update( + """ INSERT { <%s> a test:C ; test:a_string 'test-value' ; - test:a_int 6. }""" % (self.instance_b)) + test:a_int 6. }""" + % (self.instance_b) + ) def validate_status(self): # Check the ontology has_domainIndex = self.tracker.ask( - "ASK { test:B nrl:domainIndex test:a_string }") + "ASK { test:B nrl:domainIndex test:a_string }" + ) self.assertTrue(has_domainIndex) - has_domainIndex = self.tracker.ask( - "ASK { test:C nrl:domainIndex test:a_int }") + has_domainIndex = self.tracker.ask("ASK { test:C nrl:domainIndex test:a_int }") self.assertTrue(has_domainIndex) # Check the data dataok = self.tracker.ask( - "ASK { <%s> test:a_string 'test-value' }" % (self.instance_a)) + "ASK { <%s> test:a_string 'test-value' }" % (self.instance_a) + ) self.assertTrue(dataok) - dataok = self.tracker.ask( - "ASK { <%s> test:a_int 6 }" % (self.instance_b)) + dataok = self.tracker.ask("ASK { <%s> test:a_int 6 }" % (self.instance_b)) self.assertTrue(dataok) -class DomainIndexRemoveTest (OntologyChangeTestTemplate): +class DomainIndexRemoveTest(OntologyChangeTestTemplate): """ Remove nrl:domainIndex to a class and check there is no data loss. """ @@ -724,38 +783,48 @@ class DomainIndexRemoveTest (OntologyChangeTestTemplate): def insert_data(self): self.instance_a = "test://ontology-changes/properties/add-domain-index/a" - self.tracker.update (""" + self.tracker.update( + """ INSERT { <%s> a test:B ; test:a_string 'test-value' ; - test:a_n_cardinality 'another-test-value'. }""" % (self.instance_a)) + test:a_n_cardinality 'another-test-value'. }""" + % (self.instance_a) + ) self.instance_b = "test://ontology-changes/properties/add-domain-index/b" - self.tracker.update (""" + self.tracker.update( + """ INSERT { <%s> a test:C ; test:a_string 'test-value' ; - test:a_n_cardinality 'another-test-value'. }""" % (self.instance_b)) + test:a_n_cardinality 'another-test-value'. }""" + % (self.instance_b) + ) def validate_status(self): # Check the ontology has_domainIndex = self.tracker.ask( - "ASK { test:B nrl:domainIndex test:a_string }") + "ASK { test:B nrl:domainIndex test:a_string }" + ) self.assertFalse(has_domainIndex) has_domainIndex = self.tracker.ask( - "ASK { test:C nrl:domainIndex test:a_n_cardinality }") + "ASK { test:C nrl:domainIndex test:a_n_cardinality }" + ) self.assertFalse(has_domainIndex) # Check the data dataok = self.tracker.ask( - "ASK { <%s> test:a_string 'test-value' }" % (self.instance_a)) + "ASK { <%s> test:a_string 'test-value' }" % (self.instance_a) + ) self.assertTrue(dataok) dataok = self.tracker.ask( - "ASK { <%s> test:a_n_cardinality 'another-test-value' }" % (self.instance_b)) + "ASK { <%s> test:a_n_cardinality 'another-test-value' }" % (self.instance_b) + ) self.assertTrue(dataok) -class SuperclassRemovalTest (OntologyChangeTestTemplate): +class SuperclassRemovalTest(OntologyChangeTestTemplate): """ Remove the superclass relation between two classes """ @@ -774,14 +843,20 @@ class SuperclassRemovalTest (OntologyChangeTestTemplate): self.assertTrue(is_subclass) self.instance_a = "test://ontology-changes/superclasses/remove-superclass/a" - self.tracker.update (""" + self.tracker.update( + """ INSERT { <%s> a test:A . } - """ % (self.instance_a)) + """ + % (self.instance_a) + ) self.instance_b = "test://ontology-changes/superclasses/remove-superclass/b" - self.tracker.update (""" + self.tracker.update( + """ INSERT { <%s> a test:B . } - """ % (self.instance_b)) + """ + % (self.instance_b) + ) result = self.tracker.count_instances("test:B") self.assertEqual(result, 1) @@ -800,7 +875,7 @@ class SuperclassRemovalTest (OntologyChangeTestTemplate): self.assertEqual(result, 1) -class SuperclassAdditionTest (OntologyChangeTestTemplate): +class SuperclassAdditionTest(OntologyChangeTestTemplate): """ Add a superclass to a class with no superclass previously """ @@ -819,14 +894,20 @@ class SuperclassAdditionTest (OntologyChangeTestTemplate): self.assertFalse(is_subclass) self.instance_a = "test://ontology-changes/superclasses/remove-superclass/a" - self.tracker.update (""" + self.tracker.update( + """ INSERT { <%s> a test:A . } - """ % (self.instance_a)) + """ + % (self.instance_a) + ) self.instance_b = "test://ontology-changes/superclasses/remove-superclass/b" - self.tracker.update (""" + self.tracker.update( + """ INSERT { <%s> a test:B . } - """ % (self.instance_b)) + """ + % (self.instance_b) + ) result = self.tracker.count_instances("test:B") self.assertEqual(result, 1) @@ -845,7 +926,7 @@ class SuperclassAdditionTest (OntologyChangeTestTemplate): self.assertEqual(result, 2) -class PropertyPromotionTest (OntologyChangeTestTemplate): +class PropertyPromotionTest(OntologyChangeTestTemplate): """ Move a property to the superclass """ @@ -861,29 +942,40 @@ class PropertyPromotionTest (OntologyChangeTestTemplate): def insert_data(self): self.instance_b = "test://ontology-change/property/promotion-to-superclass/b" - self.tracker.update (""" + self.tracker.update( + """ INSERT { <%s> a test:B; test:b_property 'content-b-test'; test:b_property_n 'b-test-n'. } - """ % (self.instance_b)) + """ + % (self.instance_b) + ) self.instance_a = "test://ontology-change/property/promotion-to-superclass/a" - self.assertRaises(GLib.Error, - self.tracker.update, - "INSERT { <%s> a test:A; test:b_property 'content-a-test'.}" % (self.instance_a)) + self.assertRaises( + GLib.Error, + self.tracker.update, + "INSERT { <%s> a test:A; test:b_property 'content-a-test'.}" + % (self.instance_a), + ) def validate_status(self): # This insertion should work now - self.tracker.update (""" + self.tracker.update( + """ INSERT { <%s> a test:A; test:b_property 'content-a-test'.} - """ % (self.instance_a)) + """ + % (self.instance_a) + ) # No data loss - result = self.tracker.query("SELECT ?v ?w WHERE { <%s> test:b_property ?v ; test:b_property_n ?w }" - % (self.instance_b)) + result = self.tracker.query( + "SELECT ?v ?w WHERE { <%s> test:b_property ?v ; test:b_property_n ?w }" + % (self.instance_b) + ) self.assertEqual(result[0][0], "content-b-test") self.assertEqual(result[0][1], "b-test-n") -class PropertyRelegationTest (OntologyChangeTestTemplate): +class PropertyRelegationTest(OntologyChangeTestTemplate): """ Move a property to the subclass """ @@ -899,23 +991,34 @@ class PropertyRelegationTest (OntologyChangeTestTemplate): def insert_data(self): self.instance_b = "test://ontology-change/property/promotion-to-superclass/b" - self.tracker.update (""" + self.tracker.update( + """ INSERT { <%s> a test:B; test:b_property 'content-b-test'; test:b_property_n 'b-test-n'. } - """ % (self.instance_b)) + """ + % (self.instance_b) + ) self.instance_a = "test://ontology-change/property/promotion-to-superclass/a" - self.tracker.update (""" + self.tracker.update( + """ INSERT { <%s> a test:A; test:b_property 'content-a-test'.} - """ % (self.instance_a)) + """ + % (self.instance_a) + ) def validate_status(self): # This insertion should fail now - self.assertRaises(GLib.Error, - self.tracker.update, - "INSERT { <%s> a test:A; test:b_property 'content-a-test'.}" % (self.instance_a)) + self.assertRaises( + GLib.Error, + self.tracker.update, + "INSERT { <%s> a test:A; test:b_property 'content-a-test'.}" + % (self.instance_a), + ) # No data loss - result = self.tracker.query("SELECT ?v ?w WHERE { <%s> test:b_property ?v; test:b_property_n ?w }" - % (self.instance_b)) + result = self.tracker.query( + "SELECT ?v ?w WHERE { <%s> test:b_property ?v; test:b_property_n ?w }" + % (self.instance_b) + ) self.assertEqual(result[0][0], "content-b-test") self.assertEqual(result[0][1], "b-test-n") diff --git a/tests/functional-tests/test_ontology_rollback.py b/tests/functional-tests/test_ontology_rollback.py index 65ce59fe6..e9dd5f33c 100644 --- a/tests/functional-tests/test_ontology_rollback.py +++ b/tests/functional-tests/test_ontology_rollback.py @@ -21,7 +21,8 @@ Test how the database is kept in consistent state when errors occur. """ import gi -gi.require_version('Tracker', '3.0') + +gi.require_version("Tracker", "3.0") from gi.repository import GLib from gi.repository import Gio from gi.repository import Tracker @@ -51,7 +52,7 @@ TEST_PREFIX = "http://example.org/ns#" TEST2_PREFIX = "http://example2.org/ns#" -class OntologyRollbackTestTemplate (ut.TestCase): +class OntologyRollbackTestTemplate(ut.TestCase): """ Template class for the ontology rollback tests. It ensures that the db is left in a consistent state when building or updating the ontology fails. @@ -69,35 +70,45 @@ class OntologyRollbackTestTemplate (ut.TestCase): """ def setUp(self): - self.tmpdir = tempfile.mkdtemp(prefix='tracker-test-') + self.tmpdir = tempfile.mkdtemp(prefix="tracker-test-") def tearDown(self): shutil.rmtree(self.tmpdir, ignore_errors=True) def ontology_path(self, param): - return pathlib.Path(__file__).parent.joinpath('data', 'ontologies', param) + return pathlib.Path(__file__).parent.joinpath("data", "ontologies", param) def template_test_ontology_rollback(self): self.set_ontology_dirs() - self.__assert_different_ontology_dates(self.FIRST_ONTOLOGY_DIR, self.SECOND_ONTOLOGY_DIR) - self.__assert_same_ontology_dates_if_exist(self.FIRST_ONTOLOGY_DIR, self.FIRST_MALFORMED_ONTOLOGY_DIR) - self.__assert_same_ontology_dates_if_exist(self.SECOND_ONTOLOGY_DIR, self.SECOND_MALFORMED_ONTOLOGY_DIR) + self.__assert_different_ontology_dates( + self.FIRST_ONTOLOGY_DIR, self.SECOND_ONTOLOGY_DIR + ) + self.__assert_same_ontology_dates_if_exist( + self.FIRST_ONTOLOGY_DIR, self.FIRST_MALFORMED_ONTOLOGY_DIR + ) + self.__assert_same_ontology_dates_if_exist( + self.SECOND_ONTOLOGY_DIR, self.SECOND_MALFORMED_ONTOLOGY_DIR + ) # Make sure that the connection fails when the malformed ontology is used with self.assertRaises(GLib.GError): Tracker.SparqlConnection.new( Tracker.SparqlConnectionFlags.NONE, Gio.File.new_for_path(self.tmpdir), - Gio.File.new_for_path(str(self.ontology_path(self.FIRST_MALFORMED_ONTOLOGY_DIR))), - None) + Gio.File.new_for_path( + str(self.ontology_path(self.FIRST_MALFORMED_ONTOLOGY_DIR)) + ), + None, + ) # Use the error-free first ontology. It should work now conn1 = Tracker.SparqlConnection.new( Tracker.SparqlConnectionFlags.NONE, Gio.File.new_for_path(self.tmpdir), Gio.File.new_for_path(str(self.ontology_path(self.FIRST_ONTOLOGY_DIR))), - None) + None, + ) self.tracker = trackertestutils.helpers.StoreHelper(conn1) self.insert_data_into_first_ontology() @@ -111,14 +122,18 @@ class OntologyRollbackTestTemplate (ut.TestCase): Tracker.SparqlConnection.new( Tracker.SparqlConnectionFlags.NONE, Gio.File.new_for_path(self.tmpdir), - Gio.File.new_for_path(str(self.ontology_path(self.SECOND_MALFORMED_ONTOLOGY_DIR))), - None) + Gio.File.new_for_path( + str(self.ontology_path(self.SECOND_MALFORMED_ONTOLOGY_DIR)) + ), + None, + ) conn2 = Tracker.SparqlConnection.new( Tracker.SparqlConnectionFlags.NONE, Gio.File.new_for_path(self.tmpdir), Gio.File.new_for_path(str(self.ontology_path(self.SECOND_ONTOLOGY_DIR))), - None) + None, + ) self.tracker = trackertestutils.helpers.StoreHelper(conn2) self.insert_data_into_second_ontology() @@ -187,8 +202,7 @@ class OntologyRollbackTestTemplate (ut.TestCase): for row in dbus_result: if member == str(row[column]): # This is going to fail with pretty printing - self.fail("'%s' wasn't supposed to be in '%s'" % - (member, dbus_result)) + self.fail("'%s' wasn't supposed to be in '%s'" % (member, dbus_result)) return def __get_ontology_date(self, ontology_path): @@ -197,14 +211,13 @@ class OntologyRollbackTestTemplate (ut.TestCase): """ ISO9601_REGEX = "(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)" - with open(ontology_path, 'r') as f: + with open(ontology_path, "r") as f: for line in f: if "nrl:lastModified" in line: - getmodtime = re.compile( - 'nrl:lastModified\ \"' + ISO9601_REGEX + '\"') + getmodtime = re.compile('nrl:lastModified\ "' + ISO9601_REGEX + '"') modtime_match = getmodtime.search(line) - if (modtime_match): + if modtime_match: nao_date = modtime_match.group(1) return time.strptime(nao_date, "%Y-%m-%dT%H:%M:%SZ") else: @@ -215,15 +228,17 @@ class OntologyRollbackTestTemplate (ut.TestCase): Compare between the nrl:lastModified of all ontology files in first_dir and second_dir assertion_fn is used to compare between the two dates and make sure they are valid """ - ontology_files = glob.glob(str(self.ontology_path(first_dir).joinpath("*.ontology"))) - + ontology_files = glob.glob( + str(self.ontology_path(first_dir).joinpath("*.ontology")) + ) + for first_ontology in ontology_files: ontology_fname = os.path.basename(first_ontology) second_ontology = self.ontology_path(second_dir).joinpath(ontology_fname) first_date = self.__get_ontology_date(first_ontology) second_date = self.__get_ontology_date(second_ontology) - + try: assertion_fn(first_date, second_date) except AssertionError as e: @@ -234,10 +249,11 @@ class OntologyRollbackTestTemplate (ut.TestCase): Asserts that nrl:lastModified of ontologies in second_dir are more recent than that in first_dir """ + def assert_different_dates(first_date, second_date): if first_date >= second_date: self.fail("nrl:lastModified is not more recent in the second ontology") - + self.__assert_all_ontology_dates(first_dir, second_dir, assert_different_dates) def __assert_same_ontology_dates_if_exist(self, first_dir, second_dir): @@ -245,13 +261,15 @@ class OntologyRollbackTestTemplate (ut.TestCase): Asserts that nrl:lastModified of ontologies in first_dir are the same as that in second_dir if they exist and are valid """ + def assert_different_dates(first_date, second_date): if second_date is not None and first_date != second_date: self.fail("nrl:lastModified is not the same as in the second ontology") - + self.__assert_all_ontology_dates(first_dir, second_dir, assert_different_dates) -class SimpleOntologyRollback (OntologyRollbackTestTemplate): + +class SimpleOntologyRollback(OntologyRollbackTestTemplate): def test_simple_ontology_rollback(self): self.template_test_ontology_rollback() @@ -265,64 +283,78 @@ class SimpleOntologyRollback (OntologyRollbackTestTemplate): # test:a_tmp_prop only appeared in the malformed ontology with self.assertRaises(GLib.GError): self.tracker.update( - "INSERT { <http://example/t1.1> a test:A ; test:a_tmp_prop 5. }") + "INSERT { <http://example/t1.1> a test:A ; test:a_tmp_prop 5. }" + ) # The domain of test:b_a_domain should be test:A no test:B with self.assertRaises(GLib.GError): self.tracker.update( - "INSERT { <http://example/t1.2> a test:B ; test:b_a_domain 5. }") + "INSERT { <http://example/t1.2> a test:B ; test:b_a_domain 5. }" + ) # The domain should be test:B and range be test:A with self.assertRaises(GLib.GError): self.tracker.update( - "INSERT { <http://example/t1.3> a test:B . <t1.4> a test:A ; test:a_b_domain_range <http://example/t1.3>. }") + "INSERT { <http://example/t1.3> a test:B . <t1.4> a test:A ; test:a_b_domain_range <http://example/t1.3>. }" + ) # test2:C should be subclass of test:B not test:A with self.assertRaises(GLib.GError): self.tracker.update( - "INSERT { <http://example/t1.5> a test2:C ; test:b_a_domain 5. }") + "INSERT { <http://example/t1.5> a test2:C ; test:b_a_domain 5. }" + ) self.tracker.update( - "INSERT { <http://example/t1.6> a test:A ; test:b_a_domain 5. }") + "INSERT { <http://example/t1.6> a test:A ; test:b_a_domain 5. }" + ) self.tracker.update( - "INSERT { <http://example/t1.7> a test:B ; test:a_b_domain_range <http://example/t1.6>. }") + "INSERT { <http://example/t1.7> a test:B ; test:a_b_domain_range <http://example/t1.6>. }" + ) self.tracker.update( - "INSERT { <http://example/t1.8> a test2:C ; test:b_range_boolean_string \"String\". }") + 'INSERT { <http://example/t1.8> a test2:C ; test:b_range_boolean_string "String". }' + ) def validate_first_ontology_status(self): - result = self.tracker.query( - "SELECT ?p WHERE { ?p a rdf:Property. }") + result = self.tracker.query("SELECT ?p WHERE { ?p a rdf:Property. }") self.assertNotInDbusResult(TEST_PREFIX + "a_tmp_prop", result) - + result = self.tracker.query( - "SELECT ?d ?r WHERE { test:a_b_domain_range rdfs:domain ?d ; rdfs:range ?r }") + "SELECT ?d ?r WHERE { test:a_b_domain_range rdfs:domain ?d ; rdfs:range ?r }" + ) self.assertEqual(result[0][0], TEST_PREFIX + "B") self.assertEqual(result[0][1], TEST_PREFIX + "A") - self.assertFalse(self.tracker.ask("ASK { <%s> a rdfs:Class}" % ( - TEST2_PREFIX + "D")), "test2:D class is not rolled back on failure") + self.assertFalse( + self.tracker.ask("ASK { <%s> a rdfs:Class}" % (TEST2_PREFIX + "D")), + "test2:D class is not rolled back on failure", + ) def insert_data_into_second_ontology(self): # Domain was test:B in the malformed ontology # and became test:A in the error-free ontology with self.assertRaises(GLib.GError): self.tracker.update( - "INSERT { <http://example/t2.1> a test:B ; test:a_b_domain 5. }") + "INSERT { <http://example/t2.1> a test:B ; test:a_b_domain 5. }" + ) self.tracker.update( - "INSERT { <http://example/t2.2> a test:A ; test:a_b_domain 5. }") + "INSERT { <http://example/t2.2> a test:A ; test:a_b_domain 5. }" + ) def validate_second_ontology_status(self): result = self.tracker.query( - "SELECT ?d ?r WHERE { test:a_b_domain rdfs:domain ?d ; rdfs:range ?r }") + "SELECT ?d ?r WHERE { test:a_b_domain rdfs:domain ?d ; rdfs:range ?r }" + ) self.assertEqual(result[0][0], TEST_PREFIX + "A") self.assertEqual(result[0][1], XSD_INTEGER) result = self.tracker.query( - "SELECT ?v WHERE { <http://example/t2.2> test:a_b_domain ?v }") + "SELECT ?v WHERE { <http://example/t2.2> test:a_b_domain ?v }" + ) self.assertEqual(result[0][0], "5") + if __name__ == "__main__": fixtures.tracker_test_main() diff --git a/tests/functional-tests/test_portal.py b/tests/functional-tests/test_portal.py index 1cc0717bc..94b5d47e5 100644 --- a/tests/functional-tests/test_portal.py +++ b/tests/functional-tests/test_portal.py @@ -21,7 +21,8 @@ Test portal """ import gi -gi.require_version('Tracker', '3.0') + +gi.require_version("Tracker", "3.0") from gi.repository import GLib from gi.repository import Gio from gi.repository import Tracker @@ -31,50 +32,53 @@ import unittest import configuration import fixtures + class TestPortal(fixtures.TrackerPortalTest): def test_01_forbidden(self): - self.start_service('org.freedesktop.Inaccessible') + self.start_service("org.freedesktop.Inaccessible") self.assertRaises( - GLib.Error, self.query, - 'org.freedesktop.Inaccessible', - 'select ?u { BIND (1 AS ?u) }') + GLib.Error, + self.query, + "org.freedesktop.Inaccessible", + "select ?u { BIND (1 AS ?u) }", + ) def test_02_allowed(self): - self.start_service('org.freedesktop.PortalTest') - res = self.query( - 'org.freedesktop.PortalTest', - 'select ?u { BIND (1 AS ?u) }') + self.start_service("org.freedesktop.PortalTest") + res = self.query("org.freedesktop.PortalTest", "select ?u { BIND (1 AS ?u) }") self.assertEqual(len(res), 1) - self.assertEqual(res[0][0], '1') + self.assertEqual(res[0][0], "1") def test_03_graph_access(self): - self.start_service('org.freedesktop.PortalTest') + self.start_service("org.freedesktop.PortalTest") self.update( - 'org.freedesktop.PortalTest', - 'CREATE GRAPH tracker:Disallowed;' + - 'INSERT { GRAPH tracker:Disallowed { <http://example/a> a nfo:FileDataObject } };' + - 'CREATE GRAPH tracker:Allowed;' + - 'INSERT { GRAPH tracker:Allowed { <http://example/b> a nfo:FileDataObject } }') + "org.freedesktop.PortalTest", + "CREATE GRAPH tracker:Disallowed;" + + "INSERT { GRAPH tracker:Disallowed { <http://example/a> a nfo:FileDataObject } };" + + "CREATE GRAPH tracker:Allowed;" + + "INSERT { GRAPH tracker:Allowed { <http://example/b> a nfo:FileDataObject } }", + ) res = self.query( - 'org.freedesktop.PortalTest', - 'select ?u { ?u a rdfs:Resource }') + "org.freedesktop.PortalTest", "select ?u { ?u a rdfs:Resource }" + ) self.assertEqual(len(res), 1) - self.assertEqual(res[0][0], 'http://example/b') + self.assertEqual(res[0][0], "http://example/b") def test_04_rows_cols(self): - self.start_service('org.freedesktop.PortalTest') + self.start_service("org.freedesktop.PortalTest") res = self.query( - 'org.freedesktop.PortalTest', - 'select ?a ?b { VALUES (?a ?b) { (1 2) (3 4) (5 6) } }') + "org.freedesktop.PortalTest", + "select ?a ?b { VALUES (?a ?b) { (1 2) (3 4) (5 6) } }", + ) self.assertEqual(len(res), 3) - self.assertEqual(res[0][0], '1') - self.assertEqual(res[0][1], '2') + self.assertEqual(res[0][0], "1") + self.assertEqual(res[0][1], "2") self.assertEqual(len(res[0]), 2) - self.assertEqual(res[1][0], '3') - self.assertEqual(res[1][1], '4') + self.assertEqual(res[1][0], "3") + self.assertEqual(res[1][1], "4") self.assertEqual(len(res[1]), 2) - self.assertEqual(res[2][0], '5') - self.assertEqual(res[2][1], '6') + self.assertEqual(res[2][0], "5") + self.assertEqual(res[2][1], "6") self.assertEqual(len(res[2]), 2) def __wait_for_notifier(self): @@ -82,12 +86,16 @@ class TestPortal(fixtures.TrackerPortalTest): In the callback of the signals, there should be a self.loop.quit () """ self.timeout_id = GLib.timeout_add_seconds( - configuration.DEFAULT_TIMEOUT, self.__timeout_on_idle) + configuration.DEFAULT_TIMEOUT, self.__timeout_on_idle + ) self.loop.run_checked() def __timeout_on_idle(self): self.loop.quit() - self.fail("Timeout, the signal never came after %i seconds!" % configuration.DEFAULT_TIMEOUT) + self.fail( + "Timeout, the signal never came after %i seconds!" + % configuration.DEFAULT_TIMEOUT + ) def __notifier_event_cb(self, notifier, service, graph, events): self.notifier_events += events @@ -97,361 +105,385 @@ class TestPortal(fixtures.TrackerPortalTest): self.loop.quit() def test_05_local_connection_notifier(self): - self.start_service('org.freedesktop.PortalTest') + self.start_service("org.freedesktop.PortalTest") self.notifier_events = [] conn = self.create_local_connection() - notifier = conn.create_notifier(); - notifier.connect('events', self.__notifier_event_cb) + notifier = conn.create_notifier() + notifier.connect("events", self.__notifier_event_cb) signalId = notifier.signal_subscribe( - self.bus, - 'org.freedesktop.PortalTest', - None, - 'tracker:Allowed') + self.bus, "org.freedesktop.PortalTest", None, "tracker:Allowed" + ) signalId2 = notifier.signal_subscribe( - self.bus, - 'org.freedesktop.PortalTest', - None, - 'tracker:Disallowed') + self.bus, "org.freedesktop.PortalTest", None, "tracker:Disallowed" + ) self.update( - 'org.freedesktop.PortalTest', - 'INSERT { GRAPH tracker:Disallowed { <http://example/a> a nmm:MusicPiece } }') + "org.freedesktop.PortalTest", + "INSERT { GRAPH tracker:Disallowed { <http://example/a> a nmm:MusicPiece } }", + ) self.update( - 'org.freedesktop.PortalTest', - 'INSERT { GRAPH tracker:Allowed { <http://example/b> a nmm:MusicPiece } }') + "org.freedesktop.PortalTest", + "INSERT { GRAPH tracker:Allowed { <http://example/b> a nmm:MusicPiece } }", + ) self.__wait_for_notifier() - notifier.signal_unsubscribe(signalId); - notifier.signal_unsubscribe(signalId2); + notifier.signal_unsubscribe(signalId) + notifier.signal_unsubscribe(signalId2) # Only one event is expected, from the allowed graph - self.assertEqual(len(self.notifier_events), 1); - self.assertEqual(self.notifier_events[0].get_urn(), 'http://example/b') + self.assertEqual(len(self.notifier_events), 1) + self.assertEqual(self.notifier_events[0].get_urn(), "http://example/b") conn.close() def test_06_id_access(self): - self.start_service('org.freedesktop.PortalTest') + self.start_service("org.freedesktop.PortalTest") self.update( - 'org.freedesktop.PortalTest', - 'CREATE GRAPH tracker:Allowed;' + - 'INSERT { GRAPH tracker:Allowed { <http://example/b> a nfo:FileDataObject } }') + "org.freedesktop.PortalTest", + "CREATE GRAPH tracker:Allowed;" + + "INSERT { GRAPH tracker:Allowed { <http://example/b> a nfo:FileDataObject } }", + ) res = self.query( - 'org.freedesktop.PortalTest', - 'select tracker:id(xsd:string) tracker:uri(1) { }') + "org.freedesktop.PortalTest", + "select tracker:id(xsd:string) tracker:uri(1) { }", + ) self.assertEqual(len(res), 1) - self.assertEqual(res[0][0], '0') + self.assertEqual(res[0][0], "0") self.assertEqual(res[0][1], None) res = self.query( - 'org.freedesktop.PortalTest', - 'select tracker:id(<http://example/b>) tracker:uri(tracker:id(<http://example/b>)) { }') + "org.freedesktop.PortalTest", + "select tracker:id(<http://example/b>) tracker:uri(tracker:id(<http://example/b>)) { }", + ) self.assertEqual(len(res), 1) - self.assertNotEqual(res[0][0], '0') - self.assertEqual(res[0][1], 'http://example/b') + self.assertNotEqual(res[0][0], "0") + self.assertEqual(res[0][1], "http://example/b") def test_07_id_access_disallowed(self): - self.start_service('org.freedesktop.PortalTest') + self.start_service("org.freedesktop.PortalTest") # Insert resource into disallowed graph, ensure it is not visible self.update( - 'org.freedesktop.PortalTest', - 'CREATE GRAPH tracker:Disallowed;' + - 'INSERT { GRAPH tracker:Disallowed { <http://example/b> a nfo:FileDataObject } }') + "org.freedesktop.PortalTest", + "CREATE GRAPH tracker:Disallowed;" + + "INSERT { GRAPH tracker:Disallowed { <http://example/b> a nfo:FileDataObject } }", + ) res = self.query( - 'org.freedesktop.PortalTest', - 'select tracker:id(<http://example/b>) tracker:uri(tracker:id(<http://example/b>)) { }') + "org.freedesktop.PortalTest", + "select tracker:id(<http://example/b>) tracker:uri(tracker:id(<http://example/b>)) { }", + ) self.assertEqual(len(res), 1) - self.assertEqual(res[0][0], '0') + self.assertEqual(res[0][0], "0") self.assertIsNone(res[0][1]) # Insert same resource into allowed graph, ensure it is visible self.update( - 'org.freedesktop.PortalTest', - 'CREATE GRAPH tracker:Allowed;' + - 'INSERT { GRAPH tracker:Allowed { <http://example/b> a nfo:FileDataObject } }') + "org.freedesktop.PortalTest", + "CREATE GRAPH tracker:Allowed;" + + "INSERT { GRAPH tracker:Allowed { <http://example/b> a nfo:FileDataObject } }", + ) res = self.query( - 'org.freedesktop.PortalTest', - 'select tracker:id(<http://example/b>) tracker:uri(tracker:id(<http://example/b>)) { }') + "org.freedesktop.PortalTest", + "select tracker:id(<http://example/b>) tracker:uri(tracker:id(<http://example/b>)) { }", + ) self.assertEqual(len(res), 1) - self.assertNotEqual(res[0][0], '0') - self.assertEqual(res[0][1], 'http://example/b') - resourceId = res[0][0]; + self.assertNotEqual(res[0][0], "0") + self.assertEqual(res[0][1], "http://example/b") + resourceId = res[0][0] # Delete resource from allowed graph, ensure it is not visible again self.update( - 'org.freedesktop.PortalTest', - 'DELETE { GRAPH tracker:Allowed { <http://example/b> a rdfs:Resource } }') + "org.freedesktop.PortalTest", + "DELETE { GRAPH tracker:Allowed { <http://example/b> a rdfs:Resource } }", + ) res = self.query( - 'org.freedesktop.PortalTest', - 'select tracker:id(<http://example/b>) tracker:uri(tracker:id(<http://example/b>)) tracker:uri(' + str(resourceId) + ') { }') + "org.freedesktop.PortalTest", + "select tracker:id(<http://example/b>) tracker:uri(tracker:id(<http://example/b>)) tracker:uri(" + + str(resourceId) + + ") { }", + ) self.assertEqual(len(res), 1) - self.assertEqual(res[0][0], '0') + self.assertEqual(res[0][0], "0") self.assertIsNone(res[0][1]) self.assertIsNone(res[0][2]) def test_08_local_connection_service(self): - self.start_service('org.freedesktop.PortalTest') + self.start_service("org.freedesktop.PortalTest") self.notifier_events = [] conn = self.create_local_connection() self.update( - 'org.freedesktop.PortalTest', - 'INSERT { GRAPH tracker:Disallowed { <http://example/a> a nmm:MusicPiece } }') + "org.freedesktop.PortalTest", + "INSERT { GRAPH tracker:Disallowed { <http://example/a> a nmm:MusicPiece } }", + ) self.update( - 'org.freedesktop.PortalTest', - 'INSERT { GRAPH tracker:Allowed { <http://example/b> a nmm:MusicPiece } }') + "org.freedesktop.PortalTest", + "INSERT { GRAPH tracker:Allowed { <http://example/b> a nmm:MusicPiece } }", + ) # Only one resource is expected, from the allowed graph - cursor = conn.query('select ?u { SERVICE <dbus:org.freedesktop.PortalTest> { ?u a nmm:MusicPiece } }') + cursor = conn.query( + "select ?u { SERVICE <dbus:org.freedesktop.PortalTest> { ?u a nmm:MusicPiece } }" + ) self.assertTrue(cursor.next()) - self.assertEqual(cursor.get_string(0)[0], 'http://example/b') + self.assertEqual(cursor.get_string(0)[0], "http://example/b") self.assertFalse(cursor.next()) cursor.close() conn.close() # Test that all ways to specify a graph in the query hit a dead end def test_09_query_graphs(self): - self.start_service('org.freedesktop.PortalTest') + self.start_service("org.freedesktop.PortalTest") self.update( - 'org.freedesktop.PortalTest', - 'CREATE GRAPH tracker:Disallowed;' + - 'INSERT { GRAPH tracker:Disallowed { <http://example/a> a nfo:FileDataObject } }') + "org.freedesktop.PortalTest", + "CREATE GRAPH tracker:Disallowed;" + + "INSERT { GRAPH tracker:Disallowed { <http://example/a> a nfo:FileDataObject } }", + ) res = self.query( - 'org.freedesktop.PortalTest', - 'select ?u from tracker:Disallowed { ?u a rdfs:Resource }') + "org.freedesktop.PortalTest", + "select ?u from tracker:Disallowed { ?u a rdfs:Resource }", + ) self.assertEqual(len(res), 0) res = self.query( - 'org.freedesktop.PortalTest', - 'select ?u { graph tracker:Disallowed { ?u a rdfs:Resource } }') + "org.freedesktop.PortalTest", + "select ?u { graph tracker:Disallowed { ?u a rdfs:Resource } }", + ) self.assertEqual(len(res), 0) res = self.query( - 'org.freedesktop.PortalTest', - 'constraint graph tracker:Disallowed select ?u { ?u a rdfs:Resource }') + "org.freedesktop.PortalTest", + "constraint graph tracker:Disallowed select ?u { ?u a rdfs:Resource }", + ) self.assertEqual(len(res), 0) # Test that it is not possible to break through into other services def test_10_query_services(self): - self.start_service('org.freedesktop.PortalTest') - self.start_service('org.freedesktop.InaccessibleService') + self.start_service("org.freedesktop.PortalTest") + self.start_service("org.freedesktop.InaccessibleService") self.update( - 'org.freedesktop.PortalTest', - 'CREATE GRAPH tracker:Allowed;' + - 'INSERT { GRAPH tracker:Allowed { <http://example/a> a nfo:FileDataObject } }') + "org.freedesktop.PortalTest", + "CREATE GRAPH tracker:Allowed;" + + "INSERT { GRAPH tracker:Allowed { <http://example/a> a nfo:FileDataObject } }", + ) self.update( - 'org.freedesktop.InaccessibleService', - 'CREATE GRAPH tracker:Allowed;' + - 'INSERT { GRAPH tracker:Allowed { <http://example/b> a nfo:FileDataObject } }') + "org.freedesktop.InaccessibleService", + "CREATE GRAPH tracker:Allowed;" + + "INSERT { GRAPH tracker:Allowed { <http://example/b> a nfo:FileDataObject } }", + ) try: exception = None res = self.query( - 'org.freedesktop.PortalTest', - 'select ?u { service <dbus:org.freedesktop.InaccessibleService> { ?u a rdfs:Resource } }') + "org.freedesktop.PortalTest", + "select ?u { service <dbus:org.freedesktop.InaccessibleService> { ?u a rdfs:Resource } }", + ) except Exception as e: - exception = e; + exception = e finally: self.assertIsNotNone(exception) try: exception = None res = self.query( - 'org.freedesktop.InaccessibleService', - 'select ?u { ?u a rdfs:Resource }') + "org.freedesktop.InaccessibleService", + "select ?u { ?u a rdfs:Resource }", + ) except Exception as e: - exception = e; + exception = e finally: self.assertIsNotNone(exception) # Test that property paths resolve correctly across allowed # and disallowed graphs def test_11_query_property_paths(self): - self.start_service('org.freedesktop.PortalTest') + self.start_service("org.freedesktop.PortalTest") self.update( - 'org.freedesktop.PortalTest', - 'CREATE GRAPH tracker:Disallowed;' + - 'INSERT { GRAPH tracker:Disallowed { ' + - ' <http://example/a> a nfo:FileDataObject ; nfo:fileName "A" ; nie:interpretedAs <http://example/b1> .' + - ' <http://example/b1> a nmm:MusicPiece ; nie:isStoredAs <http://example/a> ; nie:title "title2" } }') + "org.freedesktop.PortalTest", + "CREATE GRAPH tracker:Disallowed;" + + "INSERT { GRAPH tracker:Disallowed { " + + ' <http://example/a> a nfo:FileDataObject ; nfo:fileName "A" ; nie:interpretedAs <http://example/b1> .' + + ' <http://example/b1> a nmm:MusicPiece ; nie:isStoredAs <http://example/a> ; nie:title "title2" } }', + ) # Test property paths with allowed/disallowed graphs in both ends res = self.query( - 'org.freedesktop.PortalTest', - 'select ?u ?t { ?u nie:interpretedAs/nie:title ?t }') + "org.freedesktop.PortalTest", + "select ?u ?t { ?u nie:interpretedAs/nie:title ?t }", + ) self.assertEqual(len(res), 0) res = self.query( - 'org.freedesktop.PortalTest', - 'select ?u ?fn { ?u nie:isStoredAs/nfo:fileName ?fn }') + "org.freedesktop.PortalTest", + "select ?u ?fn { ?u nie:isStoredAs/nfo:fileName ?fn }", + ) self.assertEqual(len(res), 0) # Insert a resource in the allowed graph self.update( - 'org.freedesktop.PortalTest', - 'CREATE GRAPH tracker:Allowed;' + - 'INSERT { GRAPH tracker:Allowed { ' + - ' <http://example/a> a nfo:FileDataObject ; nfo:fileName "A" ; nie:interpretedAs <http://example/a1> .' + - ' <http://example/a1> a nmm:MusicPiece ; nie:isStoredAs <http://example/a> ; nie:title "title1" } }') + "org.freedesktop.PortalTest", + "CREATE GRAPH tracker:Allowed;" + + "INSERT { GRAPH tracker:Allowed { " + + ' <http://example/a> a nfo:FileDataObject ; nfo:fileName "A" ; nie:interpretedAs <http://example/a1> .' + + ' <http://example/a1> a nmm:MusicPiece ; nie:isStoredAs <http://example/a> ; nie:title "title1" } }', + ) # Try the queries again res = self.query( - 'org.freedesktop.PortalTest', - 'select ?u ?t { ?u nie:interpretedAs/nie:title ?t }') + "org.freedesktop.PortalTest", + "select ?u ?t { ?u nie:interpretedAs/nie:title ?t }", + ) self.assertEqual(len(res), 1) - self.assertEqual(res[0][0], 'http://example/a') - self.assertEqual(res[0][1], 'title1') + self.assertEqual(res[0][0], "http://example/a") + self.assertEqual(res[0][1], "title1") res = self.query( - 'org.freedesktop.PortalTest', - 'select ?u ?fn { ?u nie:isStoredAs/nfo:fileName ?fn }') + "org.freedesktop.PortalTest", + "select ?u ?fn { ?u nie:isStoredAs/nfo:fileName ?fn }", + ) self.assertEqual(len(res), 1) - self.assertEqual(res[0][0], 'http://example/a1') - self.assertEqual(res[0][1], 'A') + self.assertEqual(res[0][0], "http://example/a1") + self.assertEqual(res[0][1], "A") res = self.query( - 'org.freedesktop.PortalTest', - 'select ?u ?fn { GRAPH tracker:Disallowed { ?u nie:isStoredAs/nfo:fileName ?fn } }') + "org.freedesktop.PortalTest", + "select ?u ?fn { GRAPH tracker:Disallowed { ?u nie:isStoredAs/nfo:fileName ?fn } }", + ) self.assertEqual(len(res), 0) # Delete the allowed resource again - self.update( - 'org.freedesktop.PortalTest', - 'DROP GRAPH tracker:Allowed') + self.update("org.freedesktop.PortalTest", "DROP GRAPH tracker:Allowed") # Query results should revert to the original values res = self.query( - 'org.freedesktop.PortalTest', - 'select ?u ?t { ?u nie:interpretedAs/nie:title ?t }') + "org.freedesktop.PortalTest", + "select ?u ?t { ?u nie:interpretedAs/nie:title ?t }", + ) self.assertEqual(len(res), 0) res = self.query( - 'org.freedesktop.PortalTest', - 'select ?u ?fn { ?u nie:isStoredAs/nfo:fileName ?fn }') + "org.freedesktop.PortalTest", + "select ?u ?fn { ?u nie:isStoredAs/nfo:fileName ?fn }", + ) self.assertEqual(len(res), 0) # Test that property paths resolve correctly across allowed # and disallowed graphs def test_12_query_fts(self): - self.start_service('org.freedesktop.PortalTest') + self.start_service("org.freedesktop.PortalTest") self.update( - 'org.freedesktop.PortalTest', - 'CREATE GRAPH tracker:Disallowed;' + - 'INSERT { GRAPH tracker:Disallowed { ' + - ' <http://example/a> a nfo:FileDataObject ; nie:interpretedAs <http://example/b1> .' + - ' <http://example/b1> a nmm:MusicPiece ; nie:isStoredAs <http://example/a> ; nie:title "apples and oranges" } }') + "org.freedesktop.PortalTest", + "CREATE GRAPH tracker:Disallowed;" + + "INSERT { GRAPH tracker:Disallowed { " + + " <http://example/a> a nfo:FileDataObject ; nie:interpretedAs <http://example/b1> ." + + ' <http://example/b1> a nmm:MusicPiece ; nie:isStoredAs <http://example/a> ; nie:title "apples and oranges" } }', + ) # Query for both keywords, they are expected to be non-visible res = self.query( - 'org.freedesktop.PortalTest', - 'select ?u { ?u fts:match "apples" }') + "org.freedesktop.PortalTest", 'select ?u { ?u fts:match "apples" }' + ) self.assertEqual(len(res), 0) res = self.query( - 'org.freedesktop.PortalTest', - 'select ?u { ?u fts:match "oranges" }') + "org.freedesktop.PortalTest", 'select ?u { ?u fts:match "oranges" }' + ) self.assertEqual(len(res), 0) # Insert a resource in the allowed graph self.update( - 'org.freedesktop.PortalTest', - 'CREATE GRAPH tracker:Allowed;' + - 'INSERT { GRAPH tracker:Allowed { ' + - ' <http://example/a> a nfo:FileDataObject ; nfo:fileName "file name" ; nie:interpretedAs <http://example/a1> .' + - ' <http://example/a1> a nmm:MusicPiece ; nie:isStoredAs <http://example/a> ; nie:title "apples" } }') + "org.freedesktop.PortalTest", + "CREATE GRAPH tracker:Allowed;" + + "INSERT { GRAPH tracker:Allowed { " + + ' <http://example/a> a nfo:FileDataObject ; nfo:fileName "file name" ; nie:interpretedAs <http://example/a1> .' + + ' <http://example/a1> a nmm:MusicPiece ; nie:isStoredAs <http://example/a> ; nie:title "apples" } }', + ) # Try the queries again, we should get a match from the allowed graph for 'apples' res = self.query( - 'org.freedesktop.PortalTest', - 'select ?u { ?u fts:match "apples" }') + "org.freedesktop.PortalTest", 'select ?u { ?u fts:match "apples" }' + ) self.assertEqual(len(res), 1) - self.assertEqual(res[0][0], 'http://example/a1') + self.assertEqual(res[0][0], "http://example/a1") res = self.query( - 'org.freedesktop.PortalTest', - 'select ?u { ?u fts:match "oranges" }') + "org.freedesktop.PortalTest", 'select ?u { ?u fts:match "oranges" }' + ) self.assertEqual(len(res), 0) res = self.query( - 'org.freedesktop.PortalTest', - 'select ?u { GRAPH tracker:Disallowed { ?u fts:match "oranges" } }') + "org.freedesktop.PortalTest", + 'select ?u { GRAPH tracker:Disallowed { ?u fts:match "oranges" } }', + ) self.assertEqual(len(res), 0) # Delete the allowed resource again - self.update( - 'org.freedesktop.PortalTest', - 'DROP GRAPH tracker:Allowed') + self.update("org.freedesktop.PortalTest", "DROP GRAPH tracker:Allowed") # The query results should revert to the original values res = self.query( - 'org.freedesktop.PortalTest', - 'select ?u { ?u fts:match "apples" }') + "org.freedesktop.PortalTest", 'select ?u { ?u fts:match "apples" }' + ) self.assertEqual(len(res), 0) res = self.query( - 'org.freedesktop.PortalTest', - 'select ?u { ?u fts:match "oranges" }') + "org.freedesktop.PortalTest", 'select ?u { ?u fts:match "oranges" }' + ) self.assertEqual(len(res), 0) # Test that property paths resolve correctly across allowed # and disallowed graphs def test_13_query_unrestricted_triples(self): - self.start_service('org.freedesktop.PortalTest') + self.start_service("org.freedesktop.PortalTest") self.update( - 'org.freedesktop.PortalTest', - 'CREATE GRAPH tracker:Disallowed;' + - 'INSERT { GRAPH tracker:Disallowed { ' + - ' <http://example/a> a nfo:FileDataObject ; nfo:fileName "A" . } }') + "org.freedesktop.PortalTest", + "CREATE GRAPH tracker:Disallowed;" + + "INSERT { GRAPH tracker:Disallowed { " + + ' <http://example/a> a nfo:FileDataObject ; nfo:fileName "A" . } }', + ) - res = self.query( - 'org.freedesktop.PortalTest', - 'select ?s { ?s ?p "A" }') + res = self.query("org.freedesktop.PortalTest", 'select ?s { ?s ?p "A" }') self.assertEqual(len(res), 0) res = self.query( - 'org.freedesktop.PortalTest', - 'ASK { <http://example/a> ?p "A" }') + "org.freedesktop.PortalTest", 'ASK { <http://example/a> ?p "A" }' + ) self.assertEqual(len(res), 1) - self.assertNotEqual(res[0][0], 'true') + self.assertNotEqual(res[0][0], "true") # Insert a resource in the allowed graph self.update( - 'org.freedesktop.PortalTest', - 'CREATE GRAPH tracker:Allowed;' + - 'INSERT { GRAPH tracker:Allowed { ' + - ' <http://example/a> a nfo:FileDataObject ; nfo:fileName "A" . } }') + "org.freedesktop.PortalTest", + "CREATE GRAPH tracker:Allowed;" + + "INSERT { GRAPH tracker:Allowed { " + + ' <http://example/a> a nfo:FileDataObject ; nfo:fileName "A" . } }', + ) # Try the queries again - res = self.query( - 'org.freedesktop.PortalTest', - 'select ?s { ?s ?p "A" }') + res = self.query("org.freedesktop.PortalTest", 'select ?s { ?s ?p "A" }') self.assertEqual(len(res), 1) - self.assertEqual(res[0][0], 'http://example/a') + self.assertEqual(res[0][0], "http://example/a") res = self.query( - 'org.freedesktop.PortalTest', - 'ASK { <http://example/a> ?p "A" }') + "org.freedesktop.PortalTest", 'ASK { <http://example/a> ?p "A" }' + ) self.assertEqual(len(res), 1) - self.assertEqual(res[0][0], 'true') + self.assertEqual(res[0][0], "true") res = self.query( - 'org.freedesktop.PortalTest', - 'select ?s { GRAPH tracker:Disallowed { ?s ?p "A" } }') + "org.freedesktop.PortalTest", + 'select ?s { GRAPH tracker:Disallowed { ?s ?p "A" } }', + ) self.assertEqual(len(res), 0) # Delete the allowed resource again - self.update( - 'org.freedesktop.PortalTest', - 'DROP GRAPH tracker:Allowed') + self.update("org.freedesktop.PortalTest", "DROP GRAPH tracker:Allowed") # The query results should revert to the original values - res = self.query( - 'org.freedesktop.PortalTest', - 'select ?s { ?s ?p "A" }') + res = self.query("org.freedesktop.PortalTest", 'select ?s { ?s ?p "A" }') self.assertEqual(len(res), 0) -if __name__ == '__main__': +if __name__ == "__main__": fixtures.tracker_test_main() diff --git a/tests/functional-tests/test_query.py b/tests/functional-tests/test_query.py index 18a29b6f1..8044c64d9 100644 --- a/tests/functional-tests/test_query.py +++ b/tests/functional-tests/test_query.py @@ -21,19 +21,21 @@ Test queries using libtracker-sparql. """ import gi -gi.require_version('Tracker', '3.0') + +gi.require_version("Tracker", "3.0") from gi.repository import Tracker import unittest as ut import fixtures + # We must import configuration to enable the default logging behaviour. import configuration import trackertestutils.helpers -class TrackerQueryTests(): +class TrackerQueryTests: """ Query test cases for TrackerSparqlConnection. @@ -53,7 +55,9 @@ class TrackerQueryTests(): """ self.tracker.update(CONTACT) - cursor = self.conn.query('SELECT ?url ?filesize { ?url a nfo:FileDataObject ; nfo:fileSize ?filesize }') + cursor = self.conn.query( + "SELECT ?url ?filesize { ?url a nfo:FileDataObject ; nfo:fileSize ?filesize }" + ) cursor.next() assert cursor.get_n_columns() == 2 @@ -61,11 +65,11 @@ class TrackerQueryTests(): self.assertEqual(cursor.get_value_type(1), Tracker.SparqlValueType.INTEGER) -class TrackerLocalQueryTest (fixtures.TrackerSparqlDirectTest, TrackerQueryTests): +class TrackerLocalQueryTest(fixtures.TrackerSparqlDirectTest, TrackerQueryTests): pass -class TrackerBusQueryTest (fixtures.TrackerSparqlBusTest, TrackerQueryTests): +class TrackerBusQueryTest(fixtures.TrackerSparqlBusTest, TrackerQueryTests): pass diff --git a/tests/functional-tests/test_sparql_bugs.py b/tests/functional-tests/test_sparql_bugs.py index bdd128f8c..e68f4e919 100644 --- a/tests/functional-tests/test_sparql_bugs.py +++ b/tests/functional-tests/test_sparql_bugs.py @@ -27,11 +27,10 @@ import unittest as ut import fixtures -class TrackerStoreSparqlBugsTests (fixtures.TrackerSparqlDirectTest): - +class TrackerStoreSparqlBugsTests(fixtures.TrackerSparqlDirectTest): def test_01_NB217566_union_exists_filter(self): """ - NB217566: Use of UNION in EXISTS in a FILTER breaks filtering + NB217566: Use of UNION in EXISTS in a FILTER breaks filtering """ content = """ INSERT { @@ -146,12 +145,14 @@ class TrackerStoreSparqlBugsTests (fixtures.TrackerSparqlDirectTest): """ self.tracker.update(data) - results = self.tracker.query (""" + results = self.tracker.query( + """ SELECT ?u WHERE { ?u a nco:PersonContact ; nco:fullname 'Testing bug 217636' . } - """) + """ + ) self.assertEqual(len(results), 1) self.assertEqual(len(results[0]), 1) self.assertEqual(results[0][0], "contact:test-nb217636") @@ -162,12 +163,14 @@ class TrackerStoreSparqlBugsTests (fixtures.TrackerSparqlDirectTest): """ self.tracker.update(problematic_delete) - results_after = self.tracker.query (""" + results_after = self.tracker.query( + """ SELECT ?u WHERE { ?u a nco:PersonContact ; nco:fullname 'Testing bug 217636' . } - """) + """ + ) self.assertEqual(len(results_after), 0) # Safe deletion @@ -183,10 +186,10 @@ class TrackerStoreSparqlBugsTests (fixtures.TrackerSparqlDirectTest): query = "SELECT nrl:modified (?u) ?u WHERE { ?u a nco:Contact }" original_data = self.tracker.query(query) - wrong_insert = "INSERT { <test://nb222645-wrong-class-contact> a nco:IMContact. } " - self.assertRaises(GLib.Error, - self.tracker.update, - wrong_insert) + wrong_insert = ( + "INSERT { <test://nb222645-wrong-class-contact> a nco:IMContact. } " + ) + self.assertRaises(GLib.Error, self.tracker.update, wrong_insert) new_data = self.tracker.query(query) self.assertEqual(len(original_data), len(new_data)) |