id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
148,248
MacHu-GWU/single_file_module-project
MacHu-GWU_single_file_module-project/sfm/fingerprint.py
sfm.fingerprint.FingerPrint
class FingerPrint(object): """A hashlib wrapper class allow you to use one line to do hash as you wish. :type algorithm: str :param algorithm: default "md5" Usage:: >>> from sfm.fingerprint import fingerprint >>> print(fingerprint.of_bytes(bytes(123))) b1fec41621e338896e2d26f232a6b006 >>> print(fingerprint.of_text("message")) 78e731027d8fd50ed642340b7c9a63b3 >>> print(fingerprint.of_pyobj({"key": "value"})) 4c502ab399c89c8758a2d8c37be98f69 >>> print(fingerprint.of_file("fingerprint.py")) 4cddcb5562cbff652b0e4c8a0300337a """ _mapper = { "md5": hashlib.md5, "sha1": hashlib.sha1, "sha256": hashlib.sha256, "sha512": hashlib.sha512, } def __init__(self, algorithm="md5", pk_protocol=default_pk_protocol): self.hash_algo = hashlib.md5 self.return_int = False self.pk_protocol = 2 self.use(algorithm) self.set_return_str() self.set_pickle_protocol(pk_protocol) def use(self, algorithm): """Change the hash algorithm you gonna use. """ try: self.hash_algo = self._mapper[algorithm.strip().lower()] except IndexError: # pragma: no cover template = "'%s' is not supported, try one of %s." raise ValueError(template % (algorithm, list(self._mapper))) def use_md5(self): """ Use md5 hash algorithm. """ self.use("md5") def use_sha1(self): """ Use sha1 hash algorithm. """ self.use("sha1") def use_sha256(self): """ Use sha256 hash algorithm. """ self.use("sha256") def use_sha512(self): """ Use sha512 hash algorithm. """ self.use("sha512") def digest_to_int(self, digest): """Convert hexdigest str to int. """ return int(digest, 16) def set_return_int(self): """Set to return hex integer. """ self.return_int = True def set_return_str(self): """Set to return hex string. """ self.return_int = False def set_pickle_protocol(self, pk_protocol): """Set pickle protocol. """ if pk_protocol not in [2, 3]: raise ValueError("pickle protocol has to be 2 or 3!") self.pk_protocol = pk_protocol def set_pickle2(self): """ Set pickle protocol to 2. """ self.set_pickle_protocol(2) def set_pickle3(self): """ Set pickle protocol to 3. """ self.set_pickle_protocol(3) def digest(self, hash_method): if self.return_int: return int(hash_method.hexdigest(), 16) else: return hash_method.hexdigest() # hash function def of_bytes(self, py_bytes): """ Use default hash method to return hash value of bytes. :type py_bytes: binary_type :param py_bytes: a binary object """ m = self.hash_algo() m.update(py_bytes) return self.digest(m) def of_text(self, text, encoding="utf-8"): """ Use default hash method to return hash value of a piece of string default setting use 'utf-8' encoding. :type text: text_type :param text: a text object """ m = self.hash_algo() m.update(text.encode(encoding)) return self.digest(m) def of_pyobj(self, pyobj): """ Use default hash method to return hash value of a piece of Python picklable object. :param pyobj: any python object """ m = self.hash_algo() m.update(pickle.dumps(pyobj, protocol=self.pk_protocol)) return self.digest(m) def of_file(self, abspath, nbytes=0, chunk_size=1024): """ Use default hash method to return hash value of a piece of a file Estimate processing time on: :type abspath: text_type :param abspath: the absolute path to the file. :type nbytes: int :param nbytes: only has first N bytes of the file. if 0, hash all file. :type chunk_size: int :param chunk_size: The max memory we use at one time. CPU = i7-4600U 2.10GHz - 2.70GHz, RAM = 8.00 GB 1 second can process 0.25GB data - 0.59G - 2.43 sec - 1.3G - 5.68 sec - 1.9G - 7.72 sec - 2.5G - 10.32 sec - 3.9G - 16.0 sec ATTENTION: if you change the meta data (for example, the title, years information in audio, video) of a multi-media file, then the hash value gonna also change. """ if nbytes < 0: raise ValueError("chunk_size cannot smaller than 0") if chunk_size < 1: raise ValueError("chunk_size cannot smaller than 1") if (nbytes > 0) and (nbytes < chunk_size): chunk_size = nbytes m = self.hash_algo() with open(abspath, "rb") as f: if nbytes: # use first n bytes have_reads = 0 while True: have_reads += chunk_size if have_reads > nbytes: n = nbytes - (have_reads - chunk_size) if n: data = f.read(n) m.update(data) break else: data = f.read(chunk_size) m.update(data) else: # use entire content while True: data = f.read(chunk_size) if not data: break m.update(data) return m.hexdigest()
class FingerPrint(object): '''A hashlib wrapper class allow you to use one line to do hash as you wish. :type algorithm: str :param algorithm: default "md5" Usage:: >>> from sfm.fingerprint import fingerprint >>> print(fingerprint.of_bytes(bytes(123))) b1fec41621e338896e2d26f232a6b006 >>> print(fingerprint.of_text("message")) 78e731027d8fd50ed642340b7c9a63b3 >>> print(fingerprint.of_pyobj({"key": "value"})) 4c502ab399c89c8758a2d8c37be98f69 >>> print(fingerprint.of_file("fingerprint.py")) 4cddcb5562cbff652b0e4c8a0300337a ''' def __init__(self, algorithm="md5", pk_protocol=default_pk_protocol): pass def use(self, algorithm): '''Change the hash algorithm you gonna use. ''' pass def use_md5(self): ''' Use md5 hash algorithm. ''' pass def use_sha1(self): ''' Use sha1 hash algorithm. ''' pass def use_sha256(self): ''' Use sha256 hash algorithm. ''' pass def use_sha512(self): ''' Use sha512 hash algorithm. ''' pass def digest_to_int(self, digest): '''Convert hexdigest str to int. ''' pass def set_return_int(self): '''Set to return hex integer. ''' pass def set_return_str(self): '''Set to return hex string. ''' pass def set_pickle_protocol(self, pk_protocol): '''Set pickle protocol. ''' pass def set_pickle2(self): ''' Set pickle protocol to 2. ''' pass def set_pickle3(self): ''' Set pickle protocol to 3. ''' pass def digest_to_int(self, digest): pass def of_bytes(self, py_bytes): ''' Use default hash method to return hash value of bytes. :type py_bytes: binary_type :param py_bytes: a binary object ''' pass def of_text(self, text, encoding="utf-8"): ''' Use default hash method to return hash value of a piece of string default setting use 'utf-8' encoding. :type text: text_type :param text: a text object ''' pass def of_pyobj(self, pyobj): ''' Use default hash method to return hash value of a piece of Python picklable object. :param pyobj: any python object ''' pass def of_file(self, abspath, nbytes=0, chunk_size=1024): ''' Use default hash method to return hash value of a piece of a file Estimate processing time on: :type abspath: text_type :param abspath: the absolute path to the file. :type nbytes: int :param nbytes: only has first N bytes of the file. if 0, hash all file. :type chunk_size: int :param chunk_size: The max memory we use at one time. CPU = i7-4600U 2.10GHz - 2.70GHz, RAM = 8.00 GB 1 second can process 0.25GB data - 0.59G - 2.43 sec - 1.3G - 5.68 sec - 1.9G - 7.72 sec - 2.5G - 10.32 sec - 3.9G - 16.0 sec ATTENTION: if you change the meta data (for example, the title, years information in audio, video) of a multi-media file, then the hash value gonna also change. ''' pass
18
16
9
1
5
4
2
0.94
1
4
0
0
17
3
17
17
204
36
88
31
70
83
80
30
62
10
1
5
29
148,249
MacHu-GWU/single_file_module-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_single_file_module-project/tests/test_exception_mate.py
test_exception_mate.test_ExceptionHavingDefaultMessage.OutputError
class OutputError(em.ExceptionHavingDefaultMessage): pass
class OutputError(em.ExceptionHavingDefaultMessage): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
11
2
0
2
1
1
0
2
1
1
0
4
0
0
148,250
MacHu-GWU/single_file_module-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_single_file_module-project/tests/test_marshmallow_fields.py
test_marshmallow_fields.test_LowerStringField.UserSchema
class UserSchema(Schema): name = marshmallow_fields.LowerStringField()
class UserSchema(Schema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
148,251
MacHu-GWU/single_file_module-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_single_file_module-project/tests/test_marshmallow_fields.py
test_marshmallow_fields.test_NonEmptyStringField.UserSchema
class UserSchema(Schema): name = marshmallow_fields.NonEmptyStringField()
class UserSchema(Schema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
148,252
MacHu-GWU/single_file_module-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_single_file_module-project/tests/test_marshmallow_fields.py
test_marshmallow_fields.test_TitleStringField.UserSchema
class UserSchema(Schema): name = marshmallow_fields.TitleStringField()
class UserSchema(Schema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
148,253
MacHu-GWU/single_file_module-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_single_file_module-project/tests/test_marshmallow_fields.py
test_marshmallow_fields.test_UpperStringField.UserSchema
class UserSchema(Schema): name = marshmallow_fields.UpperStringField()
class UserSchema(Schema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
148,254
MacHu-GWU/single_file_module-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_single_file_module-project/tests/test_nameddict.py
test_nameddict.test_Base.Person
class Person(Base): __attrs__ = ["id", "name"]
class Person(Base): pass
1
0
4
0
4
0
1
0
1
0
0
0
1
3
1
16
6
1
5
5
3
0
5
5
3
1
2
0
1
148,255
MacHu-GWU/single_file_module-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_single_file_module-project/tests/test_nameddict.py
test_nameddict.test_Base.Person
class Person(Base): __attrs__ = ["id", "name"]
class Person(Base): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
15
2
0
2
2
1
0
2
2
1
0
2
0
0
148,256
MacHu-GWU/single_file_module-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_single_file_module-project/tests/test_nameddict.py
test_nameddict.test_comparison.User
class User(Base): pass
class User(Base): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
15
2
0
2
1
1
0
2
1
1
0
2
0
0
148,257
MacHu-GWU/single_file_module-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_single_file_module-project/tests/test_nameddict.py
test_nameddict.test_excludes_attribute_name.User
class User(Base): __attrs__ = ["id", "name", "gender"] __excludes__ = ["name"]
class User(Base): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
15
3
0
3
3
2
0
3
3
2
0
2
0
0
148,258
MacHu-GWU/single_file_module-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_single_file_module-project/tests/test_nameddict.py
test_nameddict.test_property_decorator.Employee
class Employee(Base): __attrs__ = ["base_salary", "bonus", "total_salary"] def __init__(self, base_salary, bonus): self.base_salary = base_salary self.bonus = bonus @property def total_salary(self): return self.base_salary + self.bonus
class Employee(Base): def __init__(self, base_salary, bonus): pass @property def total_salary(self): pass
4
0
3
0
3
0
1
0
1
0
0
0
1
2
1
16
6
1
5
5
3
0
5
5
3
1
2
0
1
148,259
MacHu-GWU/single_file_module-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_single_file_module-project/tests/test_nameddict.py
test_nameddict.test_property_decorator.Employee
class Employee(Base): __attrs__ = ["base_salary", "bonus", "total_salary"] def __init__(self, base_salary, bonus): self.base_salary = base_salary self.bonus = bonus @property def total_salary(self): return self.base_salary + self.bonus
class Employee(Base): def __init__(self, base_salary, bonus): pass @property def total_salary(self): pass
4
0
3
0
3
0
1
0
1
0
0
0
2
2
2
17
10
2
8
7
4
0
7
6
4
1
2
0
2
148,260
MacHu-GWU/single_file_module-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_single_file_module-project/tests/test_nameddict.py
test_nameddict.test_reserved_attribute_name.User
class User(Base): def __init__(self, keys, values): self.keys = keys self.values = values
class User(Base): def __init__(self, keys, values): pass
2
0
0
0
0
0
0
0
1
0
0
0
0
0
0
15
2
0
2
1
1
0
2
1
1
0
2
0
0
148,261
MacHu-GWU/single_file_module-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_single_file_module-project/tests/test_nameddict.py
test_nameddict.test_reserved_attribute_name.User
class User(Base): def __init__(self, keys, values): self.keys = keys self.values = values
class User(Base): def __init__(self, keys, values): pass
2
0
3
0
3
0
1
0
1
0
0
0
1
2
1
16
5
1
4
4
2
0
4
4
2
1
2
0
1
148,262
MacHu-GWU/single_file_module-project
MacHu-GWU_single_file_module-project/sfm/nameddict.py
sfm.nameddict.Base
class Base(object): """nameddict base class. """ __attrs__ = None """该属性非常重要, 定义了哪些属性被真正视为 ``attributes``, 换言之, 就是在 :meth:`~Base.keys()`, :meth:`~Base.values()`, :meth:`~Base.items()`, :meth:`~Base.to_list()`, :meth:`~Base.to_dict()`, :meth:`~Base.to_OrderedDict()`, :meth:`~Base.to_json()`, 方法中要被包括的属性。 """ __excludes__ = [] """在此被定义的属性将不会出现在 :meth:`~Base.items()` 中 """ __reserved__ = set(["keys", "values", "items"]) def __init__(self, **kwargs): for attr, value in kwargs.items(): setattr(self, attr, value) def __setattr__(self, attr, value): if attr in self.__reserved__: raise ValueError("%r is a reserved attribute name!" % attr) object.__setattr__(self, attr, value) def __repr__(self): kwargs = list() for attr, value in self.items(): kwargs.append("%s=%r" % (attr, value)) return "%s(%s)" % (self.__class__.__name__, ", ".join(kwargs)) def __getitem__(self, key): """Access attribute. """ return object.__getattribute__(self, key) @classmethod def _make(cls, d): """Make an instance. """ return cls(**d) def items(self): """items按照属性的既定顺序返回attr, value对。当 ``__attrs__`` 未指明时, 则按照字母顺序返回。若 ``__attrs__`` 已定义时, 按照其中的顺序返回。 当有 ``@property`` 装饰器所装饰的属性时, 若没有在 ``__attrs__`` 中定义, 则items中不会包含它。 """ items = list() if self.__attrs__ is None: for key, value in self.__dict__.items(): if key not in self.__excludes__: items.append((key, value)) items = list(sorted(items, key=lambda x: x[0])) return items try: for attr in self.__attrs__: if attr not in self.__excludes__: try: items.append( (attr, copy.deepcopy(getattr(self, attr)))) except AttributeError: items.append( (attr, copy.deepcopy(self.__dict__.get(attr)))) return items except: raise AttributeError() def keys(self): """Iterate attributes name. """ return [key for key, value in self.items()] def values(self): """Iterate attributes value. """ return [value for key, value in self.items()] def __iter__(self): """Iterate attributes. """ if self.__attrs__ is None: return iter(self.keys()) try: return iter(self.__attrs__) except: raise AttributeError() def to_list(self): """Export data to list. Will create a new copy for mutable attribute. """ return self.keys() def to_dict(self): """Export data to dict. Will create a new copy for mutable attribute. """ return dict(self.items()) def to_OrderedDict(self): """Export data to OrderedDict. Will create a new copy for mutable attribute. """ return OrderedDict(self.items()) def to_json(self, sort_keys=False, indent=None): """Export data to json. If it is json serilizable. """ return json.dumps(self.to_dict(), sort_keys=sort_keys, indent=indent) def __eq__(self, other): """Equal to. """ return self.items() == other.items() def __lt__(self, other): """Less than. """ for (_, value1), (_, value2) in zip(self.items(), other.items()): if value1 >= value2: return False return True
class Base(object): '''nameddict base class. ''' def __init__(self, **kwargs): pass def __setattr__(self, attr, value): pass def __repr__(self): pass def __getitem__(self, key): '''Access attribute. ''' pass @classmethod def _make(cls, d): '''Make an instance. ''' pass def items(self): '''items按照属性的既定顺序返回attr, value对。当 ``__attrs__`` 未指明时, 则按照字母顺序返回。若 ``__attrs__`` 已定义时, 按照其中的顺序返回。 当有 ``@property`` 装饰器所装饰的属性时, 若没有在 ``__attrs__`` 中定义, 则items中不会包含它。 ''' pass def keys(self): '''Iterate attributes name. ''' pass def values(self): '''Iterate attributes value. ''' pass def __iter__(self): '''Iterate attributes. ''' pass def to_list(self): '''Export data to list. Will create a new copy for mutable attribute. ''' pass def to_dict(self): '''Export data to dict. Will create a new copy for mutable attribute. ''' pass def to_OrderedDict(self): '''Export data to OrderedDict. Will create a new copy for mutable attribute. ''' pass def to_json(self, sort_keys=False, indent=None): '''Export data to json. If it is json serilizable. ''' pass def __eq__(self, other): '''Equal to. ''' pass def __lt__(self, other): '''Less than. ''' pass
17
13
6
0
4
2
2
0.55
1
6
0
9
14
0
15
15
124
20
67
29
50
37
64
26
48
8
1
4
29
148,263
MacHu-GWU/single_file_module-project
MacHu-GWU_single_file_module-project/sfm/dtree.py
sfm.dtree.DictTree
class DictTree(object): """ Pure python xml doc tree implementation in dictionary. Usage:: >>> dt = DictTree(name="USA") >>> dt["MD"] = DictTree(name="Maryland") >>> dt["VA"] = DictTree(name="Virginia") >>> dt["MD"]["Gaithersburg"] = DictTree(name="Gaithersburg", zipcode="20878") >>> dt["MD"]["College Park"] = DictTree(name="College Park", zipcode="20740") >>> dt["VA"]["Arlington"] = DictTree(name="Arlington", zipcode="22202") >>> dt["VA"]["Fairfax"] = DictTree(name="Fairfax", zipcode="20030") # visit tree metadata >>> dt.name USA >>> dt["MD"].name Maryland # visit node >>> dt["MD"] { "College Park": { "__key__": "College Park", "__meta__": { "name": "College Park", "zipcode": "20740" } }, "Gaithersburg": { "__key__": "Gaithersburg", "__meta__": { "name": "Gaithersburg", "zipcode": "20878" } }, "__key__": "MD", "__meta__": { "name": "Maryland" } } # visit key >>> dt_MD = dt["MD"] >>> dt_MD._key() MD >>> list(dt.keys_at(depth=1)) # or values_at(depth), items_at(depth) ['MD', 'VA'] >>> list(dt.keys_at(depth=2)) ['Gaithersburg', 'College Park', 'Arlington', 'Fairfax'] **中文文档** internal data structure:: { META: {key: value}, # parent tree attributes "child_key1": ... , # child tree's key, value pair. "child_key2": ... , ... } 对于根树而言, Key为 ``"root"`` """ __slots__ = [DATA, ] def __init__(self, __data__=None, **kwargs): if __data__ is None: object.__setattr__(self, DATA, {META: kwargs, KEY: ROOT}) else: object.__setattr__(self, DATA, __data__) def __str__(self): try: return json.dumps(self.__data__, sort_keys=True, indent=4) except: return str(self.__data__) def dump(self, path): """ dump DictTree data to json files. """ try: with open(path, "wb") as f: f.write(self.__str__().encode("utf-8")) except: pass with open(path, "wb") as f: pickle.dump(self.__data__, f) @classmethod def load(cls, path): """ load DictTree from json files. """ try: with open(path, "rb") as f: return cls(__data__=json.loads(f.read().decode("utf-8"))) except: pass with open(path, "rb") as f: return cls(__data__=pickle.load(f)) def __getattribute__(self, attr): try: return object.__getattribute__(self, DATA)[META][attr] except KeyError: return object.__getattribute__(self, attr) def __setattr__(self, attr, value): self.__data__[META][attr] = value def __setitem__(self, key, dict_tree): if key in (META, KEY): raise ValueError("'key' can't be '__meta__'!") if isinstance(dict_tree, DictTree): dict_tree.__data__[KEY] = key self.__data__[key] = dict_tree.__data__ else: raise TypeError("attribute assignment only takes 'DictTree'.") def __getitem__(self, key): return DictTree(__data__=self.__data__[key]) def __delitem__(self, key): if key in (META, KEY): raise ValueError("'key' can't be '__meta__'!") self.__data__[key][KEY] = ROOT del self.__data__[key] def __contains__(self, item): return item in self.__data__ def __len__(self): """ Return number of child trees. **中文文档** 返回子树的数量。 """ return len(self.__data__) - 2 def __iter__(self): for key in self.__data__: if key not in (META, KEY): yield key def _key(self): return self.__data__[KEY] def keys(self): """ Iterate keys. """ for key in self.__data__: if key not in (META, KEY): yield key def values(self): """ Iterate values. """ for key, value in self.__data__.items(): if key not in (META, KEY): yield DictTree(__data__=value) def items(self): """ Iterate items. :return: """ for key, value in self.__data__.items(): if key not in (META, KEY): yield key, DictTree(__data__=value) def keys_at(self, depth, counter=1): """ Iterate keys at specified depth. """ if depth < 1: yield ROOT else: if counter == depth: for key in self.keys(): yield key else: counter += 1 for dict_tree in self.values(): for key in dict_tree.keys_at(depth, counter): yield key def values_at(self, depth): """ Iterate values at specified depth. """ if depth < 1: yield self else: for dict_tree in self.values(): for value in dict_tree.values_at(depth - 1): yield value def items_at(self, depth): """ Iterate items at specified depth. """ if depth < 1: yield ROOT, self elif depth == 1: for key, value in self.items(): yield key, value else: for dict_tree in self.values(): for key, value in dict_tree.items_at(depth - 1): yield key, value def length_at(self, depth): """Get the number of nodes on specific depth. """ if depth == 0: return 1 counter = 0 for dict_tree in self.values_at(depth - 1): counter += len(dict_tree) return counter def stats(self, result=None, counter=0): """ Display the node stats info on specific depth in this dict. :: [ {"depth": 0, "leaf": M0, "root": N0}, {"depth": 1, "leaf": M1, "root": N1}, ... {"depth": k, "leaf": Mk, "root": Nk}, ] """ if result is None: result = dict() if counter == 0: if len(self): result[0] = {"depth": 0, "leaf": 0, "root": 1} else: result[0] = {"depth": 0, "leaf": 1, "root": 0} counter += 1 if len(self): result.setdefault( counter, {"depth": counter, "leaf": 0, "root": 0}) for dict_tree in self.values(): if len(dict_tree): # root result[counter]["root"] += 1 else: # leaf result[counter]["leaf"] += 1 dict_tree.stats(result, counter) return [ collections.OrderedDict([ ("depth", info["depth"]), ("leaf", info["leaf"]), ("root", info["root"]), ]) for info in sorted(result.values(), key=lambda x: x["depth"]) ] def stats_at(self, depth, display=False): root, leaf = 0, 0 for dict_tree in self.values_at(depth): if len(dict_tree): root += 1 else: leaf += 1 total = root + leaf if display: # pragma: no cover print("On depth %s, having %s root nodes, %s leaf nodes. " "%s nodes in total." % (depth, root, leaf, total)) return root, leaf, total
class DictTree(object): ''' Pure python xml doc tree implementation in dictionary. Usage:: >>> dt = DictTree(name="USA") >>> dt["MD"] = DictTree(name="Maryland") >>> dt["VA"] = DictTree(name="Virginia") >>> dt["MD"]["Gaithersburg"] = DictTree(name="Gaithersburg", zipcode="20878") >>> dt["MD"]["College Park"] = DictTree(name="College Park", zipcode="20740") >>> dt["VA"]["Arlington"] = DictTree(name="Arlington", zipcode="22202") >>> dt["VA"]["Fairfax"] = DictTree(name="Fairfax", zipcode="20030") # visit tree metadata >>> dt.name USA >>> dt["MD"].name Maryland # visit node >>> dt["MD"] { "College Park": { "__key__": "College Park", "__meta__": { "name": "College Park", "zipcode": "20740" } }, "Gaithersburg": { "__key__": "Gaithersburg", "__meta__": { "name": "Gaithersburg", "zipcode": "20878" } }, "__key__": "MD", "__meta__": { "name": "Maryland" } } # visit key >>> dt_MD = dt["MD"] >>> dt_MD._key() MD >>> list(dt.keys_at(depth=1)) # or values_at(depth), items_at(depth) ['MD', 'VA'] >>> list(dt.keys_at(depth=2)) ['Gaithersburg', 'College Park', 'Arlington', 'Fairfax'] **中文文档** internal data structure:: { META: {key: value}, # parent tree attributes "child_key1": ... , # child tree's key, value pair. "child_key2": ... , ... } 对于根树而言, Key为 ``"root"`` ''' def __init__(self, __data__=None, **kwargs): pass def __str__(self): pass def dump(self, path): ''' dump DictTree data to json files. ''' pass @classmethod def load(cls, path): ''' load DictTree from json files. ''' pass def __getattribute__(self, attr): pass def __setattr__(self, attr, value): pass def __setitem__(self, key, dict_tree): pass def __getitem__(self, key): pass def __delitem__(self, key): pass def __contains__(self, item): pass def __len__(self): ''' Return number of child trees. **中文文档** 返回子树的数量。 ''' pass def __iter__(self): pass def _key(self): pass def keys(self): ''' Iterate keys. ''' pass def values(self): ''' Iterate values. ''' pass def items(self): ''' Iterate items. :return: ''' pass def keys_at(self, depth, counter=1): ''' Iterate keys at specified depth. ''' pass def values_at(self, depth): ''' Iterate values at specified depth. ''' pass def items_at(self, depth): ''' Iterate items at specified depth. ''' pass def length_at(self, depth): '''Get the number of nodes on specific depth. ''' pass def stats(self, result=None, counter=0): ''' Display the node stats info on specific depth in this dict. :: [ {"depth": 0, "leaf": M0, "root": N0}, {"depth": 1, "leaf": M1, "root": N1}, ... {"depth": k, "leaf": Mk, "root": Nk}, ] ''' pass def stats_at(self, depth, display=False): pass
24
12
9
1
7
2
3
0.68
1
6
0
0
21
1
22
22
291
47
147
44
123
100
127
40
104
7
1
4
62
148,264
MacHu-GWU/single_file_module-project
MacHu-GWU_single_file_module-project/sfm/exception_mate.py
sfm.exception_mate.Error
class Error(object): """Advance exception info data container. :param exc_value: Exception, the Exception instance. :param filename: str, the file name of the error. :param line_num: int, the line number of where the error happens. :param func_name: str, the closest function who raise the error. :param code: str, code line of where the error happens. """ exc_value = attr.ib() filename = attr.ib() line_num = attr.ib() func_name = attr.ib() code = attr.ib() @property def exc_type(self): return self.exc_value.__class__ @property def formatted(self): template = "`{exc_value.__class__.__name__}: {exc_value}`, appears in `{filename}` at line {line_num} in `{func_name}()`, code: `{code}`" return template.format( exc_value=self.exc_value, filename=self.filename, line_num=self.line_num, func_name=self.func_name, code=self.code, )
class Error(object): '''Advance exception info data container. :param exc_value: Exception, the Exception instance. :param filename: str, the file name of the error. :param line_num: int, the line number of where the error happens. :param func_name: str, the closest function who raise the error. :param code: str, code line of where the error happens. ''' @property def exc_type(self): pass @property def formatted(self): pass
5
1
6
0
6
0
1
0.37
1
0
0
0
2
0
2
2
29
3
19
11
14
7
11
9
8
1
1
0
2
148,265
MacHu-GWU/single_file_module-project
MacHu-GWU_single_file_module-project/sfm/marshmallow_fields.py
sfm.marshmallow_fields.UpperStringField
class UpperStringField(AutoConvertField): """Uppercased string. **中文文档** - 前后没有空格 - 全部小写 """ def convert(self, value): if value is None: return None if isinstance(value, string_types): value = value.strip().upper() if value: return value else: return None else: raise ValidationError("Not a string type")
class UpperStringField(AutoConvertField): '''Uppercased string. **中文文档** - 前后没有空格 - 全部小写 ''' def convert(self, value): pass
2
1
12
1
11
0
4
0.42
1
0
0
0
1
0
1
5
21
4
12
2
10
5
10
2
8
4
3
2
4
148,266
MacHu-GWU/single_file_module-project
MacHu-GWU_single_file_module-project/sfm/marshmallow_fields.py
sfm.marshmallow_fields.TitleStringField
class TitleStringField(AutoConvertField): """Titlized string. **中文文档** 标题格式的字符串。 - 字符串 - 前后都没有空格 - 不得出现连续两个以上的空格 - 每个单词首字母大写, 其他字母小写 """ def convert(self, value): if value is None: return None if isinstance(value, string_types): value = value.strip() if value: chunks = list() for s in [s.strip() for s in value.split(" ") if s.strip()]: if str.isalpha(s): s = s[0].upper() + s[1:].lower() chunks.append(s) return " ".join(chunks) else: return None else: raise ValidationError("Not a string type")
class TitleStringField(AutoConvertField): '''Titlized string. **中文文档** 标题格式的字符串。 - 字符串 - 前后都没有空格 - 不得出现连续两个以上的空格 - 每个单词首字母大写, 其他字母小写 ''' def convert(self, value): pass
2
1
17
1
16
0
6
0.47
1
2
0
0
1
0
1
5
30
5
17
4
15
8
15
4
13
6
3
4
6
148,267
MacHu-GWU/single_file_module-project
MacHu-GWU_single_file_module-project/sfm/marshmallow_fields.py
sfm.marshmallow_fields.NonEmptyStringField
class NonEmptyStringField(AutoConvertField): """A non empty string field. **中文文档** 非空字符串。 """ def convert(self, value): if value is None: return None if isinstance(value, string_types): value = value.strip() if value: return value else: return None else: raise ValidationError("Not a string type.")
class NonEmptyStringField(AutoConvertField): '''A non empty string field. **中文文档** 非空字符串。 ''' def convert(self, value): pass
2
1
12
1
11
0
4
0.33
1
0
0
0
1
0
1
5
20
4
12
2
10
4
10
2
8
4
3
2
4
148,268
MacHu-GWU/single_file_module-project
MacHu-GWU_single_file_module-project/sfm/marshmallow_fields.py
sfm.marshmallow_fields.LowerStringField
class LowerStringField(AutoConvertField): """Lowercased string. **中文文档** - 前后没有空格 - 全部小写 """ def convert(self, value): if value is None: return None if isinstance(value, string_types): value = value.strip().lower() if value: return value else: return None else: raise ValidationError("Not a string type")
class LowerStringField(AutoConvertField): '''Lowercased string. **中文文档** - 前后没有空格 - 全部小写 ''' def convert(self, value): pass
2
1
12
1
11
0
4
0.42
1
0
0
0
1
0
1
5
21
4
12
2
10
5
10
2
8
4
3
2
4
148,269
MacHu-GWU/single_file_module-project
MacHu-GWU_single_file_module-project/sfm/marshmallow_fields.py
sfm.marshmallow_fields.AllowNoneField
class AllowNoneField(fields.Field): """This field always allow None. **中文文档** 默认允许None值。 """ def __init__(self, *args, **kwargs): kwargs["allow_none"] = True super(AllowNoneField, self).__init__(*args, **kwargs)
class AllowNoneField(fields.Field): '''This field always allow None. **中文文档** 默认允许None值。 ''' def __init__(self, *args, **kwargs): pass
2
1
3
0
3
0
1
1
1
1
0
1
1
0
1
1
11
3
4
2
2
4
4
2
2
1
1
0
1
148,270
MacHu-GWU/single_file_module-project
MacHu-GWU_single_file_module-project/sfm/geo_search.py
sfm.geo_search.GeoSearchEngine
class GeoSearchEngine(object): def __init__(self, name="point", database=":memory:"): self.engine = create_engine("sqlite:///%s" % database) self.metadata = MetaData() self.t_point = Table(name, self.metadata, Column("id", String), Column("lat", Float), Column("lng", Float), Column("data", PickleType), ) def train(self, data, key_id, key_lat, key_lng, clear_old=True): """ Feed data into database. :type data: list :param data: list of point object, can have other metadata, for example: [{"id": 10001, "lat": xxx, "lng": xxx}, ...] :type key_id: callable :param key_id: callable function, take point object as input, return object id, for example: lambda x: x["id"] :type key_lat: callable :param key_lat: callable function, take point object as input, return object latitude, for example: lambda x: x["lat"] :type key_lng: callable :param key_lng: callable function, take point object as input, return object longitude, for example: lambda x: x["lng"] """ engine, t_point = self.engine, self.t_point if clear_old: try: t_point.drop(engine) except: pass t_point.create(engine) table_data = list() for record in data: id = key_id(record) lat = key_lat(record) lng = key_lng(record) row = {"id": id, "lat": lat, "lng": lng, "data": record} table_data.append(row) ins = t_point.insert() engine.execute(ins, table_data) index = Index('idx_lat_lng', t_point.c.lat, t_point.c.lng) index.create(engine) def find_n_nearest(self, lat, lng, n=5, radius=None): """Find n nearest point within certain distance from a point. :param lat: latitude of center point. :param lng: longitude of center point. :param n: max number of record to return. :param radius: only search point within ``radius`` distance. **中文文档** """ engine, t_point = self.engine, self.t_point if radius: # Use a simple box filter to minimize candidates # Define latitude longitude boundary dist_btwn_lat_deg = 69.172 dist_btwn_lon_deg = cos(lat) * 69.172 lat_degr_rad = abs(radius * 1.05 / dist_btwn_lat_deg) lon_degr_rad = abs(radius * 1.05 / dist_btwn_lon_deg) lat_lower = lat - lat_degr_rad lat_upper = lat + lat_degr_rad lng_lower = lng - lon_degr_rad lng_upper = lng + lon_degr_rad filters = [ t_point.c.lat >= lat_lower, t_point.c.lat <= lat_upper, t_point.c.lat >= lng_lower, t_point.c.lat >= lng_upper, ] else: radius = 999999.9 filters = [] s = select([t_point]).where(and_(*filters)) heap = list() for row in engine.execute(s): dist = great_circle((lat, lng), (row.lat, row.lng)) if dist <= radius: heap.append((dist, row.data)) # Use heap sort to find top-K nearest n_nearest = heapq.nsmallest(n, heap, key=lambda x: x[0]) return n_nearest
class GeoSearchEngine(object): def __init__(self, name="point", database=":memory:"): pass def train(self, data, key_id, key_lat, key_lng, clear_old=True): ''' Feed data into database. :type data: list :param data: list of point object, can have other metadata, for example: [{"id": 10001, "lat": xxx, "lng": xxx}, ...] :type key_id: callable :param key_id: callable function, take point object as input, return object id, for example: lambda x: x["id"] :type key_lat: callable :param key_lat: callable function, take point object as input, return object latitude, for example: lambda x: x["lat"] :type key_lng: callable :param key_lng: callable function, take point object as input, return object longitude, for example: lambda x: x["lng"] ''' pass def find_n_nearest(self, lat, lng, n=5, radius=None): '''Find n nearest point within certain distance from a point. :param lat: latitude of center point. :param lng: longitude of center point. :param n: max number of record to return. :param radius: only search point within ``radius`` distance. **中文文档** ''' pass
4
2
32
5
19
8
3
0.44
1
1
0
0
3
3
3
3
98
16
57
30
53
25
46
30
42
4
1
2
9
148,271
MacHu-GWU/single_file_module-project
MacHu-GWU_single_file_module-project/sfm/timer.py
sfm.timer.SerialTimer
class SerialTimer(object): def __init__(self, timer_klass=DateTimeTimer): """ :param timer_klass: """ self.timer_klass = timer_klass self.current_timer = None self.last_stopped_timer = None self.history_stopped_timer = list() def start(self, title=None, display=True): self.current_timer = self.timer_klass(title, display) self.current_timer.start() def _measure(self): if self.current_timer is None: raise RuntimeError("please call SerialTimer.start() first!") self.current_timer.end() self.last_stopped_timer = self.current_timer self.history_stopped_timer.append(self.last_stopped_timer) def end(self): self._measure() self.current_timer = None def click(self, title=None, display=True): self._measure() self.current_timer = self.timer_klass(title, display) @property def last(self): return self.last_stopped_timer @property def history(self): return self.history_stopped_timer
class SerialTimer(object): def __init__(self, timer_klass=DateTimeTimer): ''' :param timer_klass: ''' pass def start(self, title=None, display=True): pass def _measure(self): pass def end(self): pass def click(self, title=None, display=True): pass @property def last(self): pass @property def history(self): pass
10
1
4
0
3
0
1
0.11
1
3
1
0
7
4
7
7
36
6
27
14
17
3
25
12
17
2
1
1
8
148,272
MacHu-GWU/single_file_module-project
MacHu-GWU_single_file_module-project/sfm/timer.py
sfm.timer.TimeTimer
class TimeTimer(BaseTimer): """ Similar to :class:`DateTimeTimer` .. warning:: DateTimeTimer has around 0.003 seconds error in average for each measure. """ def _get_current_time(self): return time.time() def _get_delta_in_sec(self, start, end): return end - start
class TimeTimer(BaseTimer): ''' Similar to :class:`DateTimeTimer` .. warning:: DateTimeTimer has around 0.003 seconds error in average for each measure. ''' def _get_current_time(self): pass def _get_delta_in_sec(self, start, end): pass
3
1
2
0
2
0
1
1
1
0
0
0
2
0
2
11
14
4
5
3
2
5
5
3
2
1
2
0
2
148,273
MacHu-GWU/single_file_module-project
MacHu-GWU_single_file_module-project/sfm/exception_mate.py
sfm.exception_mate.ErrorTraceBackChain
class ErrorTraceBackChain(object): """ A error trace back chain data container class. Trace error from end point back to start point. Example usage:: try: some_func(**kwargs) except SomeError: etbc = ErrorTraceBackChain.get_last_exc_info() ... defines how do you want to log relative exceptions """ errors = attr.ib(default=attr.Factory(list)) @errors.validator def check_errors(self, attribute, value): if not isinstance(value, list): raise TypeError("errors must be list of Error!") for error in value: if not isinstance(error, Error): raise TypeError("errors must be list of Error!") @property def raised_error(self): """ The error of where it is raised, the end point of the trace back chain. """ # This style tells the interpreter it returns a Error type. return Error(**attr.asdict(self.errors[0])) @property def source_error(self): """ The source of the error, the start point of the track back chain. """ return Error(**attr.asdict(self.errors[-1])) @classmethod def get_last_exc_info(cls): """Get rich info of last raised error. :returns: a ErrorTrackBack instance. """ exc_type, exc_value, exc_tb = sys.exc_info() errors = list() for filename, line_num, func_name, code in traceback.extract_tb(exc_tb): error = Error( exc_value=exc_value, filename=filename, line_num=line_num, func_name=func_name, code=code, ) errors.append(error) return cls(errors=errors) def __len__(self): return len(self.errors) def __iter__(self): return iter(self.errors)
class ErrorTraceBackChain(object): ''' A error trace back chain data container class. Trace error from end point back to start point. Example usage:: try: some_func(**kwargs) except SomeError: etbc = ErrorTraceBackChain.get_last_exc_info() ... defines how do you want to log relative exceptions ''' @errors.validator def check_errors(self, attribute, value): pass @property def raised_error(self): ''' The error of where it is raised, the end point of the trace back chain. ''' pass @property def source_error(self): ''' The source of the error, the start point of the track back chain. ''' pass @classmethod def get_last_exc_info(cls): '''Get rich info of last raised error. :returns: a ErrorTrackBack instance. ''' pass def __len__(self): pass def __iter__(self): pass
11
4
7
1
5
2
2
0.61
1
3
1
0
5
0
6
6
64
11
33
17
22
20
23
13
16
4
1
2
10
148,274
MacHu-GWU/single_file_module-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_single_file_module-project/sfm/rnd.py
sfm.rnd.SimpleFaker
class SimpleFaker(object): def __init__(self, locale="en_US"): self.fake = faker.Factory.create(locale)
class SimpleFaker(object): def __init__(self, locale="en_US"): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
1
1
1
3
0
3
3
1
0
3
3
1
1
1
0
1
148,275
MacHu-GWU/single_file_module-project
MacHu-GWU_single_file_module-project/tests/test_dtree.py
test_dtree.TestDictTree
class TestDictTree(object): dt_USA = DictTree(name="USA") dt_USA["MD"] = DictTree(name="Maryland") dt_VA = DictTree(name="Virginia") dt_USA["VA"] = dt_VA dt_USA["MD"]["Gaithersburg"] = DictTree(name="Gaithersburg", zipcode="20878") dt_COLLEGE_PARK = DictTree(name="College Park", zipcode="20740") dt_USA["MD"]["College Park"] = dt_COLLEGE_PARK dt_USA["VA"]["Arlington"] = DictTree(name="Arlington", zipcode="22202") dt_FAIRFAX = DictTree(name="Fairfax", zipcode="20030") dt_USA["VA"]["Fairfax"] = dt_FAIRFAX dt_USA = DictTree(__data__=json.loads(str(dt_USA))) def test_key(self): dt = DictTree(name="USA") assert dt._key() == "__root__" dt1 = DictTree(name="Maryland") assert dt1._key() == "__root__" dt["MD"] = dt1 assert dt._key() == "__root__" assert dt1._key() == "MD" assert dt["MD"]._key() == "MD" def test_setattr_getattr(self): dt_USA = DictTree(name="USA") # assign metadata when init assert dt_USA.name == "USA" dt_USA2 = DictTree() # assign metadata afterward dt_USA2.name = "USA" assert dt_USA2.name == "USA" dt_USA["MD"] = DictTree(name="Maryland") assert dt_USA["MD"].name == "Maryland" dt_VA = DictTree() dt_USA["VA"] = dt_VA dt_USA["VA"].name = "Virginia" assert dt_USA["VA"].name == "Virginia" # test with the universal case assert self.dt_USA["MD"].name == "Maryland" assert self.dt_USA["VA"].name == "Virginia" assert self.dt_USA["MD"]["College Park"].zipcode == "20740" assert self.dt_USA["VA"]["Arlington"].zipcode == "22202" def test_setitem_getitem_delitem(self): dt = DictTree() dt.name = "USA" dt_MD = DictTree(name="Maryland") dt["MD"] = dt_MD assert dt["MD"].name == "Maryland" assert dt["MD"].__data__ == dt_MD.__data__ assert dt["MD"]._key() == "MD" assert dt_MD._key() == "MD" assert "VA" not in dt dt_VA = DictTree(name="Virginia") assert dt_VA._key() == ROOT dt["VA"] = dt_VA assert dt_VA._key() == "VA" assert "VA" in dt del dt["VA"] assert "VA" not in dt assert dt_VA._key() == ROOT def test_iter(self): keys = list(self.dt_USA.keys()) keys.sort() assert keys == ["MD", "VA"] keys = list(self.dt_USA["VA"]) keys.sort() assert keys == ["Arlington", "Fairfax"] keys = list(self.dt_USA["VA"].keys()) keys.sort() assert keys == ["Arlington", "Fairfax"] keys = list(self.dt_VA) keys.sort() assert keys == ["Arlington", "Fairfax"] keys = list(self.dt_VA.keys()) keys.sort() assert keys == ["Arlington", "Fairfax"] for value in self.dt_USA.values(): assert isinstance(value, DictTree) for key, value in self.dt_USA.items(): assert key in ["MD", "VA"] assert isinstance(value, DictTree) def test_keys_at(self): keys = list(self.dt_USA.keys_at(0)) keys.sort() assert keys == [ROOT, ] keys = list(self.dt_USA.keys_at(1)) keys.sort() assert keys == ["MD", "VA"] keys = list(self.dt_USA.keys_at(2)) keys.sort() assert keys == ["Arlington", "College Park", "Fairfax", "Gaithersburg"] def test_values_at(self): names = [value.__data__["__meta__"]["name"] for value in self.dt_USA.values_at(0)] names.sort() names == ["United State", ] names = [value.__data__["__meta__"]["name"] for value in self.dt_USA.values_at(1)] names.sort() names == ["Maryland", "Virginia"] zipcodes = [ value.__data__["__meta__"]["zipcode"] for value in self.dt_USA.values_at(2) ] zipcodes.sort() zipcodes == ["20030", "20740", "20878", "22202"] def test_items_at(self): keys = [key for key, value in self.dt_USA.items_at(0)] keys.sort() assert keys == ["__root__"] keys = [key for key, value in self.dt_USA.items_at(1)] keys.sort() assert keys == ["MD", "VA"] keys = [key for key, value in self.dt_USA.items_at(2)] keys.sort() assert keys == ["Arlington", "College Park", "Fairfax", "Gaithersburg"] def test_length_at(self): assert self.dt_USA.length_at(0) == 1 assert self.dt_USA.length_at(1) == 2 assert self.dt_USA.length_at(2) == 4 def test_mutable(self): """ **中文文档** 测试对子树的修改, 是不是也会修改母树。(因为都是Mutable的对象, 所以应该会) """ usa = DictTree(name="USA", pop=200 * 10 ** 6) # 创建母树 usa["VA"] = DictTree(name="VA", pop=3 * 10 ** 6) # 创建子树 dt = usa["VA"] # 获取子树 dt.pop = 999999 # 修改子树的属性 # 看是否也修改了母树的__data__ assert usa.__data__["VA"]["__meta__"]["pop"] == 999999 def test_stats_at(self): result = self.dt_USA.stats() assert result[0]["depth"] == 0 assert result[0]["leaf"] == 0 assert result[0]["root"] == 1 assert result[1]["depth"] == 1 assert result[1]["leaf"] == 0 assert result[1]["root"] == 2 assert result[2]["depth"] == 2 assert result[2]["leaf"] == 4 assert result[2]["root"] == 0 root, leaf, total = self.dt_USA.stats_at(0) assert (root, leaf, total) == (1, 0, 1) root, leaf, total = self.dt_USA.stats_at(1) assert (root, leaf, total) == (2, 0, 2) root, leaf, total = self.dt_USA.stats_at(2) assert (root, leaf, total) == (0, 4, 4) def test_dump_load(self): from datetime import datetime self.dt_USA.dump(TEST_FILE) dt_USA = DictTree.load(TEST_FILE) assert self.dt_USA.__data__ == dt_USA.__data__ dt1 = DictTree(create_at=datetime.utcnow()) dt1.dump(TEST_FILE) dt2 = DictTree.load(TEST_FILE) assert dt1.__data__ == dt2.__data__
class TestDictTree(object): def test_key(self): pass def test_setattr_getattr(self): pass def test_setitem_getitem_delitem(self): pass def test_iter(self): pass def test_keys_at(self): pass def test_values_at(self): pass def test_items_at(self): pass def test_length_at(self): pass def test_mutable(self): ''' **中文文档** 测试对子树的修改, 是不是也会修改母树。(因为都是Mutable的对象, 所以应该会) ''' pass def test_stats_at(self): pass def test_dump_load(self): pass
12
1
16
3
12
1
1
0.08
1
3
1
0
11
0
11
11
199
48
145
39
132
12
142
39
129
3
1
1
13
148,276
MacHu-GWU/single_file_module-project
MacHu-GWU_single_file_module-project/tests/test_marshmallow_fields.py
test_marshmallow_fields.User
class User(nameddict.Base): pass
class User(nameddict.Base): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
15
2
0
2
1
1
0
2
1
1
0
2
0
0
148,277
MacHu-GWU/single_file_module-project
MacHu-GWU_single_file_module-project/tests/test_timer.py
test_timer.TestDateTimeTimer
class TestDateTimeTimer(object): def test(self): # usage1 timer = DateTimeTimer(title="basic DateTimeTimer test") sleep_random_time() timer.end() # usage2 with DateTimeTimer(title="basic DateTimeTimer test") as timer: sleep_random_time() # usage3 timer = DateTimeTimer(title="basic DateTimeTimer test", start=False) timer.start() sleep_random_time() timer.end() # usage4 with DateTimeTimer(title="basic DateTimeTimer test", start=False) as timer: sleep_random_time() def test_avg_error(self): measures = list() for i in range(10): with DateTimeTimer(display=False) as timer: time.sleep(0.1) measures.append(timer.elapsed) avg_error = (sum(measures) - 1) / 10 print("DateTimeTimer has %.6f seconds average error" % avg_error)
class TestDateTimeTimer(object): def test(self): pass def test_avg_error(self): pass
3
0
14
2
10
2
2
0.19
1
3
1
0
2
0
2
2
30
5
21
8
18
4
21
7
18
2
1
2
3
148,278
MacHu-GWU/single_file_module-project
MacHu-GWU_single_file_module-project/tests/test_timer.py
test_timer.TestSerialTimer
class TestSerialTimer(object): def test(self): stimer = SerialTimer() with pytest.raises(RuntimeError): stimer.end() stimer.start(title="first measure") sleep_random_time() stimer.end() with pytest.raises(RuntimeError): stimer.end() stimer.start(title="second measure") sleep_random_time() stimer.click(title="third measure") sleep_random_time() stimer.click(title="fourth measure") stimer.end() assert isinstance(stimer.last, BaseTimer) assert isinstance(stimer.history, list) assert len(stimer.history) == 4 assert isinstance(stimer.history[0], BaseTimer)
class TestSerialTimer(object): def test(self): pass
2
0
22
3
19
0
1
0
1
4
2
0
1
0
1
1
23
3
20
3
18
0
20
3
18
1
1
1
1
148,279
MacHu-GWU/single_file_module-project
MacHu-GWU_single_file_module-project/tests/test_timer.py
test_timer.TestTimeTimer
class TestTimeTimer(object): def test_avg_error(self): measures = list() for i in range(10): with TimeTimer(display=False) as timer: time.sleep(0.1) measures.append(timer.elapsed) avg_error = (sum(measures) - 1) / 10 print("TimeTimer has %.6f seconds average error" % avg_error)
class TestTimeTimer(object): def test_avg_error(self): pass
2
0
9
1
8
0
2
0
1
3
1
0
1
0
1
1
10
1
9
6
7
0
9
5
7
2
1
2
2
148,280
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/sqlalchemy_mate/patterns/status_tracker/impl.py
sqlalchemy_mate.patterns.status_tracker.impl.JobLockedError
class JobLockedError(JobExecutionError): """ Raised when try to start a locked job. """ pass
class JobLockedError(JobExecutionError): ''' Raised when try to start a locked job. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
10
6
1
2
1
1
3
2
1
1
0
4
0
0
148,281
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/crud/test_crud_inserting.py
test_crud_inserting.TestInsertingApiPostgres
class TestInsertingApiPostgres(InsertingApiBaseTest): engine = engine_psql
class TestInsertingApiPostgres(InsertingApiBaseTest): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
2
0
2
2
1
0
2
2
1
0
2
0
0
148,282
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/crud/test_crud_inserting.py
test_crud_inserting.TestInsertingApiSqlite
class TestInsertingApiSqlite(InsertingApiBaseTest): engine = engine_sqlite
class TestInsertingApiSqlite(InsertingApiBaseTest): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
2
0
2
2
1
0
2
2
1
0
2
0
0
148,283
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/crud/test_crud_selecting.py
test_crud_selecting.SelectingApiBaseTest
class SelectingApiBaseTest(BaseCrudTest): @classmethod def class_level_data_setup(cls): cls.delete_all_data_in_core_table() t_user_data = [ {"user_id": 1, "name": "Alice"}, {"user_id": 2, "name": "Bob"}, {"user_id": 3, "name": "Cathy"}, ] t_inv_data = [ {"store_id": 1, "item_id": 1}, {"store_id": 1, "item_id": 2}, {"store_id": 2, "item_id": 1}, {"store_id": 2, "item_id": 2}, ] t_smart_insert_data = [{"id": i} for i in range(1, 1000 + 1)] with cls.engine.connect() as connection: connection.execute(t_user.insert(), t_user_data) connection.execute(t_inv.insert(), t_inv_data) connection.execute(t_smart_insert.insert(), t_smart_insert_data) connection.commit() @classmethod def class_level_data_teardown(cls): cls.delete_all_data_in_core_table() def test_count_row(self): assert selecting.count_row(self.engine, t_user) == 3 def test_by_pk(self): row = selecting.by_pk(self.engine, t_user, 1) assert row._fields == ("user_id", "name") assert tuple(row) == (1, "Alice") assert row._asdict() == {"user_id": 1, "name": "Alice"} row = selecting.by_pk(self.engine, t_user, (1,)) assert row._asdict() == {"user_id": 1, "name": "Alice"} assert selecting.by_pk(self.engine, t_user, 0) is None row = selecting.by_pk(self.engine, t_inv, (1, 2)) assert row._asdict() == {"store_id": 1, "item_id": 2} with pytest.raises(ValueError): selecting.by_pk(self.engine, t_user, (1, 1)) with pytest.raises(ValueError): selecting.by_pk(self.engine, t_inv, 12) with pytest.raises(ValueError): selecting.by_pk(self.engine, t_inv, (1, 2, 1, 2)) def test_select_all(self): rows = selecting.select_all(self.engine, t_user).all() assert len(rows) == 3 for tp in selecting.yield_tuple(selecting.select_all(self.engine, t_user)): assert isinstance(tp, tuple) for dct in selecting.yield_dict(selecting.select_all(self.engine, t_user)): assert isinstance(dct, dict) def test_select_single_column(self): data = selecting.select_single_column(self.engine, t_user.c.user_id) assert data == [1, 2, 3] data = selecting.select_single_column(self.engine, t_user.c.name) assert data == ["Alice", "Bob", "Cathy"] def test_select_many_column(self): data = selecting.select_many_column( self.engine, [ t_user.c.user_id, ], ) assert data == [(1,), (2,), (3,)] data = selecting.select_many_column( engine=self.engine, columns=[t_user.c.user_id, t_user.c.name] ) assert data == [(1, "Alice"), (2, "Bob"), (3, "Cathy")] def test_select_single_distinct(self): # postgres db won't return item in its original insertion order with distinct statement assert selecting.select_single_distinct( engine=self.engine, column=t_inv.c.store_id, ) in [[1, 2], [2, 1]] def test_select_many_distinct(self): result = selecting.select_many_distinct( engine=self.engine, columns=[t_inv.c.store_id, t_inv.c.item_id], ) desired_result = [(1, 1), (1, 2), (2, 1), (2, 2)] for row in desired_result: assert row in result assert len(result) == len(desired_result) def test_select_random(self): id_set = set(range(1, 1000 + 1)) results1 = [ id_ for (id_,) in selecting.select_random( engine=self.engine, table=t_smart_insert, limit=5, ) ] assert len(results1) == 5 results2 = [ id_ for (id_,) in selecting.select_random( engine=self.engine, columns=[t_smart_insert.c.id], limit=5, ) ] assert len(results2) == 5 # at least one element not the same assert sum([i1 != i2 for i1, i2 in zip(results1, results2)]) >= 1 with pytest.raises(ValueError): selecting.select_random(engine=self.engine) with pytest.raises(ValueError): selecting.select_random( engine=self.engine, table=t_smart_insert, columns=[ t_smart_insert.c.id, ], ) with pytest.raises(ValueError): selecting.select_random( engine=self.engine, table=t_smart_insert, ) with pytest.raises(ValueError): selecting.select_random( engine=self.engine, table=t_smart_insert, limit=5, perc=10, ) with pytest.raises(ValueError): selecting.select_random( engine=self.engine, table=t_smart_insert, perc=1000, ) with pytest.raises(ValueError): selecting.select_random( engine=self.engine, table=t_smart_insert, perc=-1000, ) self.psql_only_test_case() def psql_only_test_case(self): id_set = set(range(1, 1000 + 1)) results = selecting.select_random( engine=self.engine, table=t_smart_insert, perc=10, ).all() assert 50 <= len(results) <= 150 for (id_,) in results: assert id_ in id_set results = selecting.select_random( engine=self.engine, columns=[ t_smart_insert.c.id, ], perc=10, ).all() assert 50 <= len(results) <= 150 for (id_,) in results: assert id_ in id_set
class SelectingApiBaseTest(BaseCrudTest): @classmethod def class_level_data_setup(cls): pass @classmethod def class_level_data_teardown(cls): pass def test_count_row(self): pass def test_by_pk(self): pass def test_select_all(self): pass def test_select_single_column(self): pass def test_select_many_column(self): pass def test_select_single_distinct(self): pass def test_select_many_distinct(self): pass def test_select_random(self): pass def psql_only_test_case(self): pass
14
0
16
2
14
0
1
0.01
1
6
0
2
9
1
11
22
193
35
156
34
142
2
86
30
74
3
1
1
16
148,284
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/test_utils.py
test_utils.TestUtilityPostgres
class TestUtilityPostgres(UtilityTestBase): engine = engine_psql def test_timeout_bad_case(self): engine = EngineCreator( host="stampy.db.elephantsql.com", port=5432, database="diyvavwx", username="diyvavwx", password="wrongpassword", ).create_postgresql_pg8000() with pytest.raises(Exception): utils.test_connection(engine, timeout=10)
class TestUtilityPostgres(UtilityTestBase): def test_timeout_bad_case(self): pass
2
0
10
0
10
0
1
0
1
2
1
0
1
0
1
13
13
1
12
4
10
0
6
4
4
1
2
1
1
148,285
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/sqlalchemy_mate/tests/mock_aws.py
sqlalchemy_mate.tests.mock_aws.BaseMockTest
class BaseMockTest: """ Simple base class for mocking AWS services. Usage:: import moto class Test(BaseMockTest): mock_list = [ moto.mock_s3, ] @classmethod def setup_class_post_hook(cls): cls.bsm.s3_client.create_bucket(Bucket="my-bucket") cls.bsm.s3_client.put_object( Bucket="my-bucket", Key="file.txt", Body="hello world", ) def test(self): assert ( self.bsm.s3_client.get_object(Bucket="my-bucket", Key="file.txt")["Body"] .read() .decode("utf-8") == "hello world" ) """ use_mock: bool = True region_name: str = "us-east-1" mock_list: list = [] # Don't overwrite the following bsm: T.Optional[BotoSesManager] = None _mocked: T.Dict[T.Any, list] = dict() @classmethod def setup_moto(cls): if cls.use_mock: cls._mocked[cls] = [] for mock_abc in cls.mock_list: mocker = mock_abc() mocker.start() cls._mocked[cls].append(mocker) cls.bsm = BotoSesManager(region_name=cls.region_name) @classmethod def teardown_moto(cls): if cls.use_mock: for mocker in cls._mocked[cls]: mocker.stop() cls.bsm = None @classmethod def setup_class_pre_hook(cls): # pragma: no cover pass @classmethod def setup_class_post_hook(cls): # pragma: no cover pass @classmethod def setup_class(cls): cls.setup_class_pre_hook() cls.setup_moto() cls.setup_class_post_hook() @classmethod def teardown_class_pre_hook(cls): # pragma: no cover pass @classmethod def teardown_class_post_hook(cls): # pragma: no cover pass @classmethod def teardown_class(cls): cls.teardown_class_pre_hook() cls.teardown_moto() cls.teardown_class_post_hook()
class BaseMockTest: ''' Simple base class for mocking AWS services. Usage:: import moto class Test(BaseMockTest): mock_list = [ moto.mock_s3, ] @classmethod def setup_class_post_hook(cls): cls.bsm.s3_client.create_bucket(Bucket="my-bucket") cls.bsm.s3_client.put_object( Bucket="my-bucket", Key="file.txt", Body="hello world", ) def test(self): assert ( self.bsm.s3_client.get_object(Bucket="my-bucket", Key="file.txt")["Body"] .read() .decode("utf-8") == "hello world" ) ''' @classmethod def setup_moto(cls): pass @classmethod def teardown_moto(cls): pass @classmethod def setup_class_pre_hook(cls): pass @classmethod def setup_class_post_hook(cls): pass @classmethod def setup_class_post_hook(cls): pass @classmethod def teardown_class_pre_hook(cls): pass @classmethod def teardown_class_post_hook(cls): pass @classmethod def teardown_class_pre_hook(cls): pass
17
1
4
0
4
1
2
0.67
0
0
0
1
0
0
8
8
84
16
43
25
26
29
35
17
26
3
0
2
12
148,286
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/test_utils.py
test_utils.UtilityTestBase
class UtilityTestBase(BaseCrudTest): def test_timeout_good_case(self): utils.test_connection(self.engine, timeout=3)
class UtilityTestBase(BaseCrudTest): def test_timeout_good_case(self): pass
2
0
2
0
2
0
1
0
1
0
0
2
1
1
1
12
3
0
3
3
1
0
3
2
1
1
1
0
1
148,287
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/sqlalchemy_mate/patterns/status_tracker/impl.py
sqlalchemy_mate.patterns.status_tracker.impl.Updates
class Updates: """ A helper class that hold the key value you want to update at the end of the job if the job succeeded. """ values: dict = dataclasses.field(default_factory=dict) def set(self, key: str, value: T.Any): """ Use this method to set "to-update" data. Note that you should not update some columns like "id", "status", "update_at" yourself, it will be updated by the :meth:`JobMixin.start` context manager. """ if key in disallowed_cols: # pragma: no cover raise KeyError(f"You should NOT set {key!r} column yourself!") self.values[key] = value
class Updates: ''' A helper class that hold the key value you want to update at the end of the job if the job succeeded. ''' def set(self, key: str, value: T.Any): ''' Use this method to set "to-update" data. Note that you should not update some columns like "id", "status", "update_at" yourself, it will be updated by the :meth:`JobMixin.start` context manager. ''' pass
2
2
9
0
4
6
2
1.67
0
3
0
0
1
0
1
1
17
2
6
3
4
10
6
3
4
2
0
1
2
148,288
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/sqlalchemy_mate/tests/crud_test.py
sqlalchemy_mate.tests.crud_test.User
class User(Base, ExtendedBase): __tablename__ = "extended_declarative_base_user" _settings_major_attrs = ["id", "name"] id: orm.Mapped[int] = orm.mapped_column(sa.Integer, primary_key=True) # name: orm.Mapped[str] = orm.mapped_column(sa.String, unique=True) name: orm.Mapped[str] = orm.mapped_column(sa.String, nullable=True)
class User(Base, ExtendedBase): pass
1
0
0
0
0
0
0
0.2
2
0
0
0
0
0
0
26
8
2
5
4
4
1
5
4
4
0
2
0
0
148,289
MacHu-GWU/sqlalchemy_mate-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_sqlalchemy_mate-project/tests/patterns/large_binary_column/test_large_binary_column_aws_s3.py
test_large_binary_column_aws_s3.BaseTest.test.UserError
class UserError(Exception): pass
class UserError(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
3
0
0
148,290
MacHu-GWU/sqlalchemy_mate-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_sqlalchemy_mate-project/sqlalchemy_mate/engine_creator.py
sqlalchemy_mate.engine_creator.EngineCreator.DialectAndDriver
class DialectAndDriver(object): """ DB dialect and DB driver mapping. """ psql = "postgresql" psql_psycopg2 = "postgresql+psycopg2" psql_pg8000 = "postgresql+pg8000" psql_pygresql = "postgresql+pygresql" psql_psycopg2cffi = "postgresql+psycopg2cffi" psql_pypostgresql = "postgresql+pypostgresql" mysql = "mysql" mysql_mysqldb = "mysql+mysqldb" mysql_mysqlconnector = "mysql+mysqlconnector" mysql_oursql = "mysql+oursql" mysql_pymysql = "mysql+pymysql" mysql_cymysql = "mysql+cymysql" oracle = "oracle" oracle_cx_oracle = "oracle+cx_oracle" mssql_pyodbc = "mssql+pyodbc" mssql_pymssql = "mssql+pymssql" redshift_psycopg2 = "redshift+psycopg2"
class DialectAndDriver(object): ''' DB dialect and DB driver mapping. ''' pass
1
1
0
0
0
0
0
0.17
1
0
0
0
0
0
0
0
21
0
18
18
17
3
18
18
17
0
1
0
0
148,291
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/sqlalchemy_mate/tests/crud_test.py
sqlalchemy_mate.tests.crud_test.PostTagAssociation
class PostTagAssociation(Base, ExtendedBase): __tablename__ = "extended_declarative_base_edge_case_post_tag_association" post_id: orm.Mapped[int] = orm.mapped_column(sa.Integer, primary_key=True) tag_id: orm.Mapped[int] = orm.mapped_column(sa.Integer, primary_key=True) description: orm.Mapped[str] = orm.mapped_column(sa.String)
class PostTagAssociation(Base, ExtendedBase): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
26
6
1
5
5
4
0
5
5
4
0
2
0
0
148,292
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/test_utils.py
test_utils.TestUtilitySqlite
class TestUtilitySqlite(UtilityTestBase): engine = engine_sqlite def test_timeout_bad_case(self): with pytest.raises(TimeoutError): engine = EngineCreator().create_sqlite() utils.test_connection(engine, timeout=0.000001)
class TestUtilitySqlite(UtilityTestBase): def test_timeout_bad_case(self): pass
2
0
4
0
4
0
1
0
1
2
1
0
1
0
1
13
7
1
6
4
4
0
6
4
4
1
2
1
1
148,293
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/types/test_types_json_serializable.py
test_types_json_serializable.User
class User(Base): __tablename__ = "types_json_serializable_users" id: orm.Mapped[int] = orm.mapped_column(sa.Integer, primary_key=True) profile: orm.Mapped[Profile] = orm.mapped_column( JSONSerializableType(factory_class=Profile), nullable=True )
class User(Base): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
7
1
6
3
5
0
4
3
3
0
1
0
0
148,294
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/sqlalchemy_mate/tests/crud_test.py
sqlalchemy_mate.tests.crud_test.BankAccount
class BankAccount(Base, ExtendedBase): __tablename__ = "extended_declarative_base_edge_case_bank_account" _settings_major_attrs = ["id", "name"] id: orm.Mapped[int] = orm.mapped_column(sa.Integer, primary_key=True) name: orm.Mapped[str] = orm.mapped_column(sa.String, unique=True) pin: orm.Mapped[str] = orm.mapped_column(sa.String)
class BankAccount(Base, ExtendedBase): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
26
8
2
6
5
5
0
6
5
5
0
2
0
0
148,295
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/types/test_types_json_serializable.py
test_types_json_serializable.TestSqlite
class TestSqlite(JSONSerializableBaseTest): engine = engine_sqlite
class TestSqlite(JSONSerializableBaseTest): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
4
2
0
2
2
1
0
2
2
1
0
1
0
0
148,296
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/crud/test_crud_inserting.py
test_crud_inserting.InsertingApiBaseTest
class InsertingApiBaseTest(BaseCrudTest): def teardown_method(self, method): """ Make sure data in all table is cleared after each test cases. """ self.delete_all_data_in_core_table() def test_smart_insert(self): """ Test performance of smart insert. **中文文档** 测试smart_insert的基本功能, 以及与普通的insert比较性能。 """ # Use Smart Insert Method # ------ Before State ------ scale = 10 # 测试数据的数量级, 总数据量是已有的数据量的立方, 建议 5 ~ 10 n_exist = scale n_all = scale**3 exist_id_list = [random.randint(1, n_all) for _ in range(n_exist)] exist_id_list = list(set(exist_id_list)) exist_id_list.sort() n_exist = len(exist_id_list) # Smart Insert exist_data = [{"id": id} for id in exist_id_list] all_data = [{"id": i} for i in range(1, 1 + n_all)] op_count, ins_count = smart_insert(self.engine, t_smart_insert, exist_data, 5) assert op_count == 1 assert ins_count == n_exist assert count_row(self.engine, t_smart_insert) == n_exist # ------ Invoke ------ st = time.process_time() op_count, ins_count = smart_insert(self.engine, t_smart_insert, all_data, 5) assert op_count <= (0.5 * n_all) assert ins_count == (n_all - n_exist) elapse1 = time.process_time() - st # ------ After State ------ assert count_row(self.engine, t_smart_insert) == n_all # Use Regular Insert Method # ------ Before State ------ with self.engine.connect() as connection: connection.execute(t_smart_insert.delete()) connection.commit() ins = t_smart_insert.insert() with self.engine.connect() as connection: connection.execute(ins, exist_data) connection.commit() assert count_row(self.engine, t_smart_insert) == n_exist # ------ Invoke ------ st = time.process_time() with self.engine.connect() as connection: for row in all_data: try: connection.execute(ins, row) connection.commit() except IntegrityError: connection.rollback() elapse2 = time.process_time() - st assert count_row(self.engine, t_smart_insert) == n_all # ------ After State ------ assert elapse1 < elapse2 def test_smart_insert_single_row(self): assert count_row(self.engine, t_smart_insert) == 0 data = {"id": 1} op_count, ins_count = smart_insert(self.engine, t_smart_insert, data) assert op_count == 1 assert ins_count == 1 assert count_row(self.engine, t_smart_insert) == 1 op_count, ins_count = smart_insert(self.engine, t_smart_insert, data) assert op_count == 0 assert ins_count == 0 assert count_row(self.engine, t_smart_insert) == 1
class InsertingApiBaseTest(BaseCrudTest): def teardown_method(self, method): ''' Make sure data in all table is cleared after each test cases. ''' pass def test_smart_insert(self): ''' Test performance of smart insert. **中文文档** 测试smart_insert的基本功能, 以及与普通的insert比较性能。 ''' pass def test_smart_insert_single_row(self): pass
4
2
28
5
17
6
2
0.34
1
3
0
2
3
0
3
14
87
17
53
19
49
18
53
18
49
3
1
3
5
148,297
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/sqlalchemy_mate/vendor/timeout_decorator/timeout_decorator.py
sqlalchemy_mate.vendor.timeout_decorator.timeout_decorator._Timeout
class _Timeout(object): """Wrap a function and add a timeout (limit) attribute to it. Instances of this class are automatically generated by the add_timeout function defined above. Wrapping a function allows asynchronous calls to be made and termination of execution after a timeout has passed. """ def __init__(self, function, timeout_exception, exception_message, limit): """Initialize instance in preparation for being called.""" self.__limit = limit self.__function = function self.__timeout_exception = timeout_exception self.__exception_message = exception_message self.__name__ = function.__name__ self.__doc__ = function.__doc__ self.__timeout = time.time() self.__process = multiprocessing.Process() self.__queue = multiprocessing.Queue() def __call__(self, *args, **kwargs): """Execute the embedded function object asynchronously. The function given to the constructor is transparently called and requires that "ready" be intermittently polled. If and when it is True, the "value" property may then be checked for returned data. """ self.__limit = kwargs.pop('timeout', self.__limit) self.__queue = multiprocessing.Queue(1) args = (self.__queue, self.__function) + args self.__process = multiprocessing.Process(target=_target, args=args, kwargs=kwargs) self.__process.daemon = True self.__process.start() if self.__limit is not None: self.__timeout = self.__limit + time.time() while not self.ready: time.sleep(0.01) return self.value def cancel(self): """Terminate any possible execution of the embedded function.""" if self.__process.is_alive(): self.__process.terminate() _raise_exception(self.__timeout_exception, self.__exception_message) @property def ready(self): """Read-only property indicating status of "value" property.""" if self.__limit and self.__timeout < time.time(): self.cancel() return self.__queue.full() and not self.__queue.empty() @property def value(self): """Read-only property containing data returned from function.""" if self.ready is True: flag, load = self.__queue.get() if flag: return load raise load
class _Timeout(object): '''Wrap a function and add a timeout (limit) attribute to it. Instances of this class are automatically generated by the add_timeout function defined above. Wrapping a function allows asynchronous calls to be made and termination of execution after a timeout has passed. ''' def __init__(self, function, timeout_exception, exception_message, limit): '''Initialize instance in preparation for being called.''' pass def __call__(self, *args, **kwargs): '''Execute the embedded function object asynchronously. The function given to the constructor is transparently called and requires that "ready" be intermittently polled. If and when it is True, the "value" property may then be checked for returned data. ''' pass def cancel(self): '''Terminate any possible execution of the embedded function.''' pass @property def ready(self): '''Read-only property indicating status of "value" property.''' pass @property def value(self): '''Read-only property containing data returned from function.''' pass
8
6
10
0
8
2
2
0.34
1
0
0
0
5
9
5
5
62
7
41
18
33
14
37
16
31
3
1
2
11
148,298
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/sqlalchemy_mate/types/json_serializable.py
sqlalchemy_mate.types.json_serializable.JSONSerializableType
class JSONSerializableType(sa.types.TypeDecorator): """ This column store json serialized python object in form of This column should be a json serializable python type such as combination of list, dict, string, int, float, bool. Usage: import jsonpickle # a custom python class class ComputerDetails: def __init__(self, ...): ... def to_json(self) -> str: return jsonpickle.encode(self) @classmethod def from_json(cls, json_str: str) -> 'Computer': return cls(**jsonpickle.decode(json_str)) Base = declarative_base() class Computer(Base): id = Column(Integer, primary_key) details = Column(JSONSerializableType(factory_class=Computer) ... computer = Computer( id=1, details=ComputerDetails(...), ) with Session(engine) as session: session.add(computer) session.commit() computer = session.get(Computer, 1) print(computer.details) """ impl = sa.UnicodeText cache_ok = True _FACTORY_CLASS = "factory_class" def __init__(self, *args, **kwargs): if self._FACTORY_CLASS not in kwargs: raise ValueError( ( "'JSONSerializableType' take only ONE argument {}, " "it is the generic type that has ``to_json(self): -> str``, " "and ``from_json(cls, value: str):`` class method." ).format(self._FACTORY_CLASS) ) self.factory_class = kwargs.pop(self._FACTORY_CLASS) super(JSONSerializableType, self).__init__(*args, **kwargs) def load_dialect_impl(self, dialect): return self.impl def process_bind_param(self, value, dialect) -> typing.Union[str, None]: if value is None: return value else: return value.to_json() def process_result_value(self, value: typing.Union[str, None], dialect): if value is None: return value else: return self.factory_class.from_json(value)
class JSONSerializableType(sa.types.TypeDecorator): ''' This column store json serialized python object in form of This column should be a json serializable python type such as combination of list, dict, string, int, float, bool. Usage: import jsonpickle # a custom python class class ComputerDetails: def __init__(self, ...): ... def to_json(self) -> str: return jsonpickle.encode(self) @classmethod def from_json(cls, json_str: str) -> 'Computer': return cls(**jsonpickle.decode(json_str)) Base = declarative_base() class Computer(Base): id = Column(Integer, primary_key) details = Column(JSONSerializableType(factory_class=Computer) ... computer = Computer( id=1, details=ComputerDetails(...), ) with Session(engine) as session: session.add(computer) session.commit() computer = session.get(Computer, 1) print(computer.details) ''' def __init__(self, ...): pass def load_dialect_impl(self, dialect): pass def process_bind_param(self, value, dialect) -> typing.Union[str, None]: pass def process_result_value(self, value: typing.Union[str, None], dialect): pass
5
1
6
0
6
0
2
1.11
1
3
0
0
4
1
4
4
74
17
27
9
22
30
19
9
14
2
1
1
7
148,299
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/sqlalchemy_mate/tests/status_tracker_test.py
sqlalchemy_mate.tests.status_tracker_test.Job
class Job(Base, ExtendedBase, JobMixin): __tablename__ = "sqlalchemy_mate_status_tracker_job" @classmethod def start_job( cls, id: str, skip_error: bool = False, debug: bool = False, ): return cls.start( engine=engine, id=id, in_progress_status=StatusEnum.in_progress.value, failed_status=StatusEnum.failed.value, succeeded_status=StatusEnum.succeeded.value, ignored_status=StatusEnum.ignored.value, expire=15, max_retry=3, skip_error=skip_error, debug=debug, )
class Job(Base, ExtendedBase, JobMixin): @classmethod def start_job( cls, id: str, skip_error: bool = False, debug: bool = False, ): pass
3
0
18
0
18
0
1
0
3
3
1
0
0
0
1
38
22
1
21
9
13
0
4
3
2
1
2
0
1
148,300
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/sqlalchemy_mate/tests/status_tracker_test.py
sqlalchemy_mate.tests.status_tracker_test.StatusEnum
class StatusEnum(int, enum.Enum): pending = 10 in_progress = 20 failed = 30 succeeded = 40 ignored = 50
class StatusEnum(int, enum.Enum): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
104
6
0
6
6
5
0
6
6
5
0
4
0
0
148,301
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/sqlalchemy_mate/types/compressed.py
sqlalchemy_mate.types.compressed.CompressedBinaryType
class CompressedBinaryType(BaseCompressedType): """ Compressed binary data. """ impl = sa.LargeBinary cache_ok = True def _compress(self, value: typing.Union[bytes, None]) -> typing.Union[bytes, None]: if value is None: return None return zlib.compress(value) def _decompress(self, value: typing.Union[bytes, None]) -> typing.Union[bytes, None]: if value is None: return None return zlib.decompress(value)
class CompressedBinaryType(BaseCompressedType): ''' Compressed binary data. ''' def _compress(self, value: typing.Union[bytes, None]) -> typing.Union[bytes, None]: pass def _decompress(self, value: typing.Union[bytes, None]) -> typing.Union[bytes, None]: pass
3
1
4
0
4
0
2
0.27
1
1
0
0
2
0
2
8
16
2
11
5
8
3
11
5
8
2
2
1
4
148,302
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/sqlalchemy_mate/types/compressed.py
sqlalchemy_mate.types.compressed.CompressedStringType
class CompressedStringType(BaseCompressedType): """ Compressed unicode string. """ impl = sa.LargeBinary cache_ok = True def _compress(self, value: typing.Union[str, None]) -> typing.Union[bytes, None]: if value is None: return None return zlib.compress(value.encode("utf-8")) def _decompress(self, value: typing.Union[bytes, None]) -> typing.Union[str, None]: if value is None: return None return zlib.decompress(value).decode("utf-8")
class CompressedStringType(BaseCompressedType): ''' Compressed unicode string. ''' def _compress(self, value: typing.Union[str, None]) -> typing.Union[bytes, None]: pass def _decompress(self, value: typing.Union[bytes, None]) -> typing.Union[str, None]: pass
3
1
4
0
4
0
2
0.27
1
2
0
0
2
0
2
8
16
2
11
5
8
3
11
5
8
2
2
1
4
148,303
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/types/test_types_json_serializable.py
test_types_json_serializable.TestPsql
class TestPsql(JSONSerializableBaseTest): # pragma: no cover engine = engine_psql
class TestPsql(JSONSerializableBaseTest): pass
1
0
0
0
0
0
0
0.5
1
0
0
0
0
0
0
4
2
0
2
2
1
1
2
2
1
0
1
0
0
148,304
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/types/test_types_json_serializable.py
test_types_json_serializable.Profile
class Profile: def __init__(self, dob: str): self.dob = dob def to_json(self) -> str: return json.dumps(dict(dob=self.dob)) @classmethod def from_json(cls, value) -> "Profile": return cls(**json.loads(value))
class Profile: def __init__(self, dob: str): pass def to_json(self) -> str: pass @classmethod def from_json(cls, value) -> "Profile": pass
5
0
2
0
2
0
1
0
0
2
0
0
2
1
3
3
10
2
8
6
3
0
7
5
3
1
0
0
3
148,305
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/types/test_types_json_serializable.py
test_types_json_serializable.JSONSerializableBaseTest
class JSONSerializableBaseTest: engine: sa.Engine = None id_ = 1 profile = Profile(dob="2021-01-01") @classmethod def setup_class(cls): if cls.engine is None: return None Base.metadata.drop_all(cls.engine) Base.metadata.create_all(cls.engine) with cls.engine.connect() as conn: conn.execute(User.__table__.delete()) conn.commit() with orm.Session(cls.engine) as ses: user = User(id=cls.id_, profile=cls.profile) ses.add(user) ses.commit() def test_exception(self): with pytest.raises(ValueError): JSONSerializableType() def test_read_and_write(self): with orm.Session(self.engine) as ses: user = ses.get(User, self.id_) print(user.profile) assert isinstance(user.profile, Profile) assert user.profile.dob == self.profile.dob user = User(id=2) ses.add(user) ses.commit() user = ses.get(User, 2) assert user.profile == None def test_select_where(self): with orm.Session(self.engine) as ses: user = ses.scalars( sa.select(User).where(User.profile == self.profile) ).one() assert user.profile.dob == self.profile.dob
class JSONSerializableBaseTest: @classmethod def setup_class(cls): pass def test_exception(self): pass def test_read_and_write(self): pass def test_select_where(self): pass
6
0
9
1
8
0
1
0
0
4
3
2
3
0
4
4
46
9
37
16
31
0
34
11
29
2
0
1
5
148,306
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/types/test_types_compressed_json.py
test_types_compressed_json.TestSqlite
class TestSqlite(CompressedJSONBaseTest): engine = engine_sqlite
class TestSqlite(CompressedJSONBaseTest): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
4
2
0
2
2
1
0
2
2
1
0
1
0
0
148,307
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/sqlalchemy_mate/types/compressed_json.py
sqlalchemy_mate.types.compressed_json.CompressedJSONType
class CompressedJSONType(sa.types.TypeDecorator): """ This column store json serialized object and automatically compress it in form of binary before writing to the database. This column should be a json serializable python type such as combination of list, dict, string, int, float, bool. Also you can use other standard json api compatible library for better serialization / deserialization support. **NOTE**, this type doesn't support JSON path query, it treats the object as a whole and compress it to save storage only. :param json_lib: optional, the json library you want to use. It should have ``json.dumps`` method takes object as first arg, and returns a json string. Should also have ``json.loads`` method takes string as first arg, returns the original object. .. code-block:: python # standard json api compatible json library import jsonpickle class Order(Base): ... id = Column(Integer, primary_key=True) items = CompressedJSONType(json_lib=jsonpickle) items = [ {"item_name": "apple", "quantity": 12}, {"item_name": "banana", "quantity": 6}, {"item_name": "cherry", "quantity": 3}, ] order = Order(id=1, items=items) with Session(engine) as ses: ses.add(order) ses.save() order = ses.get(Order, 1) assert order.items == items # WHERE ... = ... also works stmt = select(Order).where(Order.items==items) order = ses.scalars(stmt).one() """ impl = sa.LargeBinary cache_ok = True _JSON_LIB = "json_lib" def __init__(self, *args, **kwargs): if self._JSON_LIB in kwargs: self.json_lib = kwargs.pop(self._JSON_LIB) else: self.json_lib = json super(CompressedJSONType, self).__init__(*args, **kwargs) def load_dialect_impl(self, dialect): return dialect.type_descriptor(self.impl) def process_bind_param(self, value, dialect): if value is None: return value return zlib.compress( self.json_lib.dumps(value).encode("utf-8") ) def process_result_value(self, value, dialect): if value is None: return None return self.json_lib.loads( zlib.decompress(value).decode("utf-8") )
class CompressedJSONType(sa.types.TypeDecorator): ''' This column store json serialized object and automatically compress it in form of binary before writing to the database. This column should be a json serializable python type such as combination of list, dict, string, int, float, bool. Also you can use other standard json api compatible library for better serialization / deserialization support. **NOTE**, this type doesn't support JSON path query, it treats the object as a whole and compress it to save storage only. :param json_lib: optional, the json library you want to use. It should have ``json.dumps`` method takes object as first arg, and returns a json string. Should also have ``json.loads`` method takes string as first arg, returns the original object. .. code-block:: python # standard json api compatible json library import jsonpickle class Order(Base): ... id = Column(Integer, primary_key=True) items = CompressedJSONType(json_lib=jsonpickle) items = [ {"item_name": "apple", "quantity": 12}, {"item_name": "banana", "quantity": 6}, {"item_name": "cherry", "quantity": 3}, ] order = Order(id=1, items=items) with Session(engine) as ses: ses.add(order) ses.save() order = ses.get(Order, 1) assert order.items == items # WHERE ... = ... also works stmt = select(Order).where(Order.items==items) order = ses.scalars(stmt).one() ''' def __init__(self, *args, **kwargs): pass def load_dialect_impl(self, dialect): pass def process_bind_param(self, value, dialect): pass def process_result_value(self, value, dialect): pass
5
1
5
0
5
0
2
1.46
1
1
0
0
4
1
4
4
75
16
24
9
19
35
19
9
14
2
1
1
7
148,308
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/sqlalchemy_mate/tests/crud_test.py
sqlalchemy_mate.tests.crud_test.Association
class Association(Base, ExtendedBase): __tablename__ = "extended_declarative_base_association" x_id: orm.Mapped[int] = orm.mapped_column(sa.Integer, primary_key=True) y_id: orm.Mapped[int] = orm.mapped_column(sa.Integer, primary_key=True) flag: orm.Mapped[int] = orm.mapped_column(sa.Integer)
class Association(Base, ExtendedBase): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
26
6
1
5
5
4
0
5
5
4
0
2
0
0
148,309
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/patterns/status_tracker/test_status_tracker.py
test_status_tracker.Step3StatusEnum
class Step3StatusEnum(int, enum.Enum): pending = 30 in_progress = 32 failed = 34 succeeded = 36 ignored = 38
class Step3StatusEnum(int, enum.Enum): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
104
6
0
6
6
5
0
6
6
5
0
4
0
0
148,310
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/crud/test_crud_selecting.py
test_crud_selecting.TestSelectingApiSqlite
class TestSelectingApiSqlite(SelectingApiBaseTest): engine = engine_sqlite def psql_only_test_case(self): pass
class TestSelectingApiSqlite(SelectingApiBaseTest): def psql_only_test_case(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
23
5
1
4
3
2
0
4
3
2
1
2
0
1
148,311
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/patterns/status_tracker/test_status_tracker.py
test_status_tracker.Step2StatusEnum
class Step2StatusEnum(int, enum.Enum): pending = 20 in_progress = 22 failed = 24 succeeded = 26 ignored = 28
class Step2StatusEnum(int, enum.Enum): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
104
6
0
6
6
5
0
6
6
5
0
4
0
0
148,312
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/sqlalchemy_mate/tests/crud_test.py
sqlalchemy_mate.tests.crud_test.BaseCrudTest
class BaseCrudTest: engine: sa.Engine = None @property def eng(self) -> sa.Engine: """ shortcut for ``self.engine`` """ return self.engine @classmethod def setup_class(cls): """ It is called one once before all test method start. Don't overwrite this method in Child Class! Use :meth:`BaseTest.class_level_data_setup` please """ if cls.engine is not None: metadata.create_all(cls.engine) Base.metadata.create_all(cls.engine) cls.class_level_data_setup() @classmethod def teardown_class(cls): """ It is called one once when all test method finished. Don't overwrite this method in Child Class! Use :meth:`BaseTest.class_level_data_teardown` please """ cls.class_level_data_teardown() def setup_method(self, method): """ It is called before all test method invocation Don't overwrite this method in Child Class! Use :meth:`BaseTest.method_level_data_setup` please """ self.method_level_data_setup() def teardown_method(self, method): """ It is called after all test method invocation. Don't overwrite this method in Child Class! Use :meth:`BaseTest.method_level_data_teardown` please """ self.method_level_data_teardown() @classmethod def class_level_data_setup(cls): """ Put data preparation task here. """ pass @classmethod def class_level_data_teardown(cls): """ Put data cleaning task here. """ pass def method_level_data_setup(self): """ Put data preparation task here. """ pass def method_level_data_teardown(self): """ Put data cleaning task here. """ pass @classmethod def delete_all_data_in_core_table(cls): with cls.engine.connect() as connection: connection.execute(t_user.delete()) connection.execute(t_inv.delete()) connection.execute(t_cache.delete()) connection.execute(t_graph.delete()) connection.execute(t_smart_insert.delete()) connection.commit() @classmethod def delete_all_data_in_orm_table(cls): with cls.engine.connect() as connection: connection.execute(User.__table__.delete()) connection.execute(Association.__table__.delete()) connection.execute(Order.__table__.delete()) connection.execute(BankAccount.__table__.delete()) connection.execute(PostTagAssociation.__table__.delete()) connection.commit()
class BaseCrudTest: @property def eng(self) -> sa.Engine: ''' shortcut for ``self.engine`` ''' pass @classmethod def setup_class(cls): ''' It is called one once before all test method start. Don't overwrite this method in Child Class! Use :meth:`BaseTest.class_level_data_setup` please ''' pass @classmethod def teardown_class(cls): ''' It is called one once when all test method finished. Don't overwrite this method in Child Class! Use :meth:`BaseTest.class_level_data_teardown` please ''' pass def setup_method(self, method): ''' It is called before all test method invocation Don't overwrite this method in Child Class! Use :meth:`BaseTest.method_level_data_setup` please ''' pass def teardown_method(self, method): ''' It is called after all test method invocation. Don't overwrite this method in Child Class! Use :meth:`BaseTest.method_level_data_teardown` please ''' pass @classmethod def class_level_data_setup(cls): ''' Put data preparation task here. ''' pass @classmethod def class_level_data_teardown(cls): ''' Put data cleaning task here. ''' pass def method_level_data_setup(self): ''' Put data preparation task here. ''' pass def method_level_data_teardown(self): ''' Put data cleaning task here. ''' pass @classmethod def delete_all_data_in_core_table(cls): pass @classmethod def delete_all_data_in_orm_table(cls): pass
19
9
7
0
3
3
1
0.76
0
5
5
9
5
0
11
11
96
15
46
22
27
35
39
13
27
2
0
1
12
148,313
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/test_pt.py
test_pt.TestPrettyTablePostgres
class TestPrettyTablePostgres(PrettyTableTestBase): engine = engine_psql
class TestPrettyTablePostgres(PrettyTableTestBase): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
20
2
0
2
2
1
0
2
2
1
0
2
0
0
148,314
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/test_pt.py
test_pt.TestPrettyTableSqlite
class TestPrettyTableSqlite(PrettyTableTestBase): engine = engine_sqlite
class TestPrettyTableSqlite(PrettyTableTestBase): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
20
2
0
2
2
1
0
2
2
1
0
2
0
0
148,315
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/sqlalchemy_mate/patterns/status_tracker/impl.py
sqlalchemy_mate.patterns.status_tracker.impl.JobIgnoredError
class JobIgnoredError(JobIsNotReadyToStartError): """ Raised when try to start an ignored (failed too many times) job. """ pass
class JobIgnoredError(JobIsNotReadyToStartError): ''' Raised when try to start an ignored (failed too many times) job. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
10
6
1
2
1
1
3
2
1
1
0
5
0
0
148,316
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/sqlalchemy_mate/patterns/status_tracker/impl.py
sqlalchemy_mate.patterns.status_tracker.impl.JobIsNotReadyToStartError
class JobIsNotReadyToStartError(JobExecutionError): """ Raised when try to start job that the current status shows that it is not ready to start. """ pass
class JobIsNotReadyToStartError(JobExecutionError): ''' Raised when try to start job that the current status shows that it is not ready to start. ''' pass
1
1
0
0
0
0
0
2
1
0
0
2
0
0
0
10
7
1
2
1
1
4
2
1
1
0
4
0
0
148,317
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/docs/source/05-Patterns/Large-Binary-Column-AWS-S3-Backend/test_s3_backed_column.py
test_s3_backed_column.Task
class Task(Base): __tablename__ = "tasks" url: orm.Mapped[str] = orm.mapped_column(sa.String, primary_key=True) update_at: orm.Mapped[datetime] = orm.mapped_column(sa.DateTime) html: orm.Mapped[T.Optional[str]] = orm.mapped_column(sa.String, nullable=True) image: orm.Mapped[T.Optional[str]] = orm.mapped_column(sa.String, nullable=True)
class Task(Base): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
7
1
6
6
5
0
6
6
5
0
1
0
0
148,318
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/patterns/status_tracker/test_status_tracker.py
test_status_tracker.Job
class Job(JobMixin, Base, ExtendedBase): __tablename__ = "jobs" @classmethod def start_step1( cls, engine: sa.Engine, id: str, skip_error: bool = False, debug: bool = False, ): return cls.start( engine=engine, id=id, pending_status=Step1StatusEnum.pending.value, in_progress_status=Step1StatusEnum.in_progress.value, failed_status=Step1StatusEnum.failed.value, succeeded_status=Step1StatusEnum.succeeded.value, ignored_status=Step1StatusEnum.ignored.value, more_pending_status=None, expire=900, max_retry=3, skip_error=skip_error, debug=debug, ) @classmethod def start_step2( cls, engine: sa.Engine, id: str, skip_error: bool = False, debug: bool = False, ): return cls.start( engine=engine, id=id, more_pending_status=Step1StatusEnum.succeeded.value, pending_status=Step2StatusEnum.pending.value, in_progress_status=Step2StatusEnum.in_progress.value, failed_status=Step2StatusEnum.failed.value, succeeded_status=Step2StatusEnum.succeeded.value, ignored_status=Step2StatusEnum.ignored.value, expire=900, max_retry=3, skip_error=skip_error, debug=debug, ) @classmethod def start_step3( cls, engine: sa.Engine, id: str, skip_error: bool = False, debug: bool = False, ): return cls.start( engine=engine, id=id, more_pending_status=[Step2StatusEnum.succeeded.value], pending_status=Step3StatusEnum.pending.value, in_progress_status=Step3StatusEnum.in_progress.value, failed_status=Step3StatusEnum.failed.value, succeeded_status=Step3StatusEnum.succeeded.value, ignored_status=Step3StatusEnum.ignored.value, expire=900, max_retry=3, skip_error=skip_error, debug=debug, )
class Job(JobMixin, Base, ExtendedBase): @classmethod def start_step1( cls, engine: sa.Engine, id: str, skip_error: bool = False, debug: bool = False, ): pass @classmethod def start_step2( cls, engine: sa.Engine, id: str, skip_error: bool = False, debug: bool = False, ): pass @classmethod def start_step3( cls, engine: sa.Engine, id: str, skip_error: bool = False, debug: bool = False, ): pass
7
0
21
0
21
0
1
0
3
5
3
0
0
0
3
40
71
3
68
26
43
0
8
5
4
1
2
0
3
148,319
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/patterns/status_tracker/test_status_tracker.py
test_status_tracker.StatusTrackerBaseTest
class StatusTrackerBaseTest: engine: sa.Engine = None @classmethod def setup_class(cls): Base.metadata.create_all(cls.engine) def setup_method(self): with self.engine.connect() as conn: conn.execute(Job.__table__.delete()) conn.commit() def get_job(self): with orm.Session(self.engine) as ses: return ses.get(Job, job_id) def test_create(self): _ = Job.create(id=job_id, status=Step1StatusEnum.pending.value) job = self.get_job() assert job is None def test_create_and_save(self): with orm.Session(self.engine) as ses: job = Job.create_and_save( engine_or_session=ses, id=job_id, status=Step1StatusEnum.pending.value, ) assert job.data == None job = self.get_job() assert isinstance(job, Job) def test_lock_it(self): # create a new job job = Job.create_and_save( engine_or_session=self.engine, id=job_id, status=Step1StatusEnum.pending.value, ) # then get the job from db, it should NOT be locked job = self.get_job() assert job.is_locked(expire=10) is False # then lock it, the in-memory job object should be locked job.lock_it( engine_or_session=self.engine, in_progress_status=Step1StatusEnum.in_progress.value, ) assert job.status == Step1StatusEnum.in_progress.value assert job.lock is not None assert job.is_locked(expire=10) is True # then get the job from db, it should be locked job = self.get_job() assert job.status == Step1StatusEnum.in_progress.value assert job.lock is not None assert job.is_locked(expire=10) is True def test_update(self): Job.create_and_save( engine_or_session=self.engine, id=job_id, status=Step1StatusEnum.pending.value, ) job = Job.create(id=job_id, status=Step1StatusEnum.pending.value) updates = Updates() updates.set(key="data", value={"version": 1}) job.update(engine_or_session=self.engine, updates=updates) job = self.get_job() assert job.data == {"version": 1} def _create_and_save_for_start(self): """ Create an initial job so that we can test the ``start(...)`` method. """ Job.create_and_save( engine_or_session=self.engine, id=job_id, status=Step1StatusEnum.pending.value, data={"version": 1}, ) def test_start_and_succeeded(self): self._create_and_save_for_start() with Job.start_step1(engine=self.engine, id=job_id, debug=False) as ( job, updates, ): updates.set(key="data", value={"version": job.data["version"] + 1}) job = self.get_job() assert job.status == Step1StatusEnum.succeeded.value assert job.lock == None assert job.data == {"version": 2} # print(job.__dict__) with pytest.raises(JobAlreadySucceededError): with Job.start_step1( engine=self.engine, id=job_id, skip_error=True, debug=False ) as ( job, updates, ): updates.set(key="data", value={"version": job.data["version"] + 1}) def test_start_and_failed(self): self._create_and_save_for_start() with pytest.raises(MyError): with Job.start_step1(engine=self.engine, id=job_id, debug=False) as ( job, updates, ): updates.set(key="data", value={"version": job.data["version"] + 1}) raise MyError job = self.get_job() assert job.status == Step1StatusEnum.failed.value assert job.lock == None assert job.data == {"version": 1} # print(job.__dict__) def test_start_and_ignored(self): self._create_and_save_for_start() with Job.start_step1( engine=self.engine, id=job_id, skip_error=True, debug=False ) as (job, updates): updates.set(key="data", value={"version": job.data["version"] + 1}) raise Exception with Job.start_step1( engine=self.engine, id=job_id, skip_error=True, debug=False ) as (job, updates): updates.set(key="data", value={"version": job.data["version"] + 1}) raise Exception with Job.start_step1( engine=self.engine, id=job_id, skip_error=True, debug=False ) as (job, updates): updates.set(key="data", value={"version": job.data["version"] + 1}) raise Exception job = self.get_job() assert job.status == Step1StatusEnum.ignored.value assert job.lock == None assert job.data == {"version": 1} # print(job.__dict__) with pytest.raises(JobIgnoredError): with Job.start_step1( engine=self.engine, id=job_id, skip_error=True, debug=False ) as ( job, updates, ): updates.set(key="data", value={"version": job.data["version"] + 1}) def test_start_and_concurrent_worker_conflict(self): self._create_and_save_for_start() with Job.start_step1(engine=self.engine, id=job_id, debug=False) as ( job1, updates1, ): with pytest.raises(JobLockedError): with Job.start_step1(engine=self.engine, id=job_id, debug=False) as ( job2, updates2, ): updates2.set( key="data", value={"version": job2.data["version"] + 100}, ) updates1.set(key="data", value={"version": job1.data["version"] + 1}) job = self.get_job() assert job.status == Step1StatusEnum.succeeded.value assert job.lock == None assert job.data == {"version": 2} # print(job.__dict__) def test_run_two_steps(self): self._create_and_save_for_start() with pytest.raises(JobIsNotReadyToStartError): with Job.start_step2(engine=self.engine, id=job_id, debug=False) as ( job2, updates2, ): pass with Job.start_step1(engine=self.engine, id=job_id, debug=False) as ( job1, updates1, ): pass with Job.start_step2(engine=self.engine, id=job_id, debug=False) as ( job2, updates2, ): pass with Job.start_step3(engine=self.engine, id=job_id, debug=False) as ( job3, updates3, ): pass def test_query_by_status(self): self._create_and_save_for_start() job_list = Job.query_by_status( engine_or_session=self.engine, status=Step1StatusEnum.pending.value, ) assert len(job_list) == 1 assert job_list[0].id == job_id with orm.Session(self.engine) as ses: job_list = Job.query_by_status( engine_or_session=ses, status=Step1StatusEnum.pending.value, ) assert len(job_list) == 1 assert job_list[0].id == job_id
class StatusTrackerBaseTest: @classmethod def setup_class(cls): pass def setup_method(self): pass def get_job(self): pass def test_create(self): pass def test_create_and_save(self): pass def test_lock_it(self): pass def test_update(self): pass def _create_and_save_for_start(self): ''' Create an initial job so that we can test the ``start(...)`` method. ''' pass def test_start_and_succeeded(self): pass def test_start_and_failed(self): pass def test_start_and_ignored(self): pass def test_start_and_concurrent_worker_conflict(self): pass def test_run_two_steps(self): pass def test_query_by_status(self): pass
16
1
15
1
13
1
1
0.06
0
9
8
2
13
0
14
14
222
28
183
44
167
11
113
24
98
1
0
3
14
148,320
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/types/test_types_compressed_json.py
test_types_compressed_json.TestPsql
class TestPsql(CompressedJSONBaseTest): # pragma: no cover engine = engine_psql def test_select_where(self): with orm.Session(self.engine) as ses: order = ses.scalars(sa.select(Order).where(Order.items == self.items)).one() assert order.items == self.items
class TestPsql(CompressedJSONBaseTest): def test_select_where(self): pass
2
0
4
0
4
0
1
0.17
1
1
1
0
1
0
1
5
7
1
6
5
4
1
6
4
4
1
1
1
1
148,321
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/types/test_types_compressed_json.py
test_types_compressed_json.Order
class Order(Base): __tablename__ = "types_compressed_json_orders" id: orm.Mapped[int] = orm.mapped_column(sa.Integer, primary_key=True) items: orm.Mapped[str] = orm.mapped_column(CompressedJSONType, nullable=True)
class Order(Base): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
5
1
4
3
3
0
4
3
3
0
1
0
0
148,322
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/types/test_types_compressed_json.py
test_types_compressed_json.CompressedJSONBaseTest
class CompressedJSONBaseTest: engine: sa.Engine = None id_ = 1 items = [ dict(item_id="item_001", item_name="apple", item_count=12), dict(item_id="item_002", item_name="banana", item_count=6), dict(item_id="item_003", item_name="cherry", item_count=36), ] @classmethod def setup_class(cls): if cls.engine is None: return Base.metadata.drop_all(cls.engine) Base.metadata.create_all(cls.engine) with cls.engine.connect() as conn: conn.execute(Order.__table__.delete()) conn.commit() with orm.Session(cls.engine) as ses: order = Order(id=cls.id_, items=cls.items) ses.add(order) ses.commit() def test_read_and_write(self): with orm.Session(self.engine) as ses: order = ses.get(Order, self.id_) assert order.items == self.items order = Order(id=2) ses.add(order) ses.commit() order = ses.get(Order, 2) assert order.items == None def test_underlying_data_is_compressed(self): metadata = sa.MetaData() t_user = sa.Table( "types_compressed_json_orders", metadata, sa.Column("id", sa.Integer, primary_key=True), sa.Column("items", sa.LargeBinary), ) with self.engine.connect() as conn: stmt = sa.select(t_user).where(t_user.c.id == self.id_) order = conn.execute(stmt).one() assert isinstance(order[1], bytes) assert sys.getsizeof(order[1]) <= sys.getsizeof(json.dumps(self.items)) def test_select_where(self): with orm.Session(self.engine) as ses: order = ses.scalars(sa.select(Order).where(Order.items == self.items)).one() assert order.items == self.items
class CompressedJSONBaseTest: @classmethod def setup_class(cls): pass def test_read_and_write(self): pass def test_underlying_data_is_compressed(self): pass def test_select_where(self): pass
6
0
11
1
10
0
1
0
0
2
1
2
3
0
4
4
57
10
47
21
41
0
37
15
32
2
0
1
5
148,323
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/patterns/status_tracker/test_status_tracker.py
test_status_tracker.Step1StatusEnum
class Step1StatusEnum(int, enum.Enum): pending = 10 in_progress = 12 failed = 14 succeeded = 16 ignored = 18
class Step1StatusEnum(int, enum.Enum): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
104
6
0
6
6
5
0
6
6
5
0
4
0
0
148,324
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/types/test_types_compressed.py
test_types_compressed.TestSqlite
class TestSqlite(CompressedBaseTest): engine = engine_sqlite
class TestSqlite(CompressedBaseTest): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
4
2
0
2
2
1
0
2
2
1
0
1
0
0
148,325
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/types/test_types_compressed.py
test_types_compressed.TestPsql
class TestPsql(CompressedBaseTest): # pragma: no cover engine = engine_psql
class TestPsql(CompressedBaseTest): pass
1
0
0
0
0
0
0
0.5
1
0
0
0
0
0
0
4
2
0
2
2
1
1
2
2
1
0
1
0
0
148,326
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/types/test_types_compressed.py
test_types_compressed.Image
class Image(Base): __tablename__ = "types_compressed_images" path: orm.Mapped[str] = orm.mapped_column(sa.String, primary_key=True) content: orm.Mapped[bytes] = orm.mapped_column(CompressedBinaryType)
class Image(Base): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
5
1
4
4
3
0
4
4
3
0
1
0
0
148,327
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/types/test_types_compressed.py
test_types_compressed.CompressedBaseTest
class CompressedBaseTest: engine: sa.Engine = None html = "<html><head><title>Welcome to Python.org</title></head></html>" * 10 content = ("cc1297141fcae6c70fce9a9320752a87" * 10).encode("utf-8") @classmethod def setup_class(cls): if cls.engine is None: return Base.metadata.drop_all(cls.engine) Base.metadata.create_all(cls.engine) with cls.engine.connect() as conn: conn.execute(Url.__table__.delete()) conn.execute(Image.__table__.delete()) with orm.Session(cls.engine) as ses: ses.add(Url(url="www.python.org", html=cls.html)) ses.add(Image(path="/tmp/logo.jpg", content=cls.content)) ses.commit() def test_read_and_write(self): with orm.Session(self.engine) as ses: url = ses.get(Url, "www.python.org") assert url.html == self.html image = ses.get(Image, "/tmp/logo.jpg") assert image.content == self.content def test_underlying_data_is_compressed(self): metadata = sa.MetaData() t_url = sa.Table( "types_compressed_urls", metadata, sa.Column("url", sa.String, primary_key=True), sa.Column("html", sa.LargeBinary), ) t_image = sa.Table( "types_compressed_images", metadata, sa.Column("path", sa.String, primary_key=True), sa.Column("content", sa.LargeBinary), ) with self.engine.connect() as conn: stmt = sa.select(t_url).where(t_url.c.url == "www.python.org") url = conn.execute(stmt).one() assert isinstance(url[1], bytes) assert sys.getsizeof(url[1]) <= sys.getsizeof(self.html) stmt = sa.select(t_image).where(t_image.c.path == "/tmp/logo.jpg") image = conn.execute(stmt).one() assert isinstance(image[1], bytes) assert sys.getsizeof(image[1]) <= sys.getsizeof(self.content) def test_select_where(self): with orm.Session(self.engine) as ses: url = ses.scalars(sa.select(Url).where(Url.html == self.html)).one() assert url.html == self.html image = ses.scalars( sa.select(Image).where(Image.content == self.content) ).one() assert image.content == self.content
class CompressedBaseTest: @classmethod def setup_class(cls): pass def test_read_and_write(self): pass def test_underlying_data_is_compressed(self): pass def test_select_where(self): pass
6
0
14
2
12
0
1
0
0
3
2
2
3
0
4
4
67
13
54
24
48
0
41
18
36
2
0
1
5
148,328
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/patterns/status_tracker/test_status_tracker.py
test_status_tracker.TestUpdates
class TestUpdates: def test(self): updates = Updates() with pytest.raises(KeyError): updates.set(key="status", value=0)
class TestUpdates: def test(self): pass
2
0
4
0
4
0
1
0
0
2
1
0
1
0
1
1
5
0
5
3
3
0
5
3
3
1
0
1
1
148,329
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/patterns/status_tracker/test_status_tracker.py
test_status_tracker.TestSqlite
class TestSqlite(StatusTrackerBaseTest): engine = engine_sqlite
class TestSqlite(StatusTrackerBaseTest): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
2
0
2
2
1
0
2
2
1
0
1
0
0
148,330
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/patterns/status_tracker/test_status_tracker.py
test_status_tracker.TestPsql
class TestPsql(StatusTrackerBaseTest): # pragma: no cover engine = engine_psql
class TestPsql(StatusTrackerBaseTest): pass
1
0
0
0
0
0
0
0.5
1
0
0
0
0
0
0
14
2
0
2
2
1
1
2
2
1
0
1
0
0
148,331
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/test_pt.py
test_pt.PrettyTableTestBase
class PrettyTableTestBase(BaseCrudTest): @classmethod def class_level_data_setup(cls): cls.delete_all_data_in_core_table() cls.delete_all_data_in_orm_table() t_user_data = [ {"user_id": 1, "name": "Alice"}, {"user_id": 2, "name": "Bob"}, {"user_id": 3, "name": "Cathy"}, {"user_id": 4, "name": "David"}, ] t_inv_data = [ {"store_id": 1, "item_id": 1}, {"store_id": 1, "item_id": 2}, {"store_id": 2, "item_id": 1}, {"store_id": 2, "item_id": 2}, {"store_id": 3, "item_id": 1}, {"store_id": 3, "item_id": 2}, ] with cls.engine.connect() as connection: connection.execute(sa.insert(t_user), t_user_data) connection.execute(t_inv.insert(), t_inv_data) connection.commit() with orm.Session(cls.engine) as ses: ses.add_all( [ User(id=1, name="X"), User(id=2, name="Y"), User(id=3, name="Z"), ] ) ses.add_all( [ Association(x_id=1, y_id=1, flag=1), Association(x_id=1, y_id=2, flag=2), Association(x_id=2, y_id=1, flag=3), Association(x_id=2, y_id=2, flag=4), ] ) ses.commit() def test_get_headers(self): with orm.Session(self.eng) as ses: user = ses.get(User, 1) keys, values = pt.get_keys_values(user) assert keys == ["id", "name"] assert values == [1, "X"] with self.eng.connect() as connection: row = connection.execute(sa.select(t_user).limit(1)).fetchone() keys, values = pt.get_keys_values(row) assert keys == ["user_id", "name"] assert values == [1, "Alice"] def test_from_result(self): with orm.Session(self.eng) as ses: res = ses.scalars(sa.select(User)) ptable = pt.from_result(res) assert len(ptable._rows) == 3 with self.eng.connect() as connection: res = connection.execute(sa.select(t_user)) ptable = pt.from_result(res) assert len(ptable._rows) == 4 def test_from_text_clause(self): stmt = sa.text(f"SELECT * FROM {t_user.name} LIMIT 2") tb = pt.from_text_clause(stmt, self.eng) assert isinstance(tb, PrettyTable) assert len(tb._rows) == 2 stmt = sa.text( f"SELECT * FROM {t_user.name} WHERE {t_user.name}.user_id = :user_id;" ) stmt = stmt.bindparams(user_id=1) tb = pt.from_text_clause(stmt, self.eng) assert isinstance(tb, PrettyTable) assert len(tb._rows) == 1 def test_from_stmt(self): stmt = sa.select(t_inv) tb = pt.from_stmt(stmt, self.eng) assert isinstance(tb, PrettyTable) assert len(tb._rows) == 6 stmt = sa.select(t_inv).limit(3) tb = pt.from_stmt(stmt, self.eng) assert isinstance(tb, PrettyTable) assert len(tb._rows) == 3 # ORM also works query = sa.select(User).where(User.id >= 2) tb = pt.from_stmt(query, self.eng) assert isinstance(tb, PrettyTable) assert len(tb._rows) == 2 query = sa.select(User).limit(2) tb = pt.from_stmt(query, self.eng) assert isinstance(tb, PrettyTable) assert len(tb._rows) == 2 def test_from_table(self): tb = pt.from_table(t_inv, self.eng, limit=10) assert isinstance(tb, PrettyTable) assert len(tb._rows) == 6 tb = pt.from_table(t_inv, self.eng, limit=3) assert isinstance(tb, PrettyTable) assert len(tb._rows) == 3 def test_from_model(self): tb = pt.from_model(Association, self.eng, limit=2) assert isinstance(tb, PrettyTable) assert len(tb._rows) == 2 with orm.Session(self.eng) as ses: tb = pt.from_model(User, ses, limit=2) assert isinstance(tb, PrettyTable) assert len(tb._rows) == 2 def test_from_data(self): with self.eng.connect() as connection: rows = [row._asdict() for row in connection.execute(sa.select(t_user))] tb = pt.from_dict_list(rows) assert isinstance(tb, PrettyTable) assert len(tb._rows) == 4 def test_from_everything(self): t = sa.text(f"SELECT * FROM {t_user.name} LIMIT 2") stmt = sa.select(t_user) table = t_inv query = sa.select(Association) orm_class = User result = selecting.select_all(self.engine, t_user) data = [row._asdict() for row in selecting.select_all(self.engine, t_user)] everything = [ t, stmt, table, query, orm_class, result, data, f"SELECT user_id FROM {t_user.name} WHERE name = 'Bob'", ] for thing in everything: tb = pt.from_everything(thing, self.engine, limit=10) assert isinstance(tb, PrettyTable) with pytest.raises(Exception): pt.from_everything(None)
class PrettyTableTestBase(BaseCrudTest): @classmethod def class_level_data_setup(cls): pass def test_get_headers(self): pass def test_from_result(self): pass def test_from_text_clause(self): pass def test_from_stmt(self): pass def test_from_table(self): pass def test_from_model(self): pass def test_from_data(self): pass def test_from_everything(self): pass
11
0
16
1
15
0
1
0.01
1
3
2
2
8
2
9
20
155
21
133
45
122
1
96
36
86
2
1
1
10
148,332
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/crud/test_crud_selecting.py
test_crud_selecting.TestSelectingApiPostgres
class TestSelectingApiPostgres(SelectingApiBaseTest): engine = engine_psql
class TestSelectingApiPostgres(SelectingApiBaseTest): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
22
2
0
2
2
1
0
2
2
1
0
2
0
0
148,333
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/orm/test_orm_extended_declarative_base_4_edge_case.py
test_orm_extended_declarative_base_4_edge_case.TestExtendedBaseOnSqlite
class TestExtendedBaseOnSqlite(ExtendedBaseEdgeCaseTestBase): # test on sqlite engine = engine_sqlite
class TestExtendedBaseOnSqlite(ExtendedBaseEdgeCaseTestBase): pass
1
0
0
0
0
0
0
0.5
1
0
0
0
0
0
0
14
2
0
2
2
1
1
2
2
1
0
2
0
0
148,334
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/orm/test_orm_extended_declarative_base_4_edge_case.py
test_orm_extended_declarative_base_4_edge_case.ExtendedBaseEdgeCaseTestBase
class ExtendedBaseEdgeCaseTestBase(BaseCrudTest): def test_absorb(self): user1 = BankAccount(id=1, name="Alice", pin="1234") user2 = BankAccount(name="Bob") user1.absorb(user2) assert user1.values() == [1, "Bob", "1234"] user1 = BankAccount(id=1, name="Alice", pin="1234") user2 = BankAccount(name="Bob") user1.absorb(user2, ignore_none=False) assert user1.values() == [None, "Bob", None] def test_revise(self): user1 = BankAccount(id=1, name="Alice", pin="1234") user1.revise(dict(name="Bob")) assert user1.values() == [1, "Bob", "1234"] user1 = BankAccount(id=1, name="Alice", pin="1234") user1.revise(dict(name="Bob", pin=None)) assert user1.values() == [1, "Bob", "1234"] user1 = BankAccount(id=1, name="Alice", pin="1234") user1.revise(dict(name="Bob", pin=None), ignore_none=False) assert user1.values() == [1, "Bob", None] def test_by_pk(self): PostTagAssociation.smart_insert( self.eng, [ PostTagAssociation(post_id=1, tag_id=1, description="1-1"), PostTagAssociation(post_id=1, tag_id=2, description="1-2"), ], ) PostTagAssociation.smart_insert( self.eng, [ PostTagAssociation(post_id=1, tag_id=3, description="1-3"), PostTagAssociation(post_id=1, tag_id=4, description="1-4"), ], ) pta = PostTagAssociation.by_pk(self.eng, (1, 2)) assert pta.post_id == 1 assert pta.tag_id == 2
class ExtendedBaseEdgeCaseTestBase(BaseCrudTest): def test_absorb(self): pass def test_revise(self): pass def test_by_pk(self): pass
4
0
14
1
12
0
1
0
1
3
2
2
3
1
3
14
44
6
38
9
34
0
26
8
22
1
1
0
3
148,335
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/crud/test_crud_updating.py
test_crud_updating.TestUpdatingApiPostgres
class TestUpdatingApiPostgres(UpdatingApiBaseTest): engine = engine_psql
class TestUpdatingApiPostgres(UpdatingApiBaseTest): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
2
0
2
2
1
0
2
2
1
0
2
0
0
148,336
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/crud/test_crud_updating.py
test_crud_updating.TestUpdatingApiSqlite
class TestUpdatingApiSqlite(UpdatingApiBaseTest): engine = engine_sqlite
class TestUpdatingApiSqlite(UpdatingApiBaseTest): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
2
0
2
2
1
0
2
2
1
0
2
0
0
148,337
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/crud/test_crud_updating.py
test_crud_updating.UpdatingApiBaseTest
class UpdatingApiBaseTest(BaseCrudTest): def teardown_method(self, method): """ Make sure data in all table is cleared after each test cases. """ self.delete_all_data_in_core_table() def test_upsert_all_single_primary_key_column(self): # ------ Before State ------ ins = t_cache.insert() data = [ {"key": "a1"}, ] with self.engine.connect() as connection: connection.execute(ins, data) connection.commit() # Upsert all data = [ {"key": "a1", "value": 1}, # This will update {"key": "a2", "value": 2}, # This will insert {"key": "a3", "value": 3}, # This will insert ] # ------ Invoke ------ update_counter, insert_counter = updating.upsert_all(self.engine, t_cache, data) assert update_counter == 1 assert insert_counter == 2 # ------ After State ------ assert list(selecting.select_all(self.engine, t_cache)) == [ ("a1", 1), ("a2", 2), ("a3", 3), ] def test_upsert_all_multiple_primary_key_column(self): # ------ Before State ------ ins = t_graph.insert() data = [ {"x_node_id": 1, "y_node_id": 2, "value": 0}, ] with self.engine.connect() as connection: connection.execute(ins, data) connection.commit() # ------ Invoke ------ data = [ {"x_node_id": 1, "y_node_id": 2, "value": 2}, # This will update {"x_node_id": 1, "y_node_id": 3, "value": 3}, # This will insert {"x_node_id": 1, "y_node_id": 4, "value": 4}, # This will insert ] update_counter, insert_counter = updating.upsert_all(self.engine, t_graph, data) assert update_counter == 1 assert insert_counter == 2 # ------ After State ------ assert selecting.select_all(self.engine, t_graph).all() == [ (1, 2, 2), (1, 3, 3), (1, 4, 4), ]
class UpdatingApiBaseTest(BaseCrudTest): def teardown_method(self, method): ''' Make sure data in all table is cleared after each test cases. ''' pass def test_upsert_all_single_primary_key_column(self): pass def test_upsert_all_multiple_primary_key_column(self): pass
4
1
19
1
15
5
1
0.36
1
1
0
2
3
0
3
14
61
6
45
12
41
16
25
10
21
1
1
1
3
148,338
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/test_engine_creator.py
test_engine_creator.TestEngineCreator
class TestEngineCreator(object): def test_uri(self): cred = EngineCreator( host="host", port=1234, database="dev", username="user", password="pass" ) assert cred.uri == "user:pass@host:1234/dev" cred = EngineCreator(host="host", port=1234, database="dev", username="user") assert cred.uri == "user@host:1234/dev" cred = EngineCreator( host="host", database="dev", username="user", password="pass" ) assert cred.uri == "user:pass@host/dev" cred = EngineCreator(host="host", database="dev", username="user") assert cred.uri == "user@host/dev" def test_from_json_data(self): cred = EngineCreator.from_json(json_file, json_path="mydb") assert cred.uri == "user:pass@host:1234/dev" cred.to_dict() def test_from_env(self): os.environ["DB_HOST"] = "host" os.environ["DB_PORT"] = "1234" os.environ["DB_DATABASE"] = "dev" os.environ["DB_USERNAME"] = "user" os.environ["DB_PASSWORD"] = "pass" cred = EngineCreator.from_env(prefix="DB") assert cred.uri == "user:pass@host:1234/dev" cred = EngineCreator.from_env(prefix="DB_") assert cred.uri == "user:pass@host:1234/dev" with raises(ValueError): EngineCreator.from_env(prefix="") with raises(ValueError): EngineCreator.from_env(prefix="db") with raises(ValueError): EngineCreator.from_env(prefix="VAR1") def test_validate_key_mapping(self): with raises(ValueError): EngineCreator._validate_key_mapping({}) with raises(ValueError): EngineCreator._validate_key_mapping(dict(a=1, b=2)) EngineCreator._validate_key_mapping(None) EngineCreator._validate_key_mapping( dict( host="host", port="port", database="db", username="user", password="pass", ) ) def test_transform(self): data = {"host": 1, "port": 2, "db": 3, "user": 4, "pass": 5} new_data = EngineCreator._transform( data, dict( host="host", port="port", database="db", username="user", password="pass", ), ) assert new_data == dict(host=1, port=2, database=3, username=4, password=5)
class TestEngineCreator(object): def test_uri(self): pass def test_from_json_data(self): pass def test_from_env(self): pass def test_validate_key_mapping(self): pass def test_transform(self): pass
6
0
14
2
12
0
1
0
1
3
1
0
5
0
5
5
75
13
62
11
56
0
41
11
35
1
1
1
5
148,339
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/debug/test_file_backed_column.py
test_file_backed_column.Task
class Task(Base, sam.ExtendedBase): __tablename__ = "tasks" _settings_major_attrs = ["url"] url: orm.Mapped[str] = orm.mapped_column(sa.String, primary_key=True) update_at: orm.Mapped[datetime] = orm.mapped_column(sa.DateTime) html: orm.Mapped[T.Optional[str]] = orm.mapped_column(sa.String, nullable=True) image: orm.Mapped[T.Optional[str]] = orm.mapped_column(sa.String, nullable=True)
class Task(Base, sam.ExtendedBase): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
26
9
2
7
7
6
0
7
7
6
0
2
0
0
148,340
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/test_io.py
test_io.DataIOTestBase
class DataIOTestBase(BaseCrudTest): @classmethod def class_level_data_setup(cls): with cls.engine.connect() as connection: connection.execute(t_user.delete()) data = [ {"user_id": 1, "name": "Alice"}, {"user_id": 2, "name": "Bob"}, {"user_id": 3, "name": "Cathy"}, ] connection.execute(t_user.insert(), data) def test_table_to_csv(self): filepath = __file__.replace("test_io.py", "t_user.csv") io.table_to_csv(t_user, self.engine, filepath, chunksize=1, overwrite=True)
class DataIOTestBase(BaseCrudTest): @classmethod def class_level_data_setup(cls): pass def test_table_to_csv(self): pass
4
0
6
0
6
0
1
0
1
0
0
2
1
1
2
13
15
1
14
8
10
0
9
5
6
1
1
1
2
148,341
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/test_io.py
test_io.TestDataIOPostgres
class TestDataIOPostgres(DataIOTestBase): engine = engine_psql
class TestDataIOPostgres(DataIOTestBase): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
13
2
0
2
2
1
0
2
2
1
0
2
0
0
148,342
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/test_io.py
test_io.TestDataIOSqlite
class TestDataIOSqlite(DataIOTestBase): engine = engine_sqlite
class TestDataIOSqlite(DataIOTestBase): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
13
2
0
2
2
1
0
2
2
1
0
2
0
0
148,343
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/patterns/large_binary_column/test_large_binary_column_aws_s3.py
test_large_binary_column_aws_s3.BaseTest
class BaseTest(BaseMockTest): engine: sa.Engine = None mock_list = [ moto.mock_s3, ] @classmethod def setup_class_post_hook(cls): Base.metadata.create_all(cls.engine) context.attach_boto_session(cls.bsm.boto_ses) cls.bsm.s3_client.create_bucket(Bucket=bucket) s3dir_root.delete() def setup_method(self): with self.engine.connect() as conn: conn.execute(Task.__table__.delete()) conn.commit() def test(self): engine = self.engine bsm = self.bsm url = "https://www.example.com" html_content_1 = b"<html>this is html 1</html>" image_content_1 = b"this is image 1" html_additional_kwargs = dict(ContentType="text/html") image_additional_kwargs = dict(ContentType="image/jpeg") utc_now = get_utc_now() put_s3_result = aws_s3.put_s3( api_calls=[ aws_s3.PutS3ApiCall( column="html", binary=html_content_1, old_s3_uri=None, extra_put_object_kwargs=html_additional_kwargs, ), aws_s3.PutS3ApiCall( column="image", binary=image_content_1, old_s3_uri=None, extra_put_object_kwargs=image_additional_kwargs, ), ], s3_client=bsm.s3_client, pk=url, bucket=s3dir_root.bucket, prefix=s3dir_root.key, update_at=utc_now, is_pk_url_safe=False, ) class UserError(Exception): pass with orm.Session(engine) as ses: try: with ses.begin(): task1 = Task( url=url, update_at=utc_now, # this is a helper method that convert the put s3 results # to INSERT / UPDATE values **put_s3_result.to_values(), ) # intentionally raises an error to simulate a database failure raise UserError() ses.add(task1) except Exception as e: # clean up created s3 object when create row failed # if you don't want to do that, just don't run this method put_s3_result.clean_up_created_s3_object_when_create_or_update_row_failed() assert ses.get(Task, url) is None values = put_s3_result.to_values() html_s3_uri = values["html"] image_s3_uri = values["image"] assert S3Path(html_s3_uri).exists() is False assert S3Path(image_s3_uri).exists() is False utc_now = get_utc_now() put_s3_result = aws_s3.put_s3( api_calls=[ aws_s3.PutS3ApiCall( column="html", binary=html_content_1, old_s3_uri=None, extra_put_object_kwargs=html_additional_kwargs, ), aws_s3.PutS3ApiCall( column="image", binary=image_content_1, old_s3_uri=None, extra_put_object_kwargs=image_additional_kwargs, ), ], s3_client=bsm.s3_client, pk=url, bucket=s3dir_root.bucket, prefix=s3dir_root.key, update_at=utc_now, is_pk_url_safe=False, ) with orm.Session(engine) as ses: try: with ses.begin(): task1 = Task( url=url, update_at=utc_now, # this is a helper method that convert the put s3 results # to INSERT / UPDATE values **put_s3_result.to_values(), ) ses.add(task1) except Exception as e: # clean up created s3 object when create row failed # if you don't want to do that, just don't run this method put_s3_result.clean_up_created_s3_object_when_create_or_update_row_failed() task1: Task = ses.get(Task, url) assert task1.url == url assert task1.update_at == utc_now assert S3Path(task1.html).read_bytes() == html_content_1 assert S3Path(task1.image).read_bytes() == image_content_1 html_content_2 = b"<html>this is html 2</html>" image_content_2 = b"this is image 2" utc_now = get_utc_now() put_s3_result = aws_s3.put_s3( api_calls=[ aws_s3.PutS3ApiCall( column="html", binary=html_content_2, # since this is an updates, you have to specify the old s3 object, # even it is None. we need this information to clean up old s3 object # when SQL UPDATE succeeded old_s3_uri=task1.html, extra_put_object_kwargs=html_additional_kwargs, ), aws_s3.PutS3ApiCall( column="image", binary=image_content_2, # since this is an updates, you have to specify the old s3 object, # even it is None. we need this information to clean up old s3 object # when SQL UPDATE succeeded old_s3_uri=task1.image, extra_put_object_kwargs=image_additional_kwargs, ), ], s3_client=bsm.s3_client, pk=url, bucket=s3dir_root.bucket, prefix=s3dir_root.key, update_at=utc_now, is_pk_url_safe=False, ) with orm.Session(engine) as ses: try: with ses.begin(): stmt = ( sa.update(Task).where(Task.url == url) # this is a helper method that convert the put s3 results # to INSERT / UPDATE values .values(update_at=utc_now, **put_s3_result.to_values()) ) # intentionally raises an error to simulate a database failure raise UserError() ses.execute(stmt) # clean up old s3 object when update row succeeded # if you don't want to do that, just don't run this method put_s3_result.clean_up_old_s3_object_when_update_row_succeeded() except Exception as e: # clean up created s3 object when update row failed # if you don't want to do that, just don't run this method put_s3_result.clean_up_created_s3_object_when_create_or_update_row_failed() task2: Task = ses.get(Task, url) assert task2.update_at < utc_now assert S3Path(task1.html).read_bytes() == html_content_1 assert S3Path(task1.image).read_bytes() == image_content_1 values = put_s3_result.to_values() html_s3_uri = values["html"] image_s3_uri = values["image"] assert S3Path(html_s3_uri).exists() is False assert S3Path(image_s3_uri).exists() is False # ------------------------------------------------------------------------------ # Update a Row and SQL UPDATE succeeded # ------------------------------------------------------------------------------ utc_now = get_utc_now() put_s3_result = aws_s3.put_s3( api_calls=[ aws_s3.PutS3ApiCall( column="html", binary=html_content_2, # since this is an updates, you have to specify the old s3 object, # even it is None. we need this information to clean up old s3 object # when SQL UPDATE succeeded old_s3_uri=task1.html, extra_put_object_kwargs=html_additional_kwargs, ), aws_s3.PutS3ApiCall( column="image", binary=image_content_2, # since this is an updates, you have to specify the old s3 object, # even it is None. we need this information to clean up old s3 object # when SQL UPDATE succeeded old_s3_uri=task1.image, extra_put_object_kwargs=image_additional_kwargs, ), ], s3_client=bsm.s3_client, pk=url, bucket=s3dir_root.bucket, prefix=s3dir_root.key, update_at=utc_now, is_pk_url_safe=False, ) with orm.Session(engine) as ses: try: with ses.begin(): stmt = ( sa.update(Task).where(Task.url == url) # this is a helper method that convert the put s3 results # to INSERT / UPDATE values .values(update_at=utc_now, **put_s3_result.to_values()) ) ses.execute(stmt) # clean up old s3 object when update row succeeded # if you don't want to do that, just don't run this method put_s3_result.clean_up_old_s3_object_when_update_row_succeeded() except Exception as e: # clean up created s3 object when update row failed # if you don't want to do that, just don't run this method put_s3_result.clean_up_created_s3_object_when_create_or_update_row_failed() task2: Task = ses.get(Task, url) assert task2.update_at == utc_now assert S3Path(task1.html).exists() is False assert S3Path(task1.image).exists() is False assert S3Path(task2.html).read_bytes() == html_content_2 assert S3Path(task2.image).read_bytes() == image_content_2 with orm.Session(engine) as ses: task3: Task = ses.get(Task, url) try: stmt = sa.delete(Task).where(Task.url == url) res = ses.execute(stmt) ses.commit() if res.rowcount == 1: # clean up old s3 object when delete row succeeded # if you don't want to do that, just don't run this method if task3.html: S3Path(task3.html).delete() if task3.image: S3Path(task3.image).delete() except Exception as e: ses.rollback() assert ses.get(Task, url) is None assert S3Path(task3.html).exists() is False assert S3Path(task3.image).exists() is False
class BaseTest(BaseMockTest): @classmethod def setup_class_post_hook(cls): pass def setup_method(self): pass def test(self): pass class UserError(Exception):
6
0
86
6
67
13
4
0.19
1
5
3
2
2
0
3
11
269
23
207
30
201
39
106
26
101
9
1
4
11
148,344
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/patterns/large_binary_column/test_large_binary_column_aws_s3.py
test_large_binary_column_aws_s3.Task
class Task(Base): __tablename__ = "tasks" url = orm.mapped_column(sa.String, primary_key=True) update_at = orm.mapped_column(sa.DateTime) html = orm.mapped_column(sa.String, nullable=True) image = orm.mapped_column(sa.String, nullable=True)
class Task(Base): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
7
1
6
6
5
0
6
6
5
0
1
0
0
148,345
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/patterns/large_binary_column/test_large_binary_column_aws_s3.py
test_large_binary_column_aws_s3.TestPsql
class TestPsql(BaseTest): # pragma: no cover engine = engine_psql
class TestPsql(BaseTest): pass
1
0
0
0
0
0
0
0.5
1
0
0
0
0
0
0
11
2
0
2
2
1
1
2
2
1
0
2
0
0
148,346
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/patterns/large_binary_column/test_large_binary_column_aws_s3.py
test_large_binary_column_aws_s3.TestSqlite
class TestSqlite(BaseTest): engine = engine_sqlite
class TestSqlite(BaseTest): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
11
2
0
2
2
1
0
2
2
1
0
2
0
0
148,347
MacHu-GWU/sqlalchemy_mate-project
MacHu-GWU_sqlalchemy_mate-project/tests/orm/test_orm_extended_declarative_base_1_oop.py
test_orm_extended_declarative_base_1_oop.TestExtendedBaseOOP
class TestExtendedBaseOOP: def test_keys(self): assert User.keys() == ["id", "name"] assert User(id=1).keys() == ["id", "name"] def test_values(self): assert User(id=1, name="Alice").values() == [1, "Alice"] assert User(id=1).values() == [1, None] def test_items(self): assert User(id=1, name="Alice").items() == [("id", 1), ("name", "Alice")] assert User(id=1).items() == [("id", 1), ("name", None)] def test_repr(self): user = User(id=1, name="Alice") assert str(user) == "User(id=1, name='Alice')" def test_to_dict(self): assert User(id=1, name="Alice").to_dict() == {"id": 1, "name": "Alice"} assert User(id=1).to_dict() == {"id": 1, "name": None} assert User(id=1).to_dict(include_null=False) == {"id": 1} def test_to_OrderedDict(self): assert User(id=1, name="Alice").to_OrderedDict( include_null=True ) == OrderedDict( [ ("id", 1), ("name", "Alice"), ] ) assert User(id=1).to_OrderedDict(include_null=True) == OrderedDict( [ ("id", 1), ("name", None), ] ) assert User(id=1).to_OrderedDict(include_null=False) == OrderedDict( [ ("id", 1), ] ) assert User(name="Alice").to_OrderedDict(include_null=True) == OrderedDict( [ ("id", None), ("name", "Alice"), ] ) assert User(name="Alice").to_OrderedDict(include_null=False) == OrderedDict( [ ("name", "Alice"), ] ) def test_glance(self): user = User(id=1, name="Alice") user.glance(_verbose=False) def test_absorb(self): user1 = User(id=1) user2 = User(name="Alice") user3 = User(name="Bob") user1.absorb(user2) assert user1.to_dict() == {"id": 1, "name": "Alice"} user1.absorb(user3) assert user1.to_dict() == {"id": 1, "name": "Bob"} with raises(TypeError): user1.absorb({"name": "Alice"}) def test_revise(self): user = User(id=1) user.revise({"name": "Alice"}) assert user.to_dict() == {"id": 1, "name": "Alice"} user = User(id=1, name="Alice") user.revise({"name": "Bob"}) assert user.to_dict() == {"id": 1, "name": "Bob"} with raises(TypeError): user.revise(User(name="Bob")) def test_primary_key_and_id_field(self): assert User.pk_names() == ("id",) assert tuple([field.name for field in User.pk_fields()]) == ("id",) assert User(id=1).pk_values() == (1,) assert User.id_field_name() == "id" assert User.id_field().name == "id" assert User(id=1).id_field_value() == 1 assert Association.pk_names() == ("x_id", "y_id") assert tuple([field.name for field in Association.pk_fields()]) == ( "x_id", "y_id", ) assert Association(x_id=1, y_id=2).pk_values() == (1, 2) with raises(ValueError): Association.id_field_name() with raises(ValueError): Association.id_field() with raises(ValueError): Association(x_id=1, y_id=2).id_field_value()
class TestExtendedBaseOOP: def test_keys(self): pass def test_values(self): pass def test_items(self): pass def test_repr(self): pass def test_to_dict(self): pass def test_to_OrderedDict(self): pass def test_glance(self): pass def test_absorb(self): pass def test_revise(self): pass def test_primary_key_and_id_field(self): pass
11
0
10
1
9
0
1
0
0
7
2
0
10
0
10
10
109
20
89
17
78
0
61
17
50
1
0
1
10