Best Python code snippet using autotest_python
test_objectmodel.py
Source:test_objectmodel.py
...117 s1 = Symbolic()118 s2 = Symbolic()119 py.test.raises(TypeError, "s1 < s2")120 py.test.raises(TypeError, "hash(s1)")121def test_compute_hash():122 from pypy.rlib.objectmodel import _hash_string, _hash_float, _hash_tuple123 assert compute_hash("Hello") == _hash_string("Hello")124 assert compute_hash(7) == 7125 assert compute_hash(-3.5) == _hash_float(-3.5)126 assert compute_hash(None) == 0127 assert compute_hash(("world", None, 7)) == _hash_tuple(("world", None, 7))128 #129 class Foo(object):130 def __hash__(self):131 return 42132 foo = Foo()133 h = compute_hash(foo)134 assert h == object.__hash__(foo)135 assert h == getattr(foo, '__precomputed_identity_hash')136 assert compute_hash(None) == 0137def test_compute_hash_float():138 from pypy.rlib.rarithmetic import INFINITY, NAN139 assert compute_hash(INFINITY) == 314159140 assert compute_hash(-INFINITY) == -271828141 assert compute_hash(NAN) == 0142def test_compute_identity_hash():143 class Foo(object):144 def __hash__(self):145 return 42146 foo = Foo()147 h = compute_identity_hash(foo)148 assert h == object.__hash__(foo)149 assert h == getattr(foo, '__precomputed_identity_hash')150def test_compute_unique_id():151 class Foo(object):152 pass153 foo = Foo()154 assert compute_unique_id(foo) == id(foo)155def test_current_object_addr_as_int():156 from pypy.rlib.rarithmetic import intmask157 class Foo(object):158 pass159 foo = Foo()160 assert current_object_addr_as_int(foo) == intmask(id(foo))161class BaseTestObjectModel(BaseRtypingTest):162 def test_we_are_translated(self):163 assert we_are_translated() == False164 def fn():165 return we_are_translated()166 res = self.interpret(fn, [])167 assert res is True168 169 def test_rtype_r_dict(self):170 res = self.interpret(test_r_dict, [])171 assert res is True172 def test_rtype_r_dict_bm(self):173 res = self.interpret(test_r_dict_bm, [])174 assert res is True175 def test_rtype_constant_r_dicts(self):176 d1 = r_dict(strange_key_eq, strange_key_hash)177 d1['hello'] = 666178 d2 = r_dict(strange_key_eq, strange_key_hash)179 d2['hello'] = 777180 d2['world'] = 888181 def fn(i):182 if i == 1:183 d = d1184 else:185 d = d2186 return len(d)187 res = self.interpret(fn, [1])188 assert res == 1189 res = self.interpret(fn, [2])190 assert res == 2191 def test_rtype_r_dict_singlefrozen_func(self):192 class FreezingClass(Strange):193 def _freeze_(self):194 return True195 obj = FreezingClass()196 def fn():197 d = r_dict(obj.key_eq, obj.key_hash)198 return play_with_r_dict(d)199 assert self.interpret(fn, []) is True200 def test_rtype_r_dict_singlefrozen_func_pbc(self):201 class FreezingClass(Strange):202 def _freeze_(self):203 return True204 obj = FreezingClass()205 pbc_d = r_dict(obj.key_eq, obj.key_hash) 206 def fn():207 return play_with_r_dict(pbc_d)208 assert self.interpret(fn, []) is True209 def test_rtype_r_dict_exceptions(self):210 def raising_hash(obj):211 if obj.startswith("bla"):212 raise TypeError213 return 1214 def eq(obj1, obj2):215 return obj1 is obj2216 def f():217 d1 = r_dict(eq, raising_hash)218 d1['xxx'] = 1219 try:220 x = d1["blabla"]221 except Exception:222 return 42223 return x224 res = self.interpret(f, [])225 assert res == 42226 def f():227 d1 = r_dict(eq, raising_hash)228 d1['xxx'] = 1229 try:230 x = d1["blabla"]231 except TypeError:232 return 42233 return x234 res = self.interpret(f, [])235 assert res == 42236 def f():237 d1 = r_dict(eq, raising_hash)238 d1['xxx'] = 1239 try:240 d1["blabla"] = 2241 except TypeError:242 return 42243 return 0244 res = self.interpret(f, [])245 assert res == 42246 def test_access_in_try(self):247 h = lambda x: 1248 eq = lambda x,y: x==y249 def f(d):250 try:251 return d[2]252 except ZeroDivisionError:253 return 42254 return -1255 def g(n):256 d = r_dict(eq, h)257 d[1] = n258 d[2] = 2*n259 return f(d)260 res = self.interpret(g, [3])261 assert res == 6262 def test_access_in_try_set(self):263 h = lambda x: 1264 eq = lambda x,y: x==y265 def f(d):266 try:267 d[2] = 77268 except ZeroDivisionError:269 return 42270 return -1271 def g(n):272 d = r_dict(eq, h)273 d[1] = n274 f(d)275 return d[2]276 res = self.interpret(g, [3])277 assert res == 77278 def test_compute_hash(self):279 class Foo(object):280 pass281 def f(i):282 assert compute_hash(i) == compute_hash(42)283 assert compute_hash(i+1.0) == compute_hash(43.0)284 assert compute_hash("Hello" + str(i)) == compute_hash("Hello42")285 if i == 42:286 p = None287 else:288 p = Foo()289 assert compute_hash(p) == compute_hash(None)290 assert (compute_hash(("world", None, i, 7.5)) ==291 compute_hash(("world", None, 42, 7.5)))292 q = Foo()293 assert compute_hash(q) == compute_identity_hash(q)294 from pypy.rlib.rarithmetic import INFINITY, NAN295 assert compute_hash(INFINITY) == 314159296 assert compute_hash(-INFINITY) == -271828297 assert compute_hash(NAN) == 0298 return i*2299 res = self.interpret(f, [42])300 assert res == 84301class TestLLtype(BaseTestObjectModel, LLRtypeMixin):302 def test_rtype_keepalive(self):303 from pypy.rlib import objectmodel304 def f():305 x = [1]306 y = ['b']307 objectmodel.keepalive_until_here(x,y)308 return 1309 res = self.interpret(f, [])310 assert res == 1311 def test_compute_hash_across_translation(self):312 class Foo(object):313 pass314 q = Foo()315 def f(i):316 assert compute_hash(None) == 0317 assert compute_hash(i) == h_42318 assert compute_hash(i+1.0) == h_43_dot_0319 assert compute_hash((i+3)/6.0) == h_7_dot_5320 assert compute_hash("Hello" + str(i)) == h_Hello42321 if i == 42:322 p = None323 else:324 p = Foo()325 assert compute_hash(p) == h_None326 assert compute_hash(("world", None, i, 7.5)) == h_tuple327 assert compute_hash(q) == h_q328 return i*2329 h_42 = compute_hash(42)330 h_43_dot_0 = compute_hash(43.0)331 h_7_dot_5 = compute_hash(7.5)332 h_Hello42 = compute_hash("Hello42")333 h_None = compute_hash(None)334 h_tuple = compute_hash(("world", None, 42, 7.5))335 h_q = compute_hash(q)336 337 res = self.interpret(f, [42])338 assert res == 84339class TestOOtype(BaseTestObjectModel, OORtypeMixin):340 pass341def test_specialize_decorator():342 def f():343 pass344 specialize.memo()(f)345 346 assert f._annspecialcase_ == 'specialize:memo'347 specialize.arg(0)(f)348 assert f._annspecialcase_ == 'specialize:arg(0)'349 specialize.arg(1)(f)...
b_engine.py
Source:b_engine.py
...7 self.crop_info = crop_info8 self.timestamp = timestamp9 self.previous_hash = previous_hash10 self.nonce = nonce11 def compute_hash(self):12 block_string = json.dumps(self.__dict__, sort_keys=True)13 return sha256(block_string.encode()).hexdigest()14 #json.dumps() takes an object and produces a string15 #self.__dict__ has all the object attributes16 #encode converts json formatted string to a UTF-8 string readable by hashlib17 #hashlibâs output is a byte hash - hexdigest converts from bytes to hex18class Blockchain:19 difficulty = 220 def __init__(self):21 self.unconfirmed_crop_info = []22 self.chain = []23 def create_genesis_block(self):24 genesis_block = Block(0, [], time.time(), "0")25 genesis_block.hash = genesis_block.compute_hash()26 self.chain.append(genesis_block)27 # print(genesis_block)28 @property29 def last_block(self):30 return self.chain[-1]31 def add_block(self, block, proof):32 previous_hash = self.last_block.hash33 if previous_hash != block.previous_hash:34 return False35 if not Blockchain.is_valid_proof(block, proof):36 return False37 block.hash = proof38 self.chain.append(block)39 print(self.chain)40 print("Entered add_block and appended this new block to the blockchain")41 return True42 def proof_of_work(self, block):43 block.nonce = 044 print("Entered POW and calculated compute hash for the new block")45 compute_hash = block.compute_hash()46 while not compute_hash.startswith('0' * Blockchain.difficulty):47 block.nonce += 148 compute_hash = block.compute_hash()49 return compute_hash50 def add_new_crop_info(self, crop_info):51 print("Entered add_new_crop and appended crop details")52 self.unconfirmed_crop_info.append(crop_info)53 @classmethod54 def is_valid_proof(cls, block, block_hash):55 if block_hash.startswith('0' * Blockchain.difficulty) and block_hash == block.compute_hash():56 return True57 #@classmethod58 #def check_chain_validity59 def mine(self):60 print("Entered mine function...")61 if not self.unconfirmed_crop_info:62 return False63 last_block = self.last_block64 new_block = Block(index = last_block.index + 1,65 crop_info = self.unconfirmed_crop_info,66 timestamp= time.time(),67 previous_hash = last_block.hash)68 print("Created a Block...")69 proof = self.proof_of_work(new_block) #POW returns computed hash...
public_interfaces_test.py
Source:public_interfaces_test.py
...23hashes: Dict[Callable[..., Any], str] = {}24@pytest.mark.parametrize("interface,expected_hash", list(hashes.items()))25def test_public_interfaces(interface, expected_hash):26 """Test that public interfaces have not been accidentally changed."""27 current_hash = compute_hash(interface)28 assert current_hash == expected_hash, get_warning_message(interface, current_hash)29def test_func_hash():30 """Test that changing a function signature changes its hash."""31 def some_function(a, b):32 return a + b33 original_hash = compute_hash(some_function)34 # pylint: disable=function-redefined35 def some_function(a, b, c):36 return a + b + c37 assert original_hash != compute_hash(some_function)38def test_class_hash():39 """Test that changing a class changes its hash."""40 # pylint: disable=too-few-public-methods, invalid-name41 class SomeClass:42 def __init__(self, a, b):43 self.a = a44 self.b = b45 def add(self):46 return self.a + self.b47 original_hash = compute_hash(SomeClass)48 # changing the __init__ should change the hash49 # pylint: disable=function-redefined, too-few-public-methods, invalid-name50 class SomeClass:51 def __init__(self, a, b, c):52 self.a = a53 self.b = b54 self.c = c55 def add(self):56 return self.a + self.b57 assert original_hash != compute_hash(SomeClass)58 # renaming a public method should change the hash59 # pylint: disable=function-redefined, too-few-public-methods, invalid-name60 class SomeClass:61 def __init__(self, a, b):62 self.a = a63 self.b = b64 def sum(self):65 return self.a + self.b66 assert original_hash != compute_hash(SomeClass)67 # adding a private method should not change the hash68 # pylint: disable=function-redefined, too-few-public-methods, invalid-name69 class SomeClass:70 def __init__(self, a, b):71 self.a = a72 self.b = b73 def add(self):74 return self._sum()75 def _sum(self):76 return self.a + self.b...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!