Best Python code snippet using assertpy_python
test_server.py
Source:test_server.py
1"""Tests for server module."""2from unittest import TestCase3from unittest.mock import patch4import numpy as np5from SpaceBattle.server.exceptions import NotMovableError, NotRotableError6from SpaceBattle.server.commands import MoveCommand, RotateCommand7class FakeMovableClass:8 """Fake movable class."""9 def __init__(self, position: np.ndarray, move_velocity: np.ndarray) -> None:10 """11 Init variabels.12 position - object's position on the map13 move_velocity - movement instantaneous speed14 """15 self._move_velocity: np.ndarray = move_velocity16 self._position: np.ndarray = position17 super().__init__()18 def get_position(self) -> np.ndarray:19 """Get current object's position on the map."""20 return self._position21 def set_position(self, position: np.ndarray) -> None:22 """Set new object's position."""23 self._position = position24 def get_movement_velocity(self) -> np.ndarray:25 """Get object's movement velocity."""26 return self._move_velocity27class FakeRotableClass:28 """Fake rotable class."""29 def __init__(self, direction: int, rotate_velocity: int) -> None:30 """31 Init variabels.32 direction - corrent object's direction in degrees33 rotate_velocity - object's rotate velocity in degrees34 """35 self._direction = direction36 self._rotate_velocity = rotate_velocity37 super().__init__()38 def get_direction(self) -> int:39 """Retrun object's current direction in degrees range from -360 to +360."""40 return self._direction41 def get_rotation_velocity(self) -> int:42 """Retrun object rotation velocity in degrees range from -360 to +360."""43 return self._rotate_velocity44 def set_direction(self, direction: int) -> None:45 """Set a new object's direction."""46 self._direction = direction47class TestMoveCommand(TestCase):48 """Tests for the move command."""49 def test_move(self):50 """51 Test move.52 ÐÐ»Ñ Ð¾Ð±ÑекÑа, наÑ
одÑÑегоÑÑ Ð² ÑоÑке (12, 5) и движÑÑегоÑÑ Ñо ÑкоÑоÑÑÑÑ (-7, 3)53 движение менÑÐµÑ Ð¿Ð¾Ð»Ð¾Ð¶ÐµÐ½Ð¸Ðµ обÑекÑа на (5, 8).54 """55 test_fail_msg: str = """56 The object has been moved to wrong position.57 Wrong position: {}58 Right position: {}59 """60 movable_obj = FakeMovableClass(np.array((12, 5)), np.array((-7, 3)))61 MoveCommand(movable_obj).execute()62 self.assertTrue(63 np.array_equal(movable_obj.get_position(), np.array((5, 8))),64 test_fail_msg.format(movable_obj.get_position(), np.array((5, 8)))65 )66 @patch('tests.test_server.test_server.FakeMovableClass.get_position', side_effect=AttributeError())67 def test_trying_move_object_does_not_return_position(self, mock):68 """Check that move command reraise exception if object doesn't have get_position method."""69 movable_obj = FakeMovableClass(np.array((12, 5)), np.array((-7, 3)))70 with self.assertRaises(NotMovableError):71 MoveCommand(movable_obj).execute()72 @patch('tests.test_server.test_server.FakeMovableClass.get_movement_velocity', side_effect=AttributeError())73 def test_trying_move_object_does_not_return_velocity(self, mock):74 """Check that move command reraise exception if object doesn't have get_movement_velocity method."""75 movable_obj = FakeMovableClass(np.array((12, 5)), np.array((-7, 3)))76 with self.assertRaises(NotMovableError):77 MoveCommand(movable_obj).execute()78 @patch('tests.test_server.test_server.FakeMovableClass.set_position', side_effect=AttributeError())79 def test_trying_move_object_does_not_set_position(self, mock):80 """Check that move command reraise exception if object doesn't have set_position method."""81 movable_obj = FakeMovableClass(np.array((12, 5)), np.array((-7, 3)))82 with self.assertRaises(NotMovableError):83 MoveCommand(movable_obj).execute()84class TestRotateCommand(TestCase):85 """Tests for the move command."""86 def test_move(self):87 """88 Test rotate.89 ÐÐ»Ñ Ð¾Ð±ÑекÑа c напÑавление 45 гÑадÑÑов и повоÑаÑиваÑÑегоÑÑ Ð² лево Ñо ÑкоÑоÑÑÑÑ 30 гÑадÑÑов90 ÑиналÑное напÑавление бÑÐ´ÐµÑ 15 гÑадÑÑов.91 ÐекÑÐ¾Ñ Ð½Ð°Ð¿ÑÐ°Ð²Ð»ÐµÐ½Ð¸Ñ Ð¼Ð¾Ð¶Ð½Ð¾ бÑÐ´ÐµÑ Ð²ÑÑÑиÑаÑÑ Ð¿Ð¾Ð·Ð¶Ðµ ÑеÑез маÑÑиÑÑ Ð¿Ð¾Ð²Ð¾ÑоÑа в Ñом меÑÑе где ÑÑо бÑÐ´ÐµÑ Ð½ÐµÐ¾Ð±Ñ
одимо.92 """93 test_fail_msg: str = """94 The object has been rotated to wrong direction.95 Wrong direction: {}96 Right direction: {}97 """98 right_direction: int = 1599 rotable_obj = FakeRotableClass(45, 30)100 RotateCommand(rotable_obj, 'left').execute()101 self.assertEqual(102 rotable_obj.get_direction(), right_direction,103 test_fail_msg.format(rotable_obj.get_direction(), right_direction)104 )105 @patch('tests.test_server.test_server.FakeRotableClass.get_direction', side_effect=AttributeError())106 def test_trying_move_object_does_not_return_direction(self, mock):107 """Check that move command reraise exception if object doesn't have get_direction method."""108 rotable_obj = FakeRotableClass(45, 30)109 with self.assertRaises(NotRotableError):110 RotateCommand(rotable_obj, 'left').execute()111 @patch('tests.test_server.test_server.FakeRotableClass.get_rotation_velocity', side_effect=AttributeError())112 def test_trying_move_object_does_not_return_rotation_velocity(self, mock):113 """Check that move command reraise exception if object doesn't have get_rotation_velocity method."""114 rotable_obj = FakeRotableClass(45, 30)115 with self.assertRaises(NotRotableError):116 RotateCommand(rotable_obj, 'left').execute()117 @patch('tests.test_server.test_server.FakeRotableClass.set_direction', side_effect=AttributeError())118 def test_trying_move_object_does_not_set_direction(self, mock):119 """Check that move command reraise exception if object doesn't have set_direction method."""120 rotable_obj = FakeRotableClass(45, 30)121 with self.assertRaises(NotRotableError):...
pyethereum_test_utils.py
Source:pyethereum_test_utils.py
1""" Utility class for testing via pyethereum """2from .deployment import HydraDeployment, extract_language3from ethereum.tools import tester4from ethereum import utils5import unittest6import contextlib7import sys8def bytes_to_int(bytez):9 return int(utils.encode_hex(bytez), 16)10def int_to_bytes(i):11 return int(i).to_bytes(32, byteorder='big')12# Simple utility to silently drop messages to stdout13@contextlib.contextmanager14def nostdout():15 save_stdout = sys.stdout16 sys.stdout = None17 yield18 sys.stdout = save_stdout19class PyEthereumTestCase(unittest.TestCase):20 t = None # ethereum.tools.tester module21 s = None # Chain object22 c = None # Main contract23 initial_state = None # Initial state of the chain24 @classmethod25 def setUpClass(cls):26 super(PyEthereumTestCase, cls).setUpClass()27 # Initialize tester, contract and expose relevant objects28 cls.t = tester29 cls.s = cls.t.Chain()30 cls.s.head_state.gas_limit = 10**8031 cls.s.head_state.set_balance(cls.t.a0, 10**80)32 cls.s.head_state.set_balance(cls.t.a1, 10**80)33 cls.s.head_state.set_balance(cls.t.a2, 10**80)34 cls.s.head_state.set_balance(cls.t.a3, 10**80)35 cls.initial_state = None36 def setUp(self):37 self.longMessage = True38 with nostdout():39 self.s.revert(self.initial_state)40 self.gas_used_before = self.s.head_state.gas_used41 self.refunds_before = self.s.head_state.refunds42 from ethereum.slogging import get_logger43 log_tx = get_logger('eth.pb.tx')44 #log_tx.setLevel("DEBUG")45 log_msg = get_logger('eth.pb.msg')46 #log_msg.setLevel("TRACE")47 def tearDown(self):48 gas_used_after = self.s.head_state.gas_used49 print("Test used {} gas".format(gas_used_after - self.gas_used_before))50 def deploy_contract_from_file(self, contract_file, sender=None, value=0):51 with open(contract_file, 'r') as in_file:52 code = in_file.read()53 if sender is not None:54 return self.s.contract(code, language=extract_language(contract_file),55 sender=sender, value=value, startgas=10**20)56 else:57 return self.s.contract(code, language=extract_language(contract_file),58 value=value, startgas=10**20)59 def check_logs(self, topics, data):60 found = False61 for log_entry in self.s.head_state.receipts[-1].logs:62 if topics == log_entry.topics and data == log_entry.data:63 found = True64 self.assertTrue(found, self.s.head_state.receipts[-1].logs)65 def assert_tx_failed(self, function_to_test,66 exception=tester.TransactionFailed):67 """ Ensure that transaction fails, reverting state68 (to prevent gas exhaustion) """69 initial_state = self.s.snapshot()70 self.assertRaises(exception, function_to_test)71 with nostdout():72 self.s.revert(initial_state)73 def assert_raises_msg(self, func, err_msg, test_fail_msg):74 initial_state = self.s.snapshot()75 with self.assertRaises(Exception) as context:76 func()77 self.assertTrue(str(err_msg) in str(context.exception),78 "expected {}, got {}, ".79 format(str(err_msg),80 str(context.exception)) + test_fail_msg)81 with nostdout():82 self.s.revert(initial_state)83class PyEthereumHydraDeployment(HydraDeployment):84 def __init__(self, chain, creator_key, creator_addr, path_to_metacontract,85 paths_to_heads, instrument=True, verbose=False, instrumenter_path="hydra/instrumenter/"):86 super().__init__(creator_addr, path_to_metacontract, paths_to_heads, instrument, verbose)87 self.deployment_chain = chain88 self.creator_key = creator_key89 self.creator_addr = creator_addr90 self.instrumenter_path = instrumenter_path91 # build the instrumenter92 from subprocess import check_call93 check_call(["stack", "build"], cwd=self.instrumenter_path)94 def deploy_contract(self, code, language, **kwargs):95 """96 Deploys a contract to the test chain. Returns the contract's address97 and an ABI wrapper if available98 """99 gas_used_before = self.deployment_chain.head_state.gas_used100 contract = self.deployment_chain.contract(code, sender=self.creator_key,101 language=language,102 startgas=10**20,103 value=kwargs.get('value', 0))104 gas_used_after = self.deployment_chain.head_state.gas_used105 if language == "evm":106 self.logger.debug("Deploying contract of len {} at {} used {} gas".format(107 len(utils.encode_hex(code)),108 utils.encode_hex(contract),109 gas_used_after - gas_used_before))110 return contract, None111 else:112 self.logger.debug("Deploying contract at {} used {} gas".format(113 utils.encode_hex(contract.address),114 gas_used_after - gas_used_before))115 return contract.address, contract116 def get_nonce(self):...
const.py
Source:const.py
1TEST_FAIL_MSG = 'Test Failed'...
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!!