diff --git a/Pipfile b/Pipfile index 0a45101..a3cf175 100644 --- a/Pipfile +++ b/Pipfile @@ -12,6 +12,7 @@ pytest = "*" pytest-cov = "*" pytest-server-fixtures = "*" exceptiongroup = "*" +black="*" [packages] future = "*" @@ -26,4 +27,4 @@ test = "pytest --cov rethinkdb_mock -vv" test_live = "pytest --cov rethinkdb_mock -vv -x --run rethink" last_live = "pytest --cov rethinkdb_mock -vv -x --run rethink --last-failed" isort = "isort ." -lint = "flake8 ." +lint = "black ." diff --git a/Pipfile.lock b/Pipfile.lock index ce01398..8e6cd3f 100644 --- a/Pipfile.lock +++ b/Pipfile.lock @@ -1,7 +1,7 @@ { "_meta": { "hash": { - "sha256": "dcc6105de6aa3e50a48bbc284b65cbb278a65b6f7a9efc53fd9d0b86f46a29a5" + "sha256": "3c32283cea5008340d36d3b440aa93d65344226e7f33d56a9c76634e99f74cf1" }, "pipfile-spec": 6, "requires": { @@ -57,6 +57,34 @@ "index": "pypi", "version": "==2.0.2" }, + "black": { + "hashes": [ + "sha256:01ede61aac8c154b55f35301fac3e730baf0c9cf8120f65a9cd61a81cfb4a0c3", + "sha256:022a582720b0d9480ed82576c920a8c1dde97cc38ff11d8d8859b3bd6ca9eedb", + "sha256:25cc308838fe71f7065df53aedd20327969d05671bac95b38fdf37ebe70ac087", + "sha256:27eb7a0c71604d5de083757fbdb245b1a4fae60e9596514c6ec497eb63f95320", + "sha256:327a8c2550ddc573b51e2c352adb88143464bb9d92c10416feb86b0f5aee5ff6", + "sha256:47e56d83aad53ca140da0af87678fb38e44fd6bc0af71eebab2d1f59b1acf1d3", + "sha256:501387a9edcb75d7ae8a4412bb8749900386eaef258f1aefab18adddea1936bc", + "sha256:552513d5cd5694590d7ef6f46e1767a4df9af168d449ff767b13b084c020e63f", + "sha256:5c4bc552ab52f6c1c506ccae05681fab58c3f72d59ae6e6639e8885e94fe2587", + "sha256:642496b675095d423f9b8448243336f8ec71c9d4d57ec17bf795b67f08132a91", + "sha256:6d1c6022b86f83b632d06f2b02774134def5d4d4f1dac8bef16d90cda18ba28a", + "sha256:7f3bf2dec7d541b4619b8ce526bda74a6b0bffc480a163fed32eb8b3c9aed8ad", + "sha256:831d8f54c3a8c8cf55f64d0422ee875eecac26f5f649fb6c1df65316b67c8926", + "sha256:8417dbd2f57b5701492cd46edcecc4f9208dc75529bcf76c514864e48da867d9", + "sha256:86cee259349b4448adb4ef9b204bb4467aae74a386bce85d56ba4f5dc0da27be", + "sha256:893695a76b140881531062d48476ebe4a48f5d1e9388177e175d76234ca247cd", + "sha256:9fd59d418c60c0348505f2ddf9609c1e1de8e7493eab96198fc89d9f865e7a96", + "sha256:ad0014efc7acf0bd745792bd0d8857413652979200ab924fbf239062adc12491", + "sha256:b5b0ee6d96b345a8b420100b7d71ebfdd19fab5e8301aff48ec270042cd40ac2", + "sha256:c333286dc3ddca6fdff74670b911cccedacb4ef0a60b34e491b8a67c833b343a", + "sha256:f9062af71c59c004cd519e2fb8f5d25d39e46d3af011b41ab43b9c74e27e236f", + "sha256:fb074d8b213749fa1d077d630db0d5f8cc3b2ae63587ad4116e8a436e9bbe995" + ], + "index": "pypi", + "version": "==23.7.0" + }, "certifi": { "hashes": [ "sha256:539cc1d13202e33ca466e88b2807e29f4c13049d6d87031a3c110744495cb082", @@ -146,6 +174,14 @@ "markers": "python_full_version >= '3.7.0'", "version": "==3.2.0" }, + "click": { + "hashes": [ + "sha256:48ee849951919527a045bfe3bf7baa8a959c423134e1a5b98c05c20ba75a1cbd", + "sha256:fa244bb30b3b5ee2cae3da8f55c9e5e0c0e86093306301fb418eb9dc40fbded5" + ], + "markers": "python_version >= '3.7'", + "version": "==8.1.6" + }, "contextlib2": { "hashes": [ "sha256:3fbdb64466afd23abaf6c977627b75b6139a5a3e8ce38405c5b413aed7a0471f", @@ -249,11 +285,11 @@ }, "flake8": { "hashes": [ - "sha256:3833794e27ff64ea4e9cf5d410082a8b97ff1a06c16aa3d2027339cd0f1195c7", - "sha256:c61007e76655af75e6785a931f452915b371dc48f56efd765247c8fe68f2b181" + "sha256:d5b3857f07c030bdb5bf41c7f53799571d75c4491748a3adcd47de929e34cd23", + "sha256:ffdfce58ea94c6580c77888a86506937f9a1a227dfcd15f245d694ae20a6b6e5" ], "index": "pypi", - "version": "==6.0.0" + "version": "==6.1.0" }, "flake8-isort": { "hashes": [ @@ -310,6 +346,14 @@ "markers": "python_version >= '3.6'", "version": "==5.1.0" }, + "mypy-extensions": { + "hashes": [ + "sha256:4392f6c0eb8a5668a69e23d168ffa70f0be9ccfd32b5cc2d26a34ae5b844552d", + "sha256:75dbf8955dc00442a438fc4d0666508a9a97b6bd41aa2f0ffe9d2f2725af0782" + ], + "markers": "python_version >= '3.5'", + "version": "==1.0.0" + }, "packaging": { "hashes": [ "sha256:994793af429502c4ea2ebf6bf664629d07c1a9fe974af92966e4b8d2df7edc61", @@ -334,6 +378,22 @@ "markers": "python_version >= '3.5'", "version": "==12.5.0" }, + "pathspec": { + "hashes": [ + "sha256:1d6ed233af05e679efb96b1851550ea95bbb64b7c490b0f5aa52996c11e92a20", + "sha256:e0d8d0ac2f12da61956eb2306b69f9469b42f4deb0f3cb6ed47b9cce9996ced3" + ], + "markers": "python_version >= '3.7'", + "version": "==0.11.2" + }, + "platformdirs": { + "hashes": [ + "sha256:b45696dab2d7cc691a3226759c0d3b00c47c8b6e293d96f6436f733303f77f6d", + "sha256:d7c24979f292f916dc9cbf8648319032f551ea8c49a4c9bf2fb556a02070ec1d" + ], + "markers": "python_version >= '3.7'", + "version": "==3.10.0" + }, "pluggy": { "hashes": [ "sha256:c2fd55a7d7a3863cba1a013e4e2414658b1d07b6bc57b3919e0c63c9abb99849", @@ -372,19 +432,19 @@ }, "pycodestyle": { "hashes": [ - "sha256:347187bdb476329d98f695c213d7295a846d1152ff4fe9bacb8a9590b8ee7053", - "sha256:8a4eaf0d0495c7395bdab3589ac2db602797d76207242c17d470186815706610" + "sha256:259bcc17857d8a8b3b4a2327324b79e5f020a13c16074670f9c8c8f872ea76d0", + "sha256:5d1013ba8dc7895b548be5afb05740ca82454fd899971563d2ef625d090326f8" ], - "markers": "python_version >= '3.6'", - "version": "==2.10.0" + "markers": "python_version >= '3.8'", + "version": "==2.11.0" }, "pyflakes": { "hashes": [ - "sha256:ec55bf7fe21fff7f1ad2f7da62363d749e2a470500eab1b555334b67aa1ef8cf", - "sha256:ec8b276a6b60bd80defed25add7e439881c19e64850afd9b346283d4165fd0fd" + "sha256:4132f6d49cb4dae6819e5379898f2b8cce3c5f23994194c24b77d5da2e36f774", + "sha256:a0aae034c444db0071aa077972ba4768d40c830d9539fd45bf4cd3f8f6992efc" ], - "markers": "python_version >= '3.6'", - "version": "==3.0.1" + "markers": "python_version >= '3.8'", + "version": "==3.1.0" }, "pytest": { "hashes": [ @@ -461,6 +521,14 @@ "markers": "python_version >= '3.7'", "version": "==2.3.0" }, + "tomli": { + "hashes": [ + "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc", + "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f" + ], + "markers": "python_version < '3.11'", + "version": "==2.0.1" + }, "urllib3": { "hashes": [ "sha256:8d22f86aae8ef5e410d4f539fde9ce6b2113a001bb4d189e0aed70642d602b11", diff --git a/rethinkdb_mock/ast.py b/rethinkdb_mock/ast.py index d2a479c..97ccf9b 100644 --- a/rethinkdb_mock/ast.py +++ b/rethinkdb_mock/ast.py @@ -8,6 +8,7 @@ from future.utils import iteritems from future.utils import text_type from past.utils import old_div +from rethinkdb.errors import ReqlNonExistenceError from rethinkdb_mock import ast_base from rethinkdb_mock import joins @@ -38,7 +39,7 @@ def __init__(self, *args): pass def run(self, arg, conn): - self.raise_rql_runtime_error('DEFAULT MESSAGE') + self.raise_rql_runtime_error("DEFAULT MESSAGE") class RError1(MonExp): @@ -53,7 +54,7 @@ def run(self, arg, scope): class RDb(MonExp): def do_run(self, db_name, arg, scope): - if hasattr(self, 'mockdb_ref'): + if hasattr(self, "mockdb_ref"): db = self.mockdb_ref else: db = arg @@ -66,28 +67,28 @@ def find_db_scope(self): class TypeOf(MonExp): def do_run(self, val, arg, scope): type_map = { - str: 'STRING', - dict: 'OBJECT', - int: 'NUMBER', - float: 'NUMBER', - bool: 'BOOL' + str: "STRING", + dict: "OBJECT", + int: "NUMBER", + float: "NUMBER", + bool: "BOOL", } if val is None: - return 'NULL' + return "NULL" else: val_type = type(val) if val_type in type_map: return type_map[val_type] elif util.is_iterable(val): - return 'ARRAY' + return "ARRAY" raise TypeError class Distinct(MonExp): def do_run(self, table_or_seq, arg, scope): - if 'index' in self.optargs: + if "index" in self.optargs: # table - table_or_seq = table_or_seq._index_values(self.optargs['index']) + table_or_seq = table_or_seq._index_values(self.optargs["index"]) return list(util.dictable_distinct(table_or_seq)) @@ -95,13 +96,13 @@ class Zip(MonExp): def do_run(self, sequence, arg, scope): out = [] for elem in sequence: - out.append(util.extend(elem['left'], elem['right'])) + out.append(util.extend(elem["left"], elem["right"])) return out class IsEmpty(MonExp): def do_run(self, left, arg, scope): - return (len(left) == 0) + return len(left) == 0 class RVar(MonExp): @@ -111,7 +112,7 @@ def do_run(self, symbol_name, arg, scope): class Not(MonExp): def do_run(self, left, arg, scope): - return (not left) + return not left class Keys(MonExp): @@ -121,12 +122,12 @@ def do_run(self, left, arg, scope): class Asc(MonExp): def do_run(self, left, arg, scope): - return (left, 'ASC') + return (left, "ASC") class Desc(MonExp): def do_run(self, left, arg, scope): - return (left, 'DESC') + return (left, "DESC") class Json(MonExp): @@ -152,19 +153,20 @@ def do_run(self, thing, thing_attr, arg, scope): class Get(BinExp): def do_run(self, left, right, arg, scope): - return util.find_first(util.match_attr('id', right), left) + return util.find_first(util.match_attr("id", right), left) class GetAll(BinExp): def do_run(self, left, right, arg, scope): - if 'index' in self.optargs and self.optargs['index'] != 'id': + if "index" in self.optargs and self.optargs["index"] != "id": index_func, is_multi = self.find_index_func_for_scope( - self.optargs['index'], - arg + self.optargs["index"], arg ) if isinstance(index_func, RFunc): + def map_fn(d): return index_func.run([d], scope) + else: map_fn = index_func @@ -179,8 +181,8 @@ def map_fn(d): indexed = set(indexed) for match_item in right: if match_item in indexed: - if elem['id'] not in seen_ids: - seen_ids.add(elem['id']) + if elem["id"] not in seen_ids: + seen_ids.add(elem["id"]) result.append(elem) break else: @@ -190,7 +192,7 @@ def map_fn(d): return result else: - return list(filter(util.match_attr_multi('id', right), left)) + return list(filter(util.match_attr_multi("id", right), left)) class BinOp(BinExp): @@ -255,6 +257,12 @@ class Or(BinOp): class Reduce(ByFuncBase): def do_run(self, sequence, reduce_fn, arg, scope): + if len(sequence) == 0: + raise ReqlNonExistenceError("Cannot reduce over an empty stream") + + if len(sequence) == 1: + return sequence[0] + first, second = sequence[0:2] result = reduce_fn([first, second]) for elem in sequence[2:]: @@ -267,25 +275,27 @@ def __init__(self, *args): pass def get_update_settings(self): - defaults = { - 'durability': 'hard', - 'return_changes': False, - 'non_atomic': False - } + defaults = {"durability": "hard", "return_changes": False, "non_atomic": False} return util.extend(defaults, self.optargs) def validate_nested_query_status(self): - if self.right.has_table_scope() and (not self.get_update_settings()['non_atomic']): - self.raise_rql_runtime_error('attempted nested query in update without non-atomic flag') + if self.right.has_table_scope() and ( + not self.get_update_settings()["non_atomic"] + ): + self.raise_rql_runtime_error( + "attempted nested query in update without non-atomic flag" + ) def update_table(self, result_sequence, arg, scope): settings = self.get_update_settings() current_db = self.find_db_scope() current_table = self.find_table_scope() result_sequence = util.ensure_list(result_sequence) - result, report = arg.update_by_id_in_table_in_db(current_db, current_table, result_sequence) - if not settings['return_changes']: - del report['changes'] + result, report = arg.update_by_id_in_table_in_db( + current_db, current_table, result_sequence + ) + if not settings["return_changes"]: + del report["changes"] return result, report @@ -296,13 +306,16 @@ def do_run(self, sequence, map_fn, arg, scope): def mapper(doc): ext_with = map_fn(doc) return ast_base.rql_merge_with(ext_with, doc) + return self.update_table(util.maybe_map(mapper, sequence), arg, scope) class UpdateWithObj(BinExp, UpdateBase): def do_run(self, sequence, to_update, arg, scope): self.validate_nested_query_status() - return self.update_table(util.maybe_map(ast_base.rql_merge_with(to_update), sequence), arg, scope) + return self.update_table( + util.maybe_map(ast_base.rql_merge_with(to_update), sequence), arg, scope + ) class Replace(BinExp, UpdateBase): @@ -312,10 +325,7 @@ def do_run(self, left, right, arg, scope): class Delete(MonExp): def get_delete_settings(self): - defaults = { - 'durability': 'hard', - 'return_changes': False - } + defaults = {"durability": "hard", "return_changes": False} return util.extend(defaults, self.optargs) def do_run(self, sequence, arg, scope): @@ -325,19 +335,17 @@ def do_run(self, sequence, arg, scope): sequence = [sequence] else: sequence = list(sequence) - result, report = arg.remove_by_id_in_table_in_db(current_db, current_table, sequence) - if not self.get_delete_settings()['return_changes']: - del report['changes'] + result, report = arg.remove_by_id_in_table_in_db( + current_db, current_table, sequence + ) + if not self.get_delete_settings()["return_changes"]: + del report["changes"] return result, report class Insert(BinExp): def get_insert_settings(self): - defaults = { - 'durability': 'hard', - 'return_changes': False, - 'conflict': 'error' - } + defaults = {"durability": "hard", "return_changes": False, "conflict": "error"} return util.extend(defaults, self.optargs) def do_run(self, sequence, to_insert, arg, scope): @@ -348,19 +356,21 @@ def do_run(self, sequence, to_insert, arg, scope): generated_keys = list() def ensure_id(elem): - if ('id' not in elem) or (elem['id'] is None): + if ("id" not in elem) or (elem["id"] is None): uid = text_type(uuid.uuid4()) - elem = util.extend(elem, {'id': uid}) + elem = util.extend(elem, {"id": uid}) generated_keys.append(uid) return elem to_insert = list(map(ensure_id, list(to_insert))) settings = self.get_insert_settings() - result, report = arg.insert_into_table_in_db(current_db, current_table, to_insert, conflict=settings['conflict']) - if not settings['return_changes']: - del report['changes'] + result, report = arg.insert_into_table_in_db( + current_db, current_table, to_insert, conflict=settings["conflict"] + ) + if not settings["return_changes"]: + del report["changes"] if generated_keys: - report['generated_keys'] = generated_keys + report["generated_keys"] = generated_keys return result, report @@ -397,14 +407,19 @@ def do_run(self, left, attrs, arg, scope): return util.maybe_map(util.pluck_with(attrs), left) -class MergePoly(BinExp): - def do_run(self, left, ext_with, arg, scope): - if ast_base.is_literal(ext_with): - self.raise_rql_runtime_error('invalid top-level r.literal()') - elif ast_base.has_nested_literal(ext_with): - self.raise_rql_runtime_error('invalid nested r.literal()') +class MergePolyWithRFunc(ByFuncBase): + def do_run(self, sequence, map_fn, arg, scope): + def mapper(doc): + ext_with = map_fn(doc) + + if ast_base.is_literal(ext_with): + self.raise_rql_runtime_error("invalid top-level r.literal()") + elif ast_base.has_nested_literal(ext_with): + self.raise_rql_runtime_error("invalid nested r.literal()") + + return ast_base.rql_merge_with(ext_with, doc) - return util.maybe_map(ast_base.rql_merge_with(ext_with), left) + return util.maybe_map(mapper, sequence) class HasFields(BinExp): @@ -565,7 +580,7 @@ def run(self, arg, scope): class Random1(MonExp): def do_run(self, max_num, arg, scope): - if 'float' in self.optargs and self.optargs['float']: + if "float" in self.optargs and self.optargs["float"]: return random.uniform(0, max_num) else: return random.randint(0, max_num) @@ -573,7 +588,7 @@ def do_run(self, max_num, arg, scope): class Random2(BinExp): def do_run(self, min_num, max_num, arg, scope): - if 'float' in self.optargs and self.optargs['float']: + if "float" in self.optargs and self.optargs["float"]: return random.uniform(min_num, max_num) else: return random.randint(min_num, max_num) @@ -627,10 +642,7 @@ def do_run(self, left, func, arg, scope): class UnGroup(MonExp): def do_run(self, grouped_seq, arg, scope): for group_name, group_vals in iteritems(grouped_seq): - yield { - 'group': group_name, - 'reduction': group_vals - } + yield {"group": group_name, "reduction": group_vals} class Branch(RBase): @@ -668,7 +680,7 @@ def do_run(self, sequence, test_for, arg, scope): class ContainsFuncs(RBase): def __init__(self, left, right, optargs={}): - assert (isinstance(right, MakeArray)) + assert isinstance(right, MakeArray) self.left = left self.right = right self.optargs = optargs @@ -691,6 +703,7 @@ def run(self, arg, scope): # Table and database manipulation # ################################# + class TableCreate(BinExp): def do_run(self, left, table_name, arg, scope): db_name = self.find_db_scope() @@ -738,6 +751,7 @@ def run(self, arg, scope): return tables + # ################################# # Index manipulation functions # ################################# @@ -748,13 +762,9 @@ def do_run(self, sequence, field_name, arg, scope): index_func = util.getter(field_name) current_db = self.find_db_scope() current_table = self.find_table_scope() - multi = self.optargs.get('multi', False) + multi = self.optargs.get("multi", False) return arg.create_index_in_table_in_db( - current_db, - current_table, - field_name, - index_func, - multi=multi + current_db, current_table, field_name, index_func, multi=multi ) @@ -770,13 +780,9 @@ def run(self, arg, scope): index_func = self.right current_db = self.find_db_scope() current_table = self.find_table_scope() - multi = self.optargs.get('multi', False) + multi = self.optargs.get("multi", False) return arg.create_index_in_table_in_db( - current_db, - current_table, - index_name, - index_func, - multi=multi + current_db, current_table, index_name, index_func, multi=multi ) @@ -790,71 +796,53 @@ def do_run(self, sequence, old_name, new_name, arg, scope): current_db = self.find_db_scope() current_table = self.find_table_scope() - exists = arg.index_exists_in_table_in_db( - current_db, - current_table, - new_name - ) + exists = arg.index_exists_in_table_in_db(current_db, current_table, new_name) if exists: - if not self.optargs.get('overwrite', False): - raise Exception('tried to overwrite existing index!') + if not self.optargs.get("overwrite", False): + raise Exception("tried to overwrite existing index!") return arg.rename_index_in_table_in_db( - current_db, - current_table, - old_name, - new_name + current_db, current_table, old_name, new_name ) class IndexDrop(BinExp): def do_run(self, sequence, index_name, arg, scope): - assert (isinstance(self.left, RTable)) + assert isinstance(self.left, RTable) current_db = self.find_db_scope() current_table = self.find_table_scope() - return arg.drop_index_in_table_in_db( - current_db, - current_table, - index_name - ) + return arg.drop_index_in_table_in_db(current_db, current_table, index_name) class IndexList(MonExp): def do_run(self, table, arg, scope): - assert (isinstance(self.left, RTable)) + assert isinstance(self.left, RTable) current_db = self.find_db_scope() current_table = self.find_table_scope() - return arg.list_indexes_in_table_in_db( - current_db, - current_table - ) + return arg.list_indexes_in_table_in_db(current_db, current_table) class IndexWaitAll(MonExp): def do_run(self, table, arg, scope): - assert (isinstance(self.left, RTable)) + assert isinstance(self.left, RTable) return table class IndexWaitOne(BinExp): def do_run(self, table, index_name, arg, scope): - assert (isinstance(self.left, RTable)) + assert isinstance(self.left, RTable) current_db = self.find_db_scope() current_table = self.find_table_scope() - exists = arg.index_exists_in_table_in_db( - current_db, - current_table, - index_name - ) - assert (exists) + exists = arg.index_exists_in_table_in_db(current_db, current_table, index_name) + assert exists return table class Sync(MonExp): def do_run(self, table, arg, scope): - assert (isinstance(self.left, RTable)) + assert isinstance(self.left, RTable) return table @@ -889,12 +877,12 @@ def do_run(self, string, split_on, limit, arg, scope): def operators_for_bounds(left_bound, right_bound): - if left_bound == 'closed': + if left_bound == "closed": left_oper = operator.ge else: left_oper = operator.gt - if right_bound == 'closed': + if right_bound == "closed": right_oper = operator.le else: right_oper = operator.lt @@ -904,23 +892,16 @@ def operators_for_bounds(left_bound, right_bound): class Between(Ternary): def do_run(self, table, lower_key, upper_key, arg, scope): - defaults = { - 'left_bound': 'closed', - 'right_bound': 'open', - 'index': 'id' - } + defaults = {"left_bound": "closed", "right_bound": "open", "index": "id"} options = util.extend(defaults, self.optargs) - if options['index'] == 'id': - map_fn = util.getter('id') + if options["index"] == "id": + map_fn = util.getter("id") else: - map_fn, _ = self.find_index_func_for_scope( - options['index'], - arg - ) + map_fn, _ = self.find_index_func_for_scope(options["index"], arg) left_test, right_test = operators_for_bounds( - options['left_bound'], options['right_bound'] + options["left_bound"], options["right_bound"] ) for document in table: doc_val = map_fn(document) @@ -952,9 +933,10 @@ def do_run(self, sequence, indices, arg, scope): # Joins # ########### + class EqJoin(Ternary): def do_run(self, left, field, right, arg, scope): - return joins.do_eq_join(field, left, 'id', right) + return joins.do_eq_join(field, left, "id", right) class InnerOuterJoinBase(RBase): @@ -987,6 +969,7 @@ def do_run(self, left, right, pred, arg, scope): # Time # ############ + class Year(MonExp): def do_run(self, dtime, arg, scope): return dtime.year @@ -1062,15 +1045,12 @@ def do_run(self, parts, arg, scope): class During(Ternary): def do_run(self, to_test, left, right, arg, scope): - defaults = { - 'left_bound': 'closed', - 'right_bound': 'open' - } + defaults = {"left_bound": "closed", "right_bound": "open"} options = util.extend(defaults, self.optargs) left_test, right_test = operators_for_bounds( - options['left_bound'], options['right_bound'] + options["left_bound"], options["right_bound"] ) - return (left_test(to_test, left) and right_test(to_test, right)) + return left_test(to_test, left) and right_test(to_test, right) class StrMatch(RBase): @@ -1109,7 +1089,7 @@ class CoerceTo(BinExp): def do_run(self, left, right, arg, scope): res = self.left.run(arg, scope) rname = self.right.run(arg, scope) - if rname.upper() == 'ARRAY': + if rname.upper() == "ARRAY": if isinstance(res, dict): return list(res.items()) return list(res) diff --git a/rethinkdb_mock/ast_base.py b/rethinkdb_mock/ast_base.py index 2b18cd4..f82658d 100644 --- a/rethinkdb_mock/ast_base.py +++ b/rethinkdb_mock/ast_base.py @@ -15,25 +15,26 @@ def __init__(self, attrs): # Base classes # ################# + class RBase(object): def __init__(self, *args): pass def find_table_scope(self): result = None - if hasattr(self, 'left'): + if hasattr(self, "left"): result = self.left.find_table_scope() return result def find_db_scope(self): result = None - if hasattr(self, 'left'): + if hasattr(self, "left"): result = self.left.find_db_scope() return result def has_table_scope(self): result = None - for part in ('left', 'middle', 'right'): + for part in ("left", "middle", "right"): if hasattr(self, part): result = getattr(self, part).has_table_scope() if result: @@ -43,14 +44,8 @@ def has_table_scope(self): def find_index_func_for_scope(self, index_name, db_arg): db_scope = self.find_db_scope() table_scope = self.find_table_scope() - func = db_arg.get_index_func_in_table_in_db( - db_scope, - table_scope, - index_name - ) - is_multi = db_arg.is_multi_index( - db_scope, table_scope, index_name - ) + func = db_arg.get_index_func_in_table_in_db(db_scope, table_scope, index_name) + is_multi = db_arg.is_multi_index(db_scope, table_scope, index_name) return func, is_multi def raise_rql_runtime_error(self, msg): @@ -59,23 +54,19 @@ def raise_rql_runtime_error(self, msg): # temporary jankiness to get it working # doing it this way means error messages won't # be properly printed - term = AttrHaving({ - 'args': (), - 'optargs': {}, - 'compose': (lambda x, y: 'COMPOSED') - }) + term = AttrHaving( + {"args": (), "optargs": {}, "compose": (lambda x, y: "COMPOSED")} + ) raise RqlRuntimeError(msg, term, []) def raise_rql_compile_error(self, msg): - term = AttrHaving({ - 'args': (), - 'optargs': {}, - 'compose': (lambda x, y: 'COMPOSED') - }) + term = AttrHaving( + {"args": (), "optargs": {}, "compose": (lambda x, y: "COMPOSED")} + ) raise RqlCompileError(msg, term, []) def set_mock_ref(self, other): - if hasattr(self, 'mockdb_ref'): + if hasattr(self, "mockdb_ref"): other.mockdb_ref = self.mockdb_ref @@ -121,7 +112,9 @@ def __str__(self): return f"<{class_name}: {self.left}>" def do_run(self, left, arg, scope): - raise NotImplementedError(f"method do_run not defined in class {self.__class__.__name__}") + raise NotImplementedError( + f"method do_run not defined in class {self.__class__.__name__}" + ) def run(self, arg, scope): self.set_mock_ref(self.left) @@ -140,7 +133,9 @@ def __str__(self): return f"<{class_name}: ({self.left}, {self.right})>" def do_run(self, left, right, arg, scope): - raise NotImplementedError(f"method do_run not defined in class {self.__class__.__name__}") + raise NotImplementedError( + f"method do_run not defined in class {self.__class__.__name__}" + ) def run(self, arg, scope): self.set_mock_ref(self.left) @@ -158,10 +153,12 @@ def __init__(self, left, middle, right, optargs={}): self.optargs = optargs def do_run(self, left, middle, right, arg, scope): - raise NotImplementedError(f"method do_run not defined in class {self.__class__.__name__}") + raise NotImplementedError( + f"method do_run not defined in class {self.__class__.__name__}" + ) def run(self, arg, scope): - for part in ('left', 'middle', 'right'): + for part in ("left", "middle", "right"): self.set_mock_ref(getattr(self, part)) left = self.left.run(arg, scope) middle = self.middle.run(arg, scope) @@ -176,7 +173,9 @@ def __init__(self, left, right, optargs={}): self.optargs = optargs def do_run(self, left, map_fn, arg, scope): - raise NotImplementedError(f"method do_run not defined in class {self.__class__.__name__}") + raise NotImplementedError( + f"method do_run not defined in class {self.__class__.__name__}" + ) def run(self, arg, scope): self.set_mock_ref(self.left) @@ -278,12 +277,12 @@ def rql_merge_with(ext_with, to_extend): out.update(to_extend) if is_literal(ext_with): if has_nested_literal(ext_with): - raise RqlRuntimeError('No nested r.literal()!') + raise RqlRuntimeError("No nested r.literal()!") for k, v in iteritems(ext_with): if is_literal(v): if has_nested_literal(v): - raise RqlRuntimeError('No nested r.literal()!') + raise RqlRuntimeError("No nested r.literal()!") if k not in to_extend: out[k] = util.clone(v) @@ -292,9 +291,13 @@ def rql_merge_with(ext_with, to_extend): if is_literal(v): out[k] = util.clone(v) else: - if isinstance(d1_val, dict) and (isinstance(v, dict) or isinstance(v, LITERAL_OBJECT)): + if isinstance(d1_val, dict) and ( + isinstance(v, dict) or isinstance(v, LITERAL_OBJECT) + ): out[k] = rql_merge_with(v, d1_val) - elif isinstance(d1_val, list) and (isinstance(v, list) or isinstance(v, LITERAL_LIST)): + elif isinstance(d1_val, list) and ( + isinstance(v, list) or isinstance(v, LITERAL_LIST) + ): out[k] = util.cat(d1_val, v) else: out[k] = util.clone(v) diff --git a/rethinkdb_mock/db.py b/rethinkdb_mock/db.py index fda454e..f416af6 100644 --- a/rethinkdb_mock/db.py +++ b/rethinkdb_mock/db.py @@ -3,99 +3,80 @@ from future.utils import iteritems import rethinkdb +import rethinkdb.ast as r_ast from . import rtime from . import util -from .ast_base import BinExp from .rql_rewrite import rewrite_query +from .ast_base import BinExp from .rql_rewrite import RQL_TYPE_TRANSLATIONS from .scope import Scope def fill_missing_report_results(report): - defaults = { - 'errors': 0, - 'replaced': 0, - 'inserted': 0, - 'deleted': 0, - 'changes': [] - } + defaults = {"errors": 0, "replaced": 0, "inserted": 0, "deleted": 0, "changes": []} return util.extend(defaults, report) def replace_array_elems_by_id(existing, replace_with): - report = { - 'replaced': 0, - 'changes': [] - } + report = {"replaced": 0, "changes": []} elem_index_by_id = {} for index in range(0, len(existing)): elem = existing[index] - elem_index_by_id[util.getter('id')(elem)] = index + elem_index_by_id[util.getter("id")(elem)] = index to_return = util.clone_array(existing) for elem in replace_with: - index = elem_index_by_id[util.getter('id')(elem)] - change = { - 'old_val': existing[index], - 'new_val': elem - } - report['changes'].append(change) - report['replaced'] += 1 + index = elem_index_by_id[util.getter("id")(elem)] + change = {"old_val": existing[index], "new_val": elem} + report["changes"].append(change) + report["replaced"] += 1 to_return[index] = elem return to_return, fill_missing_report_results(report) def remove_array_elems_by_id(existing, to_remove): - report = { - 'deleted': 0, - 'changes': [] - } + report = {"deleted": 0, "changes": []} result = util.clone_array(existing) for elem in to_remove: if elem in result: - report['deleted'] += 1 - report['changes'].append({'old_val': elem, 'new_val': None}) + report["deleted"] += 1 + report["changes"].append({"old_val": elem, "new_val": None}) result.remove(elem) return result, report def insert_into_table_with_conflict_setting(existing, to_insert, conflict): - assert (conflict in ('error', 'update', 'replace')) - existing_by_id = {row['id']: row for row in existing} + assert conflict in ("error", "update", "replace") + existing_by_id = {row["id"]: row for row in existing} seen = set([]) result = [] - result_report = { - 'errors': 0, - 'inserted': 0, - 'replaced': 0, - 'changes': [] - } + result_report = {"errors": 0, "inserted": 0, "replaced": 0, "changes": []} for doc in to_insert: change = {} - if doc['id'] in existing_by_id: - existing_row = existing_by_id[doc['id']] - change['old_val'] = existing_row - if conflict == 'error': - result_report['errors'] += 1 + if doc["id"] in existing_by_id: + existing_row = existing_by_id[doc["id"]] + change["old_val"] = existing_row + if conflict == "error": + result_report["errors"] += 1 continue - elif conflict == 'update': + elif conflict == "update": result_row = util.extend(existing_row, doc) - elif conflict == 'replace': + elif conflict == "replace": result_row = doc - result_report['replaced'] += 1 - seen.add(doc['id']) + result_report["replaced"] += 1 + seen.add(doc["id"]) else: - change['old_val'] = None - result_report['inserted'] += 1 + change["old_val"] = None + result_report["inserted"] += 1 result_row = doc result.append(result_row) - change['new_val'] = result_row - result_report['changes'].append(change) + change["new_val"] = result_row + result_report["changes"].append(change) - not_updated = [row for row in existing if row['id'] not in seen] + not_updated = [row for row in existing if row["id"] not in seen] result = not_updated + result return result, fill_missing_report_results(result_report) @@ -116,10 +97,12 @@ def update_by_id(self, updated_rows): return MockTableData(self.name, new_data, self.indexes), report def insert(self, new_rows, conflict): - assert (conflict in ('error', 'update', 'replace')) + assert conflict in ("error", "update", "replace") if not isinstance(new_rows, list): new_rows = [new_rows] - new_data, report = insert_into_table_with_conflict_setting(self.rows, new_rows, conflict) + new_data, report = insert_into_table_with_conflict_setting( + self.rows, new_rows, conflict + ) return MockTableData(self.name, new_data, self.indexes), report def remove_by_id(self, to_remove): @@ -132,11 +115,10 @@ def get_rows(self): return self.rows def create_index(self, index_name, index_func, multi=False): - to_add = { - 'func': index_func, - 'multi': multi - } - return MockTableData(self.name, self.rows, util.extend(self.indexes, {index_name: to_add})) + to_add = {"func": index_func, "multi": multi} + return MockTableData( + self.name, self.rows, util.extend(self.indexes, {index_name: to_add}) + ) def rename_index(self, old_name, new_name): new_indexes = util.without([old_name], self.indexes) @@ -156,14 +138,14 @@ def index_exists(self, index): def _index_values(self, index_name): func = self.get_index_func(index_name) out = [func(elem) for elem in self.rows] - pprint({'func': func, 'out': out}) + pprint({"func": func, "out": out}) return out def get_index_func(self, index): - return self.indexes[index].get('func') + return self.indexes[index].get("func") def is_multi_index(self, index): - return self.indexes[index].get('multi', False) + return self.indexes[index].get("multi", False) def __iter__(self): for elem in self.rows: @@ -193,25 +175,26 @@ def get_table(self, table_name): return self.tables_by_name[table_name] def set_table(self, table_name, new_table_instance): - assert (isinstance(new_table_instance, MockTableData)) + assert isinstance(new_table_instance, MockTableData) tables = util.obj_clone(self.tables_by_name) tables[table_name] = new_table_instance return MockDbData(tables) class MockDb(object): - def __init__(self, dbs_by_name, defaultDB=None): + def __init__(self, dbs_by_name, default_db=None): + self.dbs_by_name = dbs_by_name - self.defaultDB = defaultDB + self.default_db = default_db def get_db(self, db_name): return self.dbs_by_name[db_name] def set_db(self, db_name, db_data_instance): - assert (isinstance(db_data_instance, MockDbData)) + assert isinstance(db_data_instance, MockDbData) dbs_by_name = util.obj_clone(self.dbs_by_name) dbs_by_name[db_name] = db_data_instance - return MockDb(dbs_by_name, self.defaultDB) + return MockDb(dbs_by_name, self.default_db) def create_table_in_db(self, db_name, table_name): new_db = self.get_db(db_name) @@ -230,24 +213,28 @@ def create_db(self, db_name): return self.set_db(db_name, MockDbData({})) def drop_db(self, db_name): - return MockDb(util.without([db_name], self.dbs_by_name), self.defaultDB) + return MockDb(util.without([db_name], self.dbs_by_name), self.default_db) def list_dbs(self): return list(self.dbs_by_name.keys()) def replace_table_in_db(self, db_name, table_name, table_data_instance): - assert (isinstance(table_data_instance, MockTableData)) + assert isinstance(table_data_instance, MockTableData) db = self.get_db(db_name) new_db = db.set_table(table_name, table_data_instance) return self.set_db(db_name, new_db) def insert_into_table_in_db(self, db_name, table_name, elem_list, conflict): - assert (conflict in ('error', 'update', 'replace')) - new_table_data, report = self.get_db(db_name).get_table(table_name).insert(elem_list, conflict) + assert conflict in ("error", "update", "replace") + new_table_data, report = ( + self.get_db(db_name).get_table(table_name).insert(elem_list, conflict) + ) return self._replace_table(db_name, table_name, new_table_data), report def update_by_id_in_table_in_db(self, db_name, table_name, elem_list): - new_table_data, report = self.get_db(db_name).get_table(table_name).update_by_id(elem_list) + new_table_data, report = ( + self.get_db(db_name).get_table(table_name).update_by_id(elem_list) + ) return self._replace_table(db_name, table_name, new_table_data), report def _replace_table(self, db_name, table_name, new_table_data): @@ -255,21 +242,35 @@ def _replace_table(self, db_name, table_name, new_table_data): return self.set_db(db_name, new_db) def remove_by_id_in_table_in_db(self, db_name, table_name, elem_list): - new_table_data, report = self.get_db(db_name).get_table(table_name).remove_by_id(elem_list) + new_table_data, report = ( + self.get_db(db_name).get_table(table_name).remove_by_id(elem_list) + ) return self._replace_table(db_name, table_name, new_table_data), report - def create_index_in_table_in_db(self, db_name, table_name, index_name, index_func, multi=False): - new_table_data = self.get_db(db_name)\ - .get_table(table_name)\ + def create_index_in_table_in_db( + self, db_name, table_name, index_name, index_func, multi=False + ): + new_table_data = ( + self.get_db(db_name) + .get_table(table_name) .create_index(index_name, index_func, multi=multi) + ) return self._replace_table(db_name, table_name, new_table_data) def drop_index_in_table_in_db(self, db_name, table_name, index_name): - new_table_data = self.get_db(db_name).get_table(table_name).drop_index(index_name) + new_table_data = ( + self.get_db(db_name).get_table(table_name).drop_index(index_name) + ) return self._replace_table(db_name, table_name, new_table_data) - def rename_index_in_table_in_db(self, db_name, table_name, old_index_name, new_index_name): - new_table_data = self.get_db(db_name).get_table(table_name).rename_index(old_index_name, new_index_name) + def rename_index_in_table_in_db( + self, db_name, table_name, old_index_name, new_index_name + ): + new_table_data = ( + self.get_db(db_name) + .get_table(table_name) + .rename_index(old_index_name, new_index_name) + ) return self._replace_table(db_name, table_name, new_table_data) def list_indexes_in_table_in_db(self, db_name, table_name): @@ -290,37 +291,52 @@ def get_now_time(self): def objects_from_pods(data): dbs_by_name = {} - for db_name, db_data in iteritems(data['dbs']): + for db_name, db_data in iteritems(data["dbs"]): tables_by_name = {} - for table_name, table_data in iteritems(db_data['tables']): + for table_name, table_data in iteritems(db_data["tables"]): if isinstance(table_data, list): indexes = {} else: - indexes = table_data.get('indexes', {}) - table_data = table_data.get('rows', []) - tables_by_name[table_name] = MockTableData( - table_name, table_data, indexes - ) + indexes = table_data.get("indexes", {}) + table_data = table_data.get("rows", []) + tables_by_name[table_name] = MockTableData(table_name, table_data, indexes) dbs_by_name[db_name] = MockDbData(tables_by_name) - defaultDB = None - if 'default' in data: - defaultDB = data['default'] + default_db = None + if "default" in data: + default_db = data["default"] + + return MockDb(dbs_by_name, default_db) - return MockDb(dbs_by_name, defaultDB) def set_default_db(query, name): - if len(query._args) > 0: - if not (query._args[0].__class__ in RQL_TYPE_TRANSLATIONS and issubclass(RQL_TYPE_TRANSLATIONS[query._args[0].__class__], BinExp)): - query._args = [rethinkdb.ast.DB(name)] + query._args + NEEDS_DB_AST = [ + r_ast.TableListTL.term_type, + r_ast.TableList.term_type, + r_ast.TableCreate.term_type, + r_ast.TableDrop.term_type, + r_ast.Table.term_type, + ] + + if hasattr(query, "_args"): + for arg in query._args: + if isinstance(arg, r_ast.MakeArray): + for arr_arg in arg._args: + set_default_db(arr_arg, name) + + elif isinstance(arg, r_ast.MakeObj): + for obj_arg in arg.optargs.values(): + set_default_db(obj_arg, name) - else: - set_default_db(query._args[0], name) + else: + set_default_db(arg, name) + + if hasattr(query, "term_type") and query.term_type in NEEDS_DB_AST: + # We already have the DB + if len(query._args) != 2: + query._args = [rethinkdb.ast.DB(name)] + query._args - else: - if query.__class__ in RQL_TYPE_TRANSLATIONS and issubclass(RQL_TYPE_TRANSLATIONS[query.__class__], BinExp): - query._args = [rethinkdb.ast.DB(name)] class MockThinkConn(object): @@ -331,8 +347,8 @@ def reset_data(self, data): self.rethinkdb_mock_parent._modify_initial_data(data) def _start(self, rql_query, **global_optargs): - if self.rethinkdb_mock_parent.data.defaultDB: - set_default_db(rql_query, self.rethinkdb_mock_parent.data.defaultDB) + if self.rethinkdb_mock_parent.data.default_db: + set_default_db(rql_query, self.rethinkdb_mock_parent.data.default_db) return self.rethinkdb_mock_parent.run_query(rewrite_query(rql_query)) @@ -346,7 +362,7 @@ def close(self): class MockThink(object): def __init__(self, initial_data): self._modify_initial_data(initial_data) - self.tzinfo = rethinkdb.r.make_timezone('00:00') + self.tzinfo = rethinkdb.r.make_timezone("00:00") def _modify_initial_data(self, new_data): self.initial_data = new_data @@ -359,7 +375,7 @@ def run_query(self, query): # so it should have the same result each time within that query. # But we don't do anything if now_time has already been set. - if not hasattr(self, 'now_time'): + if not hasattr(self, "now_time"): temp_now_time = True self.now_time = self.get_now_time() @@ -376,7 +392,7 @@ def run_query(self, query): result = result.get_rows() if temp_now_time: - delattr(self, 'now_time') + delattr(self, "now_time") return result def pprint_query_ast(self, query): @@ -395,7 +411,7 @@ def set_now_time(self, dtime): self.now_time = dtime def get_now_time(self): - if hasattr(self, 'now_time'): + if hasattr(self, "now_time"): return self.now_time else: return rtime.now() diff --git a/rethinkdb_mock/joins.py b/rethinkdb_mock/joins.py index 4731532..99321bb 100644 --- a/rethinkdb_mock/joins.py +++ b/rethinkdb_mock/joins.py @@ -5,10 +5,10 @@ def do_outer_join(pred, left, right): out = [] for left_elem in left: matches = [] - result = {'left': left_elem} + result = {"left": left_elem} for right_elem in right: if pred(left_elem, right_elem): - matches.append(util.extend(result, {'right': right_elem})) + matches.append(util.extend(result, {"right": right_elem})) if not matches: matches.append(result) out = util.cat(out, matches) @@ -20,7 +20,7 @@ def do_inner_join(pred, left, right): for left_elem in left: for right_elem in right: if pred(left_elem, right_elem): - out.append({'left': left_elem, 'right': right_elem}) + out.append({"left": left_elem, "right": right_elem}) return out @@ -30,5 +30,5 @@ def do_eq_join(left_field, left, right_field, right): lval = util.getter(left_field)(elem) match = util.find_first(lambda d: util.getter(right_field)(d) == lval, right) if match: - out.append({'left': elem, 'right': match}) + out.append({"left": elem, "right": match}) return out diff --git a/rethinkdb_mock/rql_rewrite.py b/rethinkdb_mock/rql_rewrite.py index 491bcc0..a5bf1dd 100644 --- a/rethinkdb_mock/rql_rewrite.py +++ b/rethinkdb_mock/rql_rewrite.py @@ -12,7 +12,6 @@ def rewrite_query(query): RQL_TYPE_HANDLERS = {} -RQL_TYPE_TRANSLATIONS = {} def type_dispatch(rql_node): @@ -22,14 +21,15 @@ def type_dispatch(rql_node): @util.curry2 def handles_type(rql_type, func): def handler(node): - assert (type(node) == rql_type) + assert type(node) == rql_type return func(node) + RQL_TYPE_HANDLERS[rql_type] = handler return handler def process_optargs(node): - if hasattr(node, 'optargs') and node.optargs: + if hasattr(node, "optargs") and node.optargs: return {k: plain_val_of_datum(v) for k, v in iteritems(node.optargs)} return {} @@ -49,7 +49,7 @@ def handle_generic_binop(Mt_Constructor, node): return Mt_Constructor( type_dispatch(node._args[0]), type_dispatch(node._args[1]), - optargs=process_optargs(node) + optargs=process_optargs(node), ) @@ -62,14 +62,16 @@ def handle_generic_binop_poly_2(mt_type_map, node): return Mt_Constructor( type_dispatch(node._args[0]), type_dispatch(node._args[1]), - optargs=process_optargs(node) + optargs=process_optargs(node), ) @util.curry2 def handle_generic_ternop(Mt_Constructor, node): - assert (len(node._args) == 3) - return Mt_Constructor(*[type_dispatch(arg) for arg in node._args], optargs=process_optargs(node)) + assert len(node._args) == 3 + return Mt_Constructor( + *[type_dispatch(arg) for arg in node._args], optargs=process_optargs(node) + ) @util.curry2 @@ -77,19 +79,14 @@ def handle_generic_aggregation(mt_type_map, node): optargs = process_optargs(node) if len(node._args) == 1: Mt_Constructor = mt_type_map[1] - return Mt_Constructor( - type_dispatch(node._args[0]), - optargs=optargs - ) + return Mt_Constructor(type_dispatch(node._args[0]), optargs=optargs) else: for r_type, m_type in iteritems(mt_type_map[2]): if isinstance(node._args[1], r_type): Mt_Constructor = m_type break return Mt_Constructor( - type_dispatch(node._args[0]), - type_dispatch(node._args[1]), - optargs=optargs + type_dispatch(node._args[0]), type_dispatch(node._args[1]), optargs=optargs ) @@ -97,7 +94,7 @@ def handle_generic_aggregation(mt_type_map, node): 0: handle_generic_zerop, 1: handle_generic_monop, 2: handle_generic_binop, - 3: handle_generic_ternop + 3: handle_generic_ternop, } @@ -110,9 +107,17 @@ def handle_n_ary(arity_type_map, node): def makearray_of_datums(datum_list): out = [] for elem in datum_list: - expected_types = (r_ast.Datum, r_ast.Asc, r_ast.Desc, r_ast.Func, r_ast.MakeArray, r_ast.MakeObj) + expected_types = ( + r_ast.Datum, + r_ast.Asc, + r_ast.Desc, + r_ast.Func, + r_ast.MakeArray, + r_ast.MakeObj, + r_ast.Bracket, + ) if elem.__class__ not in expected_types: - raise TypeError(f'unexpected elem type: {elem}') + raise TypeError(f"unexpected elem type: {elem.__class__}") out.append(type_dispatch(elem)) return mt_ast.MakeArray(out) @@ -183,7 +188,7 @@ def binop_splat(Mt_Constructor, node): r_ast.Literal: mt_ast.Literal, r_ast.Distinct: mt_ast.Distinct, r_ast.ISO8601: mt_ast.ISO8601, - r_ast.Wait: mt_ast.Wait + r_ast.Wait: mt_ast.Wait, } # 2-ary reql terms which don't need any special handling @@ -207,7 +212,7 @@ def binop_splat(Mt_Constructor, node): r_ast.Get: mt_ast.Get, r_ast.Map: mt_ast.MapWithRFunc, r_ast.Replace: mt_ast.Replace, - r_ast.Merge: mt_ast.MergePoly, + r_ast.Merge: mt_ast.MergePolyWithRFunc, r_ast.Append: mt_ast.Append, r_ast.Prepend: mt_ast.Prepend, r_ast.Union: mt_ast.Union, @@ -223,7 +228,7 @@ def binop_splat(Mt_Constructor, node): r_ast.TableDrop: mt_ast.TableDrop, r_ast.Default: mt_ast.RDefault, r_ast.CoerceTo: mt_ast.CoerceTo, - r_ast.Limit: mt_ast.Limit + r_ast.Limit: mt_ast.Limit, } @@ -232,18 +237,15 @@ def binop_splat(Mt_Constructor, node): # at evaluation time, though we still need to branch on evaluate type of first argument # in many cases. BINOPS_BY_ARG_2_TYPE = { - r_ast.Group: { - r_ast.Datum: mt_ast.GroupByField, - r_ast.Func: mt_ast.GroupByFunc - }, + r_ast.Group: {r_ast.Datum: mt_ast.GroupByField, r_ast.Func: mt_ast.GroupByFunc}, r_ast.Filter: { r_ast.MakeObj: mt_ast.FilterWithObj, - r_ast.Func: mt_ast.FilterWithFunc + r_ast.Func: mt_ast.FilterWithFunc, }, r_ast.Update: { r_ast.MakeObj: mt_ast.UpdateWithObj, - r_ast.Func: mt_ast.UpdateByFunc - } + r_ast.Func: mt_ast.UpdateByFunc, + }, } # ReQL represents these as varargs functions, which can take an array as second arg or @@ -260,7 +262,7 @@ def binop_splat(Mt_Constructor, node): r_ast.HasFields: mt_ast.HasFields, r_ast.Without: mt_ast.WithoutPoly, r_ast.GetAll: mt_ast.GetAll, - r_ast.DeleteAt: mt_ast.DeleteAt + r_ast.DeleteAt: mt_ast.DeleteAt, } # 3-ary reql terms which don't need any special handling @@ -274,7 +276,7 @@ def binop_splat(Mt_Constructor, node): r_ast.Branch: mt_ast.Branch, r_ast.IndexRename: mt_ast.IndexRename, r_ast.Between: mt_ast.Between, - r_ast.During: mt_ast.During + r_ast.During: mt_ast.During, } # We can determine a lot about these functions' behavior based on arg count. @@ -284,89 +286,56 @@ def binop_splat(Mt_Constructor, node): r_ast.Split: { 1: mt_ast.StrSplitDefault, 2: mt_ast.StrSplitOn, - 3: mt_ast.StrSplitOnLimit + 3: mt_ast.StrSplitOnLimit, }, - r_ast.Random: { - 0: mt_ast.Random0, - 1: mt_ast.Random1, - 2: mt_ast.Random2 - }, - r_ast.IndexCreate: { - 2: mt_ast.IndexCreateByField, - 3: mt_ast.IndexCreateByFunc - }, - r_ast.IndexWait: { - 1: mt_ast.IndexWaitAll, - 2: mt_ast.IndexWaitOne - }, - r_ast.UserError: { - 0: mt_ast.RError0, - 1: mt_ast.RError1 - } + r_ast.Random: {0: mt_ast.Random0, 1: mt_ast.Random1, 2: mt_ast.Random2}, + r_ast.IndexCreate: {2: mt_ast.IndexCreateByField, 3: mt_ast.IndexCreateByFunc}, + r_ast.IndexWait: {1: mt_ast.IndexWaitAll, 2: mt_ast.IndexWaitOne}, + r_ast.UserError: {0: mt_ast.RError0, 1: mt_ast.RError1}, } NORMAL_AGGREGATIONS = { r_ast.Min: { 1: mt_ast.Min1, - 2: { - r_ast.Datum: mt_ast.MinByField, - r_ast.Func: mt_ast.MinByFunc - } + 2: {r_ast.Datum: mt_ast.MinByField, r_ast.Func: mt_ast.MinByFunc}, }, r_ast.Max: { 1: mt_ast.Max1, - 2: { - r_ast.Datum: mt_ast.MaxByField, - r_ast.Func: mt_ast.MaxByFunc - } + 2: {r_ast.Datum: mt_ast.MaxByField, r_ast.Func: mt_ast.MaxByFunc}, }, r_ast.Avg: { 1: mt_ast.Avg1, - 2: { - r_ast.Datum: mt_ast.AvgByField, - r_ast.Func: mt_ast.AvgByFunc - } + 2: {r_ast.Datum: mt_ast.AvgByField, r_ast.Func: mt_ast.AvgByFunc}, }, r_ast.Sum: { 1: mt_ast.Sum1, - 2: { - r_ast.Datum: mt_ast.SumByField, - r_ast.Func: mt_ast.SumByFunc - } - } + 2: {r_ast.Datum: mt_ast.SumByField, r_ast.Func: mt_ast.SumByFunc}, + }, } for r_type, mt_type in iteritems(NORMAL_ZEROPS): RQL_TYPE_HANDLERS[r_type] = handle_generic_zerop(mt_type) - RQL_TYPE_TRANSLATIONS[r_type] = mt_type for r_type, mt_type in iteritems(NORMAL_MONOPS): RQL_TYPE_HANDLERS[r_type] = handle_generic_monop(mt_type) - RQL_TYPE_TRANSLATIONS[r_type] = mt_type for r_type, mt_type in iteritems(NORMAL_BINOPS): RQL_TYPE_HANDLERS[r_type] = handle_generic_binop(mt_type) - RQL_TYPE_TRANSLATIONS[r_type] = mt_type for r_type, arg_2_map in iteritems(BINOPS_BY_ARG_2_TYPE): RQL_TYPE_HANDLERS[r_type] = handle_generic_binop_poly_2(arg_2_map) - RQL_TYPE_TRANSLATIONS[r_type] = mt_type for r_type, mt_type in iteritems(SPLATTED_BINOPS): RQL_TYPE_HANDLERS[r_type] = binop_splat(mt_type) - RQL_TYPE_TRANSLATIONS[r_type] = mt_type for r_type, mt_type in iteritems(NORMAL_TERNOPS): RQL_TYPE_HANDLERS[r_type] = handle_generic_ternop(mt_type) - RQL_TYPE_TRANSLATIONS[r_type] = mt_type for r_type, mt_type in iteritems(OPS_BY_ARITY): RQL_TYPE_HANDLERS[r_type] = handle_n_ary(mt_type) - RQL_TYPE_TRANSLATIONS[r_type] = mt_type for r_type, type_map in iteritems(NORMAL_AGGREGATIONS): RQL_TYPE_HANDLERS[r_type] = handle_generic_aggregation(type_map) - RQL_TYPE_TRANSLATIONS[r_type] = mt_type @handles_type(r_ast.Datum) @@ -379,7 +348,7 @@ def plain_val_of_datum(datum_node): def plain_list_of_make_array(make_array_instance): - assert (isinstance(make_array_instance, r_ast.MakeArray)) + assert isinstance(make_array_instance, r_ast.MakeArray) return list(map(plain_val_of_datum, make_array_instance._args)) @@ -413,7 +382,7 @@ def handle_order_by(node): right.append(mt_ast.Asc(type_dispatch(elem))) else: accepted = (r_ast.Desc, r_ast.Asc, r_ast.Func) - assert (elem.__class__ in accepted) + assert elem.__class__ in accepted right.append(type_dispatch(elem)) if optargs.get("index"): right.append(mt_ast.Asc(type_dispatch(r_ast.Datum(optargs["index"])))) @@ -430,13 +399,9 @@ def handle_offsets_of(node): left = type_dispatch(node._args[0]) right = type_dispatch(node._args[1]) if isinstance(node._args[1], r_ast.Func): - return mt_ast.OffsetsOfFunc( - left, right, optargs=optargs - ) + return mt_ast.OffsetsOfFunc(left, right, optargs=optargs) else: - return mt_ast.OffsetsOfValue( - left, right, optargs=optargs - ) + return mt_ast.OffsetsOfValue(left, right, optargs=optargs) @handles_type(r_ast.FunCall) @@ -474,30 +439,18 @@ def handle_count(node): left = type_dispatch(node._args[0]) if isinstance(left, mt_ast.GroupByField): - return mt_ast.CountGroup( - left, - optargs=optargs - ) + return mt_ast.CountGroup(left, optargs=optargs) elif len(node._args) == 1: - return mt_ast.Count1( - left, - optargs=optargs - ) + return mt_ast.Count1(left, optargs=optargs) else: right = type_dispatch(node._args[1]) - if is_instance_of_any((r_ast.MakeObj, r_ast.Datum, r_ast.MakeArray), node._args[1]): - return mt_ast.CountByEq( - left, - right, - optargs=optargs - ) + if is_instance_of_any( + (r_ast.MakeObj, r_ast.Datum, r_ast.MakeArray), node._args[1] + ): + return mt_ast.CountByEq(left, right, optargs=optargs) elif isinstance(node._args[1], r_ast.Func): - return mt_ast.CountByFunc( - left, - right, - optargs=optargs - ) + return mt_ast.CountByFunc(left, right, optargs=optargs) raise TypeError @@ -523,6 +476,7 @@ def handle_contains(node): # body, and replacing any ImplicitVar instances with Var(Datum(symbol)). # Once that's done, the `Func` can be evaluated in the same way as any other. + def contains_ivar(node): return r_ast._ivar_scan(node) diff --git a/rethinkdb_mock/rtime.py b/rethinkdb_mock/rtime.py index d768193..6c04f6c 100644 --- a/rethinkdb_mock/rtime.py +++ b/rethinkdb_mock/rtime.py @@ -17,18 +17,18 @@ def day_of_year(dt): def make_time(year, month, day, hour=0, minute=0, second=0, timezone=None): - timezone = timezone or rethinkdb.r.make_timezone('00:00') + timezone = timezone or rethinkdb.r.make_timezone("00:00") return datetime.datetime(year, month, day, hour, minute, second, tzinfo=timezone) def now(): dtime = datetime.datetime.now() - return dtime.replace(tzinfo=rethinkdb.r.make_timezone('00:00')) + return dtime.replace(tzinfo=rethinkdb.r.make_timezone("00:00")) def create_rql_timezone(timezone_string): - if timezone_string == 'Z': - return rethinkdb.r.make_timezone('00:00') + if timezone_string == "Z": + return rethinkdb.r.make_timezone("00:00") else: raise NotImplementedError diff --git a/rethinkdb_mock/scope.py b/rethinkdb_mock/scope.py index 3875db7..3d2a7c5 100644 --- a/rethinkdb_mock/scope.py +++ b/rethinkdb_mock/scope.py @@ -15,7 +15,7 @@ def get_sym(self, x): result = None if x in self.values: result = self.values[x] - elif hasattr(self, 'parent'): + elif hasattr(self, "parent"): result = self.parent.get_sym(x) if result is None: msg = f"symbol not defined: {x}" @@ -29,7 +29,7 @@ def push(self, vals): def get_flattened(self): vals = {k: v for k, v in list(self.values.items())} - if not hasattr(self, 'parent'): + if not hasattr(self, "parent"): return vals parent_vals = self.parent.get_flattened() parent_vals.update(vals) diff --git a/rethinkdb_mock/util.py b/rethinkdb_mock/util.py index 127c3cb..9b42125 100644 --- a/rethinkdb_mock/util.py +++ b/rethinkdb_mock/util.py @@ -11,7 +11,9 @@ def out(x, *args): def out2(y): return func(x, y) + return out2 + return out @@ -23,6 +25,7 @@ def out(x, *args): return func(x, *args) else: return curry2(lambda a, b: func(x, a, b))(args[0]) + return out @@ -209,6 +212,7 @@ def out(x): for f in funcs: result = f(result) return result + return out @@ -232,24 +236,30 @@ def pluck_extended(query: dict, data, path=None): # If query is a list, do a recursive search if isinstance(query, list): return { - k: v for subresult in [pluck_extended(subquery, data, path) for subquery in query] for k, v in subresult.items() + k: v + for subresult in [ + pluck_extended(subquery, data, path) for subquery in query + ] + for k, v in subresult.items() } # If query is a dict, do a recursive search continuing down this path if isinstance(query, dict): return { - subkey: pluck_extended(subquery, data, path + [subkey]) for subkey, subquery in query.items() + subkey: pluck_extended(subquery, data, path + [subkey]) + for subkey, subquery in query.items() } def pluck_with(attrs): def inner_pluck(thing): return pluck_extended(attrs, thing) + return inner_pluck def get_by_id(id): - return find_first(match_attr('id', id)) + return find_first(match_attr("id", id)) def as_obj(pairs): @@ -270,7 +280,7 @@ def obj_clone(a_dict): def is_iterable(x): - return hasattr(x, '__iter__') + return hasattr(x, "__iter__") @curry2 @@ -355,11 +365,9 @@ def rql_str_split(string, split_on, limit=-1): def sort_by_one(sort_key, sequence, reverse=False): out = clone_array(sequence) - kwargs = { - 'key': lambda doc: getter(sort_key, doc) - } + kwargs = {"key": lambda doc: getter(sort_key, doc)} if reverse: - kwargs['reverse'] = True + kwargs["reverse"] = True out.sort(**kwargs) return out @@ -371,7 +379,9 @@ def sort_by_many(keys_and_dirs, sequence): # this probably isn't all that efficient, but # we can figure that out later. key_for_pass = keys_and_dirs[0] - current_pass = sort_by_one(key_for_pass[0], sequence, reverse=(key_for_pass[1] == 'DESC')) + current_pass = sort_by_one( + key_for_pass[0], sequence, reverse=(key_for_pass[1] == "DESC") + ) if len(keys_and_dirs) == 1: return current_pass else: @@ -381,6 +391,7 @@ def sort_by_many(keys_and_dirs, sequence): def handle_chunk(): result.extend(sort_by_many(keys_and_dirs[1:], chunk)) + for elem in current_pass: next_key = getter(key_for_pass[0], elem) if next_key != current_key: @@ -448,7 +459,7 @@ def add(self, elem): super(DictableSet, self).add(elem) def has(self, elem): - return (make_hashable(elem) in self) + return make_hashable(elem) in self def dictable_distinct(sequence): diff --git a/setup.py b/setup.py index ac08315..a9f3099 100644 --- a/setup.py +++ b/setup.py @@ -8,9 +8,9 @@ url="https://github.com/Inveracity/rethinkdb-mock", maintainer="Christopher Baklid", maintainer_email="cbaklid@gmail.com", - packages=['rethinkdb_mock'], - package_dir={'rethinkdb_mock': 'rethinkdb_mock'}, - install_requires=['rethinkdb>=2.4.8', 'python-dateutil', 'future'], + packages=["rethinkdb_mock"], + package_dir={"rethinkdb_mock": "rethinkdb_mock"}, + install_requires=["rethinkdb>=2.4.8", "python-dateutil", "future"], classifiers=[ "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", @@ -22,7 +22,7 @@ "Topic :: Database", "Topic :: Software Development :: Testing :: Mocking", ], - python_requires='>=3.8', - long_description=open('README.md').read(), - long_description_content_type='text/markdown', + python_requires=">=3.8", + long_description=open("README.md").read(), + long_description_content_type="text/markdown", ) diff --git a/tests/common.py b/tests/common.py index a10edcb..6631db1 100644 --- a/tests/common.py +++ b/tests/common.py @@ -13,9 +13,9 @@ def real_stock_data_load(data, connection): # This db is special and can't be deleted. continue r.db_drop(db).run(connection) - for db_name, db_data in iteritems(data['dbs']): + for db_name, db_data in iteritems(data["dbs"]): r.db_create(db_name).run(connection) - for table_name, table_data in iteritems(db_data['tables']): + for table_name, table_data in iteritems(db_data["tables"]): r.db(db_name).table_create(table_name).run(connection) r.db(db_name).table(table_name).insert(table_data).run(connection) @@ -31,29 +31,21 @@ def load_stock_data(data, connection): return real_stock_data_load(data, connection) -def assertEqUnordered(x, y, msg=''): +def assertEqUnordered(x, y, msg=""): for x_elem in x: assert x_elem in y -def assertEqual(x, y, msg=''): +def assertEqual(x, y, msg=""): assert x == y def as_db_and_table(db_name, table_name, data): - return { - 'dbs': { - db_name: { - 'tables': { - table_name: data - } - } - } - } + return {"dbs": {db_name: {"tables": {table_name: data}}}} class TestCase(unittest.TestCase): - def assertEqUnordered(self, x, y, msg=''): + def assertEqUnordered(self, x, y, msg=""): return assertEqUnordered(x, y, msg) def assert_key_equality(self, keys, dict1, dict2): diff --git a/tests/conftest.py b/tests/conftest.py index ef2671f..88bf046 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -19,7 +19,8 @@ def pytest_addoption(parser): default="rethinkdb_mock", action="store", choices=["rethinkdb_mock", "rethink"], - help="Select whether tests are run on a rethinkdb_mock connection or rethink connection or both") + help="Select whether tests are run on a rethinkdb_mock connection or rethink connection or both", + ) @pytest.fixture(scope="session") @@ -35,7 +36,7 @@ def conn_sess(request): except OSError: pytest.exit("No rethinkdb binary found") elif conn_type == "rethinkdb_mock": - conn = MockThink(as_db_and_table('nothing', 'nothing', [])).get_conn() + conn = MockThink(as_db_and_table("nothing", "nothing", [])).get_conn() else: pytest.exit(f"Unknown rethinkdb_mock test connection type: {conn_type}") return conn diff --git a/tests/fixtures.py b/tests/fixtures.py index 2961e6e..24425e7 100644 --- a/tests/fixtures.py +++ b/tests/fixtures.py @@ -38,8 +38,8 @@ def _rethink_server(request): - """ This does the actual work - there are several versions of this used - with different scopes. + """This does the actual work - there are several versions of this used + with different scopes. """ test_server = RethinkDBServer() request.addfinalizer(lambda p=test_server: p.teardown()) @@ -47,32 +47,31 @@ def _rethink_server(request): return test_server -@pytest.fixture(scope='function') -@requires_config(CONFIG, ['rethink_executable']) +@pytest.fixture(scope="function") +@requires_config(CONFIG, ["rethink_executable"]) def rethink_server(request): - """ Function-scoped RethinkDB server in a local thread. + """Function-scoped RethinkDB server in a local thread. - Attributes - ---------- - conn: (``rethinkdb.Connection``) Connection to this server instance - .. also inherits all attributes from the `workspace` fixture + Attributes + ---------- + conn: (``rethinkdb.Connection``) Connection to this server instance + .. also inherits all attributes from the `workspace` fixture """ return _rethink_server(request) -@pytest.fixture(scope='session') -@requires_config(CONFIG, ['rethink_executable']) +@pytest.fixture(scope="session") +@requires_config(CONFIG, ["rethink_executable"]) def rethink_server_sess(request): - """ Same as rethink_server fixture, scoped as session instead. - """ + """Same as rethink_server fixture, scoped as session instead.""" return _rethink_server(request) @pytest.fixture(scope="function") def rethink_unique_db(rethink_server_sess): - """ Starts up a session-scoped server, and returns a connection to - a unique database for the life of a single test, and drops it after + """Starts up a session-scoped server, and returns a connection to + a unique database for the life of a single test, and drops it after """ dbid = uuid.uuid4().hex conn = rethink_server_sess.conn @@ -84,9 +83,9 @@ def rethink_unique_db(rethink_server_sess): @pytest.fixture(scope="module") def rethink_module_db(rethink_server_sess): - """ Starts up a module-scoped server, and returns a connection to - a unique database for all the tests in one module. - Drops the database after module tests are complete. + """Starts up a module-scoped server, and returns a connection to + a unique database for all the tests in one module. + Drops the database after module tests are complete. """ dbid = uuid.uuid4().hex conn = rethink_server_sess.conn @@ -100,16 +99,19 @@ def rethink_module_db(rethink_server_sess): @pytest.fixture(scope="module") def rethink_make_tables(request, rethink_module_db): - """ Module-scoped fixture that creates all tables specified in the test - module attribute FIXTURE_TABLES. + """Module-scoped fixture that creates all tables specified in the test + module attribute FIXTURE_TABLES. """ - reqd_table_list = getattr(request.module, 'FIXTURE_TABLES') + reqd_table_list = getattr(request.module, "FIXTURE_TABLES") log.debug("Do stuff before all module tests with {0}".format(reqd_table_list)) conn = rethink_module_db for table_name, primary_key in reqd_table_list: try: - r.db(conn.db).table_create(table_name, primary_key=primary_key,).run(conn) + r.db(conn.db).table_create( + table_name, + primary_key=primary_key, + ).run(conn) log.info('Made table "{0}" with key "{1}"'.format(table_name, primary_key)) except rethinkdb.errors.RqlRuntimeError as err: log.debug('Table "{0}" not made: {1}'.format(table_name, err.message)) @@ -117,14 +119,14 @@ def rethink_make_tables(request, rethink_module_db): @pytest.fixture(scope="function") def rethink_empty_db(request, rethink_module_db, rethink_make_tables): - """ Function-scoped fixture that will empty all the tables defined - for the `rethink_make_tables` fixture. + """Function-scoped fixture that will empty all the tables defined + for the `rethink_make_tables` fixture. - This is a useful approach, because of the long time taken to - create a new RethinkDB table, compared to the time to empty one. + This is a useful approach, because of the long time taken to + create a new RethinkDB table, compared to the time to empty one. """ tables_to_emptied = ( - table[0] for table in getattr(request.module, 'FIXTURE_TABLES') + table[0] for table in getattr(request.module, "FIXTURE_TABLES") ) conn = rethink_module_db @@ -160,14 +162,18 @@ def cmd_local(self): def get_args(self, **kwargs): cmd = [ - '--bind', self._listen_hostname, - '--driver-port', str(self.port), - '--http-port', str(self.http_port), - '--cluster-port', str(self.cluster_port), + "--bind", + self._listen_hostname, + "--driver-port", + str(self.port), + "--http-port", + str(self.http_port), + "--cluster-port", + str(self.cluster_port), ] - if 'workspace' in kwargs: - cmd += ['--directory', str(kwargs['workspace'] / 'db')] + if "workspace" in kwargs: + cmd += ["--directory", str(kwargs["workspace"] / "db")] return cmd @@ -189,14 +195,13 @@ def http_port(self): def check_server_up(self): """Test connection to the server.""" - log.info("Connecting to RethinkDB at {0}:{1}".format( - self.hostname, self.port)) + log.info("Connecting to RethinkDB at {0}:{1}".format(self.hostname, self.port)) if not self.hostname: return False try: - self.conn = r.connect(host=self.hostname, port=self.port, db='test') + self.conn = r.connect(host=self.hostname, port=self.port, db="test") return True except rethinkdb.errors.RqlDriverError as err: log.warning(err) diff --git a/tests/functional/common.py b/tests/functional/common.py index bb09274..8426eeb 100644 --- a/tests/functional/common.py +++ b/tests/functional/common.py @@ -1,10 +1,4 @@ class MockTest(object): @staticmethod def get_data(): - return { - 'dbs': { - 'default': { - 'tables': {} - } - } - } + return {"dbs": {"default": {"tables": {}}}} diff --git a/tests/functional/test_aggregation.py b/tests/functional/test_aggregation.py index 0440e75..91d20b5 100644 --- a/tests/functional/test_aggregation.py +++ b/tests/functional/test_aggregation.py @@ -8,71 +8,65 @@ class TestMax(MockTest): @staticmethod def get_data(): data = [ + {"id": "joe", "age": 26, "hobbies": ["sand", "water", "cats"]}, + {"id": "bill", "age": 52, "hobbies": ["watermelon"]}, { - 'id': 'joe', - 'age': 26, - 'hobbies': ['sand', 'water', 'cats'] + "id": "todd", + "age": 35, + "hobbies": ["citrus"], + "nums": [100, 550, 40, 900, 800, 36], + "nums2": [ + {"val": 26}, + {"val": 78}, + {"val": 19}, + {"val": 110}, + {"val": 82}, + ], }, - { - 'id': 'bill', - 'age': 52, - 'hobbies': ['watermelon'] - }, - { - 'id': 'todd', - 'age': 35, - 'hobbies': ['citrus'], - 'nums': [100, 550, 40, 900, 800, 36], - 'nums2': [ - {'val': 26}, - {'val': 78}, - {'val': 19}, - {'val': 110}, - {'val': 82} - ] - } ] - return as_db_and_table('x', 'people', data) + return as_db_and_table("x", "people", data) def test_max_of_table_field(self, conn): - expected = {'id': 'bill', 'age': 52, 'hobbies': ['watermelon']} - result = r.db('x').table('people').max('age').run(conn) + expected = {"id": "bill", "age": 52, "hobbies": ["watermelon"]} + result = r.db("x").table("people").max("age").run(conn) assertEqual(expected, result) def test_max_of_sequence_field(self, conn): - expected = [{'val': 110}] - result = r.db('x').table('people').filter({ - 'id': 'todd' - }).map( - lambda doc: doc['nums2'].max('val') - ).run(conn) + expected = [{"val": 110}] + result = ( + r.db("x") + .table("people") + .filter({"id": "todd"}) + .map(lambda doc: doc["nums2"].max("val")) + .run(conn) + ) assertEqual(expected, list(result)) def test_max_of_table_func(self, conn): - expected = {'id': 'bill', 'age': 52, 'hobbies': ['watermelon']} - result = r.db('x').table('people').max( - lambda d: d['age'] - ).run(conn) + expected = {"id": "bill", "age": 52, "hobbies": ["watermelon"]} + result = r.db("x").table("people").max(lambda d: d["age"]).run(conn) assertEqual(expected, result) def test_max_of_sequence_func(self, conn): - expected = [{'val': 110}] - result = r.db('x').table('people').filter({ - 'id': 'todd' - }).map( - lambda doc: doc['nums2'].max( - lambda num: num['val'] - ) - ).run(conn) + expected = [{"val": 110}] + result = ( + r.db("x") + .table("people") + .filter({"id": "todd"}) + .map(lambda doc: doc["nums2"].max(lambda num: num["val"])) + .run(conn) + ) assertEqual(expected, list(result)) def test_max_of_left_seq_no_args(self, conn): expected = [900] - result = r.db('x').table('people').filter( - lambda doc: doc['id'] == 'todd' - ).map( - lambda doc: doc['nums'].max() - ).run(conn) + result = ( + r.db("x") + .table("people") + .filter(lambda doc: doc["id"] == "todd") + .map(lambda doc: doc["nums"].max()) + .run(conn) + ) assertEqual(expected, list(result)) @@ -80,69 +74,59 @@ class TestMin(MockTest): @staticmethod def get_data(): data = [ + {"id": "joe", "age": 26, "hobbies": ["sand", "water", "cats"]}, + {"id": "bill", "age": 52, "hobbies": ["watermelon"]}, { - 'id': 'joe', - 'age': 26, - 'hobbies': ['sand', 'water', 'cats'] - }, - { - 'id': 'bill', - 'age': 52, - 'hobbies': ['watermelon'] + "id": "todd", + "age": 35, + "hobbies": ["citrus"], + "nums": [100, 550, 40, 900, 800], + "nums2": [{"val": 26}, {"val": 17}, {"val": 86}], }, - { - 'id': 'todd', - 'age': 35, - 'hobbies': ['citrus'], - 'nums': [100, 550, 40, 900, 800], - 'nums2': [ - {'val': 26}, - {'val': 17}, - {'val': 86} - ] - } ] - return as_db_and_table('x', 'people', data) + return as_db_and_table("x", "people", data) def test_min_of_table_field(self, conn): - expected = {'id': 'joe', 'age': 26, 'hobbies': ['sand', 'water', 'cats']} - result = r.db('x').table('people').min('age').run(conn) + expected = {"id": "joe", "age": 26, "hobbies": ["sand", "water", "cats"]} + result = r.db("x").table("people").min("age").run(conn) assertEqual(expected, result) def test_min_of_sequence_field(self, conn): - expected = [{'val': 17}] - result = r.db('x').table('people').filter({ - 'id': 'todd' - }).map( - lambda doc: doc['nums2'].min('val') - ).run(conn) + expected = [{"val": 17}] + result = ( + r.db("x") + .table("people") + .filter({"id": "todd"}) + .map(lambda doc: doc["nums2"].min("val")) + .run(conn) + ) assertEqual(expected, list(result)) def test_min_of_table_func(self, conn): - expected = {'id': 'joe', 'age': 26, 'hobbies': ['sand', 'water', 'cats']} - result = r.db('x').table('people').min( - lambda doc: doc['age'] - ).run(conn) + expected = {"id": "joe", "age": 26, "hobbies": ["sand", "water", "cats"]} + result = r.db("x").table("people").min(lambda doc: doc["age"]).run(conn) assertEqual(expected, result) def test_min_of_sequence_func(self, conn): - expected = [{'val': 17}] - result = r.db('x').table('people').filter({ - 'id': 'todd' - }).map( - lambda doc: doc['nums2'].min( - lambda num: num['val'] - ) - ).run(conn) + expected = [{"val": 17}] + result = ( + r.db("x") + .table("people") + .filter({"id": "todd"}) + .map(lambda doc: doc["nums2"].min(lambda num: num["val"])) + .run(conn) + ) assertEqual(expected, list(result)) def test_min_of_left_seq_no_args(self, conn): expected = [40] - result = r.db('x').table('people').filter( - lambda doc: doc['id'] == 'todd' - ).map( - lambda doc: doc['nums'].min() - ).run(conn) + result = ( + r.db("x") + .table("people") + .filter(lambda doc: doc["id"] == "todd") + .map(lambda doc: doc["nums"].min()) + .run(conn) + ) assertEqual(expected, list(result)) @@ -150,68 +134,59 @@ class TestSum(MockTest): @staticmethod def get_data(): data = [ + {"id": "joe", "age": 26, "hobbies": ["sand", "water", "cats"]}, + {"id": "bill", "age": 52, "hobbies": ["watermelon"]}, { - 'id': 'joe', - 'age': 26, - 'hobbies': ['sand', 'water', 'cats'] - }, - { - 'id': 'bill', - 'age': 52, - 'hobbies': ['watermelon'] + "id": "todd", + "age": 35, + "hobbies": ["citrus"], + "nums": [100, 50, 400, 9], + "nums2": [{"val": 40}, {"val": 53}], }, - { - 'id': 'todd', - 'age': 35, - 'hobbies': ['citrus'], - 'nums': [100, 50, 400, 9], - 'nums2': [ - {'val': 40}, - {'val': 53} - ] - } ] - return as_db_and_table('x', 'people', data) + return as_db_and_table("x", "people", data) def test_sum_of_table_field(self, conn): expected = 113 - result = r.db('x').table('people').sum('age').run(conn) + result = r.db("x").table("people").sum("age").run(conn) assertEqual(expected, result) def test_sum_of_seq_field(self, conn): expected = [93] - result = r.db('x').table('people').filter({ - 'id': 'todd' - }).map( - lambda doc: doc['nums2'].sum('val') - ).run(conn) + result = ( + r.db("x") + .table("people") + .filter({"id": "todd"}) + .map(lambda doc: doc["nums2"].sum("val")) + .run(conn) + ) assertEqual(expected, list(result)) def test_sum_of_table_func(self, conn): expected = 113 - result = r.db('x').table('people').sum( - lambda doc: doc['age'] - ).run(conn) + result = r.db("x").table("people").sum(lambda doc: doc["age"]).run(conn) assertEqual(expected, result) def test_sum_of_seq_func(self, conn): expected = [93] - result = r.db('x').table('people').filter({ - 'id': 'todd' - }).map( - lambda doc: doc['nums2'].sum( - lambda num: num['val'] - ) - ).run(conn) + result = ( + r.db("x") + .table("people") + .filter({"id": "todd"}) + .map(lambda doc: doc["nums2"].sum(lambda num: num["val"])) + .run(conn) + ) assertEqual(expected, list(result)) def test_sum_of_seq_no_args(self, conn): expected = [559] - result = r.db('x').table('people').filter( - lambda doc: doc['id'] == 'todd' - ).map( - lambda doc: doc['nums'].sum() - ).run(conn) + result = ( + r.db("x") + .table("people") + .filter(lambda doc: doc["id"] == "todd") + .map(lambda doc: doc["nums"].sum()) + .run(conn) + ) assertEqual(expected, list(result)) @@ -219,68 +194,59 @@ class TestAverage(MockTest): @staticmethod def get_data(): data = [ + {"id": "joe", "age": 43, "hobbies": ["sand", "water", "cats"]}, + {"id": "bill", "age": 48, "hobbies": ["watermelon"]}, { - 'id': 'joe', - 'age': 43, - 'hobbies': ['sand', 'water', 'cats'] - }, - { - 'id': 'bill', - 'age': 48, - 'hobbies': ['watermelon'] + "id": "todd", + "age": 29, + "hobbies": ["citrus"], + "nums": [76, 40, 100, 800], + "nums2": [{"val": 10}, {"val": 20}], }, - { - 'id': 'todd', - 'age': 29, - 'hobbies': ['citrus'], - 'nums': [76, 40, 100, 800], - 'nums2': [ - {'val': 10}, - {'val': 20} - ] - } ] - return as_db_and_table('x', 'people', data) + return as_db_and_table("x", "people", data) def test_avg_of_table_field(self, conn): expected = 40 - result = r.db('x').table('people').avg('age').run(conn) + result = r.db("x").table("people").avg("age").run(conn) assertEqual(expected, result) def test_avg_of_sequence_field(self, conn): expected = [15] - result = r.db('x').table('people').filter( - {'id': 'todd'} - ).map( - lambda doc: doc['nums2'].avg('val') - ).run(conn) + result = ( + r.db("x") + .table("people") + .filter({"id": "todd"}) + .map(lambda doc: doc["nums2"].avg("val")) + .run(conn) + ) assertEqual(expected, list(result)) def test_avg_of_table_func(self, conn): expected = 40 - result = r.db('x').table('people').avg( - lambda doc: doc['age'] - ).run(conn) + result = r.db("x").table("people").avg(lambda doc: doc["age"]).run(conn) assertEqual(expected, result) def test_avg_of_sequence_func(self, conn): expected = [15] - result = r.db('x').table('people').filter( - {'id': 'todd'} - ).map( - lambda doc: doc['nums2'].avg( - lambda num: num['val'] - ) - ).run(conn) + result = ( + r.db("x") + .table("people") + .filter({"id": "todd"}) + .map(lambda doc: doc["nums2"].avg(lambda num: num["val"])) + .run(conn) + ) assertEqual(expected, list(result)) def test_avg_of_left_seq_no_args(self, conn): expected = [254] - result = r.db('x').table('people').filter( - lambda doc: doc['id'] == 'todd' - ).map( - lambda doc: doc['nums'].avg() - ).run(conn) + result = ( + r.db("x") + .table("people") + .filter(lambda doc: doc["id"] == "todd") + .map(lambda doc: doc["nums"].avg()) + .run(conn) + ) assertEqual(expected, list(result)) @@ -288,71 +254,66 @@ class TestCount(MockTest): @staticmethod def get_data(): data = [ + {"id": "joe", "age": 43, "hobbies": ["sand", "water", "cats"]}, + {"id": "bill", "age": 48, "hobbies": ["watermelon"]}, { - 'id': 'joe', - 'age': 43, - 'hobbies': ['sand', 'water', 'cats'] + "id": "todd", + "age": 29, + "hobbies": ["citrus"], + "nums": [40, 67, 40, 800, 900], }, - { - 'id': 'bill', - 'age': 48, - 'hobbies': ['watermelon'] - }, - { - 'id': 'todd', - 'age': 29, - 'hobbies': ['citrus'], - 'nums': [40, 67, 40, 800, 900] - } ] - return as_db_and_table('x', 'people', data) + return as_db_and_table("x", "people", data) def test_table_count(self, conn): expected = 3 - result = r.db('x').table('people').count().run(conn) + result = r.db("x").table("people").count().run(conn) assertEqual(expected, result) def test_sequence_count(self, conn): expected = [5] - result = r.db('x').table('people').filter( - {'id': 'todd'} - ).map( - lambda doc: doc['nums'].count() - ).run(conn) + result = ( + r.db("x") + .table("people") + .filter({"id": "todd"}) + .map(lambda doc: doc["nums"].count()) + .run(conn) + ) assertEqual(expected, list(result)) def test_table_eq_elem_count(self, conn): expected = 1 - result = r.db('x').table('people').count({ - 'id': 'bill', - 'age': 48, - 'hobbies': ['watermelon'] - }).run(conn) + result = ( + r.db("x") + .table("people") + .count({"id": "bill", "age": 48, "hobbies": ["watermelon"]}) + .run(conn) + ) assertEqual(expected, result) def test_sequence_eq_elem_count(self, conn): expected = [2] - result = r.db('x').table('people').filter( - {'id': 'todd'} - ).map( - lambda doc: doc['nums'].count(40) - ).run(conn) + result = ( + r.db("x") + .table("people") + .filter({"id": "todd"}) + .map(lambda doc: doc["nums"].count(40)) + .run(conn) + ) assertEqual(expected, list(result)) def test_table_func_count(self, conn): expected = 2 - result = r.db('x').table('people').count( - lambda doc: doc['age'] > 40 - ).run(conn) + result = r.db("x").table("people").count(lambda doc: doc["age"] > 40).run(conn) assertEqual(expected, result) def test_sequence_func_count(self, conn): expected = [3] - result = r.db('x').table('people').filter( - {'id': 'todd'} - ).map( - lambda doc: doc['nums'].count( - lambda num: num > 40 - ) - ).run(conn) + result = ( + r.db("x") + .table("people") + .filter({"id": "todd"}) + .map(lambda doc: doc["nums"].count(lambda num: num > 40)) + .run(conn) + ) assertEqual(expected, list(result)) diff --git a/tests/functional/test_array_manip.py b/tests/functional/test_array_manip.py index 2b30912..72a37c9 100644 --- a/tests/functional/test_array_manip.py +++ b/tests/functional/test_array_manip.py @@ -9,70 +9,61 @@ class TestArrayManip(MockTest): @staticmethod def get_data(): - data = [ - {'id': 1, 'animals': ['frog', 'cow']}, - {'id': 2, 'animals': ['horse']} - ] - return as_db_and_table('x', 'farms', data) + data = [{"id": 1, "animals": ["frog", "cow"]}, {"id": 2, "animals": ["horse"]}] + return as_db_and_table("x", "farms", data) def test_insert_at(self, conn): - expected = [ - ['frog', 'pig', 'cow'], - ['horse', 'pig'] - ] - result = r.db('x').table('farms').map( - lambda d: d['animals'].insert_at(1, 'pig') - ).run(conn) + expected = [["frog", "pig", "cow"], ["horse", "pig"]] + result = ( + r.db("x") + .table("farms") + .map(lambda d: d["animals"].insert_at(1, "pig")) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_splice_at(self, conn): - expected = [ - ['frog', 'pig', 'chicken', 'cow'], - ['horse', 'pig', 'chicken'] - ] - result = r.db('x').table('farms').map( - lambda d: d['animals'].splice_at(1, ['pig', 'chicken']) - ).run(conn) + expected = [["frog", "pig", "chicken", "cow"], ["horse", "pig", "chicken"]] + result = ( + r.db("x") + .table("farms") + .map(lambda d: d["animals"].splice_at(1, ["pig", "chicken"])) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_prepend(self, conn): - expected = [ - ['pig', 'frog', 'cow'], - ['pig', 'horse'] - ] - result = r.db('x').table('farms').map( - lambda d: d['animals'].prepend('pig') - ).run(conn) + expected = [["pig", "frog", "cow"], ["pig", "horse"]] + result = ( + r.db("x") + .table("farms") + .map(lambda d: d["animals"].prepend("pig")) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_append(self, conn): - expected = [ - ['frog', 'cow', 'pig'], - ['horse', 'pig'] - ] - result = r.db('x').table('farms').map( - lambda d: d['animals'].append('pig') - ).run(conn) + expected = [["frog", "cow", "pig"], ["horse", "pig"]] + result = ( + r.db("x").table("farms").map(lambda d: d["animals"].append("pig")).run(conn) + ) assertEqUnordered(expected, list(result)) def test_change_at(self, conn): - expected = [ - ['wombat', 'cow'], - ['wombat'] - ] - result = r.db('x').table('farms').map( - lambda d: d['animals'].change_at(0, 'wombat') - ).run(conn) + expected = [["wombat", "cow"], ["wombat"]] + result = ( + r.db("x") + .table("farms") + .map(lambda d: d["animals"].change_at(0, "wombat")) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_delete_at(self, conn): - expected = [ - ['cow'], - [] - ] - result = r.db('x').table('farms').map( - lambda d: d['animals'].delete_at(0) - ).run(conn) + expected = [["cow"], []] + result = ( + r.db("x").table("farms").map(lambda d: d["animals"].delete_at(0)).run(conn) + ) res = list(result) assertEqUnordered(expected, res) @@ -80,36 +71,20 @@ def test_delete_at(self, conn): class TestUnion(MockTest): @staticmethod def get_data(): - things_1 = [ - {'id': 'thing1-1'}, - {'id': 'thing1-2'} - ] - things_2 = [ - {'id': 'thing2-1'}, - {'id': 'thing2-2'} - ] - return { - 'dbs': { - 'x': { - 'tables': { - 'things_1': things_1, - 'things_2': things_2 - } - } - } - - } + things_1 = [{"id": "thing1-1"}, {"id": "thing1-2"}] + things_2 = [{"id": "thing2-1"}, {"id": "thing2-2"}] + return {"dbs": {"x": {"tables": {"things_1": things_1, "things_2": things_2}}}} def test_table_union(self, conn): expected = [ - {'id': 'thing1-1'}, - {'id': 'thing1-2'}, - {'id': 'thing2-1'}, - {'id': 'thing2-2'} + {"id": "thing1-1"}, + {"id": "thing1-2"}, + {"id": "thing2-1"}, + {"id": "thing2-2"}, ] - result = r.db('x').table('things_1').union( - r.db('x').table('things_2') - ).run(conn) + result = ( + r.db("x").table("things_1").union(r.db("x").table("things_2")).run(conn) + ) assertEqUnordered(expected, list(result)) @@ -117,51 +92,43 @@ class TestIndexesOf(MockTest): @staticmethod def get_data(): things = [ - {'id': 'one', 'letters': ['c', 'c']}, - {'id': 'two', 'letters': ['a', 'b', 'a', ['q', 'q'], 'b']}, - {'id': 'three', 'letters': ['b', 'a', 'b', 'a']}, - {'id': 'four', 'letters': ['c', 'a', 'b', 'a', ['q', 'q']]} + {"id": "one", "letters": ["c", "c"]}, + {"id": "two", "letters": ["a", "b", "a", ["q", "q"], "b"]}, + {"id": "three", "letters": ["b", "a", "b", "a"]}, + {"id": "four", "letters": ["c", "a", "b", "a", ["q", "q"]]}, ] - return as_db_and_table('scrumptious', 'cake', things) + return as_db_and_table("scrumptious", "cake", things) def test_offsets_of_val(self, conn): - expected = [ - [], - [1, 4], - [0, 2], - [2] - ] - result = r.db('scrumptious').table('cake').map( - lambda doc: doc['letters'].offsets_of('b') - ).run(conn) + expected = [[], [1, 4], [0, 2], [2]] + result = ( + r.db("scrumptious") + .table("cake") + .map(lambda doc: doc["letters"].offsets_of("b")) + .run(conn) + ) result = list(result) pprint(result) assertEqUnordered(expected, result) def test_offsets_of_array_val(self, conn): - expected = [ - [], - [3], - [], - [4] - ] - result = r.db('scrumptious').table('cake').map( - lambda doc: doc['letters'].offsets_of(['q', 'q']) - ).run(conn) + expected = [[], [3], [], [4]] + result = ( + r.db("scrumptious") + .table("cake") + .map(lambda doc: doc["letters"].offsets_of(["q", "q"])) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_offsets_of_func(self, conn): - expected = [ - [], - [1, 4], - [0, 2], - [2] - ] - result = r.db('scrumptious').table('cake').map( - lambda doc: doc['letters'].offsets_of( - lambda letter: letter == 'b' - ) - ).run(conn) + expected = [[], [1, 4], [0, 2], [2]] + result = ( + r.db("scrumptious") + .table("cake") + .map(lambda doc: doc["letters"].offsets_of(lambda letter: letter == "b")) + .run(conn) + ) assertEqUnordered(expected, list(result)) @@ -169,32 +136,34 @@ class TestSample(MockTest): @staticmethod def get_data(): data = [ - {'id': 'one', 'data': list(range(10, 20))}, - {'id': 'two', 'data': list(range(20, 30))}, - {'id': 'three', 'data': list(range(30, 40))} + {"id": "one", "data": list(range(10, 20))}, + {"id": "two", "data": list(range(20, 30))}, + {"id": "three", "data": list(range(30, 40))}, ] - return as_db_and_table('db', 'things', data) + return as_db_and_table("db", "things", data) def test_nested(self, conn): - result = r.db('db').table('things').filter( - {'id': 'one'} - ).map( - lambda doc: doc['data'].sample(3) - ).run(conn) + result = ( + r.db("db") + .table("things") + .filter({"id": "one"}) + .map(lambda doc: doc["data"].sample(3)) + .run(conn) + ) result = list(result) - assert (len(result) == 1) + assert len(result) == 1 result = result[0] - assert (len(result) == 3) + assert len(result) == 3 for num in result: - assert (num <= 20) - assert (num >= 10) + assert num <= 20 + assert num >= 10 def test_docs(self, conn): - result = r.db('db').table('things').sample(2).run(conn) + result = r.db("db").table("things").sample(2).run(conn) result = list(result) - assert (len(result) == 2) + assert len(result) == 2 doc1, doc2 = result - assert (doc1 != doc2) - ids = set(['one', 'two', 'three']) - assert (doc1['id'] in ids) - assert (doc2['id'] in ids) + assert doc1 != doc2 + ids = set(["one", "two", "three"]) + assert doc1["id"] in ids + assert doc2["id"] in ids diff --git a/tests/functional/test_between.py b/tests/functional/test_between.py index 379e61e..4714631 100644 --- a/tests/functional/test_between.py +++ b/tests/functional/test_between.py @@ -8,104 +8,110 @@ class TestBetween(MockTest): @staticmethod def get_data(): data = [ - {'id': 'bob', 'first_name': 'Bob', 'last_name': 'Builder'}, - {'id': 'joe', 'first_name': 'Joseph', 'last_name': 'Smith'}, - {'id': 'tom', 'first_name': 'Tom', 'last_name': 'Generic'}, - {'id': 'zuul', 'first_name': 'Adam', 'last_name': 'Zuul'} - + {"id": "bob", "first_name": "Bob", "last_name": "Builder"}, + {"id": "joe", "first_name": "Joseph", "last_name": "Smith"}, + {"id": "tom", "first_name": "Tom", "last_name": "Generic"}, + {"id": "zuul", "first_name": "Adam", "last_name": "Zuul"}, ] - return as_db_and_table('s', 'people', data) + return as_db_and_table("s", "people", data) def test_between_id_default_range(self, conn): expected = [ - {'id': 'bob', 'first_name': 'Bob', 'last_name': 'Builder'}, - {'id': 'joe', 'first_name': 'Joseph', 'last_name': 'Smith'}, - {'id': 'tom', 'first_name': 'Tom', 'last_name': 'Generic'} + {"id": "bob", "first_name": "Bob", "last_name": "Builder"}, + {"id": "joe", "first_name": "Joseph", "last_name": "Smith"}, + {"id": "tom", "first_name": "Tom", "last_name": "Generic"}, ] - result = r.db('s').table('people').between( - 'bob', 'zuul' - ).run(conn) + result = r.db("s").table("people").between("bob", "zuul").run(conn) assertEqUnordered(expected, list(result)) def test_between_id_closed_right(self, conn): expected = [ - {'id': 'bob', 'first_name': 'Bob', 'last_name': 'Builder'}, - {'id': 'joe', 'first_name': 'Joseph', 'last_name': 'Smith'}, - {'id': 'tom', 'first_name': 'Tom', 'last_name': 'Generic'} + {"id": "bob", "first_name": "Bob", "last_name": "Builder"}, + {"id": "joe", "first_name": "Joseph", "last_name": "Smith"}, + {"id": "tom", "first_name": "Tom", "last_name": "Generic"}, ] - result = r.db('s').table('people').between( - 'bob', 'tom', right_bound='closed' - ).run(conn) + result = ( + r.db("s") + .table("people") + .between("bob", "tom", right_bound="closed") + .run(conn) + ) result = list(result) assertEqUnordered(expected, result) def test_between_id_open_left(self, conn): - expected = [ - {'id': 'joe', 'first_name': 'Joseph', 'last_name': 'Smith'} - ] - result = r.db('s').table('people').between( - 'bob', 'tom', left_bound='open' - ).run(conn) + expected = [{"id": "joe", "first_name": "Joseph", "last_name": "Smith"}] + result = ( + r.db("s").table("people").between("bob", "tom", left_bound="open").run(conn) + ) result = list(result) assertEqUnordered(expected, result) def test_between_id_open_left_closed_right(self, conn): expected = [ - {'id': 'joe', 'first_name': 'Joseph', 'last_name': 'Smith'}, - {'id': 'tom', 'first_name': 'Tom', 'last_name': 'Generic'} + {"id": "joe", "first_name": "Joseph", "last_name": "Smith"}, + {"id": "tom", "first_name": "Tom", "last_name": "Generic"}, ] - result = r.db('s').table('people').between( - 'bob', 'tom', left_bound='open', right_bound='closed' - ).run(conn) + result = ( + r.db("s") + .table("people") + .between("bob", "tom", left_bound="open", right_bound="closed") + .run(conn) + ) result = list(result) assertEqUnordered(expected, result) def test_between_index_default_range(self, conn): expected = [ - {'id': 'bob', 'first_name': 'Bob', 'last_name': 'Builder'}, - {'id': 'tom', 'first_name': 'Tom', 'last_name': 'Generic'} + {"id": "bob", "first_name": "Bob", "last_name": "Builder"}, + {"id": "tom", "first_name": "Tom", "last_name": "Generic"}, ] - r.db('s').table('people').index_create( - 'last_name' - ).run(conn) - r.db('s').table('people').index_wait().run(conn) - result = r.db('s').table('people').between( - 'Builder', 'Smith', index='last_name' - ).run(conn) + r.db("s").table("people").index_create("last_name").run(conn) + r.db("s").table("people").index_wait().run(conn) + result = ( + r.db("s") + .table("people") + .between("Builder", "Smith", index="last_name") + .run(conn) + ) result = list(result) assertEqUnordered(expected, result) def test_between_index_closed_right(self, conn): expected = [ - {'id': 'bob', 'first_name': 'Bob', 'last_name': 'Builder'}, - {'id': 'tom', 'first_name': 'Tom', 'last_name': 'Generic'}, - {'id': 'joe', 'first_name': 'Joseph', 'last_name': 'Smith'} + {"id": "bob", "first_name": "Bob", "last_name": "Builder"}, + {"id": "tom", "first_name": "Tom", "last_name": "Generic"}, + {"id": "joe", "first_name": "Joseph", "last_name": "Smith"}, ] - r.db('s').table('people').index_create( - 'last_name' - ).run(conn) - r.db('s').table('people').index_wait().run(conn) - result = r.db('s').table('people').between( - 'Builder', 'Smith', index='last_name', right_bound='closed' - ).run(conn) + r.db("s").table("people").index_create("last_name").run(conn) + r.db("s").table("people").index_wait().run(conn) + result = ( + r.db("s") + .table("people") + .between("Builder", "Smith", index="last_name", right_bound="closed") + .run(conn) + ) result = list(result) assertEqUnordered(expected, result) def test_between_index_open_left(self, conn): expected = [ - {'id': 'tom', 'first_name': 'Tom', 'last_name': 'Generic'}, - {'id': 'joe', 'first_name': 'Joseph', 'last_name': 'Smith'} + {"id": "tom", "first_name": "Tom", "last_name": "Generic"}, + {"id": "joe", "first_name": "Joseph", "last_name": "Smith"}, ] - r.db('s').table('people').index_create( - 'last_name' - ).run(conn) - r.db('s').table('people').index_wait().run(conn) - result = r.db('s').table('people').between( - 'Builder', - 'Smith', - index='last_name', - left_bound='open', - right_bound='closed' - ).run(conn) + r.db("s").table("people").index_create("last_name").run(conn) + r.db("s").table("people").index_wait().run(conn) + result = ( + r.db("s") + .table("people") + .between( + "Builder", + "Smith", + index="last_name", + left_bound="open", + right_bound="closed", + ) + .run(conn) + ) result = list(result) assertEqUnordered(expected, result) diff --git a/tests/functional/test_bracket_mapping.py b/tests/functional/test_bracket_mapping.py index 2e78199..1e5a237 100644 --- a/tests/functional/test_bracket_mapping.py +++ b/tests/functional/test_bracket_mapping.py @@ -7,32 +7,26 @@ class TestBracketMapping(MockTest): @staticmethod def get_data(): - data = [ - {'id': 1, 'animals': ['frog', 'cow']}, - {'id': 2, 'animals': ['horse']} - ] - return as_db_and_table('x', 'farms', data) + data = [{"id": 1, "animals": ["frog", "cow"]}, {"id": 2, "animals": ["horse"]}] + return as_db_and_table("x", "farms", data) def test_simple(self, conn): - res = r.db('x').table('farms').map( - lambda doc: doc['animals'][0] - ).run(conn) - assertEqual( - set(['frog', 'horse']), - set(list(res)) - ) + res = r.db("x").table("farms").map(lambda doc: doc["animals"][0]).run(conn) + assertEqual(set(["frog", "horse"]), set(list(res))) def test_filter_by_bracket(self, conn): - res = r.db('x').table('farms').filter( - lambda doc: doc['id'] < 2 - ).run(conn) + res = r.db("x").table("farms").filter(lambda doc: doc["id"] < 2).run(conn) expected = [1] - results = [doc['id'] for doc in res] + results = [doc["id"] for doc in res] assertEqual(expected, results) def test_order_by_bracket(self, conn): - res = r.db('x').table('farms').order_by( - lambda doc: doc['id'] - ).map(lambda doc: doc['id']).run(conn) + res = ( + r.db("x") + .table("farms") + .order_by(lambda doc: doc["id"]) + .map(lambda doc: doc["id"]) + .run(conn) + ) expected = [1, 2] assertEqual(expected, list(res)) diff --git a/tests/functional/test_contains.py b/tests/functional/test_contains.py index d90df62..a8b06e8 100644 --- a/tests/functional/test_contains.py +++ b/tests/functional/test_contains.py @@ -8,74 +8,101 @@ class TestContains(MockTest): @staticmethod def get_data(): data = [ - {'id': 'bob-id', 'age': 32, 'nums': [5, 7]}, - {'id': 'sam-id', 'age': 45}, - {'id': 'joe-id', 'age': 36} + {"id": "bob-id", "age": 32, "nums": [5, 7]}, + {"id": "sam-id", "age": 45}, + {"id": "joe-id", "age": 36}, ] - return as_db_and_table('d', 'people', data) + return as_db_and_table("d", "people", data) def test_contains_table_dict_true(self, conn): - result = r.db('d').table('people').contains({ - 'id': 'sam-id', - 'age': 45 - }).run(conn) + result = ( + r.db("d").table("people").contains({"id": "sam-id", "age": 45}).run(conn) + ) assertEqual(True, result) def test_contains_table_dict_multi_true(self, conn): - result = r.db('d').table('people').contains( - { - 'id': 'sam-id', - 'age': 45 - }, - { - 'id': 'joe-id', - 'age': 36 - } - ).run(conn) + result = ( + r.db("d") + .table("people") + .contains({"id": "sam-id", "age": 45}, {"id": "joe-id", "age": 36}) + .run(conn) + ) assertEqual(True, result) def test_contains_table_dict_false(self, conn): - result = r.db('d').table('people').contains({ - 'id': 'tara-muse-id', - 'age': 'timeless' - }).run(conn) + result = ( + r.db("d") + .table("people") + .contains({"id": "tara-muse-id", "age": "timeless"}) + .run(conn) + ) assertEqual(False, result) def test_contains_table_dict_multi_false(self, conn): - result = r.db('d').table('people').contains( - { - 'id': 'sam-id', - 'age': 45 - }, - { - 'id': 'tara-muse-id', - 'age': 'timeless' - } - ).run(conn) + result = ( + r.db("d") + .table("people") + .contains( + {"id": "sam-id", "age": 45}, {"id": "tara-muse-id", "age": "timeless"} + ) + .run(conn) + ) assertEqual(False, result) def test_contains_table_pred_true(self, conn): - result = r.db('d').table('people').contains( - lambda doc: doc['id'] == 'sam-id' - ).run(conn) + result = ( + r.db("d") + .table("people") + .contains(lambda doc: doc["id"] == "sam-id") + .run(conn) + ) assertEqual(True, result) def test_contains_table_pred_multi_true(self, conn): - result = r.db('d').table('people').contains( - lambda doc: doc['id'] == 'sam-id', - lambda doc: doc['id'] == 'joe-id' - ).run(conn) + result = ( + r.db("d") + .table("people") + .contains( + lambda doc: doc["id"] == "sam-id", lambda doc: doc["id"] == "joe-id" + ) + .run(conn) + ) assertEqual(True, result) def test_contains_table_pred_false(self, conn): - result = r.db('d').table('people').contains( - lambda doc: doc['id'] == 'tara-muse-id' - ).run(conn) + result = ( + r.db("d") + .table("people") + .contains(lambda doc: doc["id"] == "tara-muse-id") + .run(conn) + ) assertEqual(False, result) def test_contains_table_pred_multi_false(self, conn): - result = r.db('d').table('people').contains( - lambda doc: doc['id'] == 'sam-id', - lambda doc: doc['id'] == 'tara-muse-id' - ).run(conn) + result = ( + r.db("d") + .table("people") + .contains( + lambda doc: doc["id"] == "sam-id", + lambda doc: doc["id"] == "tara-muse-id", + ) + .run(conn) + ) assertEqual(False, result) + + def test_contains_lambda(self, conn): + expected = [ + {"id": "bob-id", "age": 32, "nums": [5, 7]}, + {"id": "sam-id", "age": 45}, + ] + result = ( + r.db("d") + .table("people") + .filter( + lambda doc: r.expr(["non_existent", "sam-id", "bob-id"]).contains( + doc["id"] + ) + ) + .run(conn) + ) + assertEqual(expected, list(result)) diff --git a/tests/functional/test_distinct.py b/tests/functional/test_distinct.py index 23cc9ff..b825b53 100644 --- a/tests/functional/test_distinct.py +++ b/tests/functional/test_distinct.py @@ -13,51 +13,61 @@ class TestDistinctTop(MockTest): @staticmethod def get_data(): data = [ - {'id': 'bob-id', 'first_name': 'Bob', 'last_name': 'Sanders', 'age': 35}, - {'id': 'sam-id', 'first_name': 'Sam', 'last_name': 'Fudd', 'age': 17}, - {'id': 'joe-id', 'first_name': 'Joe', 'last_name': 'Sanders', 'age': 62} + {"id": "bob-id", "first_name": "Bob", "last_name": "Sanders", "age": 35}, + {"id": "sam-id", "first_name": "Sam", "last_name": "Fudd", "age": 17}, + {"id": "joe-id", "first_name": "Joe", "last_name": "Sanders", "age": 62}, ] - return as_db_and_table('d', 'people', data) + return as_db_and_table("d", "people", data) def test_distinct_table(self, conn): expected = [ - {'id': 'bob-id', 'first_name': 'Bob', 'last_name': 'Sanders', 'age': 35}, - {'id': 'sam-id', 'first_name': 'Sam', 'last_name': 'Fudd', 'age': 17}, - {'id': 'joe-id', 'first_name': 'Joe', 'last_name': 'Sanders', 'age': 62} + {"id": "bob-id", "first_name": "Bob", "last_name": "Sanders", "age": 35}, + {"id": "sam-id", "first_name": "Sam", "last_name": "Fudd", "age": 17}, + {"id": "joe-id", "first_name": "Joe", "last_name": "Sanders", "age": 62}, ] - result = r.db('d').table('people').distinct().run(conn) + result = r.db("d").table("people").distinct().run(conn) assertEqUnordered(expected, list(result)) def test_distinct_secondary_index(self, conn): - r.db('d').table('people').index_create('last_name').run(conn) - r.db('d').table('people').index_wait().run(conn) - result = r.db('d').table('people').distinct(index='last_name').run(conn) + r.db("d").table("people").index_create("last_name").run(conn) + r.db("d").table("people").index_wait().run(conn) + result = r.db("d").table("people").distinct(index="last_name").run(conn) result = list(result) - pprint({'result': result}) + pprint({"result": result}) assertEqual(2, len(result)) - assertEqual(set(['Sanders', 'Fudd']), set(result)) + assertEqual(set(["Sanders", "Fudd"]), set(result)) class TestDistinctNested(MockTest): @staticmethod def get_data(): data = [ - {'id': 'x-id', 'nums': [1, 5, 2, 5, 3, 2]}, - {'id': 'y-id', 'nums': [{'val': 1}, {'val': 5}, {'val': 2}, {'val': 5}, {'val': 3}, {'val': 2}]} + {"id": "x-id", "nums": [1, 5, 2, 5, 3, 2]}, + { + "id": "y-id", + "nums": [ + {"val": 1}, + {"val": 5}, + {"val": 2}, + {"val": 5}, + {"val": 3}, + {"val": 2}, + ], + }, ] - return as_db_and_table('d', 'people', data) + return as_db_and_table("d", "people", data) def test_distinct_nested(self, conn): ex1 = set([1, 2, 5, 3]) - ex2 = DictableSet([{'val': 1}, {'val': 2}, {'val': 5}, {'val': 3}]) - result = r.db('d').table('people').map( - lambda doc: doc['nums'].distinct() - ).run(conn) + ex2 = DictableSet([{"val": 1}, {"val": 2}, {"val": 5}, {"val": 3}]) + result = ( + r.db("d").table("people").map(lambda doc: doc["nums"].distinct()).run(conn) + ) result = list(result) for elem in result: if isinstance(elem[0], dict): for dict_elem in elem: - assert (ex2.has(dict_elem)) + assert ex2.has(dict_elem) else: assertEqual(ex1, set(elem)) diff --git a/tests/functional/test_grouping.py b/tests/functional/test_grouping.py index 6b48c21..96ae9f5 100644 --- a/tests/functional/test_grouping.py +++ b/tests/functional/test_grouping.py @@ -9,48 +9,45 @@ class TestGroup(MockTest): @staticmethod def get_data(): data = [ - {'id': 'joe', 'type': 'bro'}, - {'id': 'bill', 'type': 'hipster'}, - {'id': 'todd', 'type': 'hipster'} + {"id": "joe", "type": "bro"}, + {"id": "bill", "type": "hipster"}, + {"id": "todd", "type": "hipster"}, ] - return as_db_and_table('x', 'people', data) + return as_db_and_table("x", "people", data) def test_group_by_field(self, conn): expected = { - 'bro': [ - {'id': 'joe', 'type': 'bro'}, + "bro": [ + {"id": "joe", "type": "bro"}, + ], + "hipster": [ + {"id": "bill", "type": "hipster"}, + {"id": "todd", "type": "hipster"}, ], - 'hipster': [ - {'id': 'bill', 'type': 'hipster'}, - {'id': 'todd', 'type': 'hipster'} - ] } - result = r.db('x').table('people').group('type').run(conn) - assertEqual(expected['bro'], result['bro']) - assertEqUnordered(expected['hipster'], result['hipster']) - assertEqual(set(['bro', 'hipster']), set(result.keys())) + result = r.db("x").table("people").group("type").run(conn) + assertEqual(expected["bro"], result["bro"]) + assertEqUnordered(expected["hipster"], result["hipster"]) + assertEqual(set(["bro", "hipster"]), set(result.keys())) def test_group_by_func(self, conn): expected = { - 'bro': [ - {'id': 'joe', 'type': 'bro'}, + "bro": [ + {"id": "joe", "type": "bro"}, + ], + "hipster": [ + {"id": "bill", "type": "hipster"}, + {"id": "todd", "type": "hipster"}, ], - 'hipster': [ - {'id': 'bill', 'type': 'hipster'}, - {'id': 'todd', 'type': 'hipster'} - ] } - result = r.db('x').table('people').group(lambda d: d['type']).run(conn) - assertEqual(expected['bro'], result['bro']) - assertEqUnordered(expected['hipster'], result['hipster']) - assertEqual(set(['bro', 'hipster']), set(result.keys())) + result = r.db("x").table("people").group(lambda d: d["type"]).run(conn) + assertEqual(expected["bro"], result["bro"]) + assertEqUnordered(expected["hipster"], result["hipster"]) + assertEqual(set(["bro", "hipster"]), set(result.keys())) def test_group_count(self, conn): - expected = { - 'bro': 1, - 'hipster': 2 - } - result = r.db('x').table('people').group('type').count().run(conn) + expected = {"bro": 1, "hipster": 2} + result = r.db("x").table("people").group("type").count().run(conn) assertEqual(expected, result) @@ -58,80 +55,88 @@ class TestUngroup(MockTest): @staticmethod def get_data(): data = [ - {'id': 'joe', 'type': 'bro'}, - {'id': 'bill', 'type': 'hipster'}, - {'id': 'todd', 'type': 'hipster'}, - {'id': 'sam', 'type': 'bro'}, - {'id': 'glenn', 'type': 'unknown'} + {"id": "joe", "type": "bro"}, + {"id": "bill", "type": "hipster"}, + {"id": "todd", "type": "hipster"}, + {"id": "sam", "type": "bro"}, + {"id": "glenn", "type": "unknown"}, ] - return as_db_and_table('x', 'people', data) + return as_db_and_table("x", "people", data) def test_ungroup_grouped_by_field(self, conn): expected = [ { - 'group': 'bro', - 'reduction': [ - {'id': 'joe', 'type': 'bro'}, - {'id': 'sam', 'type': 'bro'} - ] + "group": "bro", + "reduction": [ + {"id": "joe", "type": "bro"}, + {"id": "sam", "type": "bro"}, + ], }, { - 'group': 'hipster', - 'reduction': [ - {'id': 'bill', 'type': 'hipster'}, - {'id': 'todd', 'type': 'hipster'} - ] + "group": "hipster", + "reduction": [ + {"id": "bill", "type": "hipster"}, + {"id": "todd", "type": "hipster"}, + ], }, { - 'group': 'unknown', - 'reduction': [ - {'id': 'glenn', 'type': 'unknown'}, - ] - } + "group": "unknown", + "reduction": [ + {"id": "glenn", "type": "unknown"}, + ], + }, ] - result = r.db('x').table('people').group('type').ungroup().run(conn) + result = r.db("x").table("people").group("type").ungroup().run(conn) result = list(result) assertEqual(3, len(result)) - assertEqual(set(['bro', 'hipster', 'unknown']), set([doc['group'] for doc in result])) + assertEqual( + set(["bro", "hipster", "unknown"]), set([doc["group"] for doc in result]) + ) def is_group(group): - return lambda doc: doc['group'] == group - for group in ('bro', 'hipster', 'unknown'): + return lambda doc: doc["group"] == group + + for group in ("bro", "hipster", "unknown"): result_group = list(filter(is_group(group), result))[0] expected_group = list(filter(is_group(group), expected))[0] - assertEqUnordered(expected_group['reduction'], result_group['reduction']) + assertEqUnordered(expected_group["reduction"], result_group["reduction"]) def test_ungroup_grouped_by_func(self, conn): expected = [ { - 'group': 'bro', - 'reduction': [ - {'id': 'joe', 'type': 'bro'}, - {'id': 'sam', 'type': 'bro'} - ] + "group": "bro", + "reduction": [ + {"id": "joe", "type": "bro"}, + {"id": "sam", "type": "bro"}, + ], }, { - 'group': 'hipster', - 'reduction': [ - {'id': 'bill', 'type': 'hipster'}, - {'id': 'todd', 'type': 'hipster'} - ] + "group": "hipster", + "reduction": [ + {"id": "bill", "type": "hipster"}, + {"id": "todd", "type": "hipster"}, + ], }, { - 'group': 'unknown', - 'reduction': [ - {'id': 'glenn', 'type': 'unknown'}, - ] - } + "group": "unknown", + "reduction": [ + {"id": "glenn", "type": "unknown"}, + ], + }, ] - result = r.db('x').table('people').group(lambda d: d['type']).ungroup().run(conn) + result = ( + r.db("x").table("people").group(lambda d: d["type"]).ungroup().run(conn) + ) result = list(result) assertEqual(3, len(result)) - assertEqual(set(['bro', 'hipster', 'unknown']), set([doc['group'] for doc in result])) + assertEqual( + set(["bro", "hipster", "unknown"]), set([doc["group"] for doc in result]) + ) def is_group(group): - return lambda doc: doc['group'] == group - for group in ('bro', 'hipster', 'unknown'): + return lambda doc: doc["group"] == group + + for group in ("bro", "hipster", "unknown"): result_group = list(filter(is_group(group), result))[0] expected_group = list(filter(is_group(group), expected))[0] - assertEqUnordered(expected_group['reduction'], result_group['reduction']) + assertEqUnordered(expected_group["reduction"], result_group["reduction"]) diff --git a/tests/functional/test_indexes.py b/tests/functional/test_indexes.py index 44f630b..f1d7b83 100644 --- a/tests/functional/test_indexes.py +++ b/tests/functional/test_indexes.py @@ -11,126 +11,104 @@ class TestIndexes(MockTest): @staticmethod def get_data(): data = [ - {'id': 'bob', 'first_name': 'Bob', 'last_name': 'Builder'}, - {'id': 'joe', 'first_name': 'Joseph', 'last_name': 'Smith'}, - {'id': 'tom', 'first_name': 'Tom', 'last_name': 'Generic'} + {"id": "bob", "first_name": "Bob", "last_name": "Builder"}, + {"id": "joe", "first_name": "Joseph", "last_name": "Smith"}, + {"id": "tom", "first_name": "Tom", "last_name": "Generic"}, ] - return as_db_and_table('s', 'people', data) + return as_db_and_table("s", "people", data) def test_field_index_create(self, conn): - expected = ['first_name'] - r.db('s').table('people').index_create('first_name').run(conn) - result = r.db('s').table('people').index_list().run(conn) + expected = ["first_name"] + r.db("s").table("people").index_create("first_name").run(conn) + result = r.db("s").table("people").index_list().run(conn) assertEqUnordered(expected, list(result)) def test_field_index_create_works(self, conn): - expected = [ - {'id': 'bob', 'first_name': 'Bob', 'last_name': 'Builder'} - ] + expected = [{"id": "bob", "first_name": "Bob", "last_name": "Builder"}] - r.db('s').table('people').index_create('first_name').run(conn) - r.db('s').table('people').index_wait('first_name').run(conn) - result = r.db('s').table('people').get_all('Bob', index='first_name').run(conn) + r.db("s").table("people").index_create("first_name").run(conn) + r.db("s").table("people").index_wait("first_name").run(conn) + result = r.db("s").table("people").get_all("Bob", index="first_name").run(conn) result = list(result) pprint(result) assertEqUnordered(expected, result) def test_func_index_create(self, conn): - expected = ['first_and_last'] - r.db('s').table('people').index_create( - 'first_and_last', - lambda doc: doc['first_name'] + doc['last_name'] + expected = ["first_and_last"] + r.db("s").table("people").index_create( + "first_and_last", lambda doc: doc["first_name"] + doc["last_name"] ).run(conn) - result = r.db('s').table('people').index_list().run(conn) + result = r.db("s").table("people").index_list().run(conn) assertEqUnordered(expected, list(result)) def test_func_index_create_works(self, conn): expected = [ - {'id': 'bob', 'first_name': 'Bob', 'last_name': 'Builder'}, - {'id': 'tom', 'first_name': 'Tom', 'last_name': 'Generic'} + {"id": "bob", "first_name": "Bob", "last_name": "Builder"}, + {"id": "tom", "first_name": "Tom", "last_name": "Generic"}, ] - r.db('s').table('people').index_create( - 'first_and_last', - lambda doc: doc['first_name'] + doc['last_name'] - ).run(conn) - r.db('s').table('people').index_wait('first_and_last').run(conn) - result = r.db('s').table('people').get_all( - 'BobBuilder', 'TomGeneric', - index='first_and_last' + r.db("s").table("people").index_create( + "first_and_last", lambda doc: doc["first_name"] + doc["last_name"] ).run(conn) + r.db("s").table("people").index_wait("first_and_last").run(conn) + result = ( + r.db("s") + .table("people") + .get_all("BobBuilder", "TomGeneric", index="first_and_last") + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_index_drop_works(self, conn): - r.db('s').table('people').index_create( - 'last_name' - ).run(conn) - indexes = list(r.db('s').table('people').index_list().run(conn)) - assertEqual(['last_name'], indexes) - r.db('s').table('people').index_drop( - 'last_name' - ).run(conn) - indexes = list(r.db('s').table('people').index_list().run(conn)) + r.db("s").table("people").index_create("last_name").run(conn) + indexes = list(r.db("s").table("people").index_list().run(conn)) + assertEqual(["last_name"], indexes) + r.db("s").table("people").index_drop("last_name").run(conn) + indexes = list(r.db("s").table("people").index_list().run(conn)) assertEqual([], indexes) def test_index_rename_works(self, conn): - r.db('s').table('people').index_create( - 'last_name' - ).run(conn) - indexes = list(r.db('s').table('people').index_list().run(conn)) - assertEqual(['last_name'], indexes) - r.db('s').table('people').index_rename( - 'last_name', 'new_last_name' - ).run(conn) - indexes = list(r.db('s').table('people').index_list().run(conn)) - assertEqual(['new_last_name'], indexes) + r.db("s").table("people").index_create("last_name").run(conn) + indexes = list(r.db("s").table("people").index_list().run(conn)) + assertEqual(["last_name"], indexes) + r.db("s").table("people").index_rename("last_name", "new_last_name").run(conn) + indexes = list(r.db("s").table("people").index_list().run(conn)) + assertEqual(["new_last_name"], indexes) def test_index_rename_works_2(self, conn): - expected = [ - {'id': 'tom', 'first_name': 'Tom', 'last_name': 'Generic'} - ] - r.db('s').table('people').index_create( - 'last_name' - ).run(conn) - indexes = list(r.db('s').table('people').index_list().run(conn)) - assertEqual(['last_name'], indexes) - r.db('s').table('people').index_rename( - 'last_name', 'new_last_name' - ).run(conn) - r.db('s').table('people').index_wait('new_last_name').run(conn) - result = r.db('s').table('people').get_all( - 'Generic', - index='new_last_name' - ).run(conn) + expected = [{"id": "tom", "first_name": "Tom", "last_name": "Generic"}] + r.db("s").table("people").index_create("last_name").run(conn) + indexes = list(r.db("s").table("people").index_list().run(conn)) + assertEqual(["last_name"], indexes) + r.db("s").table("people").index_rename("last_name", "new_last_name").run(conn) + r.db("s").table("people").index_wait("new_last_name").run(conn) + result = ( + r.db("s") + .table("people") + .get_all("Generic", index="new_last_name") + .run(conn) + ) assertEqual(expected, list(result)) def test_index_wait_one_works(self, conn): - expected = [ - {'id': 'bob', 'first_name': 'Bob', 'last_name': 'Builder'} - ] + expected = [{"id": "bob", "first_name": "Bob", "last_name": "Builder"}] - r.db('s').table('people').index_create( - 'last_name' - ).run(conn) - r.db('s').table('people').index_wait('last_name').run(conn) - result = r.db('s').table('people').get_all( - 'Builder', index='last_name' - ).run(conn) + r.db("s").table("people").index_create("last_name").run(conn) + r.db("s").table("people").index_wait("last_name").run(conn) + result = ( + r.db("s").table("people").get_all("Builder", index="last_name").run(conn) + ) assertEqual(expected, list(result)) def test_index_wait_all_works(self, conn): - expected = [ - {'id': 'bob', 'first_name': 'Bob', 'last_name': 'Builder'} - ] + expected = [{"id": "bob", "first_name": "Bob", "last_name": "Builder"}] - r.db('s').table('people').index_create( - 'last_name' - ).run(conn) - r.db('s').table('people').index_wait().run(conn) - result = r.db('s').table('people').get_all( - 'Builder', index='last_name' - ).run(conn) + r.db("s").table("people").index_create("last_name").run(conn) + r.db("s").table("people").index_wait().run(conn) + result = ( + r.db("s").table("people").get_all("Builder", index="last_name").run(conn) + ) assertEqual(expected, list(result)) @@ -138,48 +116,40 @@ class TestIndexUpdating(MockTest): @staticmethod def get_data(): data = [ - {'id': 'bob', 'first_name': 'Bob', 'last_name': 'Builder'}, - {'id': 'joe', 'first_name': 'Joseph', 'last_name': 'Smith'}, - {'id': 'tom', 'first_name': 'Tom', 'last_name': 'Generic'} + {"id": "bob", "first_name": "Bob", "last_name": "Builder"}, + {"id": "joe", "first_name": "Joseph", "last_name": "Smith"}, + {"id": "tom", "first_name": "Tom", "last_name": "Generic"}, ] - return as_db_and_table('s', 'people', data) + return as_db_and_table("s", "people", data) def test_index_update(self, conn): - people = r.db('s').table('people') - people.index_create( - 'last_name' - ).run(conn) + people = r.db("s").table("people") + people.index_create("last_name").run(conn) people.index_wait().run(conn) - people.insert({ - 'id': 'someone', - 'first_name': 'Some', - 'last_name': 'One' - }).run(conn) - result = list( - people - .get_all('One', index='last_name') - .run(conn) + people.insert({"id": "someone", "first_name": "Some", "last_name": "One"}).run( + conn ) + result = list(people.get_all("One", index="last_name").run(conn)) assertEqual(1, len(result)) result = result[0] - assertEqual('someone', result['id']) + assertEqual("someone", result["id"]) class TestMoreIndices(MockTest): @staticmethod def get_data(): data = [ - {'id': 'a-id', 'name': 'a', 'parent': None, 'parents': []}, - {'id': 'b-id', 'name': 'b', 'parent': 'a-id', 'parents': ['a-id']}, - {'id': 'c-id', 'name': 'c', 'parent': 'a-id', 'parents': ['a-id']}, - {'id': 'd-id', 'name': 'd', 'parent': 'c-id', 'parents': ['c-id', 'a-id']}, - {'id': 'e-id', 'name': 'e', 'parent': 'b-id', 'parents': ['b-id', 'a-id']} + {"id": "a-id", "name": "a", "parent": None, "parents": []}, + {"id": "b-id", "name": "b", "parent": "a-id", "parents": ["a-id"]}, + {"id": "c-id", "name": "c", "parent": "a-id", "parents": ["a-id"]}, + {"id": "d-id", "name": "d", "parent": "c-id", "parents": ["c-id", "a-id"]}, + {"id": "e-id", "name": "e", "parent": "b-id", "parents": ["b-id", "a-id"]}, ] - return as_db_and_table('s', 'spaces', data) + return as_db_and_table("s", "spaces", data) def test_basic(self, conn): - spaces = r.db('s').table('spaces') - spaces.index_create('parents', multi=True).run(conn) + spaces = r.db("s").table("spaces") + spaces.index_create("parents", multi=True).run(conn) spaces.index_wait().run(conn) - children = list(spaces.get_all('a-id', index='parents').run(conn)) + children = list(spaces.get_all("a-id", index="parents").run(conn)) assertEqual(4, len(children)) diff --git a/tests/functional/test_joins.py b/tests/functional/test_joins.py index eaefa63..dd6f3d2 100644 --- a/tests/functional/test_joins.py +++ b/tests/functional/test_joins.py @@ -5,30 +5,29 @@ def common_join_data(): people_data = [ - {'id': 'joe-id', 'name': 'Joe'}, - {'id': 'tom-id', 'name': 'Tom'}, - {'id': 'arnold-id', 'name': 'Arnold'} + {"id": "joe-id", "name": "Joe"}, + {"id": "tom-id", "name": "Tom"}, + {"id": "arnold-id", "name": "Arnold"}, ] job_data = [ - {'id': 'lawyer-id', 'name': 'Lawyer'}, - {'id': 'nurse-id', 'name': 'Nurse'}, - {'id': 'semipro-wombat-id', 'name': 'Semi-Professional Wombat'} + {"id": "lawyer-id", "name": "Lawyer"}, + {"id": "nurse-id", "name": "Nurse"}, + {"id": "semipro-wombat-id", "name": "Semi-Professional Wombat"}, ] employee_data = [ - {'id': 'joe-emp-id', 'person': 'joe-id', 'job': 'lawyer-id'}, - {'id': 'arnold-emp-id', 'person': 'arnold-id', 'job': 'nurse-id'} + {"id": "joe-emp-id", "person": "joe-id", "job": "lawyer-id"}, + {"id": "arnold-emp-id", "person": "arnold-id", "job": "nurse-id"}, ] data = { - 'dbs': { - 'jezebel': { - 'tables': { - 'people': people_data, - 'jobs': job_data, - 'employees': employee_data + "dbs": { + "jezebel": { + "tables": { + "people": people_data, + "jobs": job_data, + "employees": employee_data, } } } - } return data @@ -41,29 +40,24 @@ def get_data(): def test_eq_join_1(self, conn): expected = [ { - 'left': { - 'id': 'joe-emp-id', - 'person': 'joe-id', - 'job': 'lawyer-id' - }, - 'right': { - 'id': 'joe-id', - 'name': 'Joe' - } + "left": {"id": "joe-emp-id", "person": "joe-id", "job": "lawyer-id"}, + "right": {"id": "joe-id", "name": "Joe"}, }, { - 'left': { - 'id': 'arnold-emp-id', - 'person': 'arnold-id', - 'job': 'nurse-id' + "left": { + "id": "arnold-emp-id", + "person": "arnold-id", + "job": "nurse-id", }, - 'right': { - 'id': 'arnold-id', - 'name': 'Arnold' - } - } + "right": {"id": "arnold-id", "name": "Arnold"}, + }, ] - result = r.db('jezebel').table('employees').eq_join('person', r.db('jezebel').table('people')).run(conn) + result = ( + r.db("jezebel") + .table("employees") + .eq_join("person", r.db("jezebel").table("people")) + .run(conn) + ) assertEqUnordered(expected, list(result)) @@ -75,32 +69,27 @@ def get_data(): def test_inner_join_1(self, conn): expected = [ { - 'left': { - 'id': 'joe-emp-id', - 'person': 'joe-id', - 'job': 'lawyer-id' - }, - 'right': { - 'id': 'joe-id', - 'name': 'Joe' - } + "left": {"id": "joe-emp-id", "person": "joe-id", "job": "lawyer-id"}, + "right": {"id": "joe-id", "name": "Joe"}, }, { - 'left': { - 'id': 'arnold-emp-id', - 'person': 'arnold-id', - 'job': 'nurse-id' + "left": { + "id": "arnold-emp-id", + "person": "arnold-id", + "job": "nurse-id", }, - 'right': { - 'id': 'arnold-id', - 'name': 'Arnold' - } - } + "right": {"id": "arnold-id", "name": "Arnold"}, + }, ] - result = r.db('jezebel').table('employees').inner_join( - r.db('jezebel').table('people'), - lambda employee, person: employee['person'] == person['id'] - ).run(conn) + result = ( + r.db("jezebel") + .table("employees") + .inner_join( + r.db("jezebel").table("people"), + lambda employee, person: employee["person"] == person["id"], + ) + .run(conn) + ) assertEqUnordered(expected, list(result)) @@ -108,72 +97,42 @@ class TestOuterJoin(MockTest): @staticmethod def get_data(): people = [ - {'id': 'sam-id', 'name': 'Sam'}, - {'id': 'miguel-id', 'name': 'Miguel'}, - {'id': 'mark-id', 'name': 'Mark'} + {"id": "sam-id", "name": "Sam"}, + {"id": "miguel-id", "name": "Miguel"}, + {"id": "mark-id", "name": "Mark"}, ] pets = [ - {'id': 'pet1-id', 'name': 'Pet1', 'owner': 'miguel-id'}, - {'id': 'pet2-id', 'name': 'Pet2', 'owner': 'mark-id'}, - {'id': 'pet3-id', 'name': 'Pet3', 'owner': 'miguel-id'}, + {"id": "pet1-id", "name": "Pet1", "owner": "miguel-id"}, + {"id": "pet2-id", "name": "Pet2", "owner": "mark-id"}, + {"id": "pet3-id", "name": "Pet3", "owner": "miguel-id"}, ] - return { - 'dbs': { - 'awesomesauce': { - 'tables': { - 'pets': pets, - 'people': people - } - } - } - } + return {"dbs": {"awesomesauce": {"tables": {"pets": pets, "people": people}}}} def test_outer_join_1(self, conn): expected = [ { - 'left': { - 'id': 'miguel-id', - 'name': 'Miguel' - }, - 'right': { - 'id': 'pet1-id', - 'name': 'Pet1', - 'owner': 'miguel-id' - } + "left": {"id": "miguel-id", "name": "Miguel"}, + "right": {"id": "pet1-id", "name": "Pet1", "owner": "miguel-id"}, }, { - 'left': { - 'id': 'miguel-id', - 'name': 'Miguel' - }, - 'right': { - 'id': 'pet3-id', - 'name': 'Pet3', - 'owner': 'miguel-id' - } + "left": {"id": "miguel-id", "name": "Miguel"}, + "right": {"id": "pet3-id", "name": "Pet3", "owner": "miguel-id"}, }, { - 'left': { - 'id': 'mark-id', - 'name': 'Mark' - }, - 'right': { - 'id': 'pet2-id', - 'name': 'Pet2', - 'owner': 'mark-id' - } + "left": {"id": "mark-id", "name": "Mark"}, + "right": {"id": "pet2-id", "name": "Pet2", "owner": "mark-id"}, }, - { - 'left': { - 'id': 'sam-id', - 'name': 'Sam' - } - } + {"left": {"id": "sam-id", "name": "Sam"}}, ] - result = r.db('awesomesauce').table('people').outer_join( - r.db('awesomesauce').table('pets'), - lambda person, pet: pet['owner'] == person['id'] - ).run(conn) + result = ( + r.db("awesomesauce") + .table("people") + .outer_join( + r.db("awesomesauce").table("pets"), + lambda person, pet: pet["owner"] == person["id"], + ) + .run(conn) + ) assertEqUnordered(expected, list(result)) @@ -181,56 +140,25 @@ class TestZip(MockTest): @staticmethod def get_data(): left = [ - { - 'id': 'one', - 'lname': 'One', - 'rval': 'r-one' - }, - { - 'id': 'two', - 'lname': 'Two', - 'rval': 'r-two' - } + {"id": "one", "lname": "One", "rval": "r-one"}, + {"id": "two", "lname": "Two", "rval": "r-two"}, ] right = [ - { - 'id': 'r-one', - 'rname': 'RightOne' - }, - { - 'id': 'r-two', - 'rname': 'RightTwo' - } + {"id": "r-one", "rname": "RightOne"}, + {"id": "r-two", "rname": "RightTwo"}, ] - return { - 'dbs': { - 'x': { - 'tables': { - 'ltab': left, - 'rtab': right - } - } - } - - - } + return {"dbs": {"x": {"tables": {"ltab": left, "rtab": right}}}} def test_zip_1(self, conn): expected = [ - { - 'id': 'r-one', - 'lname': 'One', - 'rname': 'RightOne', - 'rval': 'r-one' - }, - { - 'id': 'r-two', - 'lname': 'Two', - 'rname': 'RightTwo', - 'rval': 'r-two' - } + {"id": "r-one", "lname": "One", "rname": "RightOne", "rval": "r-one"}, + {"id": "r-two", "lname": "Two", "rname": "RightTwo", "rval": "r-two"}, ] - result = r.db('x').table('ltab').eq_join( - 'rval', r.db('x').table('rtab') - ).zip().run(conn) + result = ( + r.db("x") + .table("ltab") + .eq_join("rval", r.db("x").table("rtab")) + .zip() + .run(conn) + ) assertEqUnordered(expected, list(result)) diff --git a/tests/functional/test_logic.py b/tests/functional/test_logic.py index ea797a6..3141fe8 100644 --- a/tests/functional/test_logic.py +++ b/tests/functional/test_logic.py @@ -9,79 +9,86 @@ class TestLogic1(MockTest): @staticmethod def get_data(): data = [ - {'id': 'joe', 'has_eyes': True, 'age': 22, 'hair_color': 'brown'}, - {'id': 'sam', 'has_eyes': True, 'age': 17, 'hair_color': 'bald'}, - {'id': 'angela', 'has_eyes': False, 'age': 26, 'hair_color': 'black'}, - {'id': 'johnson', 'has_eyes': False, 'age': 16, 'hair_color': 'blonde'} + {"id": "joe", "has_eyes": True, "age": 22, "hair_color": "brown"}, + {"id": "sam", "has_eyes": True, "age": 17, "hair_color": "bald"}, + {"id": "angela", "has_eyes": False, "age": 26, "hair_color": "black"}, + {"id": "johnson", "has_eyes": False, "age": 16, "hair_color": "blonde"}, ] - return as_db_and_table('pdb', 'p', data) + return as_db_and_table("pdb", "p", data) def test_not(self, conn): - expected = [ - {'id': 'johnson'}, - {'id': 'angela'} - ] - result = r.db('pdb').table('p').filter( - lambda doc: ~doc['has_eyes'] - ).pluck('id').run(conn) + expected = [{"id": "johnson"}, {"id": "angela"}] + result = ( + r.db("pdb") + .table("p") + .filter(lambda doc: ~doc["has_eyes"]) + .pluck("id") + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_and(self, conn): - expected = [ - {'id': 'sam'} - ] - result = r.db('pdb').table('p').filter( - lambda doc: doc['has_eyes'].and_(doc['age'].lt(20)) - ).pluck('id').run(conn) + expected = [{"id": "sam"}] + result = ( + r.db("pdb") + .table("p") + .filter(lambda doc: doc["has_eyes"].and_(doc["age"].lt(20))) + .pluck("id") + .run(conn) + ) assertEqual(expected, list(result)) def test_or(self, conn): - expected = [ - {'id': 'sam'}, - {'id': 'angela'}, - {'id': 'joe'} - ] - result = r.db('pdb').table('p').filter( - lambda doc: doc['has_eyes'].or_(doc['age'].gt(20)) - ).pluck('id').run(conn) + expected = [{"id": "sam"}, {"id": "angela"}, {"id": "joe"}] + result = ( + r.db("pdb") + .table("p") + .filter(lambda doc: doc["has_eyes"].or_(doc["age"].gt(20))) + .pluck("id") + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_gt(self, conn): - expected = [ - {'id': 'joe'}, - {'id': 'angela'} - ] - result = r.db('pdb').table('p').filter( - lambda doc: doc['age'] > 20 - ).pluck('id').run(conn) + expected = [{"id": "joe"}, {"id": "angela"}] + result = ( + r.db("pdb") + .table("p") + .filter(lambda doc: doc["age"] > 20) + .pluck("id") + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_lt(self, conn): - expected = [ - {'id': 'sam'}, - {'id': 'johnson'} - ] - result = r.db('pdb').table('p').filter( - lambda doc: doc['age'].lt(20) - ).pluck('id').run(conn) + expected = [{"id": "sam"}, {"id": "johnson"}] + result = ( + r.db("pdb") + .table("p") + .filter(lambda doc: doc["age"].lt(20)) + .pluck("id") + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_eq(self, conn): - expected = [ - {'id': 'sam'} - ] - result = r.db('pdb').table('p').filter( - lambda doc: doc['hair_color'] == 'bald' - ).pluck('id').run(conn) + expected = [{"id": "sam"}] + result = ( + r.db("pdb") + .table("p") + .filter(lambda doc: doc["hair_color"] == "bald") + .pluck("id") + .run(conn) + ) assertEqual(expected, list(result)) def test_neq(self, conn): - expected = [ - {'id': 'sam'}, - {'id': 'angela'}, - {'id': 'joe'} - ] - result = r.db('pdb').table('p').filter( - lambda doc: doc['hair_color'] != 'blonde' - ).pluck('id').run(conn) + expected = [{"id": "sam"}, {"id": "angela"}, {"id": "joe"}] + result = ( + r.db("pdb") + .table("p") + .filter(lambda doc: doc["hair_color"] != "blonde") + .pluck("id") + .run(conn) + ) assertEqUnordered(expected, list(result)) diff --git a/tests/functional/test_math.py b/tests/functional/test_math.py index a043f34..8e3c69d 100644 --- a/tests/functional/test_math.py +++ b/tests/functional/test_math.py @@ -8,48 +8,49 @@ class TestMath(MockTest): @staticmethod def get_data(): - data = [ - { - 'id': 'pt-1', - 'x': 10, - 'y': 25 - }, - { - 'id': 'pt-2', - 'x': 100, - 'y': 3 - } - ] - return as_db_and_table('math_db', 'points', data) + data = [{"id": "pt-1", "x": 10, "y": 25}, {"id": "pt-2", "x": 100, "y": 3}] + return as_db_and_table("math_db", "points", data) def test_add_method(self, conn): expected = [35, 103] - result = r.db('math_db').table('points').map(lambda t: t['x'].add(t['y'])).run(conn) + result = ( + r.db("math_db").table("points").map(lambda t: t["x"].add(t["y"])).run(conn) + ) assertEqUnordered(expected, list(result)) def test_add_oper(self, conn): expected = [35, 103] - result = r.db('math_db').table('points').map(lambda t: t['x'] + t['y']).run(conn) + result = ( + r.db("math_db").table("points").map(lambda t: t["x"] + t["y"]).run(conn) + ) assertEqUnordered(expected, list(result)) def test_sub_method(self, conn): expected = [-15, 97] - result = r.db('math_db').table('points').map(lambda t: t['x'].sub(t['y'])).run(conn) + result = ( + r.db("math_db").table("points").map(lambda t: t["x"].sub(t["y"])).run(conn) + ) assertEqUnordered(expected, list(result)) def test_sub_oper(self, conn): expected = [-15, 97] - result = r.db('math_db').table('points').map(lambda t: t['x'] - t['y']).run(conn) + result = ( + r.db("math_db").table("points").map(lambda t: t["x"] - t["y"]).run(conn) + ) assertEqUnordered(expected, list(result)) def test_mul_method(self, conn): expected = [250, 300] - result = r.db('math_db').table('points').map(lambda t: t['x'].mul(t['y'])).run(conn) + result = ( + r.db("math_db").table("points").map(lambda t: t["x"].mul(t["y"])).run(conn) + ) assertEqUnordered(expected, list(result)) def test_mul_oper(self, conn): expected = [250, 300] - result = r.db('math_db').table('points').map(lambda t: t['x'] * t['y']).run(conn) + result = ( + r.db("math_db").table("points").map(lambda t: t["x"] * t["y"]).run(conn) + ) assertEqUnordered(expected, list(result)) @@ -57,85 +58,72 @@ class TestMath2(MockTest): @staticmethod def get_data(): data = [ - { - 'id': 'pt-1', - 'x': 30, - 'y': 3, - 'z': 18 - }, - { - 'id': 'pt-2', - 'x': 24, - 'y': 6, - 'z': 10 - } + {"id": "pt-1", "x": 30, "y": 3, "z": 18}, + {"id": "pt-2", "x": 24, "y": 6, "z": 10}, ] - return as_db_and_table('math_db', 'points', data) + return as_db_and_table("math_db", "points", data) def test_div_method(self, conn): expected = set([10, 4]) - result = r.db('math_db').table('points').map( - lambda t: t['x'].div(t['y']) - ).run(conn) + result = ( + r.db("math_db").table("points").map(lambda t: t["x"].div(t["y"])).run(conn) + ) assertEqual(expected, set(list(result))) def test_div_oper(self, conn): expected = set([10, 4]) - result = r.db('math_db').table('points').map( - lambda t: t['x'] / t['y'] - ).run(conn) + result = ( + r.db("math_db").table("points").map(lambda t: t["x"] / t["y"]).run(conn) + ) assertEqual(expected, set(list(result))) def test_mod_method(self, conn): expected = set([12, 4]) - result = r.db('math_db').table('points').map( - lambda t: t['x'].mod(t['z']) - ).run(conn) + result = ( + r.db("math_db").table("points").map(lambda t: t["x"].mod(t["z"])).run(conn) + ) assertEqual(expected, set(list(result))) def test_mod_oper(self, conn): expected = set([12, 4]) - result = r.db('math_db').table('points').map( - lambda t: t['x'] % t['z'] - ).run(conn) + result = ( + r.db("math_db").table("points").map(lambda t: t["x"] % t["z"]).run(conn) + ) assertEqual(expected, set(list(result))) class TestRandom(MockTest): @staticmethod def get_data(): - data = [ - {'id': 'x', 'val': 12}, - {'id': 'y', 'val': 30} - ] - return as_db_and_table('things', 'pointless', data) + data = [{"id": "x", "val": 12}, {"id": "y", "val": 30}] + return as_db_and_table("things", "pointless", data) def test_random_0(self, conn): result = r.random().run(conn) - assert (result <= 1) - assert (result >= 0) - assert (type(result) == float) + assert result <= 1 + assert result >= 0 + assert type(result) == float def test_random_1(self, conn): result = r.random(10).run(conn) - assert (result <= 10) - assert (result >= 0) - assert (type(result) == int) + assert result <= 10 + assert result >= 0 + assert type(result) == int def test_random_1_float(self, conn): result = r.random(10).run(conn) - assert (result <= 10) - assert (result >= 0) - assert (type(result) == int) + assert result <= 10 + assert result >= 0 + assert type(result) == int def test_random_2(self, conn): result = r.random(10, 20).run(conn) - assert (result <= 20) - assert (result >= 10) - assert (type(result) == int) + assert result <= 20 + assert result >= 10 + assert type(result) == int def test_random_2_float(self, conn): result = r.random(10, 20, float=True).run(conn) - assert (result <= 20) - assert (result >= 10) - assert (type(result) == float) + assert result <= 20 + assert result >= 10 + assert type(result) == float diff --git a/tests/functional/test_merge.py b/tests/functional/test_merge.py index 87a86e8..f1d04c9 100644 --- a/tests/functional/test_merge.py +++ b/tests/functional/test_merge.py @@ -1,5 +1,4 @@ from rethinkdb import r -from tests.common import as_db_and_table from tests.common import assertEqUnordered from tests.functional.common import MockTest @@ -9,100 +8,103 @@ class TestMerge(MockTest): def get_data(): data = [ { - 'id': 'id-1', - 'x': { - 'x-val': 'x-val-1' - }, - 'y': { - 'y-val': 'y-val-1' - } + "id": "id-1", + "extra_id": "extra-id-1", + "x": {"x-val": "x-val-1"}, + "y": {"y-val": "y-val-1"}, }, - { - 'id': 'id-2', - 'x': { - 'x-val': 'x-val-2' - }, - 'y': { - 'y-val': 'y-val-2' + {"id": "id-2", "x": {"x-val": "x-val-2"}, "y": {"y-val": "y-val-2"}}, + ] + data2 = [{"id": "extra-id-1", "extra_info": {"key": "value"}}] + + return { + "dbs": { + "jezebel": { + "tables": { + "things": data, + "extra_things": data2, + } } } - ] - return as_db_and_table('jezebel', 'things', data) + } def test_merge_toplevel(self, conn): expected = [ { - 'id': 'id-1', - 'x': { - 'x-val': 'x-val-1' - }, - 'y': { - 'y-val': 'y-val-1' - }, - 'z': 'Z-VALUE' + "id": "id-1", + "extra_id": "extra-id-1", + "x": {"x-val": "x-val-1"}, + "y": {"y-val": "y-val-1"}, + "z": "Z-VALUE", }, { - 'id': 'id-2', - 'x': { - 'x-val': 'x-val-2' - }, - 'y': { - 'y-val': 'y-val-2' - }, - 'z': 'Z-VALUE' - } + "id": "id-2", + "x": {"x-val": "x-val-2"}, + "y": {"y-val": "y-val-2"}, + "z": "Z-VALUE", + }, ] - result = r.db('jezebel').table('things').merge({'z': 'Z-VALUE'}).run(conn) + result = r.db("jezebel").table("things").merge({"z": "Z-VALUE"}).run(conn) assertEqUnordered(expected, list(result)) def test_merge_nested(self, conn): expected = [ - { - 'y-val': 'y-val-1', - 'extra-y-val': 'extra' - }, - { - 'y-val': 'y-val-2', - 'extra-y-val': 'extra' - } + {"y-val": "y-val-1", "extra-y-val": "extra"}, + {"y-val": "y-val-2", "extra-y-val": "extra"}, ] - result = r.db('jezebel').table('things').map( - lambda d: d['y'].merge({'extra-y-val': 'extra'}) - ).run(conn) + result = ( + r.db("jezebel") + .table("things") + .map(lambda d: d["y"].merge({"extra-y-val": "extra"})) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_merge_nested_with_prop(self, conn): expected = [ - { - 'x-val': 'x-val-1', - 'y-val': 'y-val-1' - }, - { - 'x-val': 'x-val-2', - 'y-val': 'y-val-2' - } + {"x-val": "x-val-1", "y-val": "y-val-1"}, + {"x-val": "x-val-2", "y-val": "y-val-2"}, ] - result = r.db('jezebel').table('things').map( - lambda d: d['x'].merge(d['y']) - ).run(conn) + result = ( + r.db("jezebel") + .table("things") + .map(lambda d: d["x"].merge(d["y"])) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_merge_nested_with_prop2(self, conn): expected = [ - { - 'x-val': 'x-val-1', - 'nested': { - 'y-val': 'y-val-1' - } - }, - { - 'x-val': 'x-val-2', - 'nested': { - 'y-val': 'y-val-2' - } - } + {"x-val": "x-val-1", "nested": {"y-val": "y-val-1"}}, + {"x-val": "x-val-2", "nested": {"y-val": "y-val-2"}}, ] - result = r.db('jezebel').table('things').map( - lambda d: d['x'].merge({'nested': d['y']}) - ).run(conn) + result = ( + r.db("jezebel") + .table("things") + .map(lambda d: d["x"].merge({"nested": d["y"]})) + .run(conn) + ) assertEqUnordered(expected, list(result)) + + def test_merge_wihtout_map(self, conn): + expected = { + "id": "id-1", + "extra_id": "extra-id-1", + "x": {"x-val": "x-val-1"}, + "y": {"y-val": "y-val-1"}, + "extra": {"key": "value"}, + } + result = ( + r.db("jezebel") + .table("things") + .get("id-1") + .merge( + lambda t: { + "extra": r.db("jezebel") + .table("extra_things") + .get(t["extra_id"])["extra_info"] + } + ) + .run(conn) + ) + assertEqUnordered(expected, result) diff --git a/tests/functional/test_misc.py b/tests/functional/test_misc.py index 29620dc..7ec598b 100644 --- a/tests/functional/test_misc.py +++ b/tests/functional/test_misc.py @@ -1,4 +1,5 @@ from rethinkdb import r +from rethinkdb.errors import ReqlNonExistenceError from rethinkdb.errors import RqlRuntimeError from tests.common import as_db_and_table from tests.common import assertEqual @@ -11,41 +12,38 @@ class TestGet(MockTest): @staticmethod def get_data(): - data = [ - {'id': 'joe-id', 'name': 'joe'}, - {'id': 'bob-id', 'name': 'bob'} - ] - return as_db_and_table('x', 'people', data) + data = [{"id": "joe-id", "name": "joe"}, {"id": "bob-id", "name": "bob"}] + return as_db_and_table("x", "people", data) def test_get_one_by_id(self, conn): - result = r.db('x').table('people').get('bob-id').run(conn) - assertEqual({'id': 'bob-id', 'name': 'bob'}, result) + result = r.db("x").table("people").get("bob-id").run(conn) + assertEqual({"id": "bob-id", "name": "bob"}, result) class TestGetAll(MockTest): @staticmethod def get_data(): data = [ - {'id': 'sam-id', 'name': 'sam'}, - {'id': 'anne-id', 'name': 'anne'}, - {'id': 'joe-id', 'name': 'joe'}, - {'id': 'bob-id', 'name': 'bob'} + {"id": "sam-id", "name": "sam"}, + {"id": "anne-id", "name": "anne"}, + {"id": "joe-id", "name": "joe"}, + {"id": "bob-id", "name": "bob"}, ] - return as_db_and_table('x', 'people', data) + return as_db_and_table("x", "people", data) def test_get_all_by_id(self, conn): expected = [ - {'id': 'anne-id', 'name': 'anne'}, - {'id': 'joe-id', 'name': 'joe'}, + {"id": "anne-id", "name": "anne"}, + {"id": "joe-id", "name": "joe"}, ] - result = r.db('x').table('people').get_all('anne-id', 'joe-id').run(conn) + result = r.db("x").table("people").get_all("anne-id", "joe-id").run(conn) assertEqUnordered(expected, result) def test_get_all_just_one(self, conn): expected = [ - {'id': 'bob-id', 'name': 'bob'}, + {"id": "bob-id", "name": "bob"}, ] - result = r.db('x').table('people').get_all('bob-id').run(conn) + result = r.db("x").table("people").get_all("bob-id").run(conn) assertEqual(expected, list(result)) @@ -53,32 +51,32 @@ class TestFiltering(MockTest): @staticmethod def get_data(): data = [ - {'id': 'joe-id', 'name': 'joe', 'age': 28}, - {'id': 'bob-id', 'name': 'bob', 'age': 19}, - {'id': 'bill-id', 'name': 'bill', 'age': 35}, - {'id': 'kimye-id', 'name': 'kimye', 'age': 17} + {"id": "joe-id", "name": "joe", "age": 28}, + {"id": "bob-id", "name": "bob", "age": 19}, + {"id": "bill-id", "name": "bill", "age": 35}, + {"id": "kimye-id", "name": "kimye", "age": 17}, ] - return as_db_and_table('x', 'people', data) + return as_db_and_table("x", "people", data) def test_filter_lambda_gt(self, conn): expected = [ - {'id': 'joe-id', 'name': 'joe', 'age': 28}, - {'id': 'bill-id', 'name': 'bill', 'age': 35} + {"id": "joe-id", "name": "joe", "age": 28}, + {"id": "bill-id", "name": "bill", "age": 35}, ] - result = r.db('x').table('people').filter(lambda p: p['age'] > 20).run(conn) + result = r.db("x").table("people").filter(lambda p: p["age"] > 20).run(conn) assertEqUnordered(expected, list(result)) def test_filter_lambda_lt(self, conn): expected = [ - {'id': 'bob-id', 'name': 'bob', 'age': 19}, - {'id': 'kimye-id', 'name': 'kimye', 'age': 17} + {"id": "bob-id", "name": "bob", "age": 19}, + {"id": "kimye-id", "name": "kimye", "age": 17}, ] - result = r.db('x').table('people').filter(lambda p: p['age'] < 20).run(conn) + result = r.db("x").table("people").filter(lambda p: p["age"] < 20).run(conn) assertEqUnordered(expected, list(result)) def test_filter_dict_match(self, conn): - expected = [{'id': 'bill-id', 'name': 'bill', 'age': 35}] - result = r.db('x').table('people').filter({'age': 35}).run(conn) + expected = [{"id": "bill-id", "name": "bill", "age": 35}] + result = r.db("x").table("people").filter({"age": 35}).run(conn) assertEqual(expected, list(result)) def test_filter_dict_match_bitwise(self, conn): @@ -86,8 +84,8 @@ def test_filter_dict_match_bitwise(self, conn): Test bitwise operators and other bitwise operators """ expected = [ - {'id': 'kimye-id', 'name': 'kimye', 'age': 17}, - {'id': 'bill-id', 'name': 'bill', 'age': 35} + {"id": "kimye-id", "name": "kimye", "age": 17}, + {"id": "bill-id", "name": "bill", "age": 35}, ] not_joe = r.row["id"] != "joe-id" @@ -95,40 +93,42 @@ def test_filter_dict_match_bitwise(self, conn): bill = r.row["id"] == "bill-id" kimye = r.row["name"] == "kimye" - result = r.db('x').table('people').filter(not_joe & not_bob & (kimye | bill)).run(conn) # not joe and not bob and either kimye or bill + result = ( + r.db("x") + .table("people") + .filter(not_joe & not_bob & (kimye | bill)) + .run(conn) + ) # not joe and not bob and either kimye or bill - assertEqual(sorted(expected, key=lambda i: i['age']), sorted(list(result), key=lambda i: i['age'])) + assertEqual( + sorted(expected, key=lambda i: i["age"]), + sorted(list(result), key=lambda i: i["age"]), + ) class TestMapping(MockTest): @staticmethod def get_data(): data = [ - {'id': 'joe-id', 'name': 'joe', 'age': 28}, - {'id': 'bob-id', 'name': 'bob', 'age': 19}, - {'id': 'bill-id', 'name': 'bill', 'age': 35}, - {'id': 'kimye-id', 'name': 'kimye', 'age': 17} + {"id": "joe-id", "name": "joe", "age": 28}, + {"id": "bob-id", "name": "bob", "age": 19}, + {"id": "bill-id", "name": "bill", "age": 35}, + {"id": "kimye-id", "name": "kimye", "age": 17}, ] - return as_db_and_table('x', 'people', data) + return as_db_and_table("x", "people", data) def test_map_gt(self, conn): - expected = [ - True, False, True, False - ] - result = r.db('x').table('people').map( - lambda p: p['age'] > 20 - ).run(conn) + expected = [True, False, True, False] + result = r.db("x").table("people").map(lambda p: p["age"] > 20).run(conn) assertEqUnordered(expected, list(result)) def test_map_missing_field_no_default(self, conn): err = None try: - r.db('x').table('people').map( - lambda p: p['missing'] > 15 - ).run(conn) + r.db("x").table("people").map(lambda p: p["missing"] > 15).run(conn) except RqlRuntimeError as e: err = e - assert (isinstance(err, RqlRuntimeError)) + assert isinstance(err, RqlRuntimeError) class TestBracket(MockTest): @@ -136,36 +136,28 @@ class TestBracket(MockTest): def get_data(): data = [ { - 'id': 'thing-1', - 'other_val': 'other-1', - 'values': { - 'a': 'a-1', - 'b': 'b-1', - 'c': 'c-1', - 'd': 'd-1' - } + "id": "thing-1", + "other_val": "other-1", + "values": {"a": "a-1", "b": "b-1", "c": "c-1", "d": "d-1"}, }, { - 'id': 'thing-2', - 'other_val': 'other-2', - 'values': { - 'a': 'a-2', - 'b': 'b-2', - 'c': 'c-2', - 'd': 'd-2' - } + "id": "thing-2", + "other_val": "other-2", + "values": {"a": "a-2", "b": "b-2", "c": "c-2", "d": "d-2"}, }, ] - return as_db_and_table('some_db', 'things', data) + return as_db_and_table("some_db", "things", data) def test_one_level(self, conn): - expected = ['other-1', 'other-2'] - result = r.db('some_db').table('things').map(lambda t: t['other_val']).run(conn) + expected = ["other-1", "other-2"] + result = r.db("some_db").table("things").map(lambda t: t["other_val"]).run(conn) assertEqUnordered(expected, list(result)) def test_nested(self, conn): - expected = ['c-1', 'c-2'] - result = r.db('some_db').table('things').map(lambda t: t['values']['c']).run(conn) + expected = ["c-1", "c-2"] + result = ( + r.db("some_db").table("things").map(lambda t: t["values"]["c"]).run(conn) + ) assertEqUnordered(expected, list(result)) @@ -173,58 +165,67 @@ class TestHasFields(MockTest): @staticmethod def get_data(): people = [ - {'id': 'joe', 'first_name': 'Joe', 'age': 26}, - {'id': 'todd', 'first_name': 'Todd', 'last_name': 'Last', 'age': 35}, - {'id': 'phil', 'first_name': 'Phil', 'last_name': 'LastPhil'}, - {'id': 'sam', 'first_name': 'Sam', 'last_name': 'SamLast', 'age': 31} - + {"id": "joe", "first_name": "Joe", "age": 26}, + {"id": "todd", "first_name": "Todd", "last_name": "Last", "age": 35}, + {"id": "phil", "first_name": "Phil", "last_name": "LastPhil"}, + {"id": "sam", "first_name": "Sam", "last_name": "SamLast", "age": 31}, ] - return as_db_and_table('x', 'people', people) + return as_db_and_table("x", "people", people) def test_has_fields_1(self, conn): expected = [ - {'id': 'todd', 'first_name': 'Todd', 'last_name': 'Last', 'age': 35}, - {'id': 'sam', 'first_name': 'Sam', 'last_name': 'SamLast', 'age': 31} + {"id": "todd", "first_name": "Todd", "last_name": "Last", "age": 35}, + {"id": "sam", "first_name": "Sam", "last_name": "SamLast", "age": 31}, ] - result = r.db('x').table('people').has_fields('last_name', 'age').run(conn) + result = r.db("x").table("people").has_fields("last_name", "age").run(conn) assertEqUnordered(expected, list(result)) def test_has_fields_array(self, conn): expected = [ - {'id': 'todd', 'first_name': 'Todd', 'last_name': 'Last', 'age': 35}, - {'id': 'sam', 'first_name': 'Sam', 'last_name': 'SamLast', 'age': 31} + {"id": "todd", "first_name": "Todd", "last_name": "Last", "age": 35}, + {"id": "sam", "first_name": "Sam", "last_name": "SamLast", "age": 31}, ] - result = r.db('x').table('people').has_fields(['last_name', 'age']).run(conn) + result = r.db("x").table("people").has_fields(["last_name", "age"]).run(conn) assertEqUnordered(expected, list(result)) class TestIsEmpty(MockTest): @staticmethod def get_data(): - data = [ - {'id': 'id-1', 'things': []}, - {'id': 'id-2', 'things': ['x', 'y']} - ] - return as_db_and_table('some_db', 'some_table', data) + data = [{"id": "id-1", "things": []}, {"id": "id-2", "things": ["x", "y"]}] + return as_db_and_table("some_db", "some_table", data) def test_is_empty_nested(self, conn): expected = [ - {'id': 'id-1', 'things_empty': True, 'things': []}, - {'id': 'id-2', 'things_empty': False, 'things': ['x', 'y']} + {"id": "id-1", "things_empty": True, "things": []}, + {"id": "id-2", "things_empty": False, "things": ["x", "y"]}, ] - result = r.db('some_db').table('some_table').map( - lambda d: d.merge({'things_empty': d['things'].is_empty()}) - ).run(conn) + result = ( + r.db("some_db") + .table("some_table") + .map(lambda d: d.merge({"things_empty": d["things"].is_empty()})) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_is_empty_toplevel_empty(self, conn): - result = r.db('some_db').table('some_table').filter({ - 'some_key': 'some-value' - }).is_empty().run(conn) + result = ( + r.db("some_db") + .table("some_table") + .filter({"some_key": "some-value"}) + .is_empty() + .run(conn) + ) assertEqual(True, result) def test_is_empty_toplevel_not_empty(self, conn): - result = r.db('some_db').table('some_table').has_fields('things').is_empty().run(conn) + result = ( + r.db("some_db") + .table("some_table") + .has_fields("things") + .is_empty() + .run(conn) + ) assertEqual(False, result) @@ -232,114 +233,92 @@ class TestDo(MockTest): @staticmethod def get_data(): data = [ - { - 'id': 'one', - 'name': 'One', - 'pets': ['dog', 'cat', 'bird'] - }, - { - 'id': 'two', - 'name': 'Two', - 'pets': ['fish', 'another fish'] - }, - { - 'id': 'three', - 'name': 'Three', - 'pets': ['toad', 'rabbit'] - } + {"id": "one", "name": "One", "pets": ["dog", "cat", "bird"]}, + {"id": "two", "name": "Two", "pets": ["fish", "another fish"]}, + {"id": "three", "name": "Three", "pets": ["toad", "rabbit"]}, ] - return as_db_and_table('generic', 'table', data) + return as_db_and_table("generic", "table", data) def test_do_simple_1(self, conn): - result = r.db('generic').table('table').get('one').do( - lambda d: d['name'] - ).run(conn) - assertEqual('One', result) + result = ( + r.db("generic").table("table").get("one").do(lambda d: d["name"]).run(conn) + ) + assertEqual("One", result) def test_do_simple_2(self, conn): result = r.do( - r.db('generic').table('table').get('two'), - lambda d: d['name'] + r.db("generic").table("table").get("two"), lambda d: d["name"] ).run(conn) - assertEqual('Two', result) + assertEqual("Two", result) def test_do_two(self, conn): - base = r.db('generic').table('table') + base = r.db("generic").table("table") result = r.do( - base.get('one'), base.get('two'), - lambda d1, d2: [d1['name'], d2['name']] + base.get("one"), base.get("two"), lambda d1, d2: [d1["name"], d2["name"]] ).run(conn) - assertEqual(['One', 'Two'], result) + assertEqual(["One", "Two"], result) def test_do_three(self, conn): - base = r.db('generic').table('table') + base = r.db("generic").table("table") result = r.do( - base.get('one'), - base.get('two'), - base.get('three'), - lambda d1, d2, d3: [d1['name'], d2['name'], d3['name']] + base.get("one"), + base.get("two"), + base.get("three"), + lambda d1, d2, d3: [d1["name"], d2["name"], d3["name"]], ).run(conn) - assertEqual(['One', 'Two', 'Three'], result) + assertEqual(["One", "Two", "Three"], result) class TestSets(MockTest): @staticmethod def get_data(): data = [ - { - 'id': 'one', - 'simple': ['x', 'y'], - 'complex': [{'val': 10}, {'val': 16}] - }, - { - 'id': 'two', - 'simple': ['x', 'z'], - 'complex': [{'val': 10}] - } + {"id": "one", "simple": ["x", "y"], "complex": [{"val": 10}, {"val": 16}]}, + {"id": "two", "simple": ["x", "z"], "complex": [{"val": 10}]}, ] - return as_db_and_table('z', 't', data) + return as_db_and_table("z", "t", data) def test_set_insert(self, conn): - expected = [ - set(['x', 'y']), - set(['x', 'y', 'z']) - ] - result = r.db('z').table('t').map( - lambda doc: doc['simple'].set_insert('y') - ).run(conn) + expected = [set(["x", "y"]), set(["x", "y", "z"])] + result = ( + r.db("z") + .table("t") + .map(lambda doc: doc["simple"].set_insert("y")) + .run(conn) + ) result = [set(d) for d in result] assertEqUnordered(expected, result) def test_set_union(self, conn): - expected = [ - set(['x', 'y', 'a']), - set(['x', 'y', 'z', 'a']) - ] - result = r.db('z').table('t').map( - lambda doc: doc['simple'].set_union(['y', 'a']) - ).run(conn) + expected = [set(["x", "y", "a"]), set(["x", "y", "z", "a"])] + result = ( + r.db("z") + .table("t") + .map(lambda doc: doc["simple"].set_union(["y", "a"])) + .run(conn) + ) result = [set(d) for d in result] assertEqUnordered(expected, result) def test_set_intersection(self, conn): - expected = [ - set(['x', 'y']), - set(['x']) - ] - result = r.db('z').table('t').map( - lambda doc: doc['simple'].set_intersection(['x', 'y']) - ).run(conn) + expected = [set(["x", "y"]), set(["x"])] + result = ( + r.db("z") + .table("t") + .map(lambda doc: doc["simple"].set_intersection(["x", "y"])) + .run(conn) + ) result = [set(d) for d in result] assertEqUnordered(expected, result) def test_set_difference(self, conn): - expected = [ - set(['x']), - set(['x', 'z']) - ] - result = r.db('z').table('t').map( - lambda doc: doc['simple'].set_difference(['y']) - ).run(conn) + expected = [set(["x"]), set(["x", "z"])] + result = ( + r.db("z") + .table("t") + .map(lambda doc: doc["simple"].set_difference(["y"])) + .run(conn) + ) result = list(result) result = [set(d) for d in result] assertEqUnordered(expected, result) @@ -350,62 +329,51 @@ class TestObjectManip(MockTest): def get_data(): data = [ { - 'id': 'joe', - 'attributes': { - 'face': 'bad', - 'toes': 'fugly' - }, - 'joe-attr': True + "id": "joe", + "attributes": {"face": "bad", "toes": "fugly"}, + "joe-attr": True, }, { - 'id': 'sam', - 'attributes': { - 'face': 'eh', - 'blog': 'dry' - }, - 'sam-attr': True - } + "id": "sam", + "attributes": {"face": "eh", "blog": "dry"}, + "sam-attr": True, + }, ] - return as_db_and_table('y', 'people', data) + return as_db_and_table("y", "people", data) def test_keys_document(self, conn): - result = list(r.db('y').table('people').map( - lambda d: d.keys() - ).run(conn)) + result = list(r.db("y").table("people").map(lambda d: d.keys()).run(conn)) assertEqual(3, len(result[0])) assertEqual(3, len(result[1])) key_set = set(util.cat(result[0], result[1])) - assertEqual(set(['id', 'attributes', 'joe-attr', 'sam-attr']), key_set) + assertEqual(set(["id", "attributes", "joe-attr", "sam-attr"]), key_set) def test_keys_nested(self, conn): - result = list(r.db('y').table('people').map( - lambda d: d['attributes'].keys() - ).run(conn)) + result = list( + r.db("y").table("people").map(lambda d: d["attributes"].keys()).run(conn) + ) assertEqual(2, len(result[0])) assertEqual(2, len(result[1])) key_set = set(util.cat(result[0], result[1])) - assertEqual(set(['face', 'toes', 'blog']), key_set) + assertEqual(set(["face", "toes", "blog"]), key_set) class TestJson(MockTest): @staticmethod def get_data(): - data = [ - {'id': 'one'}, - {'id': 'two'} - ] - return as_db_and_table('d', 't', data) + data = [{"id": "one"}, {"id": "two"}] + return as_db_and_table("d", "t", data) def test_update_with_json(self, conn): - expected = [ - {'id': 'one', 'nums': [1, 2, 3]}, - {'id': 'two', 'nums': [1, 2, 3]} - ] - result = r.db('d').table('t').map( - lambda doc: doc.merge(r.json('{"nums": [1, 2, 3]}')) - ).run(conn) + expected = [{"id": "one", "nums": [1, 2, 3]}, {"id": "two", "nums": [1, 2, 3]}] + result = ( + r.db("d") + .table("t") + .map(lambda doc: doc.merge(r.json('{"nums": [1, 2, 3]}'))) + .run(conn) + ) assertEqUnordered(expected, list(result)) @@ -413,49 +381,82 @@ class TestReduce(MockTest): @staticmethod def get_data(): data = [ - {'id': 'one', 'points': 10}, - {'id': 'two', 'points': 25}, - {'id': 'three', 'points': 100}, - {'id': 'four', 'points': 50}, - {'id': 'five', 'points': 6} + {"id": "one", "points": 10}, + {"id": "two", "points": 25}, + {"id": "three", "points": 100}, + {"id": "four", "points": 50}, + {"id": "five", "points": 6}, ] - return as_db_and_table('d', 'nums', data) + return as_db_and_table("d", "nums", data) def test_reduce_1(self, conn): expected = 191 - result = r.db('d').table('nums').map( - lambda doc: doc['points'] - ).reduce( - lambda elem, acc: elem + acc - ).run(conn) + result = ( + r.db("d") + .table("nums") + .map(lambda doc: doc["points"]) + .reduce(lambda elem, acc: elem + acc) + .run(conn) + ) + assertEqual(expected, result) + + def test_reduce_one(self, conn): + expected = {"count": 1} + result = ( + r.expr([{"count": 1}]) + .reduce( + lambda left, right: { + "count": left["count"] + right["count"], + } + ) + .run(conn) + ) assertEqual(expected, result) + def test_reduce_errors(self, conn): + err = None + try: + r.expr([]).reduce( + lambda left, right: { + "count": left["count"] + right["count"], + } + ).run(conn) + except ReqlNonExistenceError as e: + err = e + + assert isinstance(err, ReqlNonExistenceError) + class TestBranch(MockTest): @staticmethod def get_data(): data = [ - {'id': 'one', 'value': 5}, - {'id': 'three', 'value': 22}, - {'id': 'two', 'value': 12}, - {'id': 'four', 'value': 31} + {"id": "one", "value": 5}, + {"id": "three", "value": 22}, + {"id": "two", "value": 12}, + {"id": "four", "value": 31}, ] - return as_db_and_table('x', 't', data) + return as_db_and_table("x", "t", data) def test_branch_1(self, conn): expected = [ - {'id': 'one', 'value': 5, 'over_20': False}, - {'id': 'three', 'value': 22, 'over_20': True}, - {'id': 'two', 'value': 12, 'over_20': False}, - {'id': 'four', 'value': 31, 'over_20': True} + {"id": "one", "value": 5, "over_20": False}, + {"id": "three", "value": 22, "over_20": True}, + {"id": "two", "value": 12, "over_20": False}, + {"id": "four", "value": 31, "over_20": True}, ] - result = r.db('x').table('t').map( - r.branch( - r.row['value'] > 20, - r.row.merge({'over_20': True}), - r.row.merge({'over_20': False}) + result = ( + r.db("x") + .table("t") + .map( + r.branch( + r.row["value"] > 20, + r.row.merge({"over_20": True}), + r.row.merge({"over_20": False}), + ) ) - ).run(conn) + .run(conn) + ) result = list(result) assertEqUnordered(expected, list(result)) @@ -463,39 +464,32 @@ def test_branch_1(self, conn): class TestSync(MockTest): @staticmethod def get_data(): - data = [ - {'id': 'x', 'name': 'x-name'}, - {'id': 'y', 'name': 'y-name'} - ] - return as_db_and_table('d', 'things', data) + data = [{"id": "x", "name": "x-name"}, {"id": "y", "name": "y-name"}] + return as_db_and_table("d", "things", data) def test_sync(self, conn): expected = [ - {'id': 'x', 'name': 'x-name'}, - {'id': 'y', 'name': 'y-name'}, - {'id': 'z', 'name': 'z-name'} + {"id": "x", "name": "x-name"}, + {"id": "y", "name": "y-name"}, + {"id": "z", "name": "z-name"}, ] - r.db('d').table('things').insert( - {'id': 'z', 'name': 'z-name'} - ).run(conn) - r.db('d').table('things').sync().run(conn) - result = r.db('d').table('things').run(conn) + r.db("d").table("things").insert({"id": "z", "name": "z-name"}).run(conn) + r.db("d").table("things").sync().run(conn) + result = r.db("d").table("things").run(conn) assertEqUnordered(expected, list(result)) class TestError(MockTest): @staticmethod def get_data(): - data = [ - {'id': 'foo'} - ] - return as_db_and_table('db', 'fonz', data) + data = [{"id": "foo"}] + return as_db_and_table("db", "fonz", data) def test_error1(self, conn): try: - r.error('msg').run(conn) + r.error("msg").run(conn) except RqlRuntimeError as err: rql_err = err - assertEqual('msg', err.message) - assert (isinstance(rql_err, RqlRuntimeError)) + assertEqual("msg", err.message) + assert isinstance(rql_err, RqlRuntimeError) diff --git a/tests/functional/test_order_by.py b/tests/functional/test_order_by.py index 160a6be..e5157e9 100644 --- a/tests/functional/test_order_by.py +++ b/tests/functional/test_order_by.py @@ -8,75 +8,75 @@ class TestOrderByOne(MockTest): @staticmethod def get_data(): data = [ - {'id': 'bill', 'age': 35, 'score': 78}, - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'todd', 'age': 52, 'score': 15} + {"id": "bill", "age": 35, "score": 78}, + {"id": "joe", "age": 26, "score": 60}, + {"id": "todd", "age": 52, "score": 15}, ] - return as_db_and_table('y', 'scores', data) + return as_db_and_table("y", "scores", data) def test_sort_1_attr(self, conn): expected = [ - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'bill', 'age': 35, 'score': 78}, - {'id': 'todd', 'age': 52, 'score': 15} + {"id": "joe", "age": 26, "score": 60}, + {"id": "bill", "age": 35, "score": 78}, + {"id": "todd", "age": 52, "score": 15}, ] - result = r.db('y').table('scores').order_by('age').run(conn) + result = r.db("y").table("scores").order_by("age").run(conn) assertEqual(expected, list(result)) def test_sort_1_attr_asc(self, conn): expected = [ - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'bill', 'age': 35, 'score': 78}, - {'id': 'todd', 'age': 52, 'score': 15} + {"id": "joe", "age": 26, "score": 60}, + {"id": "bill", "age": 35, "score": 78}, + {"id": "todd", "age": 52, "score": 15}, ] - result = r.db('y').table('scores').order_by(r.asc('age')).run(conn) + result = r.db("y").table("scores").order_by(r.asc("age")).run(conn) assertEqual(expected, list(result)) def test_sort_1_attr_desc(self, conn): expected = [ - {'id': 'todd', 'age': 52, 'score': 15}, - {'id': 'bill', 'age': 35, 'score': 78}, - {'id': 'joe', 'age': 26, 'score': 60} + {"id": "todd", "age": 52, "score": 15}, + {"id": "bill", "age": 35, "score": 78}, + {"id": "joe", "age": 26, "score": 60}, ] - result = r.db('y').table('scores').order_by(r.desc('age')).run(conn) + result = r.db("y").table("scores").order_by(r.desc("age")).run(conn) assertEqual(expected, list(result)) def test_sort_1_attr_2(self, conn): expected = [ - {'id': 'todd', 'age': 52, 'score': 15}, - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'bill', 'age': 35, 'score': 78}, + {"id": "todd", "age": 52, "score": 15}, + {"id": "joe", "age": 26, "score": 60}, + {"id": "bill", "age": 35, "score": 78}, ] - result = r.db('y').table('scores').order_by('score').run(conn) + result = r.db("y").table("scores").order_by("score").run(conn) assertEqual(expected, list(result)) def test_sort_1_attr_2_asc(self, conn): expected = [ - {'id': 'todd', 'age': 52, 'score': 15}, - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'bill', 'age': 35, 'score': 78}, + {"id": "todd", "age": 52, "score": 15}, + {"id": "joe", "age": 26, "score": 60}, + {"id": "bill", "age": 35, "score": 78}, ] - result = r.db('y').table('scores').order_by(r.asc('score')).run(conn) + result = r.db("y").table("scores").order_by(r.asc("score")).run(conn) assertEqual(expected, list(result)) def test_sort_1_attr_2_desc(self, conn): expected = [ - {'id': 'bill', 'age': 35, 'score': 78}, - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'todd', 'age': 52, 'score': 15}, + {"id": "bill", "age": 35, "score": 78}, + {"id": "joe", "age": 26, "score": 60}, + {"id": "todd", "age": 52, "score": 15}, ] - result = r.db('y').table('scores').order_by(r.desc('score')).run(conn) + result = r.db("y").table("scores").order_by(r.desc("score")).run(conn) assertEqual(expected, list(result)) def test_sort_1_attr_2_asc_index(self, conn): - r.db('y').table('scores').index_create('score').run(conn) - r.db('y').table('scores').index_wait().run(conn) + r.db("y").table("scores").index_create("score").run(conn) + r.db("y").table("scores").index_wait().run(conn) expected = [ - {'id': 'todd', 'age': 52, 'score': 15}, - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'bill', 'age': 35, 'score': 78}, + {"id": "todd", "age": 52, "score": 15}, + {"id": "joe", "age": 26, "score": 60}, + {"id": "bill", "age": 35, "score": 78}, ] - result = r.db('y').table('scores').order_by(index='score').run(conn) + result = r.db("y").table("scores").order_by(index="score").run(conn) assertEqual(expected, list(result)) @@ -84,65 +84,69 @@ class TestOrderByMulti(MockTest): @staticmethod def get_data(): data = [ - {'id': 'bill', 'age': 35, 'score': 78}, - {'id': 'glen', 'age': 26, 'score': 15}, - {'id': 'todd', 'age': 52, 'score': 15}, - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'pale', 'age': 52, 'score': 30} + {"id": "bill", "age": 35, "score": 78}, + {"id": "glen", "age": 26, "score": 15}, + {"id": "todd", "age": 52, "score": 15}, + {"id": "joe", "age": 26, "score": 60}, + {"id": "pale", "age": 52, "score": 30}, ] - return as_db_and_table('y', 'scores', data) + return as_db_and_table("y", "scores", data) def test_sort_multi_1(self, conn): expected = [ - {'id': 'glen', 'age': 26, 'score': 15}, - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'bill', 'age': 35, 'score': 78}, - {'id': 'todd', 'age': 52, 'score': 15}, - {'id': 'pale', 'age': 52, 'score': 30} + {"id": "glen", "age": 26, "score": 15}, + {"id": "joe", "age": 26, "score": 60}, + {"id": "bill", "age": 35, "score": 78}, + {"id": "todd", "age": 52, "score": 15}, + {"id": "pale", "age": 52, "score": 30}, ] - result = r.db('y').table('scores').order_by('age', 'score').run(conn) + result = r.db("y").table("scores").order_by("age", "score").run(conn) assertEqual(expected, list(result)) def test_sort_multi_1_asc(self, conn): expected = [ - {'id': 'glen', 'age': 26, 'score': 15}, - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'bill', 'age': 35, 'score': 78}, - {'id': 'todd', 'age': 52, 'score': 15}, - {'id': 'pale', 'age': 52, 'score': 30} + {"id": "glen", "age": 26, "score": 15}, + {"id": "joe", "age": 26, "score": 60}, + {"id": "bill", "age": 35, "score": 78}, + {"id": "todd", "age": 52, "score": 15}, + {"id": "pale", "age": 52, "score": 30}, ] - result = r.db('y').table('scores').order_by(r.asc('age'), r.asc('score')).run(conn) + result = ( + r.db("y").table("scores").order_by(r.asc("age"), r.asc("score")).run(conn) + ) assertEqual(expected, list(result)) def test_sort_multi_1_desc_1(self, conn): expected = [ - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'glen', 'age': 26, 'score': 15}, - {'id': 'bill', 'age': 35, 'score': 78}, - {'id': 'pale', 'age': 52, 'score': 30}, - {'id': 'todd', 'age': 52, 'score': 15} + {"id": "joe", "age": 26, "score": 60}, + {"id": "glen", "age": 26, "score": 15}, + {"id": "bill", "age": 35, "score": 78}, + {"id": "pale", "age": 52, "score": 30}, + {"id": "todd", "age": 52, "score": 15}, ] - result = r.db('y').table('scores').order_by(r.asc('age'), r.desc('score')).run(conn) + result = ( + r.db("y").table("scores").order_by(r.asc("age"), r.desc("score")).run(conn) + ) assertEqual(expected, list(result)) def test_sort_multi_1_desc_2(self, conn): expected = [ - {'id': 'todd', 'age': 52, 'score': 15}, - {'id': 'pale', 'age': 52, 'score': 30}, - {'id': 'bill', 'age': 35, 'score': 78}, - {'id': 'glen', 'age': 26, 'score': 15}, - {'id': 'joe', 'age': 26, 'score': 60} + {"id": "todd", "age": 52, "score": 15}, + {"id": "pale", "age": 52, "score": 30}, + {"id": "bill", "age": 35, "score": 78}, + {"id": "glen", "age": 26, "score": 15}, + {"id": "joe", "age": 26, "score": 60}, ] - result = r.db('y').table('scores').order_by(r.desc('age'), 'score').run(conn) + result = r.db("y").table("scores").order_by(r.desc("age"), "score").run(conn) assertEqual(expected, list(result)) def test_sort_multi_2(self, conn): expected = [ - {'id': 'glen', 'age': 26, 'score': 15}, - {'id': 'todd', 'age': 52, 'score': 15}, - {'id': 'pale', 'age': 52, 'score': 30}, - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'bill', 'age': 35, 'score': 78} + {"id": "glen", "age": 26, "score": 15}, + {"id": "todd", "age": 52, "score": 15}, + {"id": "pale", "age": 52, "score": 30}, + {"id": "joe", "age": 26, "score": 60}, + {"id": "bill", "age": 35, "score": 78}, ] - result = r.db('y').table('scores').order_by('score', 'age').run(conn) + result = r.db("y").table("scores").order_by("score", "age").run(conn) assertEqual(expected, list(result)) diff --git a/tests/functional/test_pluck.py b/tests/functional/test_pluck.py index 3a00c45..7fba2ef 100644 --- a/tests/functional/test_pluck.py +++ b/tests/functional/test_pluck.py @@ -8,41 +8,43 @@ class TestPlucking(MockTest): @staticmethod def get_data(): data = [ - {'id': 'joe-id', 'name': 'joe', 'hobby': 'guitar'}, - {'id': 'bob-id', 'name': 'bob', 'hobby': 'pseudointellectualism'}, - {'id': 'bill-id', 'name': 'bill'}, - {'id': 'kimye-id', 'name': 'kimye', 'hobby': 'being kimye'} + {"id": "joe-id", "name": "joe", "hobby": "guitar"}, + {"id": "bob-id", "name": "bob", "hobby": "pseudointellectualism"}, + {"id": "bill-id", "name": "bill"}, + {"id": "kimye-id", "name": "kimye", "hobby": "being kimye"}, ] - return as_db_and_table('x', 'people', data) + return as_db_and_table("x", "people", data) def test_pluck_missing_attr(self, conn): expected = [ - {'id': 'joe-id', 'hobby': 'guitar'}, - {'id': 'bob-id', 'hobby': 'pseudointellectualism'}, - {'id': 'bill-id'}, - {'id': 'kimye-id', 'hobby': 'being kimye'} + {"id": "joe-id", "hobby": "guitar"}, + {"id": "bob-id", "hobby": "pseudointellectualism"}, + {"id": "bill-id"}, + {"id": "kimye-id", "hobby": "being kimye"}, ] - result = r.db('x').table('people').pluck('id', 'hobby').run(conn) + result = r.db("x").table("people").pluck("id", "hobby").run(conn) assertEqUnordered(expected, list(result)) def test_pluck_missing_attr_list(self, conn): expected = [ - {'id': 'joe-id', 'hobby': 'guitar'}, - {'id': 'bob-id', 'hobby': 'pseudointellectualism'}, - {'id': 'bill-id'}, - {'id': 'kimye-id', 'hobby': 'being kimye'} + {"id": "joe-id", "hobby": "guitar"}, + {"id": "bob-id", "hobby": "pseudointellectualism"}, + {"id": "bill-id"}, + {"id": "kimye-id", "hobby": "being kimye"}, ] - result = r.db('x').table('people').pluck(['id', 'hobby']).run(conn) + result = r.db("x").table("people").pluck(["id", "hobby"]).run(conn) assertEqUnordered(expected, list(result)) def test_sub_pluck(self, conn): expected = [ - {'id': 'joe-id', 'hobby': 'guitar'}, - {'id': 'bob-id', 'hobby': 'pseudointellectualism'}, - {'id': 'bill-id'}, - {'id': 'kimye-id', 'hobby': 'being kimye'} + {"id": "joe-id", "hobby": "guitar"}, + {"id": "bob-id", "hobby": "pseudointellectualism"}, + {"id": "bill-id"}, + {"id": "kimye-id", "hobby": "being kimye"}, ] - result = r.db('x').table('people').map(lambda p: p.pluck('id', 'hobby')).run(conn) + result = ( + r.db("x").table("people").map(lambda p: p.pluck("id", "hobby")).run(conn) + ) assertEqUnordered(expected, list(result)) @@ -51,62 +53,58 @@ class TestPlucking2(MockTest): def get_data(): data = [ { - 'id': 'thing-1', - 'values': { - 'a': 'a-1', - 'b': 'b-1', - 'c': 'c-1', - 'd': 'd-1' - } + "id": "thing-1", + "values": {"a": "a-1", "b": "b-1", "c": "c-1", "d": "d-1"}, }, { - 'id': 'thing-2', - 'values': { - 'a': 'a-2', - 'b': 'b-2', - 'c': 'c-2', - 'd': 'd-2' - } + "id": "thing-2", + "values": {"a": "a-2", "b": "b-2", "c": "c-2", "d": "d-2"}, }, ] - return as_db_and_table('some_db', 'things', data) + return as_db_and_table("some_db", "things", data) def test_sub_sub(self, conn): - expected = [ - {'a': 'a-1', 'd': 'd-1'}, - {'a': 'a-2', 'd': 'd-2'} - ] - result = r.db('some_db').table('things').map(lambda t: t['values'].pluck('a', 'd')).run(conn) + expected = [{"a": "a-1", "d": "d-1"}, {"a": "a-2", "d": "d-2"}] + result = ( + r.db("some_db") + .table("things") + .map(lambda t: t["values"].pluck("a", "d")) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_sub_sub_list(self, conn): - expected = [ - {'a': 'a-1', 'd': 'd-1'}, - {'a': 'a-2', 'd': 'd-2'} - ] - result = r.db('some_db').table('things').map(lambda t: t['values'].pluck('a', 'd')).run(conn) + expected = [{"a": "a-1", "d": "d-1"}, {"a": "a-2", "d": "d-2"}] + result = ( + r.db("some_db") + .table("things") + .map(lambda t: t["values"].pluck("a", "d")) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_sub_dict(self, conn): - expected = [ - {"values": {"a": "a-1"}}, - {"values": {"a": "a-2"}} - ] - result = r.db('some_db').table('things').pluck({'values': 'a'}).run(conn) + expected = [{"values": {"a": "a-1"}}, {"values": {"a": "a-2"}}] + result = r.db("some_db").table("things").pluck({"values": "a"}).run(conn) assertEqUnordered(expected, result) def test_sub_dict2(self, conn): expected = [ {"id": "thing-1", "values": {"a": "a-1"}}, - {"id": "thing-2", "values": {"a": "a-2"}} + {"id": "thing-2", "values": {"a": "a-2"}}, ] - result = r.db('some_db').table('things').pluck('id', {'values': 'a'}).run(conn) + result = r.db("some_db").table("things").pluck("id", {"values": "a"}).run(conn) assertEqUnordered(expected, result) def test_sub_dict_list(self, conn): expected = [ {"id": "thing-1", "values": {"a": "a-1", "b": "b-1"}}, - {"id": "thing-2", "values": {"a": "a-2", "b": "b-2"}} + {"id": "thing-2", "values": {"a": "a-2", "b": "b-2"}}, ] - result = r.db('some_db').table('things').pluck('id', {'values': ['a', 'b']}).run(conn) + result = ( + r.db("some_db") + .table("things") + .pluck("id", {"values": ["a", "b"]}) + .run(conn) + ) assertEqUnordered(expected, result) diff --git a/tests/functional/test_strings.py b/tests/functional/test_strings.py index 498400e..f150f63 100644 --- a/tests/functional/test_strings.py +++ b/tests/functional/test_strings.py @@ -9,74 +9,76 @@ class TestStrings(MockTest): @staticmethod def get_data(): data = [ - {'id': 'a', 'text': 'something with spaces'}, - {'id': 'b', 'text': 'some,csv,file'}, - {'id': 'c', 'text': 'someething'} + {"id": "a", "text": "something with spaces"}, + {"id": "b", "text": "some,csv,file"}, + {"id": "c", "text": "someething"}, ] - return as_db_and_table('library', 'texts', data) + return as_db_and_table("library", "texts", data) def test_upcase(self, conn): - expected = set([ - 'SOMETHING WITH SPACES', - 'SOME,CSV,FILE', - 'SOMEETHING' - ]) - result = r.db('library').table('texts').map( - lambda doc: doc['text'].upcase() - ).run(conn) + expected = set(["SOMETHING WITH SPACES", "SOME,CSV,FILE", "SOMEETHING"]) + result = ( + r.db("library") + .table("texts") + .map(lambda doc: doc["text"].upcase()) + .run(conn) + ) assertEqual(expected, set(list(result))) def test_downcase(self, conn): - expected = set([ - 'something with spaces', - 'some,csv,file', - 'someething' - ]) - result = r.db('library').table('texts').map( - lambda doc: doc['text'].downcase() - ).run(conn) + expected = set(["something with spaces", "some,csv,file", "someething"]) + result = ( + r.db("library") + .table("texts") + .map(lambda doc: doc["text"].downcase()) + .run(conn) + ) assertEqual(expected, set(list(result))) def test_split_1(self, conn): - expected = [ - ['something', 'with', 'spaces'], - ['some,csv,file'], - ['someething'] - ] - result = r.db('library').table('texts').map( - lambda doc: doc['text'].split() - ).run(conn) + expected = [["something", "with", "spaces"], ["some,csv,file"], ["someething"]] + result = ( + r.db("library") + .table("texts") + .map(lambda doc: doc["text"].split()) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_split_2(self, conn): - expected = [ - ['something with spaces'], - ['some', 'csv', 'file'], - ['someething'] - ] - result = r.db('library').table('texts').map( - lambda doc: doc['text'].split(',') - ).run(conn) + expected = [["something with spaces"], ["some", "csv", "file"], ["someething"]] + result = ( + r.db("library") + .table("texts") + .map(lambda doc: doc["text"].split(",")) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_split_3(self, conn): expected = [ - ['som', 'thing with spac', 's'], - ['som', ',csv,fil', ''], - ['som', '', 'thing'] + ["som", "thing with spac", "s"], + ["som", ",csv,fil", ""], + ["som", "", "thing"], ] - result = r.db('library').table('texts').map( - lambda doc: doc['text'].split('e') - ).run(conn) + result = ( + r.db("library") + .table("texts") + .map(lambda doc: doc["text"].split("e")) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_split_4(self, conn): expected = [ - ['som', 'thing with spaces'], - ['som', ',csv,file'], - ['som', 'ething'] + ["som", "thing with spaces"], + ["som", ",csv,file"], + ["som", "ething"], ] - result = r.db('library').table('texts').map( - lambda doc: doc['text'].split('e', 1) - ).run(conn) + result = ( + r.db("library") + .table("texts") + .map(lambda doc: doc["text"].split("e", 1)) + .run(conn) + ) assertEqUnordered(expected, list(result)) diff --git a/tests/functional/test_table_db_mod.py b/tests/functional/test_table_db_mod.py index e58a71a..004ce2e 100644 --- a/tests/functional/test_table_db_mod.py +++ b/tests/functional/test_table_db_mod.py @@ -7,70 +7,60 @@ class TestTableMod(MockTest): @staticmethod def get_data(): return { - 'dbs': { - 'db_one': { - 'tables': { - 'one_x': [], - 'one_y': [] - } - }, - 'db_two': { - 'tables': { - 'two_x': [], - 'two_y': [] - } - } + "dbs": { + "db_one": {"tables": {"one_x": [], "one_y": []}}, + "db_two": {"tables": {"two_x": [], "two_y": []}}, } } def test_table_list_1(self, conn): - expected = set(['one_x', 'one_y']) - result = r.db('db_one').table_list().run(conn) + expected = set(["one_x", "one_y"]) + result = r.db("db_one").table_list().run(conn) assertEqual(expected, set(list(result))) def test_table_list_2(self, conn): - expected = set(['two_x', 'two_y']) - result = r.db('db_two').table_list().run(conn) + expected = set(["two_x", "two_y"]) + result = r.db("db_two").table_list().run(conn) assertEqual(expected, set(list(result))) def test_table_create_1(self, conn): - expected_1 = set(['one_x', 'one_y', 'one_z']) - expected_2 = set(['two_x', 'two_y']) - r.db('db_one').table_create('one_z').run(conn) - result_1 = r.db('db_one').table_list().run(conn) + expected_1 = set(["one_x", "one_y", "one_z"]) + expected_2 = set(["two_x", "two_y"]) + r.db("db_one").table_create("one_z").run(conn) + result_1 = r.db("db_one").table_list().run(conn) assertEqual(expected_1, set(list(result_1))) - result_2 = r.db('db_two').table_list().run(conn) + result_2 = r.db("db_two").table_list().run(conn) assertEqual(expected_2, set(list(result_2))) def test_table_create_2(self, conn): - expected_1 = set(['one_x', 'one_y']) - expected_2 = set(['two_x', 'two_y', 'two_z']) - r.db('db_two').table_create('two_z').run(conn) - result_1 = r.db('db_one').table_list().run(conn) + expected_1 = set(["one_x", "one_y"]) + expected_2 = set(["two_x", "two_y", "two_z"]) + r.db("db_two").table_create("two_z").run(conn) + result_1 = r.db("db_one").table_list().run(conn) assertEqual(expected_1, set(list(result_1))) - result_2 = r.db('db_two').table_list().run(conn) + result_2 = r.db("db_two").table_list().run(conn) assertEqual(expected_2, set(list(result_2))) def test_table_drop_1(self, conn): - expected_1 = set(['one_x']) - expected_2 = set(['two_x', 'two_y']) - r.db('db_one').table_drop('one_y').run(conn) - result_1 = r.db('db_one').table_list().run(conn) + expected_1 = set(["one_x"]) + expected_2 = set(["two_x", "two_y"]) + r.db("db_one").table_drop("one_y").run(conn) + result_1 = r.db("db_one").table_list().run(conn) assertEqual(expected_1, set(list(result_1))) - result_2 = r.db('db_two').table_list().run(conn) + result_2 = r.db("db_two").table_list().run(conn) assertEqual(expected_2, set(list(result_2))) def test_table_drop_2(self, conn): - expected_1 = set(['one_x', 'one_y']) - expected_2 = set(['two_x']) - r.db('db_two').table_drop('two_y').run(conn) - result_1 = r.db('db_one').table_list().run(conn) + expected_1 = set(["one_x", "one_y"]) + expected_2 = set(["two_x"]) + r.db("db_two").table_drop("two_y").run(conn) + result_1 = r.db("db_one").table_list().run(conn) assertEqual(expected_1, set(list(result_1))) - result_2 = r.db('db_two').table_list().run(conn) + result_2 = r.db("db_two").table_list().run(conn) assertEqual(expected_2, set(list(result_2))) @@ -78,39 +68,69 @@ class TestDbMod(MockTest): @staticmethod def get_data(): return { - 'dbs': { - 'db_one': { - 'tables': { - 'one_x': [], - 'one_y': [] - } - }, - 'db_two': { - 'tables': { - 'two_x': [], - 'two_y': [] - } - } + "dbs": { + "db_one": {"tables": {"one_x": [], "one_y": []}}, + "db_two": {"tables": {"two_x": [], "two_y": []}}, } } def test_db_list(self, conn): - expected = set(['db_one', 'db_two']) + expected = set(["db_one", "db_two"]) result = self.db_list(conn) assertEqual(expected, result) def test_db_create(self, conn): - expected = set(['db_one', 'db_two', 'db_three']) - r.db_create('db_three').run(conn) + expected = set(["db_one", "db_two", "db_three"]) + r.db_create("db_three").run(conn) result = self.db_list(conn) assertEqual(expected, result) def test_db_drop(self, conn): - expected = set(['db_one']) - r.db_drop('db_two').run(conn) + expected = set(["db_one"]) + r.db_drop("db_two").run(conn) result = self.db_list(conn) assertEqual(expected, result) def db_list(self, conn): # rethinkdb is special and always present; we don't care, for these tests - return set(r.db_list().run(conn)) - {'rethinkdb'} + return set(r.db_list().run(conn)) - {"rethinkdb"} + + +class TestDbDefault(MockTest): + @staticmethod + def get_data(): + return { + "dbs": { + "db_one": { + "tables": { + "one_x": [ + { + "id": "x", + } + ], + "one_y": [{"id": "y", "one_x_id": "x", "content": "value"}], + } + }, + "db_two": {"tables": {"two_x": [], "two_y": []}}, + }, + "default": "db_one", + } + + def test_db_default(self, conn): + expected = {"id": "x"} + result = r.table("one_x").get("x").run(conn) + assertEqual(expected, result) + + def test_db_default_nested(self, conn): + expected = {"id": "x", "content": "value"} + result = ( + r.table("one_x") + .get("x") + .merge( + lambda doc: r.table("one_y") + .filter({"one_x_id": doc["id"]}) + .pluck(["content"])[0] + ) + .run(conn) + ) + assertEqual(expected, result) diff --git a/tests/functional/test_time.py b/tests/functional/test_time.py index f586677..b431971 100644 --- a/tests/functional/test_time.py +++ b/tests/functional/test_time.py @@ -16,81 +16,104 @@ class TestDateTimeGetters(MockTest): @staticmethod def get_data(): data = [ - {'id': 'joe', 'last_updated': rtime.make_time(2014, 6, 3, 12, 10, 32)}, - {'id': 'sam', 'last_updated': rtime.make_time(2014, 8, 25, 17, 3, 54)} + {"id": "joe", "last_updated": rtime.make_time(2014, 6, 3, 12, 10, 32)}, + {"id": "sam", "last_updated": rtime.make_time(2014, 8, 25, 17, 3, 54)}, ] - return as_db_and_table('d', 'people', data) + return as_db_and_table("d", "people", data) def test_year(self, conn): expected = [2014, 2014] - result = r.db('d').table('people').map( - lambda doc: doc['last_updated'].year() - ).run(conn) + result = ( + r.db("d") + .table("people") + .map(lambda doc: doc["last_updated"].year()) + .run(conn) + ) assertEqual(expected, list(result)) def test_month(self, conn): expected = set([6, 8]) - result = r.db('d').table('people').map( - lambda doc: doc['last_updated'].month() - ).run(conn) + result = ( + r.db("d") + .table("people") + .map(lambda doc: doc["last_updated"].month()) + .run(conn) + ) assertEqual(expected, set(list(result))) def test_day(self, conn): expected = set([3, 25]) - result = r.db('d').table('people').map( - lambda doc: doc['last_updated'].day() - ).run(conn) + result = ( + r.db("d") + .table("people") + .map(lambda doc: doc["last_updated"].day()) + .run(conn) + ) assertEqual(expected, set(list(result))) def test_hours(self, conn): expected = set([12, 17]) - result = r.db('d').table('people').map( - lambda doc: doc['last_updated'].hours() - ).run(conn) + result = ( + r.db("d") + .table("people") + .map(lambda doc: doc["last_updated"].hours()) + .run(conn) + ) assertEqual(expected, set(list(result))) def test_minutes(self, conn): expected = set([10, 3]) - result = r.db('d').table('people').map( - lambda doc: doc['last_updated'].minutes() - ).run(conn) + result = ( + r.db("d") + .table("people") + .map(lambda doc: doc["last_updated"].minutes()) + .run(conn) + ) assertEqual(expected, set(list(result))) def test_seconds(self, conn): expected = set([32, 54]) - result = r.db('d').table('people').map( - lambda doc: doc['last_updated'].seconds() - ).run(conn) + result = ( + r.db("d") + .table("people") + .map(lambda doc: doc["last_updated"].seconds()) + .run(conn) + ) assertEqual(expected, set(list(result))) def test_time_of_day(self, conn): - expected = set([ - ((((12 * 60) + 10) * 60) + 32), - ((((17 * 60) + 3) * 60) + 54) - ]) - result = r.db('d').table('people').map( - lambda doc: doc['last_updated'].time_of_day() - ).run(conn) + expected = set([((((12 * 60) + 10) * 60) + 32), ((((17 * 60) + 3) * 60) + 54)]) + result = ( + r.db("d") + .table("people") + .map(lambda doc: doc["last_updated"].time_of_day()) + .run(conn) + ) assertEqual(expected, set(list(result))) def test_day_of_week(self, conn): - expected = set([ - 1, # 2014 August 25 -> Monday - 2 # 2014 June 3 -> Tuesday - ]) - result = r.db('d').table('people').map( - lambda doc: doc['last_updated'].day_of_week() - ).run(conn) + expected = set([1, 2]) # 2014 August 25 -> Monday # 2014 June 3 -> Tuesday + result = ( + r.db("d") + .table("people") + .map(lambda doc: doc["last_updated"].day_of_week()) + .run(conn) + ) assertEqual(expected, set(list(result))) def test_date(self, conn): - expected = set([ - datetime.datetime(2014, 8, 25, tzinfo=r.make_timezone('00:00')), - datetime.datetime(2014, 6, 3, tzinfo=r.make_timezone('00:00')) - ]) - result = r.db('d').table('people').map( - lambda doc: doc['last_updated'].date() - ).run(conn) + expected = set( + [ + datetime.datetime(2014, 8, 25, tzinfo=r.make_timezone("00:00")), + datetime.datetime(2014, 6, 3, tzinfo=r.make_timezone("00:00")), + ] + ) + result = ( + r.db("d") + .table("people") + .map(lambda doc: doc["last_updated"].date()) + .run(conn) + ) assertEqual(expected, set(list(result))) @@ -98,181 +121,208 @@ class TestMoreTime(MockTest): @staticmethod def get_data(): data = [ - {'id': 'joe', 'last_updated': datetime.datetime(2014, 6, 3, 0, 0, 1, tzinfo=r.make_timezone('00:00'))}, - {'id': 'sam', 'last_updated': datetime.datetime(2014, 8, 25, 0, 0, 0, tzinfo=r.make_timezone('00:00'))} + { + "id": "joe", + "last_updated": datetime.datetime( + 2014, 6, 3, 0, 0, 1, tzinfo=r.make_timezone("00:00") + ), + }, + { + "id": "sam", + "last_updated": datetime.datetime( + 2014, 8, 25, 0, 0, 0, tzinfo=r.make_timezone("00:00") + ), + }, ] - return as_db_and_table('d', 'people', data) + return as_db_and_table("d", "people", data) def test_epoch_time(self, conn): - results = r.db('d').table('people').map( - lambda d: d.merge({'as_epoch': d['last_updated'].to_epoch_time()}) - ).run(conn) + results = ( + r.db("d") + .table("people") + .map(lambda d: d.merge({"as_epoch": d["last_updated"].to_epoch_time()})) + .run(conn) + ) results = list(results) - jan1 = datetime.datetime(1970, 1, 1, tzinfo=r.make_timezone('00:00')) + jan1 = datetime.datetime(1970, 1, 1, tzinfo=r.make_timezone("00:00")) for doc in results: - expected = int((doc['last_updated'] - jan1).total_seconds()) - assertEqual(expected, doc['as_epoch']) + expected = int((doc["last_updated"] - jan1).total_seconds()) + assertEqual(expected, doc["as_epoch"]) class TestTime(MockTest): @staticmethod def get_data(): data = [ - {'id': 'say_anything'}, + {"id": "say_anything"}, ] - return as_db_and_table('unimportant', 'very', data) + return as_db_and_table("unimportant", "very", data) def test_time_year_month_day_tz(self, conn): - r.db('unimportant').table('very').update( - lambda doc: doc.merge({'updated': r.time(2014, 6, 10, 'Z')}) + r.db("unimportant").table("very").update( + lambda doc: doc.merge({"updated": r.time(2014, 6, 10, "Z")}) ).run(conn) - result = r.db('unimportant').table('very').get('say_anything').run(conn) - update_time = result['updated'] + result = r.db("unimportant").table("very").get("say_anything").run(conn) + update_time = result["updated"] assertEqual(2014, update_time.year) assertEqual(6, update_time.month) assertEqual(10, update_time.day) - assert (isinstance(update_time.tzinfo, RqlTzinfo)) + assert isinstance(update_time.tzinfo, RqlTzinfo) def test_time_year_month_day_hour_minute_second_tz(self, conn): - r.db('unimportant').table('very').update({ - 'updated': r.time(2014, 6, 10, 15, 30, 45, 'Z') - }).run(conn) + r.db("unimportant").table("very").update( + {"updated": r.time(2014, 6, 10, 15, 30, 45, "Z")} + ).run(conn) - result = r.db('unimportant').table('very').get('say_anything').run(conn) - update_time = result['updated'] + result = r.db("unimportant").table("very").get("say_anything").run(conn) + update_time = result["updated"] assertEqual(2014, update_time.year) assertEqual(6, update_time.month) assertEqual(10, update_time.day) assertEqual(15, update_time.hour) assertEqual(30, update_time.minute) assertEqual(45, update_time.second) - assert (isinstance(update_time.tzinfo, RqlTzinfo)) + assert isinstance(update_time.tzinfo, RqlTzinfo) def test_error_with_less_than_4_args(self, conn): try: - r.db('unimportant').table('very').update({ - 'update_time': r.time(2014, 3, 24) - }).run(conn) + r.db("unimportant").table("very").update( + {"update_time": r.time(2014, 3, 24)} + ).run(conn) except RqlCompileError as e: err = e - assert ('expected between 4 and 7' in err.message.lower()) + assert "expected between 4 and 7" in err.message.lower() def test_error_with_no_timezone(self, conn): date = datetime.datetime(2014, 3, 24, 12) try: - r.db('unimportant').table('very').update({ - 'update_time': date - }).run(conn) + r.db("unimportant").table("very").update({"update_time": date}).run(conn) except ReqlDriverCompileError as e: err = e - assert ('datetime' in err.message.lower()) - assert ('timezone' in err.message.lower()) + assert "datetime" in err.message.lower() + assert "timezone" in err.message.lower() class TestDuring(MockTest): @staticmethod def get_data(): data = [ - {'id': 'joe', 'last_updated': r.time(2014, 6, 3, 'Z')}, - {'id': 'sam', 'last_updated': r.time(2014, 8, 25, 'Z')} + {"id": "joe", "last_updated": r.time(2014, 6, 3, "Z")}, + {"id": "sam", "last_updated": r.time(2014, 8, 25, "Z")}, ] - return as_db_and_table('d', 'people', data) + return as_db_and_table("d", "people", data) def test_during_1(self, conn): - expected = [ - {'id': 'joe', 'is_during': False}, - {'id': 'sam', 'is_during': True} - ] - result = r.db('d').table('people').map( - lambda doc: { - 'id': doc['id'], - 'is_during': doc['last_updated'].during(r.time(2014, 7, 10, 'Z'), r.time(2014, 12, 1, 'Z')) - } - ).run(conn) + expected = [{"id": "joe", "is_during": False}, {"id": "sam", "is_during": True}] + result = ( + r.db("d") + .table("people") + .map( + lambda doc: { + "id": doc["id"], + "is_during": doc["last_updated"].during( + r.time(2014, 7, 10, "Z"), r.time(2014, 12, 1, "Z") + ), + } + ) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_during_2(self, conn): - expected = [ - {'id': 'joe', 'is_during': True}, - {'id': 'sam', 'is_during': False} - ] - result = r.db('d').table('people').map( - lambda doc: { - 'id': doc['id'], - 'is_during': doc['last_updated'].during( - r.time(2014, 5, 10, 'Z'), - r.time(2014, 7, 1, 'Z') - ) - } - ).run(conn) + expected = [{"id": "joe", "is_during": True}, {"id": "sam", "is_during": False}] + result = ( + r.db("d") + .table("people") + .map( + lambda doc: { + "id": doc["id"], + "is_during": doc["last_updated"].during( + r.time(2014, 5, 10, "Z"), r.time(2014, 7, 1, "Z") + ), + } + ) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_during_3(self, conn): - expected = [ - {'id': 'joe', 'is_during': True}, - {'id': 'sam', 'is_during': False} - ] - result = r.db('d').table('people').map( - lambda doc: { - 'id': doc['id'], - 'is_during': doc['last_updated'].during( - r.time(2014, 6, 3, 'Z'), - r.time(2014, 8, 25, 'Z') - ) - } - ).run(conn) + expected = [{"id": "joe", "is_during": True}, {"id": "sam", "is_during": False}] + result = ( + r.db("d") + .table("people") + .map( + lambda doc: { + "id": doc["id"], + "is_during": doc["last_updated"].during( + r.time(2014, 6, 3, "Z"), r.time(2014, 8, 25, "Z") + ), + } + ) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_during_closed_right(self, conn): - expected = [ - {'id': 'joe', 'is_during': True} - ] - result = r.db('d').table('people').map( - lambda doc: { - 'id': doc['id'], - 'is_during': doc['last_updated'].during( - r.time(2014, 6, 2, 'Z'), - r.time(2014, 8, 25, 'Z'), - right_bound='closed' - ) - } - ).run(conn) + expected = [{"id": "joe", "is_during": True}] + result = ( + r.db("d") + .table("people") + .map( + lambda doc: { + "id": doc["id"], + "is_during": doc["last_updated"].during( + r.time(2014, 6, 2, "Z"), + r.time(2014, 8, 25, "Z"), + right_bound="closed", + ), + } + ) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_during_open_left(self, conn): expected = [ - {'id': 'joe', 'is_during': False}, - {'id': 'sam', 'is_during': False} + {"id": "joe", "is_during": False}, + {"id": "sam", "is_during": False}, ] - result = r.db('d').table('people').map( - lambda doc: { - 'id': doc['id'], - 'is_during': doc['last_updated'].during( - r.time(2014, 6, 3, 'Z'), - r.time(2014, 8, 25, 'Z'), - left_bound='open' - ) - } - ).run(conn) + result = ( + r.db("d") + .table("people") + .map( + lambda doc: { + "id": doc["id"], + "is_during": doc["last_updated"].during( + r.time(2014, 6, 3, "Z"), + r.time(2014, 8, 25, "Z"), + left_bound="open", + ), + } + ) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_during_open_left_closed_right(self, conn): - expected = [ - {'id': 'joe', 'is_during': False}, - {'id': 'sam', 'is_during': True} - ] - result = r.db('d').table('people').map( - lambda doc: { - 'id': doc['id'], - 'is_during': doc['last_updated'].during( - r.time(2014, 6, 3, 'Z'), - r.time(2014, 8, 25, 'Z'), - left_bound='open', - right_bound='closed' - ) - } - ).run(conn) + expected = [{"id": "joe", "is_during": False}, {"id": "sam", "is_during": True}] + result = ( + r.db("d") + .table("people") + .map( + lambda doc: { + "id": doc["id"], + "is_during": doc["last_updated"].during( + r.time(2014, 6, 3, "Z"), + r.time(2014, 8, 25, "Z"), + left_bound="open", + right_bound="closed", + ), + } + ) + .run(conn) + ) assertEqUnordered(expected, list(result)) @@ -280,19 +330,18 @@ class TestDuring2(MockTest): @staticmethod def get_data(): data = [ - {'id': 'joe', 'last_updated': rtime.make_time(2014, 6, 3)}, - {'id': 'sam', 'last_updated': rtime.make_time(2014, 7, 25)}, - {'id': 'bob', 'last_updated': rtime.make_time(2014, 6, 17)}, - {'id': 'sam', 'last_updated': rtime.make_time(2014, 5, 1)} + {"id": "joe", "last_updated": rtime.make_time(2014, 6, 3)}, + {"id": "sam", "last_updated": rtime.make_time(2014, 7, 25)}, + {"id": "bob", "last_updated": rtime.make_time(2014, 6, 17)}, + {"id": "sam", "last_updated": rtime.make_time(2014, 5, 1)}, ] - return as_db_and_table('d', 'people', data) + return as_db_and_table("d", "people", data) def test_filter_during(self, conn): - table = r.db('d').table('people') + table = r.db("d").table("people") result = table.filter( - lambda doc: doc['last_updated'].during( - r.time(2014, 6, 1, 'Z'), - r.time(2014, 6, 30, 'Z') + lambda doc: doc["last_updated"].during( + r.time(2014, 6, 1, "Z"), r.time(2014, 6, 30, "Z") ) ).run(conn) result = list(result) @@ -303,14 +352,14 @@ class TestTimeComparison(MockTest): @staticmethod def get_data(): data = [ - {'id': 'joe', 'last_updated': rtime.make_time(2019, 6, 2)}, - {'id': 'sam', 'last_updated': rtime.make_time(2020, 6, 3)}, - {'id': 'mia', 'last_updated': rtime.make_time(2030, 6, 3)} + {"id": "joe", "last_updated": rtime.make_time(2019, 6, 2)}, + {"id": "sam", "last_updated": rtime.make_time(2020, 6, 3)}, + {"id": "mia", "last_updated": rtime.make_time(2030, 6, 3)}, ] - return as_db_and_table('d', 'people', data) + return as_db_and_table("d", "people", data) def test_filter_older_than_now(self, conn): - table = r.db('d').table('people') + table = r.db("d").table("people") old = r.row["last_updated"] <= r.now() result = table.filter(old).run(conn) @@ -318,7 +367,7 @@ def test_filter_older_than_now(self, conn): assertEqual(2, len(result)) def test_filter_newer_than_now(self, conn): - table = r.db('d').table('people') + table = r.db("d").table("people") new = r.row["last_updated"] >= r.now() result = table.filter(new).run(conn) @@ -330,29 +379,29 @@ class TestTimeCalculation(MockTest): @staticmethod def get_data(): data = [ - {'id': 'present', 'last_updated': rtime.now()}, # Present - {'id': 'past', 'last_updated': rtime.make_time(2020, 6, 3)}, # Past - {'id': 'future', 'last_updated': rtime.make_time(2030, 6, 3)} # Future + {"id": "present", "last_updated": rtime.now()}, # Present + {"id": "past", "last_updated": rtime.make_time(2020, 6, 3)}, # Past + {"id": "future", "last_updated": rtime.make_time(2030, 6, 3)}, # Future ] - return as_db_and_table('d', 'people', data) + return as_db_and_table("d", "people", data) def test_subtract_seconds(self, conn): """ Find entries older than 3 hours """ - table = r.db('d').table('people') + table = r.db("d").table("people") three_hours = 10_800 old = r.row["last_updated"].lt(r.now().sub(three_hours)) result = table.filter(old).run(conn) result = list(result) - assertEqual("past", result[0]['id']) + assertEqual("past", result[0]["id"]) def test_add_seconds(self, conn): """ Find entries from 3 hours ago to now """ - table = r.db('d').table('people') + table = r.db("d").table("people") three_hours = 10_800 old = r.row["last_updated"].lt(r.now().add(three_hours)) diff --git a/tests/functional/test_typeof_coerce.py b/tests/functional/test_typeof_coerce.py index 2e843f9..837f47a 100644 --- a/tests/functional/test_typeof_coerce.py +++ b/tests/functional/test_typeof_coerce.py @@ -9,55 +9,73 @@ class TestTypeOf(MockTest): def get_data(): data = [ { - 'id': 'one', - 'null_attr': None, - 'list_attr': [5], - 'dict_attr': {'x': 10}, - 'bool_attr': True, - 'num_attr': 3.2, - 'str_attr': 'text' + "id": "one", + "null_attr": None, + "list_attr": [5], + "dict_attr": {"x": 10}, + "bool_attr": True, + "num_attr": 3.2, + "str_attr": "text", } ] - return as_db_and_table('a_db', 'types', data) + return as_db_and_table("a_db", "types", data) def test_null(self, conn): - expected = ['NULL'] - result = r.db('a_db').table('types').map( - lambda doc: doc['null_attr'].type_of() - ).run(conn) + expected = ["NULL"] + result = ( + r.db("a_db") + .table("types") + .map(lambda doc: doc["null_attr"].type_of()) + .run(conn) + ) assertEqual(expected, list(result)) def test_num(self, conn): - expected = ['NUMBER'] - result = r.db('a_db').table('types').map( - lambda doc: doc['num_attr'].type_of() - ).run(conn) + expected = ["NUMBER"] + result = ( + r.db("a_db") + .table("types") + .map(lambda doc: doc["num_attr"].type_of()) + .run(conn) + ) assertEqual(expected, list(result)) def test_obj(self, conn): - expected = ['OBJECT'] - result = r.db('a_db').table('types').map( - lambda doc: doc['dict_attr'].type_of() - ).run(conn) + expected = ["OBJECT"] + result = ( + r.db("a_db") + .table("types") + .map(lambda doc: doc["dict_attr"].type_of()) + .run(conn) + ) assertEqual(expected, list(result)) def test_bool(self, conn): - expected = ['BOOL'] - result = r.db('a_db').table('types').map( - lambda doc: doc['bool_attr'].type_of() - ).run(conn) + expected = ["BOOL"] + result = ( + r.db("a_db") + .table("types") + .map(lambda doc: doc["bool_attr"].type_of()) + .run(conn) + ) assertEqual(expected, list(result)) def test_array(self, conn): - expected = ['ARRAY'] - result = r.db('a_db').table('types').map( - lambda doc: doc['list_attr'].type_of() - ).run(conn) + expected = ["ARRAY"] + result = ( + r.db("a_db") + .table("types") + .map(lambda doc: doc["list_attr"].type_of()) + .run(conn) + ) assertEqual(expected, list(result)) def test_string(self, conn): - expected = ['STRING'] - result = r.db('a_db').table('types').map( - lambda doc: doc['str_attr'].type_of() - ).run(conn) + expected = ["STRING"] + result = ( + r.db("a_db") + .table("types") + .map(lambda doc: doc["str_attr"].type_of()) + .run(conn) + ) assertEqual(expected, list(result)) diff --git a/tests/functional/test_update_insert_delete.py b/tests/functional/test_update_insert_delete.py index b104bda..bdb4d02 100644 --- a/tests/functional/test_update_insert_delete.py +++ b/tests/functional/test_update_insert_delete.py @@ -14,38 +14,42 @@ class TestReplace(MockTest): @staticmethod def get_data(): data = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'} + {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, ] - return as_db_and_table('things', 'muppets', data) + return as_db_and_table("things", "muppets", data) def test_replace_selected(self, conn): expected = [ - {'id': 'kermit-id', 'name': 'Just Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'} + {"id": "kermit-id", "name": "Just Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, ] - r.db('things').table('muppets').get('kermit-id').replace({'id': 'kermit-id', 'name': 'Just Kermit'}).run(conn) - result = r.db('things').table('muppets').run(conn) + r.db("things").table("muppets").get("kermit-id").replace( + {"id": "kermit-id", "name": "Just Kermit"} + ).run(conn) + result = r.db("things").table("muppets").run(conn) assertEqUnordered(expected, result) def test_replace_one_from_table(self, conn): expected = [ - {'id': 'kermit-id', 'name': 'Just Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'} + {"id": "kermit-id", "name": "Just Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, ] - r.db('things').table('muppets').replace({'id': 'kermit-id', 'name': 'Just Kermit'}).run(conn) - result = r.db('things').table('muppets').run(conn) + r.db("things").table("muppets").replace( + {"id": "kermit-id", "name": "Just Kermit"} + ).run(conn) + result = r.db("things").table("muppets").run(conn) assertEqUnordered(expected, result) def test_replace_one_from_sequence(self, conn): expected = [ - {'id': 'kermit-id', 'name': 'Just Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'} + {"id": "kermit-id", "name": "Just Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, ] - r.db('things').table('muppets').filter( - lambda doc: True - ).replace({'id': 'kermit-id', 'name': 'Just Kermit'}).run(conn) - result = r.db('things').table('muppets').run(conn) + r.db("things").table("muppets").filter(lambda doc: True).replace( + {"id": "kermit-id", "name": "Just Kermit"} + ).run(conn) + result = r.db("things").table("muppets").run(conn) assertEqUnordered(expected, result) @@ -53,100 +57,77 @@ class TestInsert(MockTest): @staticmethod def get_data(): data = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'} + {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, ] - return as_db_and_table('things', 'muppets', data) + return as_db_and_table("things", "muppets", data) def test_insert_one(self, conn): expected = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'}, - {'id': 'elmo-id', 'species': 'methhead', 'name': 'Elmo'} - ] - r.db('things').table('muppets').insert({ - 'id': 'elmo-id', - 'species': 'methhead', - 'name': 'Elmo' - }).run(conn) - result = r.db('things').table('muppets').run(conn) + {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, + {"id": "elmo-id", "species": "methhead", "name": "Elmo"}, + ] + r.db("things").table("muppets").insert( + {"id": "elmo-id", "species": "methhead", "name": "Elmo"} + ).run(conn) + result = r.db("things").table("muppets").run(conn) assertEqUnordered(expected, list(result)) def test_insert_array(self, conn): expected = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'}, - {'id': 'elmo-id', 'species': 'methhead', 'name': 'Elmo'}, - {'id': 'fonz-id', 'species': 'guido', 'name': 'The Fonz'} - ] - r.db('things').table('muppets').insert([ - { - 'id': 'elmo-id', - 'species': 'methhead', - 'name': 'Elmo' - }, - { - 'id': 'fonz-id', - 'species': 'guido', - 'name': 'The Fonz' - } - ]).run(conn) - result = r.db('things').table('muppets').run(conn) + {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, + {"id": "elmo-id", "species": "methhead", "name": "Elmo"}, + {"id": "fonz-id", "species": "guido", "name": "The Fonz"}, + ] + r.db("things").table("muppets").insert( + [ + {"id": "elmo-id", "species": "methhead", "name": "Elmo"}, + {"id": "fonz-id", "species": "guido", "name": "The Fonz"}, + ] + ).run(conn) + result = r.db("things").table("muppets").run(conn) assertEqUnordered(expected, list(result)) def test_insert_one_no_id(self, conn): - r.db('things').table('muppets').insert({ - 'name': 'joe' - }).run(conn) - result = r.db('things').table('muppets').filter({ - 'name': 'joe' - }).run(conn) + r.db("things").table("muppets").insert({"name": "joe"}).run(conn) + result = r.db("things").table("muppets").filter({"name": "joe"}).run(conn) result = list(result) assertEqual(1, len(result)) joe = result[0] - assert (isinstance(joe['id'], text_type)) + assert isinstance(joe["id"], text_type) def test_insert_array_no_ids(self, conn): - r.db('things').table('muppets').insert([ - { - 'name': 'joe', - 'wanted': True - }, - { - 'name': 'todd', - 'wanted': True - } - ]).run(conn) - result = r.db('things').table('muppets').filter({ - 'wanted': True - }).run(conn) + r.db("things").table("muppets").insert( + [{"name": "joe", "wanted": True}, {"name": "todd", "wanted": True}] + ).run(conn) + result = r.db("things").table("muppets").filter({"wanted": True}).run(conn) result = list(result) assertEqual(2, len(result)) - assert (isinstance(result[0]['id'], text_type)) - assert (isinstance(result[1]['id'], text_type)) + assert isinstance(result[0]["id"], text_type) + assert isinstance(result[1]["id"], text_type) class TestInsertDurability(MockTest): @staticmethod def get_data(): data = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'} + {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, ] - return as_db_and_table('things', 'muppets', data) + return as_db_and_table("things", "muppets", data) def test_durability_does_nothing_for_mock_1(self, conn): expected = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'}, - {'id': 'elmo-id', 'species': 'methhead', 'name': 'Elmo'} - ] - r.db('things').table('muppets').insert({ - 'id': 'elmo-id', - 'species': 'methhead', - 'name': 'Elmo' - }, durability='hard').run(conn) - result = r.db('things').table('muppets').run(conn) + {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, + {"id": "elmo-id", "species": "methhead", "name": "Elmo"}, + ] + r.db("things").table("muppets").insert( + {"id": "elmo-id", "species": "methhead", "name": "Elmo"}, durability="hard" + ).run(conn) + result = r.db("things").table("muppets").run(conn) assertEqUnordered(expected, list(result)) # this isn't effectively testing the mock, since the point is that table.sync() doesn't do anything @@ -154,17 +135,15 @@ def test_durability_does_nothing_for_mock_1(self, conn): def test_durability_does_nothing_for_mock_2(self, conn): expected = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'}, - {'id': 'elmo-id', 'species': 'methhead', 'name': 'Elmo'} - ] - r.db('things').table('muppets').insert({ - 'id': 'elmo-id', - 'species': 'methhead', - 'name': 'Elmo' - }, durability='soft').run(conn) - r.db('things').table('muppets').sync().run(conn) - result = r.db('things').table('muppets').run(conn) + {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, + {"id": "elmo-id", "species": "methhead", "name": "Elmo"}, + ] + r.db("things").table("muppets").insert( + {"id": "elmo-id", "species": "methhead", "name": "Elmo"}, durability="soft" + ).run(conn) + r.db("things").table("muppets").sync().run(conn) + result = r.db("things").table("muppets").run(conn) assertEqUnordered(expected, list(result)) @@ -172,197 +151,192 @@ class TestInsertConflicts(MockTest): @staticmethod def get_data(): data = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'} + {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, ] - return as_db_and_table('things', 'muppets', data) + return as_db_and_table("things", "muppets", data) def test_conflict_error(self, conn): expected = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'}, + {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, ] # try to insert and assert that errors are raised - result_obj = r.db('things').table('muppets').insert({ - 'id': 'kermit-id', - }, conflict='error').run(conn) - assertEqual(1, result_obj['errors']) - assertEqual(0, result_obj['inserted']) - assertEqual(0, result_obj['replaced']) + result_obj = ( + r.db("things") + .table("muppets") + .insert( + { + "id": "kermit-id", + }, + conflict="error", + ) + .run(conn) + ) + assertEqual(1, result_obj["errors"]) + assertEqual(0, result_obj["inserted"]) + assertEqual(0, result_obj["replaced"]) # ensure the table really is unchanged. - result = r.db('things').table('muppets').run(conn) + result = r.db("things").table("muppets").run(conn) assertEqUnordered(expected, list(result)) def test_conflict_has_error_as_default(self, conn): expected = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'}, + {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, ] # try to insert and assert that errors are raised - result_obj = r.db('things').table('muppets').insert({ - 'id': 'kermit-id', - }, conflict='error').run(conn) - assertEqual(1, result_obj['errors']) - assertEqual(0, result_obj['inserted']) - assertEqual(0, result_obj['replaced']) + result_obj = ( + r.db("things") + .table("muppets") + .insert( + { + "id": "kermit-id", + }, + conflict="error", + ) + .run(conn) + ) + assertEqual(1, result_obj["errors"]) + assertEqual(0, result_obj["inserted"]) + assertEqual(0, result_obj["replaced"]) # ensure the table really is unchanged. - result = r.db('things').table('muppets').run(conn) + result = r.db("things").table("muppets").run(conn) assertEqUnordered(expected, list(result)) def test_conflict_replace(self, conn): expected = [ - {'id': 'kermit-id', 'x-key': 'x-val', 'name': 'New Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'}, - ] - - result_obj = r.db('things').table('muppets').insert({ - 'id': 'kermit-id', - 'x-key': 'x-val', - 'name': 'New Kermit' - }, conflict='replace').run(conn) - assertEqual(1, result_obj['replaced']) - assertEqual(0, result_obj['inserted']) - assertEqual(0, result_obj['errors']) - - result = r.db('things').table('muppets').run(conn) + {"id": "kermit-id", "x-key": "x-val", "name": "New Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, + ] + + result_obj = ( + r.db("things") + .table("muppets") + .insert( + {"id": "kermit-id", "x-key": "x-val", "name": "New Kermit"}, + conflict="replace", + ) + .run(conn) + ) + assertEqual(1, result_obj["replaced"]) + assertEqual(0, result_obj["inserted"]) + assertEqual(0, result_obj["errors"]) + + result = r.db("things").table("muppets").run(conn) assertEqUnordered(expected, list(result)) def test_conflict_update(self, conn): - result_obj = r.db('things').table('muppets').insert({ - 'id': 'kermit-id', - 'x-key': 'x-val', - 'name': 'Updated Kermit' - }, conflict='update').run(conn) - assertEqual(1, result_obj['replaced']) - assertEqual(0, result_obj['inserted']) - assertEqual(0, result_obj['errors']) + result_obj = ( + r.db("things") + .table("muppets") + .insert( + {"id": "kermit-id", "x-key": "x-val", "name": "Updated Kermit"}, + conflict="update", + ) + .run(conn) + ) + assertEqual(1, result_obj["replaced"]) + assertEqual(0, result_obj["inserted"]) + assertEqual(0, result_obj["errors"]) class TestInsertReturnChanges(MockTest): @staticmethod def get_data(): data = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'} + {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, ] - return as_db_and_table('things', 'muppets', data) + return as_db_and_table("things", "muppets", data) def test_insert_one(self, conn): expected = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'}, - {'id': 'elmo-id', 'species': 'methhead', 'name': 'Elmo'} + {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, + {"id": "elmo-id", "species": "methhead", "name": "Elmo"}, ] - elmo_doc = { - 'id': 'elmo-id', - 'species': 'methhead', - 'name': 'Elmo' - } - expected_changes = [{ - 'old_val': None, - 'new_val': elmo_doc - }] + elmo_doc = {"id": "elmo-id", "species": "methhead", "name": "Elmo"} + expected_changes = [{"old_val": None, "new_val": elmo_doc}] - result_obj = r.db('things').table('muppets').insert( - elmo_doc, return_changes=True - ).run(conn) + result_obj = ( + r.db("things") + .table("muppets") + .insert(elmo_doc, return_changes=True) + .run(conn) + ) - assertEqual(result_obj['changes'], expected_changes) + assertEqual(result_obj["changes"], expected_changes) - result = r.db('things').table('muppets').run(conn) + result = r.db("things").table("muppets").run(conn) assertEqUnordered(expected, list(result)) def test_insert_array(self, conn): expected = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'}, - {'id': 'elmo-id', 'species': 'methhead', 'name': 'Elmo'}, - {'id': 'fonz-id', 'species': 'guido', 'name': 'The Fonz'} + {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, + {"id": "elmo-id", "species": "methhead", "name": "Elmo"}, + {"id": "fonz-id", "species": "guido", "name": "The Fonz"}, ] to_insert = [ - { - 'id': 'elmo-id', - 'species': 'methhead', - 'name': 'Elmo' - }, - { - 'id': 'fonz-id', - 'species': 'guido', - 'name': 'The Fonz' - } + {"id": "elmo-id", "species": "methhead", "name": "Elmo"}, + {"id": "fonz-id", "species": "guido", "name": "The Fonz"}, ] expected_changes = [ - { - 'old_val': None, - 'new_val': to_insert[0] - }, - { - 'old_val': None, - 'new_val': to_insert[1] - } + {"old_val": None, "new_val": to_insert[0]}, + {"old_val": None, "new_val": to_insert[1]}, ] - result_obj = r.db('things').table('muppets').insert( - to_insert, return_changes=True - ).run(conn) + result_obj = ( + r.db("things") + .table("muppets") + .insert(to_insert, return_changes=True) + .run(conn) + ) - assertEqUnordered(expected_changes, result_obj['changes']) + assertEqUnordered(expected_changes, result_obj["changes"]) - result = r.db('things').table('muppets').run(conn) + result = r.db("things").table("muppets").run(conn) assertEqUnordered(expected, list(result)) def test_insert_array_with_update(self, conn): expected = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'New Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'}, - {'id': 'elmo-id', 'species': 'methhead', 'name': 'Elmo'}, - {'id': 'fonz-id', 'species': 'guido', 'name': 'The Fonz'} + {"id": "kermit-id", "species": "frog", "name": "New Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, + {"id": "elmo-id", "species": "methhead", "name": "Elmo"}, + {"id": "fonz-id", "species": "guido", "name": "The Fonz"}, ] to_insert = [ - { - 'id': 'elmo-id', - 'species': 'methhead', - 'name': 'Elmo' - }, - { - 'id': 'fonz-id', - 'species': 'guido', - 'name': 'The Fonz' - }, - { - 'id': 'kermit-id', - 'name': 'New Kermit' - } + {"id": "elmo-id", "species": "methhead", "name": "Elmo"}, + {"id": "fonz-id", "species": "guido", "name": "The Fonz"}, + {"id": "kermit-id", "name": "New Kermit"}, ] expected_changes = [ { - 'old_val': {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - 'new_val': {'id': 'kermit-id', 'species': 'frog', 'name': 'New Kermit'} + "old_val": {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + "new_val": {"id": "kermit-id", "species": "frog", "name": "New Kermit"}, }, - { - 'old_val': None, - 'new_val': to_insert[0] - }, - { - 'old_val': None, - 'new_val': to_insert[1] - } + {"old_val": None, "new_val": to_insert[0]}, + {"old_val": None, "new_val": to_insert[1]}, ] - result_obj = r.db('things').table('muppets').insert( - to_insert, return_changes=True, conflict='update' - ).run(conn) + result_obj = ( + r.db("things") + .table("muppets") + .insert(to_insert, return_changes=True, conflict="update") + .run(conn) + ) - assertEqUnordered(expected_changes, result_obj['changes']) + assertEqUnordered(expected_changes, result_obj["changes"]) - result = r.db('things').table('muppets').run(conn) + result = r.db("things").table("muppets").run(conn) assertEqUnordered(expected, list(result)) @@ -370,24 +344,36 @@ class TestUpdate(MockTest): @staticmethod def get_data(): data = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'} + {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, ] - return as_db_and_table('things', 'muppets', data) + return as_db_and_table("things", "muppets", data) def test_update_one(self, conn): - expected = {'id': 'kermit-id', 'species': 'green frog', 'name': 'Kermit'} - r.db('things').table('muppets').get('kermit-id').update({'species': 'green frog'}).run(conn) - result = r.db('things').table('muppets').get('kermit-id').run(conn) + expected = {"id": "kermit-id", "species": "green frog", "name": "Kermit"} + r.db("things").table("muppets").get("kermit-id").update( + {"species": "green frog"} + ).run(conn) + result = r.db("things").table("muppets").get("kermit-id").run(conn) assertEqual(expected, result) def test_update_sequence(self, conn): expected = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit', 'is_muppet': 'very'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy', 'is_muppet': 'very'} + { + "id": "kermit-id", + "species": "frog", + "name": "Kermit", + "is_muppet": "very", + }, + { + "id": "piggy-id", + "species": "pig", + "name": "Ms. Piggy", + "is_muppet": "very", + }, ] - r.db('things').table('muppets').update({'is_muppet': 'very'}).run(conn) - result = r.db('things').table('muppets').run(conn) + r.db("things").table("muppets").update({"is_muppet": "very"}).run(conn) + result = r.db("things").table("muppets").run(conn) assertEqual(expected, list(result)) @@ -395,104 +381,145 @@ class TestUpdateNestedQuery(MockTest): @staticmethod def get_data(): data = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'} + {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, ] - return as_db_and_table('things', 'muppets', data) + return as_db_and_table("things", "muppets", data) def test_update_nonatomic_happy(self, conn): expected = { - 'id': 'kermit-id', - 'species': 'pig', - 'name': 'Kermit', + "id": "kermit-id", + "species": "pig", + "name": "Kermit", } - r.db('things').table('muppets').get('kermit-id').update( - lambda doc: doc.merge(r.db('things').table('muppets').get('piggy-id').pluck('species')), - non_atomic=True + r.db("things").table("muppets").get("kermit-id").update( + lambda doc: doc.merge( + r.db("things").table("muppets").get("piggy-id").pluck("species") + ), + non_atomic=True, ).run(conn) - result = r.db('things').table('muppets').get('kermit-id').run(conn) + result = r.db("things").table("muppets").get("kermit-id").run(conn) assertEqual(expected, result) def test_update_nonatomic_error(self, conn): err = None try: - r.db('things').table('muppets').get('kermit-id').update( - lambda doc: doc.merge(r.db('things').table('muppets').get('piggy-id').pluck('species')), - non_atomic=False + r.db("things").table("muppets").get("kermit-id").update( + lambda doc: doc.merge( + r.db("things").table("muppets").get("piggy-id").pluck("species") + ), + non_atomic=False, ).run(conn) except RqlRuntimeError as e: err = e - assert (isinstance(err, RqlRuntimeError)) + assert isinstance(err, RqlRuntimeError) def test_update_nonatomic_error_is_default(self, conn): err = None try: - r.db('things').table('muppets').get('kermit-id').update( - lambda doc: doc.merge(r.db('things').table('muppets').get('piggy-id').pluck('species')) + r.db("things").table("muppets").get("kermit-id").update( + lambda doc: doc.merge( + r.db("things").table("muppets").get("piggy-id").pluck("species") + ) ).run(conn) except RqlRuntimeError as e: err = e - assert (isinstance(err, RqlRuntimeError)) + assert isinstance(err, RqlRuntimeError) class TestUpdateReturnChanges(MockTest): @staticmethod def get_data(): data = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'} + {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, ] - return as_db_and_table('things', 'muppets', data) + return as_db_and_table("things", "muppets", data) def test_update_one(self, conn): - expected = {'id': 'kermit-id', 'species': 'frog', 'name': 'New Kermit', 'new_key': 'new_key_val'} - expected_changes = [{ - 'old_val': {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - 'new_val': { - 'id': 'kermit-id', - 'species': 'frog', - 'name': 'New Kermit', - 'new_key': 'new_key_val' + expected = { + "id": "kermit-id", + "species": "frog", + "name": "New Kermit", + "new_key": "new_key_val", + } + expected_changes = [ + { + "old_val": {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + "new_val": { + "id": "kermit-id", + "species": "frog", + "name": "New Kermit", + "new_key": "new_key_val", + }, } - }] - - result_obj = r.db('things').table('muppets').get('kermit-id').update( - {'name': 'New Kermit', 'new_key': 'new_key_val'}, - return_changes=True - ).run(conn) + ] - assertEqual(expected_changes, result_obj['changes']) - assertEqual(1, result_obj['replaced']) - assertEqual(0, result_obj['inserted']) - result = r.db('things').table('muppets').get('kermit-id').run(conn) + result_obj = ( + r.db("things") + .table("muppets") + .get("kermit-id") + .update( + {"name": "New Kermit", "new_key": "new_key_val"}, return_changes=True + ) + .run(conn) + ) + + assertEqual(expected_changes, result_obj["changes"]) + assertEqual(1, result_obj["replaced"]) + assertEqual(0, result_obj["inserted"]) + result = r.db("things").table("muppets").get("kermit-id").run(conn) assertEqual(expected, result) def test_update_many(self, conn): expected = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit', 'new_key': 'new_key_val'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy', 'new_key': 'new_key_val'} + { + "id": "kermit-id", + "species": "frog", + "name": "Kermit", + "new_key": "new_key_val", + }, + { + "id": "piggy-id", + "species": "pig", + "name": "Ms. Piggy", + "new_key": "new_key_val", + }, ] expected_changes = [ { - 'old_val': {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - 'new_val': {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit', 'new_key': 'new_key_val'} + "old_val": {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + "new_val": { + "id": "kermit-id", + "species": "frog", + "name": "Kermit", + "new_key": "new_key_val", + }, }, { - 'old_val': {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'}, - 'new_val': {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy', 'new_key': 'new_key_val'} - } + "old_val": {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, + "new_val": { + "id": "piggy-id", + "species": "pig", + "name": "Ms. Piggy", + "new_key": "new_key_val", + }, + }, ] - result_obj = r.db('things').table('muppets').update({ - 'new_key': 'new_key_val' - }, return_changes=True).run(conn) + result_obj = ( + r.db("things") + .table("muppets") + .update({"new_key": "new_key_val"}, return_changes=True) + .run(conn) + ) - assertEqUnordered(expected_changes, result_obj['changes']) - assertEqual(2, result_obj['replaced']) - assertEqual(0, result_obj['inserted']) - assertEqual(0, result_obj['errors']) + assertEqUnordered(expected_changes, result_obj["changes"]) + assertEqual(2, result_obj["replaced"]) + assertEqual(0, result_obj["inserted"]) + assertEqual(0, result_obj["errors"]) - result = r.db('things').table('muppets').run(conn) + result = r.db("things").table("muppets").run(conn) assertEqUnordered(expected, list(result)) @@ -500,28 +527,28 @@ class TestUpdateRql(MockTest): @staticmethod def get_data(): data = [ - {'id': 'kermit-id', 'species': 'frog', 'name': 'Kermit'}, - {'id': 'piggy-id', 'species': 'pig', 'name': 'Ms. Piggy'} + {"id": "kermit-id", "species": "frog", "name": "Kermit"}, + {"id": "piggy-id", "species": "pig", "name": "Ms. Piggy"}, ] - return as_db_and_table('things', 'muppets', data) + return as_db_and_table("things", "muppets", data) def test_update_many(self, conn): expected = [ - {'id': 'kermit-id', 'species': 'unknown', 'name': 'Kermit'}, - {'id': 'piggy-id', 'species': 'unknown', 'name': 'Ms. Piggy'} + {"id": "kermit-id", "species": "unknown", "name": "Kermit"}, + {"id": "piggy-id", "species": "unknown", "name": "Ms. Piggy"}, ] - r.db('things').table('muppets').update( - r.row.merge({'species': 'unknown'}) - ).run(conn) - result = r.db('things').table('muppets').run(conn) + r.db("things").table("muppets").update(r.row.merge({"species": "unknown"})).run( + conn + ) + result = r.db("things").table("muppets").run(conn) assertEqUnordered(expected, list(result)) def test_update_one(self, conn): - expected = {'id': 'kermit-id', 'species': 'unknown', 'name': 'Kermit'} - r.db('things').table('muppets').get('kermit-id').update( - r.row.merge({'species': 'unknown'}) + expected = {"id": "kermit-id", "species": "unknown", "name": "Kermit"} + r.db("things").table("muppets").get("kermit-id").update( + r.row.merge({"species": "unknown"}) ).run(conn) - result = r.db('things').table('muppets').get('kermit-id').run(conn) + result = r.db("things").table("muppets").get("kermit-id").run(conn) assertEqual(expected, result) @@ -529,133 +556,75 @@ class TestNestedUpdateNotLit(MockTest): @staticmethod def get_data(): data = [ - { - 'id': 'one', - 'points': { - 'pt1': { - 'x': 'x-1', - 'y': 'y-1' - } - } - }, - { - 'id': 'two', - 'points': { - 'pt1': { - 'x': 'x-2', - 'y': 'y-2' - } - } - }, - { - 'id': 'three', - 'things': { - 'x': [1, 3, 5] - } - } + {"id": "one", "points": {"pt1": {"x": "x-1", "y": "y-1"}}}, + {"id": "two", "points": {"pt1": {"x": "x-2", "y": "y-2"}}}, + {"id": "three", "things": {"x": [1, 3, 5]}}, ] - return as_db_and_table('things', 'points', data) + return as_db_and_table("things", "points", data) def test_update_merge(self, conn): expected = { - 'id': 'one', - 'points': { - 'pt1': { - 'x': 'x-1', - 'y': 'y-1', - 'z': 'z-1' - } - } + "id": "one", + "points": {"pt1": {"x": "x-1", "y": "y-1", "z": "z-1"}}, } - r.db('things').table('points').filter({'id': 'one'}).update( - r.row.merge({'points': {'pt1': {'z': 'z-1'}}}) + r.db("things").table("points").filter({"id": "one"}).update( + r.row.merge({"points": {"pt1": {"z": "z-1"}}}) ).run(conn) - result = r.db('things').table('points').get('one').run(conn) + result = r.db("things").table("points").get("one").run(conn) assertEqual(expected, result) def test_update_no_merge(self, conn): expected = { - 'id': 'one', - 'points': { - 'pt1': { - 'x': 'x-1', - 'y': 'y-1', - 'z': 'z-1' - } - } + "id": "one", + "points": {"pt1": {"x": "x-1", "y": "y-1", "z": "z-1"}}, } - r.db('things').table('points').filter({'id': 'one'}).update( - {'points': {'pt1': {'z': 'z-1'}}} + r.db("things").table("points").filter({"id": "one"}).update( + {"points": {"pt1": {"z": "z-1"}}} ).run(conn) - result = r.db('things').table('points').get('one').run(conn) + result = r.db("things").table("points").get("one").run(conn) assertEqual(expected, result) def test_update_merge_deep(self, conn): # this behavior is pretty weird, but it's what rethink does expected = { - 'id': 'one', - 'points': { - 'pt1': { - 'x': 'x-1', - 'y': 'y-1' - } - }, - 'pt1': { - 'x': 'x-1', - 'y': 'y-1', - 'z': 'z-1' - } + "id": "one", + "points": {"pt1": {"x": "x-1", "y": "y-1"}}, + "pt1": {"x": "x-1", "y": "y-1", "z": "z-1"}, } - r.db('things').table('points').filter({'id': 'one'}).update( - r.row['points'].merge({'pt1': {'z': 'z-1'}}) + r.db("things").table("points").filter({"id": "one"}).update( + r.row["points"].merge({"pt1": {"z": "z-1"}}) ).run(conn) - result = r.db('things').table('points').get('one').run(conn) - pprint({'merge_deep': result}) + result = r.db("things").table("points").get("one").run(conn) + pprint({"merge_deep": result}) assertEqual(expected, result) def test_update_merge_array(self, conn): - expected = { - 'id': 'three', - 'things': { - 'x': [1, 3, 5, 7, 9] - } - } - r.db('things').table('points').filter({'id': 'three'}).update( - r.row.merge({'things': {'x': [7, 9]}}) + expected = {"id": "three", "things": {"x": [1, 3, 5, 7, 9]}} + r.db("things").table("points").filter({"id": "three"}).update( + r.row.merge({"things": {"x": [7, 9]}}) ).run(conn) - result = r.db('things').table('points').get('three').run(conn) + result = r.db("things").table("points").get("three").run(conn) pprint(result) assertEqUnordered(expected, result) def test_update_no_merge_array(self, conn): - expected = { - 'id': 'three', - 'things': { - 'x': [1, 3, 5, 7, 9] - } - } - r.db('things').table('points').filter({'id': 'three'}).update( - {'things': {'x': [7, 9]}} + expected = {"id": "three", "things": {"x": [1, 3, 5, 7, 9]}} + r.db("things").table("points").filter({"id": "three"}).update( + {"things": {"x": [7, 9]}} ).run(conn) - result = r.db('things').table('points').get('three').run(conn) + result = r.db("things").table("points").get("three").run(conn) pprint(result) assertEqUnordered(expected, result) def test_update_merge_array_deep(self, conn): - expected = { - 'id': 'three', - 'things': { - 'x': [1, 3, 5] - }, - 'x': [1, 3, 5, 7, 9] - } - r.db('things').table('points').filter({'id': 'three'}).update( - r.row['things'].merge({'x': [7, 9]}) + expected = {"id": "three", "things": {"x": [1, 3, 5]}, "x": [1, 3, 5, 7, 9]} + r.db("things").table("points").filter({"id": "three"}).update( + r.row["things"].merge({"x": [7, 9]}) ).run(conn) - result = r.db('things').table('points').get('three').run(conn) + result = r.db("things").table("points").get("three").run(conn) pprint(result) assertEqUnordered(expected, result) @@ -664,89 +633,58 @@ class TestLiteral(MockTest): @staticmethod def get_data(): data = [ - { - 'id': 'one', - 'points': { - 'pt1': { - 'x': 'x-1', - 'y': 'y-1' - } - } - }, - { - 'id': 'two', - 'points': { - 'pt1': { - 'x': 'x-2', - 'y': 'y-2' - } - } - }, - { - 'id': 'three', - 'things': { - 'x': [1, 3, 5] - } - } + {"id": "one", "points": {"pt1": {"x": "x-1", "y": "y-1"}}}, + {"id": "two", "points": {"pt1": {"x": "x-2", "y": "y-2"}}}, + {"id": "three", "things": {"x": [1, 3, 5]}}, ] - return as_db_and_table('things', 'points', data) + return as_db_and_table("things", "points", data) def test_map_merge_no_literal(self, conn): expected = { - 'id': 'one', - 'points': { - 'pt1': { - 'x': 'x-1', - 'y': 'y-1', - 'z': 'z-1' - } - } + "id": "one", + "points": {"pt1": {"x": "x-1", "y": "y-1", "z": "z-1"}}, } - result = r.db('things').table('points').filter({'id': 'one'}).map( - lambda doc: doc.merge({'points': {'pt1': {'z': 'z-1'}}}) - ).run(conn) + result = ( + r.db("things") + .table("points") + .filter({"id": "one"}) + .map(lambda doc: doc.merge({"points": {"pt1": {"z": "z-1"}}})) + .run(conn) + ) assertEqual(expected, list(result)[0]) def test_map_merge_literal(self, conn): - expected = { - 'id': 'one', - 'points': { - 'pt1': { - 'z': 'z-1' - } - } - } - result = r.db('things').table('points').filter({'id': 'one'}).map( - lambda doc: doc.merge({'points': {'pt1': r.literal({'z': 'z-1'})}}) - ).run(conn) + expected = {"id": "one", "points": {"pt1": {"z": "z-1"}}} + result = ( + r.db("things") + .table("points") + .filter({"id": "one"}) + .map(lambda doc: doc.merge({"points": {"pt1": r.literal({"z": "z-1"})}})) + .run(conn) + ) assertEqual(expected, list(result)[0]) def test_top_level_literal_throws_merge(self, conn): with pytest.raises(RqlRuntimeError): - r.db('things').table('points').filter({'id': 'one'}).map( - lambda doc: doc.merge(r.literal({'points': {'pt1': {'z': 'z-1'}}})) + r.db("things").table("points").filter({"id": "one"}).map( + lambda doc: doc.merge(r.literal({"points": {"pt1": {"z": "z-1"}}})) ).run(conn) def test_nested_literal_throws_merge(self, conn): with pytest.raises(RqlRuntimeError): - r.db('things').table('points').filter({'id': 'one'}).map( - lambda doc: doc.merge({'points': r.literal({'pt1': r.literal({'z': 'z-1'})})}) + r.db("things").table("points").filter({"id": "one"}).map( + lambda doc: doc.merge( + {"points": r.literal({"pt1": r.literal({"z": "z-1"})})} + ) ).run(conn) def test_update_literal(self, conn): - expected = { - 'id': 'one', - 'points': { - 'pt1': { - 'z': 'z-1' - } - } - } - r.db('things').table('points').filter({'id': 'one'}).update( - {'points': r.literal({'pt1': {'z': 'z-1'}})} + expected = {"id": "one", "points": {"pt1": {"z": "z-1"}}} + r.db("things").table("points").filter({"id": "one"}).update( + {"points": r.literal({"pt1": {"z": "z-1"}})} ).run(conn) - result = r.db('things').table('points').get('one').run(conn) + result = r.db("things").table("points").get("one").run(conn) assertEqual(expected, result) @@ -754,48 +692,46 @@ class TestDelete(MockTest): @staticmethod def get_data(): data = [ - {'id': 'sam-id', 'name': 'sam'}, - {'id': 'joe-id', 'name': 'joe'}, - {'id': 'tom-id', 'name': 'tom'}, - {'id': 'sally-id', 'name': 'sally'} + {"id": "sam-id", "name": "sam"}, + {"id": "joe-id", "name": "joe"}, + {"id": "tom-id", "name": "tom"}, + {"id": "sally-id", "name": "sally"}, ] - return as_db_and_table('ephemeral', 'people', data) + return as_db_and_table("ephemeral", "people", data) def test_delete_one(self, conn): expected = [ - {'id': 'sam-id', 'name': 'sam'}, - {'id': 'tom-id', 'name': 'tom'}, - {'id': 'sally-id', 'name': 'sally'} + {"id": "sam-id", "name": "sam"}, + {"id": "tom-id", "name": "tom"}, + {"id": "sally-id", "name": "sally"}, ] - r.db('ephemeral').table('people').get('joe-id').delete().run(conn) - result = r.db('ephemeral').table('people').run(conn) + r.db("ephemeral").table("people").get("joe-id").delete().run(conn) + result = r.db("ephemeral").table("people").run(conn) assertEqUnordered(expected, list(result)) def test_delete_one_from_sequence(self, conn): expected = [ - {'id': 'sam-id', 'name': 'sam'}, - {'id': 'tom-id', 'name': 'tom'}, - {'id': 'sally-id', 'name': 'sally'} - ] - r.db('ephemeral').table('people').filter({ - 'id': 'joe-id' - }).delete().run(conn) - result = r.db('ephemeral').table('people').run(conn) + {"id": "sam-id", "name": "sam"}, + {"id": "tom-id", "name": "tom"}, + {"id": "sally-id", "name": "sally"}, + ] + r.db("ephemeral").table("people").filter({"id": "joe-id"}).delete().run(conn) + result = r.db("ephemeral").table("people").run(conn) assertEqUnordered(expected, list(result)) def test_delete_get_all(self, conn): expected = [ - {'id': 'sally-id', 'name': 'sally'}, - {'id': 'joe-id', 'name': 'joe'} + {"id": "sally-id", "name": "sally"}, + {"id": "joe-id", "name": "joe"}, ] - r.db('ephemeral').table('people').get_all('sam-id', 'tom-id').delete().run(conn) - result = r.db('ephemeral').table('people').run(conn) + r.db("ephemeral").table("people").get_all("sam-id", "tom-id").delete().run(conn) + result = r.db("ephemeral").table("people").run(conn) assertEqUnordered(expected, list(result)) def test_delete_all_table_rows(self, conn): expected = [] - r.db('ephemeral').table('people').delete().run(conn) - result = r.db('ephemeral').table('people').run(conn) + r.db("ephemeral").table("people").delete().run(conn) + result = r.db("ephemeral").table("people").run(conn) assertEqUnordered(expected, list(result)) @@ -803,53 +739,52 @@ class TestDeleteReturnChanges(MockTest): @staticmethod def get_data(): data = [ - {'id': 'sam-id', 'name': 'sam'}, - {'id': 'joe-id', 'name': 'joe'}, - {'id': 'tom-id', 'name': 'tom'}, - {'id': 'sally-id', 'name': 'sally'} + {"id": "sam-id", "name": "sam"}, + {"id": "joe-id", "name": "joe"}, + {"id": "tom-id", "name": "tom"}, + {"id": "sally-id", "name": "sally"}, ] - return as_db_and_table('ephemeral', 'people', data) + return as_db_and_table("ephemeral", "people", data) def test_delete_one(self, conn): expected = [ - {'id': 'sam-id', 'name': 'sam'}, - {'id': 'tom-id', 'name': 'tom'}, - {'id': 'sally-id', 'name': 'sally'} + {"id": "sam-id", "name": "sam"}, + {"id": "tom-id", "name": "tom"}, + {"id": "sally-id", "name": "sally"}, ] expected_changes = [ - { - 'old_val': {'id': 'joe-id', 'name': 'joe'}, - 'new_val': None - } - ] - report = r.db('ephemeral').table('people').get('joe-id').delete( - return_changes=True - ).run(conn) + {"old_val": {"id": "joe-id", "name": "joe"}, "new_val": None} + ] + report = ( + r.db("ephemeral") + .table("people") + .get("joe-id") + .delete(return_changes=True) + .run(conn) + ) pprint(report) - assertEqual(expected_changes, report['changes']) - assertEqual(1, report['deleted']) - result = r.db('ephemeral').table('people').run(conn) + assertEqual(expected_changes, report["changes"]) + assertEqual(1, report["deleted"]) + result = r.db("ephemeral").table("people").run(conn) assertEqUnordered(expected, list(result)) def test_delete_multiple(self, conn): expected = [ - {'id': 'sally-id', 'name': 'sally'}, - {'id': 'joe-id', 'name': 'joe'} + {"id": "sally-id", "name": "sally"}, + {"id": "joe-id", "name": "joe"}, ] expected_changes = [ - { - 'old_val': {'id': 'sam-id', 'name': 'sam'}, - 'new_val': None - }, - { - 'old_val': {'id': 'tom-id', 'name': 'tom'}, - 'new_val': None - } - ] - report = r.db('ephemeral').table('people').get_all( - 'sam-id', 'tom-id' - ).delete(return_changes=True).run(conn) - assertEqUnordered(expected_changes, report['changes']) - assertEqual(2, report['deleted']) - result = r.db('ephemeral').table('people').run(conn) + {"old_val": {"id": "sam-id", "name": "sam"}, "new_val": None}, + {"old_val": {"id": "tom-id", "name": "tom"}, "new_val": None}, + ] + report = ( + r.db("ephemeral") + .table("people") + .get_all("sam-id", "tom-id") + .delete(return_changes=True) + .run(conn) + ) + assertEqUnordered(expected_changes, report["changes"]) + assertEqual(2, report["deleted"]) + result = r.db("ephemeral").table("people").run(conn) assertEqUnordered(expected, list(result)) diff --git a/tests/functional/test_without.py b/tests/functional/test_without.py index 644cfaa..fced2bd 100644 --- a/tests/functional/test_without.py +++ b/tests/functional/test_without.py @@ -8,51 +8,61 @@ class TestWithout(MockTest): @staticmethod def get_data(): data = [ - {'id': 'joe-id', 'name': 'joe', 'hobby': 'guitar'}, - {'id': 'bob-id', 'name': 'bob', 'hobby': 'pseudointellectualism'}, - {'id': 'bill-id', 'name': 'bill'}, - {'id': 'kimye-id', 'name': 'kimye', 'hobby': 'being kimye'} + {"id": "joe-id", "name": "joe", "hobby": "guitar"}, + {"id": "bob-id", "name": "bob", "hobby": "pseudointellectualism"}, + {"id": "bill-id", "name": "bill"}, + {"id": "kimye-id", "name": "kimye", "hobby": "being kimye"}, ] - return as_db_and_table('x', 'people', data) + return as_db_and_table("x", "people", data) def test_without_missing_attr(self, conn): expected = [ - {'id': 'joe-id'}, - {'id': 'bob-id'}, - {'id': 'bill-id'}, - {'id': 'kimye-id'} + {"id": "joe-id"}, + {"id": "bob-id"}, + {"id": "bill-id"}, + {"id": "kimye-id"}, ] - result = r.db('x').table('people').without('name', 'hobby').run(conn) + result = r.db("x").table("people").without("name", "hobby").run(conn) assertEqUnordered(expected, list(result)) def test_without_missing_attr_list(self, conn): expected = [ - {'id': 'joe-id'}, - {'id': 'bob-id'}, - {'id': 'bill-id'}, - {'id': 'kimye-id'} + {"id": "joe-id"}, + {"id": "bob-id"}, + {"id": "bill-id"}, + {"id": "kimye-id"}, ] - result = r.db('x').table('people').without(['name', 'hobby']).run(conn) + result = r.db("x").table("people").without(["name", "hobby"]).run(conn) assertEqUnordered(expected, list(result)) def test_sub_without(self, conn): expected = [ - {'id': 'joe-id'}, - {'id': 'bob-id'}, - {'id': 'bill-id'}, - {'id': 'kimye-id'} + {"id": "joe-id"}, + {"id": "bob-id"}, + {"id": "bill-id"}, + {"id": "kimye-id"}, ] - result = r.db('x').table('people').map(lambda p: p.without('name', 'hobby')).run(conn) + result = ( + r.db("x") + .table("people") + .map(lambda p: p.without("name", "hobby")) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_sub_without_list(self, conn): expected = [ - {'id': 'joe-id'}, - {'id': 'bob-id'}, - {'id': 'bill-id'}, - {'id': 'kimye-id'} + {"id": "joe-id"}, + {"id": "bob-id"}, + {"id": "bill-id"}, + {"id": "kimye-id"}, ] - result = r.db('x').table('people').map(lambda p: p.without(['name', 'hobby'])).run(conn) + result = ( + r.db("x") + .table("people") + .map(lambda p: p.without(["name", "hobby"])) + .run(conn) + ) assertEqUnordered(expected, list(result)) @@ -61,38 +71,32 @@ class TestWithout2(MockTest): def get_data(): data = [ { - 'id': 'thing-1', - 'values': { - 'a': 'a-1', - 'b': 'b-1', - 'c': 'c-1', - 'd': 'd-1' - } + "id": "thing-1", + "values": {"a": "a-1", "b": "b-1", "c": "c-1", "d": "d-1"}, }, { - 'id': 'thing-2', - 'values': { - 'a': 'a-2', - 'b': 'b-2', - 'c': 'c-2', - 'd': 'd-2' - } + "id": "thing-2", + "values": {"a": "a-2", "b": "b-2", "c": "c-2", "d": "d-2"}, }, ] - return as_db_and_table('some_db', 'things', data) + return as_db_and_table("some_db", "things", data) def test_sub_sub(self, conn): - expected = [ - {'b': 'b-1', 'c': 'c-1'}, - {'b': 'b-2', 'c': 'c-2'} - ] - result = r.db('some_db').table('things').map(lambda t: t['values'].without('a', 'd')).run(conn) + expected = [{"b": "b-1", "c": "c-1"}, {"b": "b-2", "c": "c-2"}] + result = ( + r.db("some_db") + .table("things") + .map(lambda t: t["values"].without("a", "d")) + .run(conn) + ) assertEqUnordered(expected, list(result)) def test_sub_sub_list(self, conn): - expected = [ - {'b': 'b-1', 'c': 'c-1'}, - {'b': 'b-2', 'c': 'c-2'} - ] - result = r.db('some_db').table('things').map(lambda t: t['values'].without(['a', 'd'])).run(conn) + expected = [{"b": "b-1", "c": "c-1"}, {"b": "b-2", "c": "c-2"}] + result = ( + r.db("some_db") + .table("things") + .map(lambda t: t["values"].without(["a", "d"])) + .run(conn) + ) assertEqUnordered(expected, list(result)) diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py index bb09274..8426eeb 100644 --- a/tests/integration/__init__.py +++ b/tests/integration/__init__.py @@ -1,10 +1,4 @@ class MockTest(object): @staticmethod def get_data(): - return { - 'dbs': { - 'default': { - 'tables': {} - } - } - } + return {"dbs": {"default": {"tables": {}}}} diff --git a/tests/integration/test_things.py b/tests/integration/test_things.py index 30e1a7f..5214e20 100644 --- a/tests/integration/test_things.py +++ b/tests/integration/test_things.py @@ -8,125 +8,105 @@ class TestThings(MockTest): @staticmethod def get_data(): people_data = [ - {'id': 'joe-id', 'name': 'joe', 'age': 26}, - {'id': 'bob-id', 'name': 'bob', 'age': 19}, - {'id': 'tim-id', 'name': 'tim', 'age': 53}, - {'id': 'todd-id', 'name': 'todd', 'age': 17} + {"id": "joe-id", "name": "joe", "age": 26}, + {"id": "bob-id", "name": "bob", "age": 19}, + {"id": "tim-id", "name": "tim", "age": 53}, + {"id": "todd-id", "name": "todd", "age": 17}, ] job_data = [ - {'id': 'lawyer-id', 'name': 'Lawyer'}, - {'id': 'nurse-id', 'name': 'Nurse'}, - {'id': 'assistant-id', 'name': 'Assistant'} + {"id": "lawyer-id", "name": "Lawyer"}, + {"id": "nurse-id", "name": "Nurse"}, + {"id": "assistant-id", "name": "Assistant"}, ] employee_data = [ - {'id': 'joe-employee-id', 'person': 'joe-id', 'job': 'lawyer-id'}, - {'id': 'tim-employee-id', 'person': 'tim-id', 'job': 'nurse-id'}, - {'id': 'bob-employee-id', 'person': 'bob-id', 'job': 'assistant-id'}, - {'id': 'todd-employee-id', 'person': 'todd-id', 'job': 'lawyer-id'} + {"id": "joe-employee-id", "person": "joe-id", "job": "lawyer-id"}, + {"id": "tim-employee-id", "person": "tim-id", "job": "nurse-id"}, + {"id": "bob-employee-id", "person": "bob-id", "job": "assistant-id"}, + {"id": "todd-employee-id", "person": "todd-id", "job": "lawyer-id"}, ] return { - 'dbs': { - 'x': { - 'tables': { - 'people': people_data, - 'jobs': job_data, - 'employees': employee_data + "dbs": { + "x": { + "tables": { + "people": people_data, + "jobs": job_data, + "employees": employee_data, } } } } def test_join_filter_map(self, conn): - query = r.db('x').table('employees').eq_join( - 'person', r.db('x').table('people') - ).filter( - lambda p: p['right']['age'] > 20 - ).map( - lambda d: d['left'].merge({'person': d['right']['name']}) + query = ( + r.db("x") + .table("employees") + .eq_join("person", r.db("x").table("people")) + .filter(lambda p: p["right"]["age"] > 20) + .map(lambda d: d["left"].merge({"person": d["right"]["name"]})) ) expected = [ - { - 'id': 'joe-employee-id', - 'person': 'joe', - 'job': 'lawyer-id' - }, - { - 'id': 'tim-employee-id', - 'person': 'tim', - 'job': 'nurse-id' - } + {"id": "joe-employee-id", "person": "joe", "job": "lawyer-id"}, + {"id": "tim-employee-id", "person": "tim", "job": "nurse-id"}, ] assertEqUnordered(expected, list(query.run(conn))) def test_index_getall_map_orderby(self, conn): - r.db('x').table('people').index_create( - 'name_and_id', - lambda doc: doc['name'] + doc['id'] + r.db("x").table("people").index_create( + "name_and_id", lambda doc: doc["name"] + doc["id"] ).run(conn) - r.db('x').table('people').index_wait().run(conn) + r.db("x").table("people").index_wait().run(conn) - query = r.db('x').table('people').get_all( - 'joejoe-id', 'timtim-id', index='name_and_id' - ).map( - lambda doc: doc.merge({ - 'also_name': doc['name'], - 'age_plus_10': doc['age'] + 10, - 'age_times_2': doc['age'] * 2 - }) - ).order_by('name') + query = ( + r.db("x") + .table("people") + .get_all("joejoe-id", "timtim-id", index="name_and_id") + .map( + lambda doc: doc.merge( + { + "also_name": doc["name"], + "age_plus_10": doc["age"] + 10, + "age_times_2": doc["age"] * 2, + } + ) + ) + .order_by("name") + ) expected = [ { - 'id': 'joe-id', - 'name': 'joe', - 'also_name': 'joe', - 'age': 26, - 'age_plus_10': 36, - 'age_times_2': 52 + "id": "joe-id", + "name": "joe", + "also_name": "joe", + "age": 26, + "age_plus_10": 36, + "age_times_2": 52, }, { - 'id': 'tim-id', - 'name': 'tim', - 'also_name': 'tim', - 'age': 53, - 'age_plus_10': 63, - 'age_times_2': 106 - } + "id": "tim-id", + "name": "tim", + "also_name": "tim", + "age": 53, + "age_plus_10": 63, + "age_times_2": 106, + }, ] assertEqual(expected, list(query.run(conn))) def test_multi_join(self, conn): - query = r.db('x').table('employees').eq_join( - 'person', r.db('x').table('people') - ).map( - lambda d: d['left'].merge({'person': d['right']['name']}) - ).eq_join( - 'job', r.db('x').table('jobs') - ).map( - lambda d: d['left'].merge({'job': d['right']['name']}) + query = ( + r.db("x") + .table("employees") + .eq_join("person", r.db("x").table("people")) + .map(lambda d: d["left"].merge({"person": d["right"]["name"]})) + .eq_join("job", r.db("x").table("jobs")) + .map(lambda d: d["left"].merge({"job": d["right"]["name"]})) ) expected = [ - { - 'id': 'joe-employee-id', - 'person': 'joe', - 'job': 'Lawyer' - }, - { - 'id': 'tim-employee-id', - 'person': 'tim', - 'job': 'Nurse' - }, - { - 'id': 'bob-employee-id', - 'person': 'bob', - 'job': 'Assistant' - }, - { - 'id': 'todd-employee-id', - 'person': 'todd', - 'job': 'Lawyer' - } + {"id": "joe-employee-id", "person": "joe", "job": "Lawyer"}, + {"id": "tim-employee-id", "person": "tim", "job": "Nurse"}, + {"id": "bob-employee-id", "person": "bob", "job": "Assistant"}, + {"id": "todd-employee-id", "person": "todd", "job": "Lawyer"}, ] assertEqUnordered(expected, list(query.run(conn))) diff --git a/tests/unit/test_ast_base.py b/tests/unit/test_ast_base.py index a5bc28e..8e00721 100644 --- a/tests/unit/test_ast_base.py +++ b/tests/unit/test_ast_base.py @@ -8,105 +8,65 @@ class TestAst(unittest.TestCase): def test_rql_merge_with(self): to_ext = { - 'x': { - 'x1': { - 'val': 'x1-val' - }, - 'x2': { - 'val': 'x2-val' - } - }, - 'y': { - 'ykey': True - }, - 'nums1': [1, 3, 5], - 'nums2': [1, 3, 5] + "x": {"x1": {"val": "x1-val"}, "x2": {"val": "x2-val"}}, + "y": {"ykey": True}, + "nums1": [1, 3, 5], + "nums2": [1, 3, 5], } ext_with = { - 'x': { - 'x1': { - 'val2': 'x1-val-2' - }, - 'x2': ast_base.LITERAL_OBJECT.from_dict({ - 'val2': 'x2-val-2' - }) + "x": { + "x1": {"val2": "x1-val-2"}, + "x2": ast_base.LITERAL_OBJECT.from_dict({"val2": "x2-val-2"}), }, - 'y': 'new-y-val', - 'nums1': [7, 9], - 'nums2': ast_base.LITERAL_LIST.from_list([7, 9]) + "y": "new-y-val", + "nums1": [7, 9], + "nums2": ast_base.LITERAL_LIST.from_list([7, 9]), } expected = { - 'x': { - 'x1': { - 'val': 'x1-val', - 'val2': 'x1-val-2' - }, - 'x2': { - 'val2': 'x2-val-2' - }, + "x": { + "x1": {"val": "x1-val", "val2": "x1-val-2"}, + "x2": {"val2": "x2-val-2"}, }, - 'y': 'new-y-val', - 'nums1': [1, 3, 5, 7, 9], - 'nums2': [7, 9] + "y": "new-y-val", + "nums1": [1, 3, 5, 7, 9], + "nums2": [7, 9], } assertEqual(expected, ast_base.rql_merge_with(ext_with, to_ext)) def test_contains_literals_obj(self): - thing = { - 'x': { - 'val1': ast_base.LITERAL_OBJECT({'is_val_1': True}) - } - } + thing = {"x": {"val1": ast_base.LITERAL_OBJECT({"is_val_1": True})}} self.assertTrue(ast_base.contains_literals(thing)) - self.assertTrue(ast_base.contains_literals(thing['x'])) + self.assertTrue(ast_base.contains_literals(thing["x"])) def test_contains_literals_list(self): - thing = { - 'x': { - 'val1': ast_base.LITERAL_LIST([1, 2, 3]) - } - } + thing = {"x": {"val1": ast_base.LITERAL_LIST([1, 2, 3])}} self.assertTrue(ast_base.contains_literals(thing)) - self.assertTrue(ast_base.contains_literals(thing['x'])) + self.assertTrue(ast_base.contains_literals(thing["x"])) def test_has_nested_literal_has_nested_obj(self): - thing = ast_base.LITERAL_OBJECT({ - 'x': { - 'val1': ast_base.LITERAL_OBJECT({'is_val_1': True}) - } - }) + thing = ast_base.LITERAL_OBJECT( + {"x": {"val1": ast_base.LITERAL_OBJECT({"is_val_1": True})}} + ) self.assertTrue(ast_base.has_nested_literal(thing)) def test_has_nested_literal_has_nested_obj_2(self): - thing = ast_base.LITERAL_LIST([{ - 'x': { - 'val1': ast_base.LITERAL_OBJECT({'is_val_1': True}) - } - }]) + thing = ast_base.LITERAL_LIST( + [{"x": {"val1": ast_base.LITERAL_OBJECT({"is_val_1": True})}}] + ) self.assertTrue(ast_base.has_nested_literal(thing)) def test_has_nested_literal_happy(self): - thing = ast_base.LITERAL_OBJECT({ - 'x': { - 'val1': {'is_val_1': True} - } - }) + thing = ast_base.LITERAL_OBJECT({"x": {"val1": {"is_val_1": True}}}) self.assertFalse(ast_base.has_nested_literal(thing)) def test_has_nested_literal_has_nested_list(self): - thing = ast_base.LITERAL_OBJECT({ - 'x': { - 'val1': ast_base.LITERAL_LIST([1, 2, 3]) - } - }) + thing = ast_base.LITERAL_OBJECT( + {"x": {"val1": ast_base.LITERAL_LIST([1, 2, 3])}} + ) self.assertTrue(ast_base.has_nested_literal(thing)) def test_has_nested_literal_has_nested_list_2(self): - thing = ast_base.LITERAL_LIST([ - { - 'x': { - 'val1': ast_base.LITERAL_LIST([1, 2, 3]) - } - } - ]) + thing = ast_base.LITERAL_LIST( + [{"x": {"val1": ast_base.LITERAL_LIST([1, 2, 3])}}] + ) self.assertTrue(ast_base.has_nested_literal(thing)) diff --git a/tests/unit/test_db.py b/tests/unit/test_db.py index 3a4b7cc..ec33ade 100644 --- a/tests/unit/test_db.py +++ b/tests/unit/test_db.py @@ -6,111 +6,102 @@ def db_insert_starting_data(): return [ - {'id': 'a', 'name': 'a-name', 'age': 'a-age'}, - {'id': 'b', 'name': 'b-name', 'age': 'b-age'}, - {'id': 'c', 'name': 'c-name', 'age': 'c-age'} + {"id": "a", "name": "a-name", "age": "a-age"}, + {"id": "b", "name": "b-name", "age": "b-age"}, + {"id": "c", "name": "c-name", "age": "c-age"}, ] class TestDbInsertWithConflictSettings(TestCase): def test_error(self): expected_result = [ - {'id': 'a', 'name': 'a-name', 'age': 'a-age'}, - {'id': 'b', 'name': 'b-name', 'age': 'b-age'}, - {'id': 'c', 'name': 'c-name', 'age': 'c-age'}, - {'id': 'd', 'name': 'deshawn'} + {"id": "a", "name": "a-name", "age": "a-age"}, + {"id": "b", "name": "b-name", "age": "b-age"}, + {"id": "c", "name": "c-name", "age": "c-age"}, + {"id": "d", "name": "deshawn"}, ] expected_report = { - 'replaced': 0, - 'inserted': 1, - 'errors': 1, - 'changes': [{ - 'old_val': None, - 'new_val': { - 'id': 'd', - 'name': 'deshawn' - } - }] + "replaced": 0, + "inserted": 1, + "errors": 1, + "changes": [{"old_val": None, "new_val": {"id": "d", "name": "deshawn"}}], } to_insert = [ - {'id': 'c', 'something': 'someval'}, - {'id': 'd', 'name': 'deshawn'} + {"id": "c", "something": "someval"}, + {"id": "d", "name": "deshawn"}, ] result, report = db.insert_into_table_with_conflict_setting( - db_insert_starting_data(), - to_insert, - conflict='error' + db_insert_starting_data(), to_insert, conflict="error" ) assertEqual(expected_result, result) - keys = ('replaced', 'inserted', 'errors', 'changes') + keys = ("replaced", "inserted", "errors", "changes") self.assert_key_equality(keys, expected_report, report) def test_update(self): expected_result = [ - {'id': 'a', 'name': 'a-name', 'age': 'a-age'}, - {'id': 'b', 'name': 'b-name', 'age': 'b-age'}, - {'id': 'c', 'name': 'new c name', 'new_c_key': 'new_c_val', 'age': 'c-age'}, - {'id': 'd', 'name': 'deshawn'} + {"id": "a", "name": "a-name", "age": "a-age"}, + {"id": "b", "name": "b-name", "age": "b-age"}, + {"id": "c", "name": "new c name", "new_c_key": "new_c_val", "age": "c-age"}, + {"id": "d", "name": "deshawn"}, ] expected_report = { - 'replaced': 1, - 'inserted': 1, - 'errors': 0, - 'changes': [ + "replaced": 1, + "inserted": 1, + "errors": 0, + "changes": [ { - 'old_val': {'id': 'c', 'name': 'c-name', 'age': 'c-age'}, - 'new_val': {'id': 'c', 'name': 'new c name', 'new_c_key': 'new_c_val', 'age': 'c-age'} + "old_val": {"id": "c", "name": "c-name", "age": "c-age"}, + "new_val": { + "id": "c", + "name": "new c name", + "new_c_key": "new_c_val", + "age": "c-age", + }, }, - { - 'old_val': None, - 'new_val': {'id': 'd', 'name': 'deshawn'} - } - ] + {"old_val": None, "new_val": {"id": "d", "name": "deshawn"}}, + ], } to_insert = [ - {'id': 'c', 'name': 'new c name', 'new_c_key': 'new_c_val'}, - {'id': 'd', 'name': 'deshawn'} + {"id": "c", "name": "new c name", "new_c_key": "new_c_val"}, + {"id": "d", "name": "deshawn"}, ] result, report = db.insert_into_table_with_conflict_setting( - db_insert_starting_data(), - to_insert, - conflict='update' + db_insert_starting_data(), to_insert, conflict="update" ) assertEqual(expected_result, result) - keys = ('replaced', 'inserted', 'errors', 'changes') + keys = ("replaced", "inserted", "errors", "changes") self.assert_key_equality(keys, expected_report, report) def test_replace(self): expected_result = [ - {'id': 'a', 'name': 'a-name', 'age': 'a-age'}, - {'id': 'b', 'name': 'b-name', 'age': 'b-age'}, - {'id': 'c', 'name': 'new c name', 'new_c_key': 'new_c_val'}, - {'id': 'd', 'name': 'deshawn'} + {"id": "a", "name": "a-name", "age": "a-age"}, + {"id": "b", "name": "b-name", "age": "b-age"}, + {"id": "c", "name": "new c name", "new_c_key": "new_c_val"}, + {"id": "d", "name": "deshawn"}, ] expected_report = { - 'replaced': 1, - 'inserted': 1, - 'errors': 0, - 'changes': [ + "replaced": 1, + "inserted": 1, + "errors": 0, + "changes": [ { - 'old_val': {'id': 'c', 'name': 'c-name', 'age': 'c-age'}, - 'new_val': {'id': 'c', 'name': 'new c name', 'new_c_key': 'new_c_val'} + "old_val": {"id": "c", "name": "c-name", "age": "c-age"}, + "new_val": { + "id": "c", + "name": "new c name", + "new_c_key": "new_c_val", + }, }, - { - 'old_val': None, - 'new_val': {'id': 'd', 'name': 'deshawn'} - } - ] + {"old_val": None, "new_val": {"id": "d", "name": "deshawn"}}, + ], } to_insert = [ - {'id': 'c', 'name': 'new c name', 'new_c_key': 'new_c_val'}, - {'id': 'd', 'name': 'deshawn'} + {"id": "c", "name": "new c name", "new_c_key": "new_c_val"}, + {"id": "d", "name": "deshawn"}, ] result, report = db.insert_into_table_with_conflict_setting( - db_insert_starting_data(), - to_insert, - conflict='replace' + db_insert_starting_data(), to_insert, conflict="replace" ) assertEqual(expected_result, result) - keys = ('replaced', 'inserted', 'errors', 'changes') + keys = ("replaced", "inserted", "errors", "changes") self.assert_key_equality(keys, expected_report, report) diff --git a/tests/unit/test_joins.py b/tests/unit/test_joins.py index 4a68a87..a8dea49 100644 --- a/tests/unit/test_joins.py +++ b/tests/unit/test_joins.py @@ -8,97 +8,60 @@ class TestJoins(unittest.TestCase): def test_eq_join(self): left = [ - { - 'id': 'left-1', - 'rel_field': 'right-1-name' - }, - { - 'id': 'left-2', - 'rel_field': 'right-4-name' - } + {"id": "left-1", "rel_field": "right-1-name"}, + {"id": "left-2", "rel_field": "right-4-name"}, ] right = [ - { - 'id': 'right-1', - 'name': 'right-1-name' - }, - { - 'id': 'right-2', - 'name': 'right-2-name' - }, - { - 'id': 'right-3', - 'name': 'right-3-name' - }, - { - 'id': 'right-4', - 'name': 'right-4-name' - } + {"id": "right-1", "name": "right-1-name"}, + {"id": "right-2", "name": "right-2-name"}, + {"id": "right-3", "name": "right-3-name"}, + {"id": "right-4", "name": "right-4-name"}, ] expected = [ { - 'left': { - 'id': 'left-1', - 'rel_field': 'right-1-name' - }, - 'right': { - 'id': 'right-1', - 'name': 'right-1-name' - } + "left": {"id": "left-1", "rel_field": "right-1-name"}, + "right": {"id": "right-1", "name": "right-1-name"}, }, { - 'left': { - 'id': 'left-2', - 'rel_field': 'right-4-name' - }, - 'right': { - 'id': 'right-4', - 'name': 'right-4-name' - } - } + "left": {"id": "left-2", "rel_field": "right-4-name"}, + "right": {"id": "right-4", "name": "right-4-name"}, + }, ] - assertEqual( - expected, - joins.do_eq_join('rel_field', left, 'name', right) - ) + assertEqual(expected, joins.do_eq_join("rel_field", left, "name", right)) def test_inner_join(self): left = list(range(1, 5)) right = list(range(1, 5)) expected = [ - {'left': 2, 'right': 1}, - {'left': 3, 'right': 1}, - {'left': 3, 'right': 2}, - {'left': 4, 'right': 1}, - {'left': 4, 'right': 2}, - {'left': 4, 'right': 3} + {"left": 2, "right": 1}, + {"left": 3, "right": 1}, + {"left": 3, "right": 2}, + {"left": 4, "right": 1}, + {"left": 4, "right": 2}, + {"left": 4, "right": 3}, ] def pred(x, y): return x > y - assertEqual( - expected, - joins.do_inner_join(pred, left, right) - ) + + assertEqual(expected, joins.do_inner_join(pred, left, right)) def test_outer_join(self): left = list(range(1, 6)) right = list(range(1, 6)) expected = [ - {'left': 1}, - {'left': 2}, - {'left': 3, 'right': 1}, - {'left': 3, 'right': 2}, - {'left': 4}, - {'left': 5, 'right': 1}, - {'left': 5, 'right': 2}, - {'left': 5, 'right': 3}, - {'left': 5, 'right': 4} + {"left": 1}, + {"left": 2}, + {"left": 3, "right": 1}, + {"left": 3, "right": 2}, + {"left": 4}, + {"left": 5, "right": 1}, + {"left": 5, "right": 2}, + {"left": 5, "right": 3}, + {"left": 5, "right": 4}, ] def pred(x, y): return (x % 2 == 1) and (x > y) - assertEqual( - expected, - joins.do_outer_join(pred, left, right) - ) + + assertEqual(expected, joins.do_outer_join(pred, left, right)) diff --git a/tests/unit/test_rtime.py b/tests/unit/test_rtime.py index c235cf9..88bbf41 100644 --- a/tests/unit/test_rtime.py +++ b/tests/unit/test_rtime.py @@ -9,7 +9,7 @@ class TestRTime(unittest.TestCase): def test_to_date(self): - timezone = rethinkdb.r.make_timezone('00:00') + timezone = rethinkdb.r.make_timezone("00:00") dt = datetime.datetime(2014, 6, 3, 12, 5, 36, tzinfo=timezone) as_date = rtime.to_date(dt) assertEqual(2014, as_date.year) diff --git a/tests/unit/test_util.py b/tests/unit/test_util.py index caf30fb..0470a8e 100644 --- a/tests/unit/test_util.py +++ b/tests/unit/test_util.py @@ -11,6 +11,7 @@ class TestUtil(unittest.TestCase): def test_curry2(self): def fun(x, y): return x + y + curried = util.curry2(fun) assertEqual(8, curried(5, 3)) assertEqual(8, curried(5)(3)) @@ -18,6 +19,7 @@ def fun(x, y): def test_curry3(self): def fun(x, y, z): return x + y + z + curried = util.curry3(fun) assertEqual(15, curried(3, 5, 7)) assertEqual(15, curried(3, 5)(7)) @@ -25,25 +27,15 @@ def fun(x, y, z): assertEqual(15, curried(3)(5)(7)) def test_extend(self): - dict_1 = {'x': 'x1-val', 'y': 'y1-val'} - dict_2 = {'x': 'x2-val', 'z': 'z2-val'} + dict_1 = {"x": "x1-val", "y": "y1-val"} + dict_2 = {"x": "x2-val", "z": "z2-val"} extended = util.extend(dict_1, dict_2) - assertEqual({ - 'x': 'x2-val', - 'y': 'y1-val', - 'z': 'z2-val' - }, extended) - - assertEqual({ - 'x': 'x1-val', - 'y': 'y1-val' - }, dict_1) - - assertEqual({ - 'x': 'x2-val', - 'z': 'z2-val' - }, dict_2) + assertEqual({"x": "x2-val", "y": "y1-val", "z": "z2-val"}, extended) + + assertEqual({"x": "x1-val", "y": "y1-val"}, dict_1) + + assertEqual({"x": "x2-val", "z": "z2-val"}, dict_2) def test_cat(self): list_1 = [1, 2, 3] @@ -54,31 +46,29 @@ def test_cat(self): assertEqual([7, 8, 9], list_2) def test_extend_with(self): - with mock.patch('rethinkdb_mock.util.extend') as extend: - extend.return_value = 'EXTENDED' - util.extend_with('X', 'Y') - util.extend_with('X')('Y') + with mock.patch("rethinkdb_mock.util.extend") as extend: + extend.return_value = "EXTENDED" + util.extend_with("X", "Y") + util.extend_with("X")("Y") - extend.assert_has_calls([ - mock.call('Y', 'X'), - mock.call('Y', 'X') - ]) + extend.assert_has_calls([mock.call("Y", "X"), mock.call("Y", "X")]) def test_map_with(self): def add_1(x): return x + 1 + nums = [10, 20, 30] # map_fn = util.map_with(add_1) assertEqual([11, 21, 31], util.map_with(add_1)(nums)) assertEqual([11, 21, 31], util.map_with(add_1, nums)) def test_has_attrs(self): - thing1 = {'a': 'a-val', 'b': 'b-val'} - thing2 = {'x': 'x-val'} - self.assertTrue(util.has_attrs(['a'], thing1)) - self.assertTrue(util.has_attrs(['a', 'b'], thing1)) - self.assertFalse(util.has_attrs(['a'], thing2)) - self.assertFalse(util.has_attrs(['a', 'b'], thing2)) + thing1 = {"a": "a-val", "b": "b-val"} + thing2 = {"x": "x-val"} + self.assertTrue(util.has_attrs(["a"], thing1)) + self.assertTrue(util.has_attrs(["a", "b"], thing1)) + self.assertFalse(util.has_attrs(["a"], thing2)) + self.assertFalse(util.has_attrs(["a", "b"], thing2)) def test_nth(self): nums = [10, 20, 30, 40, 50] @@ -86,44 +76,31 @@ def test_nth(self): assertEqual(40, util.nth(3)(nums)) def test_as_obj(self): - expected = { - 'x': 'x-val', - 'y': 'y-val' - } - pairs = [ - ['x', 'x-val'], - ['y', 'y-val'] - ] + expected = {"x": "x-val", "y": "y-val"} + pairs = [["x", "x-val"], ["y", "y-val"]] assertEqual(expected, util.as_obj(pairs)) def test_without(self): - obj = { - 'x': 'x-val', - 'y': 'y-val', - 'z': 'z-val' - } - assertEqual({ - 'z': 'z-val' - }, util.without(['x', 'y'], obj)) + obj = {"x": "x-val", "y": "y-val", "z": "z-val"} + assertEqual({"z": "z-val"}, util.without(["x", "y"], obj)) - assertEqual({ - 'x': 'x-val', - 'y': 'y-val' - }, util.without(['z'], obj)) + assertEqual({"x": "x-val", "y": "y-val"}, util.without(["z"], obj)) def test_pluck_with(self): - obj = { - 'x': 'x-val', - 'y': 'y-val', - 'z': 'z-val' - } - assertEqual({ - 'x': 'x-val', - }, util.pluck_with('x')(obj)) - assertEqual({ - 'x': 'x-val', - 'y': 'y-val', - }, util.pluck_with(['x', 'y'])(obj)) + obj = {"x": "x-val", "y": "y-val", "z": "z-val"} + assertEqual( + { + "x": "x-val", + }, + util.pluck_with("x")(obj), + ) + assertEqual( + { + "x": "x-val", + "y": "y-val", + }, + util.pluck_with(["x", "y"])(obj), + ) def test_pipeline(self): def add_5(x): @@ -136,76 +113,51 @@ def mul_2(x): assertEqual(19, util.pipeline(mul_2, add_5)(7)) def test_match_attrs_matching(self): - to_match = { - 'x': 'good-x', - 'y': 'good-y' - } - good_test = { - 'x': 'good-x', - 'y': 'good-y', - 'z': 'good-z' - } + to_match = {"x": "good-x", "y": "good-y"} + good_test = {"x": "good-x", "y": "good-y", "z": "good-z"} self.assertTrue(util.match_attrs(to_match, good_test)) def test_match_attrs_not_matching(self): - to_match = { - 'x': 'good-x', - 'y': 'good-y' - } - bad_test = { - 'x': 'good-x', - 'y': 'bad-y', - 'z': 'good-z' - } + to_match = {"x": "good-x", "y": "good-y"} + bad_test = {"x": "good-x", "y": "bad-y", "z": "good-z"} self.assertFalse(util.match_attrs(to_match, bad_test)) def test_match_attrs_missing_val(self): - to_match = { - 'x': 'good-x', - 'y': 'good-y' - } - bad_test = { - 'x': 'good-x', - 'z': 'good-z' - } + to_match = {"x": "good-x", "y": "good-y"} + bad_test = {"x": "good-x", "z": "good-z"} self.assertFalse(util.match_attrs(to_match, bad_test)) def test_getter_dict(self): - a_dict = { - 'x': 'x-val' - } - assertEqual('x-val', util.getter('x')(a_dict)) - assertEqual(None, util.getter('y')(a_dict)) + a_dict = {"x": "x-val"} + assertEqual("x-val", util.getter("x")(a_dict)) + assertEqual(None, util.getter("y")(a_dict)) def test_getter_obj(self): - class Thing(object): def __init__(self, a_dict): for k, v in list(a_dict.items()): setattr(self, k, v) - thing = Thing({'x': 'x-val'}) + thing = Thing({"x": "x-val"}) - assertEqual('x-val', util.getter('x')(thing)) - assertEqual(None, util.getter('y')(thing)) + assertEqual("x-val", util.getter("x")(thing)) + assertEqual(None, util.getter("y")(thing)) def test_maybe_map_simple(self): def add_5(x): return x + 5 + assertEqual(13, util.maybe_map(add_5, 8)) assertEqual([5, 10, 15], util.maybe_map(add_5, [0, 5, 10])) def test_maybe_map_dict(self): def set_y_by_x(thing): - return {'x': thing['x'], 'y': thing['x'] + 1} + return {"x": thing["x"], "y": thing["x"] + 1} + assertEqual({"x": 5, "y": 6}, util.maybe_map(set_y_by_x, {"x": 5})) assertEqual( - {'x': 5, 'y': 6}, - util.maybe_map(set_y_by_x, {'x': 5}) - ) - assertEqual( - [{'x': 5, 'y': 6}, {'x': 10, 'y': 11}], - util.maybe_map(set_y_by_x, [{'x': 5}, {'x': 10}]) + [{"x": 5, "y": 6}, {"x": 10, "y": 11}], + util.maybe_map(set_y_by_x, [{"x": 5}, {"x": 10}]), ) def test_splice(self): @@ -224,139 +176,121 @@ def test_change_at(self): def test_sort_by_one(self): people = [ - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'todd', 'age': 52, 'score': 15}, - {'id': 'bill', 'age': 35, 'score': 78} + {"id": "joe", "age": 26, "score": 60}, + {"id": "todd", "age": 52, "score": 15}, + {"id": "bill", "age": 35, "score": 78}, ] expected = [ - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'bill', 'age': 35, 'score': 78}, - {'id': 'todd', 'age': 52, 'score': 15} + {"id": "joe", "age": 26, "score": 60}, + {"id": "bill", "age": 35, "score": 78}, + {"id": "todd", "age": 52, "score": 15}, ] - result = util.sort_by_one('age', people) + result = util.sort_by_one("age", people) for index in range(0, len(expected)): assertEqual(expected[index], result[index]) def test_sort_by_many_1(self): people = [ - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'todd', 'age': 52, 'score': 15}, - {'id': 'bill', 'age': 35, 'score': 78} + {"id": "joe", "age": 26, "score": 60}, + {"id": "todd", "age": 52, "score": 15}, + {"id": "bill", "age": 35, "score": 78}, ] expected = [ - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'bill', 'age': 35, 'score': 78}, - {'id': 'todd', 'age': 52, 'score': 15} + {"id": "joe", "age": 26, "score": 60}, + {"id": "bill", "age": 35, "score": 78}, + {"id": "todd", "age": 52, "score": 15}, ] - result = util.sort_by_many([('age', 'ASC')], people) + result = util.sort_by_many([("age", "ASC")], people) for index in range(0, len(expected)): assertEqual(expected[index], result[index]) def test_sort_by_many_2(self): people = [ - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'todd', 'age': 52, 'score': 15}, - {'id': 'joe', 'age': 26, 'score': 20}, - {'id': 'bill', 'age': 35, 'score': 78}, - {'id': 'todd', 'age': 52, 'score': 80} + {"id": "joe", "age": 26, "score": 60}, + {"id": "todd", "age": 52, "score": 15}, + {"id": "joe", "age": 26, "score": 20}, + {"id": "bill", "age": 35, "score": 78}, + {"id": "todd", "age": 52, "score": 80}, ] expected = [ - {'id': 'joe', 'age': 26, 'score': 20}, - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'bill', 'age': 35, 'score': 78}, - {'id': 'todd', 'age': 52, 'score': 15}, - {'id': 'todd', 'age': 52, 'score': 80} + {"id": "joe", "age": 26, "score": 20}, + {"id": "joe", "age": 26, "score": 60}, + {"id": "bill", "age": 35, "score": 78}, + {"id": "todd", "age": 52, "score": 15}, + {"id": "todd", "age": 52, "score": 80}, ] - result = util.sort_by_many([('age', 'ASC'), ('score', 'ASC')], people) - pprint({'RESULT': result}) + result = util.sort_by_many([("age", "ASC"), ("score", "ASC")], people) + pprint({"RESULT": result}) for index in range(0, len(expected)): assertEqual(expected[index], result[index]) def test_sort_by_many_3(self): people = [ - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'todd', 'age': 52, 'score': 15}, - {'id': 'joe', 'age': 26, 'score': 20}, - {'id': 'bill', 'age': 35, 'score': 78}, - {'id': 'todd', 'age': 52, 'score': 80} + {"id": "joe", "age": 26, "score": 60}, + {"id": "todd", "age": 52, "score": 15}, + {"id": "joe", "age": 26, "score": 20}, + {"id": "bill", "age": 35, "score": 78}, + {"id": "todd", "age": 52, "score": 80}, ] expected = [ - {'id': 'joe', 'age': 26, 'score': 60}, - {'id': 'joe', 'age': 26, 'score': 20}, - {'id': 'bill', 'age': 35, 'score': 78}, - {'id': 'todd', 'age': 52, 'score': 80}, - {'id': 'todd', 'age': 52, 'score': 15} + {"id": "joe", "age": 26, "score": 60}, + {"id": "joe", "age": 26, "score": 20}, + {"id": "bill", "age": 35, "score": 78}, + {"id": "todd", "age": 52, "score": 80}, + {"id": "todd", "age": 52, "score": 15}, ] - result = util.sort_by_many([('age', 'ASC'), ('score', 'DESC')], people) - pprint({'RESULT': result}) + result = util.sort_by_many([("age", "ASC"), ("score", "DESC")], people) + pprint({"RESULT": result}) for index in range(0, len(expected)): assertEqual(expected[index], result[index]) def test_min_mapped(self): sequence = [ - {'val': 5}, - {'val': 10}, - {'val': 17}, - {'val': 2}, - {'val': 28}, - {'val': 8} + {"val": 5}, + {"val": 10}, + {"val": 17}, + {"val": 2}, + {"val": 28}, + {"val": 8}, ] def get_val(doc): - return doc['val'] - assertEqual({'val': 2}, util.min_mapped(get_val, sequence)) + return doc["val"] + + assertEqual({"val": 2}, util.min_mapped(get_val, sequence)) def test_max_mapped(self): sequence = [ - {'val': 5}, - {'val': 10}, - {'val': 17}, - {'val': 2}, - {'val': 28}, - {'val': 8} + {"val": 5}, + {"val": 10}, + {"val": 17}, + {"val": 2}, + {"val": 28}, + {"val": 8}, ] def get_val(doc): - return doc['val'] - assertEqual({'val': 28}, util.max_mapped(get_val, sequence)) + return doc["val"] + + assertEqual({"val": 28}, util.max_mapped(get_val, sequence)) def test_deep_extend_pair(self): - obj = { - 'x': { - 'x1': { - 'v1': 5, - 'v2': 7 - }, - 'nums': [1, 3, 5] - }, - 'a_list': [10, 20] - } + obj = {"x": {"x1": {"v1": 5, "v2": 7}, "nums": [1, 3, 5]}, "a_list": [10, 20]} ext_with = { - 'x': { - 'x2': { - 'x2-key': 'x2-val' - }, - 'x1': { - 'v2': 'new-v2-val', - 'v3': 'v3-val' - }, - 'nums': [7, 9] + "x": { + "x2": {"x2-key": "x2-val"}, + "x1": {"v2": "new-v2-val", "v3": "v3-val"}, + "nums": [7, 9], }, - 'a_list': 'new-a-list-val' + "a_list": "new-a-list-val", } expected = { - 'x': { - 'x2': { - 'x2-key': 'x2-val' - }, - 'x1': { - 'v1': 5, - 'v2': 'new-v2-val', - 'v3': 'v3-val' - }, - 'nums': [1, 3, 5, 7, 9] + "x": { + "x2": {"x2-key": "x2-val"}, + "x1": {"v1": 5, "v2": "new-v2-val", "v3": "v3-val"}, + "nums": [1, 3, 5, 7, 9], }, - 'a_list': 'new-a-list-val' + "a_list": "new-a-list-val", } result = util.deep_extend_pair(obj, ext_with) assertEqual(expected, result) @@ -364,15 +298,16 @@ def test_deep_extend_pair(self): class TestDictableSet(unittest.TestCase): def test_simple(self): - x = {'x': 10} + x = {"x": 10} foo = util.DictableSet([x]) self.assertTrue(foo.has(x)) - y = {'y': 15} + y = {"y": 15} self.assertFalse(foo.has(y)) def test_reordered_vals(self): def get_doc(): - return {'x': [5, 10]} + return {"x": [5, 10]} + foo = util.DictableSet([get_doc()]) self.assertTrue(foo.has(get_doc())) - self.assertTrue(foo.has({'x': [10, 5]})) + self.assertTrue(foo.has({"x": [10, 5]}))