How to use patched_init method in responses

Best Python code snippet using responses

test_blockchain.py

Source:test_blockchain.py Github

copy

Full Screen

1import unittest2from mock import patch, Mock, MagicMock, call3from crankycoin.blockchain import *4class TestBlockchain(unittest.TestCase):5 def test_Blockchain_whenConstructedWithNoBlocks_thenCreatesGenesisBlock(self):6 mock_genesis_block = Mock(Block)7 with patch.object(Blockchain, 'get_genesis_block', return_value=mock_genesis_block) as patched_get_genesis_block, \8 patch.object(Blockchain, 'add_block', return_value=True) as patched_add_block:9 resp = Blockchain()10 patched_get_genesis_block.assert_called_once()11 patched_add_block.assert_called_once_with(mock_genesis_block)12 def test_Blockchain_whenConstructedWithBlocks_thenAddsBlocksWithoutGenesisBlock(self):13 mock_block_one = Mock(Block)14 mock_block_two = Mock(Block)15 with patch.object(Blockchain, 'get_genesis_block') as patched_get_genesis_block, \16 patch.object(Blockchain, 'add_block', return_value=True) as patched_add_block:17 resp = Blockchain([mock_block_one, mock_block_two])18 patched_get_genesis_block.assert_not_called()19 patched_add_block.assert_has_calls([call(mock_block_one), call(mock_block_two)])20 def test_get_genesis_block_whenCalled_thenCreatesAndReturnsBlockWithGenesisTransactions(self):21 genesis_transactions = [{22 'from': '0',23 'timestamp': 0,24 'to': '0409eb9224f408ece7163f40a33274d99b6b3f60e41b447dd45fcc6371f57b88d9d3583c358b1ea8aea4422d17c57de1418554d3a1cd620ca4cb296357888ea596',25 'amount': 1000,26 'signature': '0',27 'hash': 028 },29 {30 "from": "0",31 "to": "0466f992cd361e24e4fa0eeca9a7ddbea1d257a2053dbe16aeb36ac155679a797bf89776903290d7c93e4b5ba49968fbf8ab8a49190f3d7cafe11cc6e925e489f6",32 "amount": 1000,33 "signature": "0",34 "timestamp": 0,35 "hash": 036 }]37 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \38 patch.object(Blockchain, 'calculate_block_hash', return_value="mock_block_hash") as patched_calculate_block_hash, \39 patch('crankycoin.blockchain.Block') as patched_Block:40 subject = Blockchain()41 genesis_block = subject.get_genesis_block()42 patched_calculate_block_hash.assert_called_once_with(0, 0, 0, genesis_transactions, 0)43 patched_Block.assert_called_once_with(0, genesis_transactions, 0, 'mock_block_hash', 0, 0)44 def test_calculate_transaction_hash_whenCalledWithSameTransactions_thenReturnsConsistentSha256Hash(self):45 transaction_one = {46 'from': 'from',47 'timestamp': 0,48 'to': 'to',49 'amount': 50,50 'signature': 'signature',51 'hash': 052 }53 transaction_two = {54 'from': 'from',55 'timestamp': 0,56 'to': 'to',57 'amount': 50,58 'signature': 'signature'59 }60 transaction_three = {61 'to': 'to',62 'timestamp': 0,63 'from': 'from',64 'signature': 'signature',65 'amount': 50,66 'hash': 067 }68 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:69 subject = Blockchain()70 transaction_hash_one = subject.calculate_transaction_hash(transaction_one)71 transaction_hash_two = subject.calculate_transaction_hash(transaction_two)72 transaction_hash_three = subject.calculate_transaction_hash(transaction_three)73 self.assertEqual(transaction_hash_one, transaction_hash_two)74 self.assertEqual(transaction_hash_one, transaction_hash_three)75 self.assertEquals(1, len(set([transaction_hash_one, transaction_hash_two, transaction_hash_three])))76 def test_calculate_transaction_hash_whenCalledWithDifferentTransactions_thenReturnsDifferentSha256Hash(self):77 transaction_one = {78 'from': 'from',79 'timestamp': 0,80 'to': 'to',81 'amount': 50,82 'signature': 'signature',83 'hash': 084 }85 transaction_two = {86 'from': 'different_from',87 'timestamp': 0,88 'to': 'to',89 'amount': 50,90 'signature': 'signature',91 'hash': 092 }93 transaction_three = {94 'from': 'from',95 'timestamp': 0,96 'to': 'to',97 'amount': 50,98 'signature': 'different_signature',99 'hash': 0100 }101 transaction_four = {102 'from': 'from',103 'timestamp': 0,104 'to': 'different_to',105 'amount': 50,106 'signature': 'signature',107 'hash': 0108 }109 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:110 subject = Blockchain()111 transaction_hash_one = subject.calculate_transaction_hash(transaction_one)112 transaction_hash_two = subject.calculate_transaction_hash(transaction_two)113 transaction_hash_three = subject.calculate_transaction_hash(transaction_three)114 transaction_hash_four = subject.calculate_transaction_hash(transaction_four)115 self.assertNotEqual(transaction_hash_one, transaction_hash_two)116 self.assertNotEqual(transaction_hash_one, transaction_hash_three)117 self.assertNotEqual(transaction_one, transaction_hash_four)118 self.assertEquals(4, len(set([transaction_hash_one, transaction_hash_two, transaction_hash_three, transaction_hash_four])))119 def test_calculate_block_hash_whenCalledWithSameBlockData_thenReturnsConsistentSha256Hash(self):120 transaction_one = {121 'from': 'from',122 'timestamp': 0,123 'to': 'to',124 'amount': 50,125 'signature': 'signature',126 'hash': 0127 }128 transaction_two = {129 'from': 'different_from',130 'timestamp': 0,131 'to': 'to',132 'amount': 50,133 'signature': 'signature',134 'hash': 0135 }136 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:137 subject = Blockchain()138 block_hash_one = subject.calculate_block_hash(1, "previous_hash", 0, [transaction_one, transaction_two], "1234")139 block_hash_two = subject.calculate_block_hash(1, "previous_hash", 0, [transaction_one, transaction_two], "1234")140 self.assertEqual(block_hash_one, block_hash_two)141 def test_calculate_block_hash_whenCalledWithDifferentBlockData_thenReturnsDifferentSha256Hash(self):142 transaction_one = {143 'from': 'from',144 'timestamp': 0,145 'to': 'to',146 'amount': 50,147 'signature': 'signature',148 'hash': 0149 }150 transaction_two = {151 'from': 'different_from',152 'timestamp': 0,153 'to': 'to',154 'amount': 50,155 'signature': 'signature',156 'hash': 0157 }158 transaction_three = {159 'from': 'from',160 'timestamp': 0,161 'to': 'to',162 'amount': 50,163 'signature': 'different_signature',164 'hash': 0165 }166 transaction_four = {167 'from': 'from',168 'timestamp': 0,169 'to': 'different_to',170 'amount': 50,171 'signature': 'signature',172 'hash': 0173 }174 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:175 subject = Blockchain()176 block_hash_one = subject.calculate_block_hash(1, "previous_hash", 0, [transaction_one, transaction_two], "1234")177 block_hash_two = subject.calculate_block_hash(2, "previous_hash", 0, [transaction_one, transaction_two], "1234")178 block_hash_three = subject.calculate_block_hash(1, "different_previous_hash", 0, [transaction_one, transaction_two], "1234")179 block_hash_four = subject.calculate_block_hash(1, "previous_hash", 1, [transaction_one, transaction_two], "1234")180 block_hash_five = subject.calculate_block_hash(1, "previous_hash", 0, [transaction_three, transaction_four], "1234")181 block_hash_six = subject.calculate_block_hash(1, "previous_hash", 0, [transaction_one, transaction_two], "5678")182 self.assertNotEqual(block_hash_one, block_hash_two)183 self.assertNotEqual(block_hash_one, block_hash_three)184 self.assertNotEqual(block_hash_one, block_hash_four)185 self.assertNotEqual(block_hash_one, block_hash_five)186 self.assertNotEqual(block_hash_one, block_hash_six)187 self.assertEquals(6, len(set([block_hash_one, block_hash_two, block_hash_three, block_hash_four, block_hash_five, block_hash_six])))188 def test_check_hash_and_hash_pattern_whenBlockHasValidHashAndPattern_thenReturnsTrue(self):189 mock_block = Mock(Block)190 transaction = {191 'from': 'from',192 'timestamp': 0,193 'to': 'to',194 'amount': 50,195 'signature': 'signature',196 'hash': 0197 }198 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \199 patch.object(Blockchain, 'calculate_block_hash', return_value="0000_valid_block_hash") as patched_calculate_block_hash:200 mock_block.current_hash = "0000_valid_block_hash"201 mock_block.index = 35202 mock_block.previous_hash = "0000_valid_previous_hash"203 mock_block.transactions = [transaction]204 mock_block.nonce = 37205 mock_block.timestamp = 12341234206 subject = Blockchain()207 resp = subject._check_hash_and_hash_pattern(mock_block)208 self.assertIsNone(resp)209 def test_check_hash_and_hash_pattern_whenBlockHasInvalidHash_thenReturnsFalse(self):210 mock_block = Mock(Block)211 transaction = {212 'from': 'from',213 'timestamp': 0,214 'to': 'to',215 'amount': 50,216 'signature': 'signature',217 'hash': 0218 }219 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \220 patch.object(Blockchain, 'calculate_block_hash', return_value="0000_wrong_block_hash") as patched_calculate_block_hash:221 mock_block.current_hash = "0000_valid_block_hash"222 mock_block.index = 35223 mock_block.previous_hash = "0000_valid_previous_hash"224 mock_block.transactions = [transaction]225 mock_block.nonce = 37226 mock_block.timestamp = 12341234227 subject = Blockchain()228 with self.assertRaises(InvalidHash) as context:229 subject._check_hash_and_hash_pattern(mock_block)230 self.assertTrue("Block Hash Mismatch" in str(context.exception))231 def test_check_hash_and_hash_pattern_whenBlockHasInvalidPattern_thenReturnsFalse(self):232 mock_block = Mock(Block)233 transaction = {234 'from': 'from',235 'timestamp': 0,236 'to': 'to',237 'amount': 50,238 'signature': 'signature',239 'hash': 0240 }241 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \242 patch.object(Blockchain, 'calculate_block_hash', return_value="invalid_block_hash") as patched_calculate_block_hash:243 mock_block.current_hash = "invalid_block_hash"244 mock_block.index = 35245 mock_block.previous_hash = "0000_valid_previous_hash"246 mock_block.transactions = [transaction]247 mock_block.nonce = 37248 mock_block.timestamp = 12341234249 subject = Blockchain()250 with self.assertRaises(InvalidHash) as context:251 subject._check_hash_and_hash_pattern(mock_block)252 self.assertTrue("Incompatible Block Hash" in str(context.exception))253 def test_check_index_and_previous_hash_whenBlockHasValidIndexAndPreviousHash_thenReturnsTrue(self):254 mock_block = Mock(Block)255 mock_block.index = 35256 mock_block.previous_hash = "0000_hash_of_block_34"257 mock_latest_block = Mock(Block)258 mock_latest_block.index = 34259 mock_latest_block.current_hash = "0000_hash_of_block_34"260 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \261 patch.object(Blockchain, 'get_latest_block', return_value=mock_latest_block) as patched_get_latest_block:262 subject = Blockchain()263 resp = subject._check_index_and_previous_hash(mock_block)264 self.assertIsNone(resp)265 def test_check_index_and_previous_hash_whenBlockHasInValidIndex_thenReturnsFalse(self):266 mock_block = Mock(Block)267 mock_block.index = 35268 mock_block.previous_hash = "0000_hash_of_block_34"269 mock_latest_block = Mock(Block)270 mock_latest_block.index = 33271 mock_latest_block.current_hash = "0000_hash_of_block_34"272 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \273 patch.object(Blockchain, 'get_latest_block', return_value=mock_latest_block) as patched_get_latest_block:274 subject = Blockchain()275 with self.assertRaises(ChainContinuityError) as context:276 subject._check_index_and_previous_hash(mock_block)277 self.assertTrue("Incompatible block index" in str(context.exception))278 def test_check_index_and_previous_hash_whenBlockHasInValidPreviousHash_thenReturnsFalse(self):279 mock_block = Mock(Block)280 mock_block.index = 35281 mock_block.previous_hash = "0000_wrong_hash_of_block_34"282 mock_latest_block = Mock(Block)283 mock_latest_block.index = 34284 mock_latest_block.current_hash = "0000_hash_of_block_34"285 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \286 patch.object(Blockchain, 'get_latest_block', return_value=mock_latest_block) as patched_get_latest_block:287 subject = Blockchain()288 with self.assertRaises(ChainContinuityError) as context:289 subject._check_index_and_previous_hash(mock_block)290 self.assertTrue("Incompatible block hash" in str(context.exception))291 def test_check_transactions_and_block_reward_whenValid_thenReturnsTrue(self):292 mock_block = Mock(Block)293 transaction = {294 'from': 'from',295 'timestamp': 1498923800,296 'to': 'to',297 'amount': 50,298 'signature': 'signature',299 'hash': "transaction_hash_one"300 }301 reward_transaction = {302 'from': "0",303 'timestamp': 1498933800,304 'to': 'to',305 'amount': 50,306 'signature': 'signature',307 'hash': 0308 }309 mock_block.index = 5310 mock_block.transactions = [transaction, reward_transaction]311 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \312 patch.object(Blockchain, 'calculate_transaction_hash', return_value="transaction_hash_one") as patched_calculate_transaction_hash, \313 patch.object(Blockchain, 'find_duplicate_transactions', return_value=False) as patched_find_duplicate_transactions, \314 patch.object(Blockchain, 'verify_signature', return_value=True) as patched_verify_signature, \315 patch.object(Blockchain, 'get_balance', return_value=50) as patched_get_balance, \316 patch.object(Blockchain, 'get_reward', return_value=50) as patched_get_reward:317 subject = Blockchain()318 resp = subject._check_transactions_and_block_reward(mock_block)319 self.assertIsNone(resp)320 def test_check_transactions_and_block_reward_whenValidMultipleTransactionsFromSamePayer_thenReturnsTrue(self):321 mock_block = Mock(Block)322 transaction_one = {323 'from': 'from',324 'timestamp': 1498923800,325 'to': 'to',326 'amount': 25,327 'signature': 'signature_one',328 'hash': "transaction_hash_one"329 }330 transaction_two = {331 'from': 'from',332 'timestamp': 1498924800,333 'to': 'to',334 'amount': 25,335 'signature': 'signature_two',336 'hash': "transaction_hash_two"337 }338 reward_transaction = {339 'from': "0",340 'timestamp': 1498933800,341 'to': 'to',342 'amount': 50,343 'signature': '0',344 'hash': "0"345 }346 mock_block.index = 5347 mock_block.transactions = [transaction_one, transaction_two, reward_transaction]348 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \349 patch.object(Blockchain, 'calculate_transaction_hash', side_effect=["transaction_hash_one", "transaction_hash_two"]) as patched_calculate_transaction_hash, \350 patch.object(Blockchain, 'find_duplicate_transactions', return_value=False) as patched_find_duplicate_transactions, \351 patch.object(Blockchain, 'verify_signature', return_value=True) as patched_verify_signature, \352 patch.object(Blockchain, 'get_balance', return_value=50) as patched_get_balance, \353 patch.object(Blockchain, 'get_reward', return_value=50) as patched_get_reward:354 subject = Blockchain()355 resp = subject._check_transactions_and_block_reward(mock_block)356 self.assertIsNone(resp)357 def test_check_transactions_and_block_reward_whenInvalidHash_thenReturnsFalse(self):358 mock_block = Mock(Block)359 transaction = {360 'from': 'from',361 'timestamp': 1498923800,362 'to': 'to',363 'amount': 50,364 'signature': 'signature',365 'hash': "invalid_transaction_hash_one"366 }367 reward_transaction = {368 'from': 0,369 'timestamp': 1498933800,370 'to': 'to',371 'amount': 50,372 'signature': 'signature',373 'hash': 0374 }375 mock_block.index = 2376 mock_block.transactions = [transaction, reward_transaction]377 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \378 patch.object(Blockchain, 'calculate_transaction_hash', return_value="transaction_hash_one") as patched_calculate_transaction_hash, \379 patch.object(Blockchain, 'find_duplicate_transactions', return_value=False) as patched_find_duplicate_transactions, \380 patch.object(Blockchain, 'get_balance', return_value=50) as patched_get_balance, \381 patch.object(Blockchain, 'get_reward', return_value=50) as patched_get_reward:382 subject = Blockchain()383 with self.assertRaises(InvalidTransactions) as context:384 subject._check_transactions_and_block_reward(mock_block)385 self.assertTrue("Incorrect transaction hash" in str(context.exception))386 def test_check_transactions_and_block_reward_whenDuplicateTransaction_thenReturnsFalse(self):387 mock_block = Mock(Block)388 transaction = {389 'from': 'from',390 'timestamp': 1498923800,391 'to': 'to',392 'amount': 50,393 'signature': 'signature',394 'hash': "transaction_hash_one"395 }396 reward_transaction = {397 'from': 0,398 'timestamp': 1498933800,399 'to': 'to',400 'amount': 50,401 'signature': 'signature',402 'hash': 0403 }404 mock_block.index = 2405 mock_block.transactions = [transaction, reward_transaction]406 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \407 patch.object(Blockchain, 'calculate_transaction_hash', return_value="transaction_hash_one") as patched_calculate_transaction_hash, \408 patch.object(Blockchain, 'find_duplicate_transactions', return_value=True) as patched_find_duplicate_transactions, \409 patch.object(Blockchain, 'get_balance', return_value=50) as patched_get_balance, \410 patch.object(Blockchain, 'get_reward', return_value=50) as patched_get_reward:411 subject = Blockchain()412 with self.assertRaises(InvalidTransactions) as context:413 subject._check_transactions_and_block_reward(mock_block)414 self.assertTrue("Transactions not valid. Duplicate transaction detected" in str(context.exception))415 def test_check_transactions_and_block_reward_whenInsufficientBalanceFromPayer_thenReturnsFalse(self):416 mock_block = Mock(Block)417 transaction_one = {418 'from': 'from',419 'timestamp': 1498923800,420 'to': 'to',421 'amount': 25,422 'signature': 'signature_one',423 'hash': "transaction_hash_one"424 }425 transaction_two = {426 'from': 'from',427 'timestamp': 1498924800,428 'to': 'to',429 'amount': 25,430 'signature': 'signature_two',431 'hash': "transaction_hash_two"432 }433 reward_transaction = {434 'from': 0,435 'timestamp': 1498933800,436 'to': 'to',437 'amount': 50,438 'signature': '0',439 'hash': 0440 }441 mock_block.index = 5442 mock_block.transactions = [transaction_one, transaction_two, reward_transaction]443 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \444 patch.object(Blockchain, 'calculate_transaction_hash', side_effect=["transaction_hash_one", "transaction_hash_two"]) as patched_calculate_transaction_hash, \445 patch.object(Blockchain, 'find_duplicate_transactions', return_value=False) as patched_find_duplicate_transactions, \446 patch.object(Blockchain, 'verify_signature', return_value=True) as patched_verify_signature, \447 patch.object(Blockchain, 'get_balance', return_value=49) as patched_get_balance, \448 patch.object(Blockchain, 'get_reward', return_value=50) as patched_get_reward:449 subject = Blockchain()450 with self.assertRaises(InvalidTransactions) as context:451 subject._check_transactions_and_block_reward(mock_block)452 self.assertTrue("Insufficient funds" in str(context.exception))453 def test_check_transactions_and_block_reward_whenInvalidBlockReward_thenReturnsFalse(self):454 mock_block = Mock(Block)455 transaction_one = {456 'from': 'from',457 'timestamp': 1498923800,458 'to': 'to',459 'amount': 25,460 'signature': 'signature_one',461 'hash': "transaction_hash_one"462 }463 transaction_two = {464 'from': 'from',465 'timestamp': 1498924800,466 'to': 'to',467 'amount': 25,468 'signature': 'signature_two',469 'hash': "transaction_hash_two"470 }471 reward_transaction = {472 'from': 0,473 'timestamp': 1498933800,474 'to': 'to',475 'amount': 51,476 'signature': '0',477 'hash': 0478 }479 mock_block.index = 5480 mock_block.transactions = [transaction_one, transaction_two, reward_transaction]481 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \482 patch.object(Blockchain, 'calculate_transaction_hash', side_effect=["transaction_hash_one", "transaction_hash_two"]) as patched_calculate_transaction_hash, \483 patch.object(Blockchain, 'find_duplicate_transactions', return_value=False) as patched_find_duplicate_transactions, \484 patch.object(Blockchain, 'verify_signature', return_value=True) as patched_verify_signature, \485 patch.object(Blockchain, 'get_balance', return_value=50) as patched_get_balance, \486 patch.object(Blockchain, 'get_reward', return_value=50) as patched_get_reward:487 subject = Blockchain()488 with self.assertRaises(InvalidTransactions) as context:489 subject._check_transactions_and_block_reward(mock_block)490 self.assertTrue("Incorrect block reward" in str(context.exception))491 def test_check_transactions_and_block_reward_whenInvalidBlockRewardSource_thenReturnsFalse(self):492 mock_block = Mock(Block)493 transaction_one = {494 'from': 'from',495 'timestamp': 1498923800,496 'to': 'to',497 'amount': 25,498 'signature': 'signature_one',499 'hash': "transaction_hash_one"500 }501 transaction_two = {502 'from': 'from',503 'timestamp': 1498924800,504 'to': 'to',505 'amount': 25,506 'signature': 'signature_two',507 'hash': "transaction_hash_two"508 }509 reward_transaction = {510 'from': 'a different source',511 'timestamp': 1498933800,512 'to': 'to',513 'amount': 50,514 'signature': '0',515 'hash': 0516 }517 mock_block.index = 5518 mock_block.transactions = [transaction_one, transaction_two, reward_transaction]519 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \520 patch.object(Blockchain, 'calculate_transaction_hash', side_effect=["transaction_hash_one", "transaction_hash_two"]) as patched_calculate_transaction_hash, \521 patch.object(Blockchain, 'find_duplicate_transactions', return_value=False) as patched_find_duplicate_transactions, \522 patch.object(Blockchain, 'verify_signature', return_value=True) as patched_verify_signature, \523 patch.object(Blockchain, 'get_balance', return_value=50) as patched_get_balance, \524 patch.object(Blockchain, 'get_reward', return_value=50) as patched_get_reward:525 subject = Blockchain()526 with self.assertRaises(InvalidTransactions) as context:527 subject._check_transactions_and_block_reward(mock_block)528 self.assertTrue("Incorrect block reward" in str(context.exception))529 def test_validate_block_whenValid_returnsTrue(self):530 mock_block = Mock(Block)531 mock_block.index = 51000532 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \533 patch.object(Blockchain, '_check_hash_and_hash_pattern', return_value=True) as patched_check_hash_and_hash_pattern, \534 patch.object(Blockchain, '_check_index_and_previous_hash', return_value=True) as patched_check_index_and_previous_hash, \535 patch.object(Blockchain, '_check_transactions_and_block_reward', return_value=True) as patched_check_transactions_and_block_reward:536 subject = Blockchain()537 resp = subject.validate_block(mock_block)538 self.assertTrue(resp)539 def test_validate_block_whenValidGenesisBlock_returnsTrue(self):540 genesis_block = Mock(Block)541 genesis_block.index = 0542 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \543 patch.object(Blockchain, 'get_genesis_block', return_value=genesis_block) as patched_get_genesis_block:544 subject = Blockchain()545 resp = subject.validate_block(genesis_block)546 self.assertTrue(resp)547 def test_validate_block_whenInvalidGenesisBlock_raisesGenesisBlockMismatchException(self):548 invalid_genesis_block = Mock(Block)549 invalid_genesis_block.index = 0550 genesis_block = Mock(Block)551 genesis_block.index = 0552 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \553 patch.object(Blockchain, 'get_genesis_block', return_value=genesis_block) as patched_get_genesis_block:554 subject = Blockchain()555 resp = subject.validate_block(invalid_genesis_block)556 self.assertFalse(resp)557 def test_validate_block_whenInvalidHash_raisesInvalidHashException(self):558 mock_block = Mock(Block)559 mock_block.index = 51000560 mock_block.current_hash = "invalid_hash"561 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \562 patch.object(Blockchain, '_check_hash_and_hash_pattern', side_effect=InvalidHash(51000, "Invalid Hash")) as patched_check_hash_and_hash_pattern:563 subject = Blockchain()564 resp = subject.validate_block(mock_block)565 self.assertFalse(resp)566 def test_validate_block_whenInvalidIncompatibleBlock_raisesChainContinuityErrorException(self):567 mock_block = Mock(Block)568 mock_block.index = 51000569 mock_block.current_hash = "0000_current_hash"570 mock_block.previous_hash = "0000_previous_hash"571 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \572 patch.object(Blockchain, '_check_hash_and_hash_pattern') as patched_check_hash_and_hash_pattern, \573 patch.object(Blockchain, '_check_index_and_previous_hash', side_effect=ChainContinuityError(51000, "")) as patched_check_index_and_previous_hash:574 subject = Blockchain()575 resp = subject.validate_block(mock_block)576 self.assertFalse(resp)577 def test_validate_block_whenInvalidTransactions_raisesInvalidTransactionsException(self):578 mock_block = Mock(Block)579 mock_block.index = 51000580 mock_block.current_hash = "0000_current_hash"581 mock_block.previous_hash = "0000_previous_hash"582 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \583 patch.object(Blockchain, '_check_hash_and_hash_pattern') as patched_check_hash_and_hash_pattern, \584 patch.object(Blockchain, '_check_index_and_previous_hash') as patched_check_index_and_previous_hash, \585 patch.object(Blockchain, '_check_transactions_and_block_reward', side_effect=InvalidTransactions(51000, "")) as patched__check_transactions_and_block_reward:586 subject = Blockchain()587 resp = subject.validate_block(mock_block)588 self.assertFalse(resp)589 def test_alter_chain_whenNewChainIsLonger_thenReplacesChainAndReturnsTrue(self):590 # difficult to unit test; Likely code smell591 mock_block_one = Mock(Block, name="mock_block_one")592 mock_block_one.index = 0593 mock_block_two = Mock(Block, name="mock_block_two")594 mock_block_two.index = 1595 mock_block_three = Mock(Block, name="mock_block_three")596 mock_block_three.index = 2597 mock_block_four = Mock(Block, name="mock_block_four")598 mock_block_four.index = 3599 mock_block_five = Mock(Block, name="mock_block_five")600 mock_block_five.index = 4601 mock_forked_block_four = Mock(Block, name="mock_forked_block_four")602 mock_forked_block_four.index = 3603 mock_forked_block_five = Mock(Block, name="mock_forked_block_five")604 mock_forked_block_five.index = 4605 mock_forked_block_six = Mock(Block, name="mock_forked_block_six")606 mock_forked_block_six.index = 5607 mock_blocks = [608 mock_block_one,609 mock_block_two,610 mock_block_three,611 mock_block_four,612 mock_block_five613 ]614 mock_forked_blocks = [615 mock_forked_block_four,616 mock_forked_block_five,617 mock_forked_block_six618 ]619 mock_altered_blocks = [620 mock_block_one,621 mock_block_two,622 mock_block_three,623 mock_forked_block_four,624 mock_forked_block_five,625 mock_forked_block_six626 ]627 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \628 patch.object(Blockchain, 'get_size', side_effect=[6, 5]) as patched_get_size:629 subject = Blockchain()630 subject.blocks = mock_blocks631 subject.blocks_lock = threading.Lock()632 resp = subject.alter_chain(mock_forked_blocks)633 self.assertTrue(resp)634 self.assertEqual(subject.blocks, mock_altered_blocks)635 def test_alter_chain_whenNewChainIsNotLonger_thenDoesNotAlterChainAndReturnsFalse(self):636 # difficult to unit test; Likely code smell637 mock_block_one = Mock(Block, name="mock_block_one")638 mock_block_one.index = 0639 mock_block_two = Mock(Block, name="mock_block_two")640 mock_block_two.index = 1641 mock_block_three = Mock(Block, name="mock_block_three")642 mock_block_three.index = 2643 mock_block_four = Mock(Block, name="mock_block_four")644 mock_block_four.index = 3645 mock_block_five = Mock(Block, name="mock_block_five")646 mock_block_five.index = 4647 mock_forked_block_four = Mock(Block, name="mock_forked_block_four")648 mock_forked_block_four.index = 3649 mock_forked_block_five = Mock(Block, name="mock_forked_block_five")650 mock_forked_block_five.index = 4651 mock_blocks = [652 mock_block_one,653 mock_block_two,654 mock_block_three,655 mock_block_four,656 mock_block_five657 ]658 mock_forked_blocks = [659 mock_forked_block_four,660 mock_forked_block_five661 ]662 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \663 patch.object(Blockchain, 'get_size', return_value=5) as patched_get_size:664 subject = Blockchain()665 subject.blocks = mock_blocks666 resp = subject.alter_chain(mock_forked_blocks)667 self.assertFalse(resp)668 self.assertEqual(subject.blocks, mock_blocks)669 def test_add_block_whenValidBlock_thenAddsBlockAndReturnsTrue(self):670 mock_block = Mock(Block)671 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \672 patch.object(Blockchain, 'validate_block', return_value=True) as patched_validate_block:673 subject = Blockchain()674 mock_blocks = Mock()675 subject.blocks = mock_blocks676 subject.blocks_lock = threading.Lock()677 resp = subject.add_block(mock_block)678 self.assertTrue(resp)679 mock_blocks.append.assert_called_once_with(mock_block)680 def test_add_block_whenInvalidBlock_thenDoesNotAddBlockAndReturnsFalse(self):681 mock_block = Mock(Block)682 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \683 patch.object(Blockchain, 'validate_block', return_value=False) as patched_validate_block:684 subject = Blockchain()685 mock_blocks = Mock()686 subject.blocks = mock_blocks687 subject.blocks_lock = threading.Lock()688 resp = subject.add_block(mock_block)689 self.assertFalse(resp)690 mock_blocks.append.assert_not_called()691 def test_mine_block_whenNoUnconfirmedTransactions_thenReturnsNone(self):692 latest_block = Mock(Block)693 latest_block.index = 35694 latest_block.current_hash = "latest_block_hash"695 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \696 patch.object(Blockchain, 'get_latest_block', return_value=latest_block) as patched_get_latest_block, \697 patch.object(Blockchain, 'pop_next_unconfirmed_transaction', return_value=None) as patched_pop_next_unconfirmed_transaction:698 subject = Blockchain()699 resp = subject.mine_block("reward_address")700 self.assertIsNone(resp)701 patched_pop_next_unconfirmed_transaction.assert_called_once()702 def test_mine_block_whenOneTransaction_andIncorrectTransactionHash_thenReturnsNone(self):703 transaction = {704 'from': 'from',705 'timestamp': 1498923800,706 'to': 'to',707 'amount': 25,708 'signature': 'signature',709 'hash': 'incorrect_transaction_hash'710 }711 latest_block = Mock(Block)712 latest_block.index = 35713 latest_block.current_hash = "latest_block_hash"714 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \715 patch.object(Blockchain, 'get_latest_block', return_value=latest_block) as patched_get_latest_block, \716 \717 patch.object(Blockchain, 'pop_next_unconfirmed_transaction', side_effect=[transaction, None]) as patched_pop_next_unconfirmed_transaction, \718 patch.object(Blockchain, 'calculate_transaction_hash', return_value="transaction_hash") as patched_calculate_transaction_hash:719 subject = Blockchain()720 resp = subject.mine_block("reward_address")721 self.assertIsNone(resp)722 self.assertEqual(patched_pop_next_unconfirmed_transaction.call_count, 2)723 patched_calculate_transaction_hash.assert_called_once_with(transaction)724 def test_mine_block_whenOneDuplicateTransaction_thenReturnsNone(self):725 transaction = {726 'from': 'from',727 'timestamp': 1498923800,728 'to': 'to',729 'amount': 25,730 'signature': 'signature',731 'hash': 'transaction_hash'732 }733 block_id_with_same_transaction = 38734 latest_block = Mock(Block)735 latest_block.index = 35736 latest_block.current_hash = "latest_block_hash"737 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \738 patch.object(Blockchain, 'get_latest_block', return_value=latest_block) as patched_get_latest_block, \739 \740 patch.object(Blockchain, 'pop_next_unconfirmed_transaction', side_effect=[transaction, None]) as patched_pop_next_unconfirmed_transaction, \741 patch.object(Blockchain, 'calculate_transaction_hash', return_value="transaction_hash") as patched_calculate_transaction_hash, \742 patch.object(Blockchain, 'find_duplicate_transactions', return_value=block_id_with_same_transaction) as patched_find_duplicate_transactions:743 subject = Blockchain()744 resp = subject.mine_block("reward_address")745 self.assertIsNone(resp)746 self.assertEqual(patched_pop_next_unconfirmed_transaction.call_count, 2)747 patched_calculate_transaction_hash.assert_called_once_with(transaction)748 patched_find_duplicate_transactions.asssert_called_once_with("transaction_hash")749 def test_mine_block_whenDuplicateTransactionsInUnconfirmedPool_thenMinesOneOfThemAndReturnsBlock(self):750 # this is difficult to test; likely code smell751 transaction = {752 'from': 'from',753 'timestamp': 1498923800,754 'to': 'to',755 'amount': 25,756 'signature': 'signature',757 'hash': 'transaction_hash'758 }759 duplicate_transaction = {760 'from': 'from',761 'timestamp': 1498923800,762 'to': 'to',763 'amount': 25,764 'signature': 'signature',765 'hash': 'transaction_hash'766 }767 latest_block = Mock(Block)768 latest_block.index = 31769 latest_block.current_hash = "latest_block_current_hash"770 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \771 patch.object(Blockchain, 'pop_next_unconfirmed_transaction', side_effect=[transaction, duplicate_transaction, None]) as patched_pop_next_unconfirmed_transaction, \772 patch.object(Blockchain, 'calculate_transaction_hash', side_effect=["transaction_hash", "transaction_hash", "reward_transaction_hash"]) as patched_calculate_transaction_hash, \773 patch.object(Blockchain, 'find_duplicate_transactions', return_value=False) as patched_find_duplicate_transactions, \774 patch.object(Blockchain, 'verify_signature', return_value=True) as patched_verify_signature, \775 patch.object(Blockchain, 'get_latest_block', return_value=latest_block) as patched_get_latest_block, \776 patch.object(Blockchain, 'get_reward', return_value=50) as patched_get_reward, \777 patch.object(Blockchain, 'calculate_block_hash', side_effect=["bad_hash", "bad_hash", "0000_good_hash", "0000_good_hash"]) as patched_calculate_block_hash, \778 patch("crankycoin.datetime.datetime") as patched_datetime:779 subject = Blockchain()780 mock_utcnow = Mock()781 mock_utcnow.isoformat.return_value = 5555555555782 patched_datetime.utcnow.return_value = mock_utcnow783 resp = subject.mine_block("reward_address")784 self.assertIsInstance(resp, Block)785 self.assertEqual(len(resp.transactions), 2)786 self.assertEqual(patched_pop_next_unconfirmed_transaction.call_count, 3)787 self.assertEqual(patched_calculate_transaction_hash.call_count, 3)788 patched_find_duplicate_transactions.assert_called_once_with("transaction_hash")789 patched_verify_signature.assert_called_once_with("signature", "from:to:25:1498923800", "from")790 self.assertEqual(patched_calculate_block_hash.call_count, 4)791 def test_get_transaction_history_whenAddressHasTransactions_returnHistory(self):792 transaction_one = {793 'from': 'from',794 'timestamp': 1498923800,795 'to': 'address',796 'amount': 1,797 'signature': 'signature_one',798 'hash': "transaction_hash_one"799 }800 transaction_two = {801 'from': 'from',802 'timestamp': 1498924800,803 'to': 'address',804 'amount': 3,805 'signature': 'signature_two',806 'hash': "transaction_hash_two"807 }808 transaction_three = {809 'from': 'from',810 'timestamp': 1498925800,811 'to': 'to',812 'amount': 5,813 'signature': 'signature_three',814 'hash': "transaction_hash_three"815 }816 transaction_four = {817 'from': 'from',818 'timestamp': 1498926800,819 'to': 'address',820 'amount': 7,821 'signature': 'signature_four',822 'hash': "transaction_hash_four"823 }824 transaction_five = {825 'from': 'address',826 'timestamp': 1498927800,827 'to': 'to',828 'amount': 11,829 'signature': 'signature_five',830 'hash': "transaction_hash_five"831 }832 transaction_six = {833 'from': 'from',834 'timestamp': 1498928800,835 'to': 'to',836 'amount': 13,837 'signature': 'signature_six',838 'hash': "transaction_hash_six"839 }840 block_one = Mock(Block)841 block_one.transactions = [transaction_one, transaction_two]842 block_two = Mock(Block)843 block_two.transactions = [transaction_three, transaction_four]844 block_three = Mock(Block)845 block_three.transactions = [transaction_five, transaction_six]846 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:847 subject = Blockchain()848 subject.blocks = [block_one, block_two, block_three]849 transaction_history = subject.get_transaction_history('address')850 self.assertEqual(len(transaction_history), 4)851 self.assertEqual(transaction_history, [transaction_one, transaction_two, transaction_four, transaction_five])852 def test_get_transaction_history_whenAddressHasNoTransactions_returnEmptyList(self):853 transaction_one = {854 'from': 'from',855 'timestamp': 1498923800,856 'to': 'to',857 'amount': 1,858 'signature': 'signature_one',859 'hash': "transaction_hash_one"860 }861 transaction_two = {862 'from': 'from',863 'timestamp': 1498924800,864 'to': 'to',865 'amount': 3,866 'signature': 'signature_two',867 'hash': "transaction_hash_two"868 }869 transaction_three = {870 'from': 'from',871 'timestamp': 1498925800,872 'to': 'to',873 'amount': 5,874 'signature': 'signature_three',875 'hash': "transaction_hash_three"876 }877 transaction_four = {878 'from': 'from',879 'timestamp': 1498926800,880 'to': 'to',881 'amount': 7,882 'signature': 'signature_four',883 'hash': "transaction_hash_four"884 }885 transaction_five = {886 'from': 'from',887 'timestamp': 1498927800,888 'to': 'to',889 'amount': 11,890 'signature': 'signature_five',891 'hash': "transaction_hash_five"892 }893 transaction_six = {894 'from': 'from',895 'timestamp': 1498928800,896 'to': 'to',897 'amount': 13,898 'signature': 'signature_six',899 'hash': "transaction_hash_six"900 }901 block_one = Mock(Block)902 block_one.transactions = [transaction_one, transaction_two]903 block_two = Mock(Block)904 block_two.transactions = [transaction_three, transaction_four]905 block_three = Mock(Block)906 block_three.transactions = [transaction_five, transaction_six]907 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:908 subject = Blockchain()909 subject.blocks = [block_one, block_two, block_three]910 transaction_history = subject.get_transaction_history('address')911 self.assertEqual(len(transaction_history), 0)912 def test_get_balance_whenAddressHasTransactions_returnBalance(self):913 transaction_one = {914 'from': 'from',915 'timestamp': 1498923800,916 'to': 'address',917 'amount': 1,918 'signature': 'signature_one',919 'hash': "transaction_hash_one"920 }921 transaction_two = {922 'from': 'from',923 'timestamp': 1498924800,924 'to': 'address',925 'amount': 3,926 'signature': 'signature_two',927 'hash': "transaction_hash_two"928 }929 transaction_three = {930 'from': 'from',931 'timestamp': 1498925800,932 'to': 'to',933 'amount': 5,934 'signature': 'signature_three',935 'hash': "transaction_hash_three"936 }937 transaction_four = {938 'from': 'from',939 'timestamp': 1498926800,940 'to': 'address',941 'amount': 7,942 'signature': 'signature_four',943 'hash': "transaction_hash_four"944 }945 transaction_five = {946 'from': 'address',947 'timestamp': 1498927800,948 'to': 'to',949 'amount': .11,950 'signature': 'signature_fave',951 'hash': "transaction_hash_five"952 }953 transaction_six = {954 'from': 'address',955 'timestamp': 1498928800,956 'to': 'to',957 'amount': .13,958 'signature': 'signature_six',959 'hash': "transaction_hash_six"960 }961 block_one = Mock(Block)962 block_one.transactions = [transaction_one, transaction_two]963 block_two = Mock(Block)964 block_two.transactions = [transaction_three, transaction_four]965 block_three = Mock(Block)966 block_three.transactions = [transaction_five, transaction_six]967 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:968 subject = Blockchain()969 subject.blocks = [block_one, block_two, block_three]970 balance = subject.get_balance('address')971 self.assertEqual(balance, 10.76)972 def test_get_balance_whenAddressHasNoTransactions_returnZeroBalance(self):973 transaction_one = {974 'from': 'from',975 'timestamp': 1498923800,976 'to': 'to',977 'amount': 1,978 'signature': 'signature_one',979 'hash': "transaction_hash_one"980 }981 transaction_two = {982 'from': 'from',983 'timestamp': 1498924800,984 'to': 'to',985 'amount': 3,986 'signature': 'signature_two',987 'hash': "transaction_hash_two"988 }989 transaction_three = {990 'from': 'from',991 'timestamp': 1498925800,992 'to': 'to',993 'amount': 5,994 'signature': 'signature_three',995 'hash': "transaction_hash_three"996 }997 block_one = Mock(Block)998 block_one.transactions = [transaction_one]999 block_two = Mock(Block)1000 block_two.transactions = [transaction_two]1001 block_three = Mock(Block)1002 block_three.transactions = [transaction_three]1003 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:1004 subject = Blockchain()1005 subject.blocks = [block_one, block_two, block_three]1006 balance = subject.get_balance('address')1007 self.assertEqual(balance, 0)1008 def test_find_duplicate_transactions_WhenHashExists_thenReturnBlockIndex(self):1009 transaction_one = {1010 'from': 'from',1011 'timestamp': 1498923800,1012 'to': 'to',1013 'amount': 1,1014 'signature': 'signature_one',1015 'hash': "transaction_hash_one"1016 }1017 transaction_two = {1018 'from': 'from',1019 'timestamp': 1498924800,1020 'to': 'to',1021 'amount': 3,1022 'signature': 'signature_two',1023 'hash': "transaction_hash_two"1024 }1025 transaction_three = {1026 'from': 'from',1027 'timestamp': 1498925800,1028 'to': 'to',1029 'amount': 5,1030 'signature': 'signature_three',1031 'hash': "transaction_hash_three"1032 }1033 transaction_four = {1034 'from': 'from',1035 'timestamp': 1498926800,1036 'to': 'address',1037 'amount': 7,1038 'signature': 'signature_four',1039 'hash': "transaction_hash_four"1040 }1041 block_one = Mock(Block)1042 block_one.transactions = [transaction_one]1043 block_one.index = 01044 block_two = Mock(Block)1045 block_two.transactions = [transaction_two]1046 block_two.index = 11047 block_three = Mock(Block)1048 block_three.transactions = [transaction_three, transaction_four]1049 block_three.index = 21050 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:1051 subject = Blockchain()1052 subject.blocks = [block_one, block_two, block_three]1053 resp = subject.find_duplicate_transactions("transaction_hash_four")1054 self.assertEqual(resp, block_three.index)1055 def test_find_duplicate_transactions_WhenHashNotFound_thenReturnFalse(self):1056 transaction_one = {1057 'from': 'from',1058 'timestamp': 1498923800,1059 'to': 'to',1060 'amount': 1,1061 'signature': 'signature_one',1062 'hash': "transaction_hash_one"1063 }1064 transaction_two = {1065 'from': 'from',1066 'timestamp': 1498924800,1067 'to': 'to',1068 'amount': 3,1069 'signature': 'signature_two',1070 'hash': "transaction_hash_two"1071 }1072 transaction_three = {1073 'from': 'from',1074 'timestamp': 1498925800,1075 'to': 'to',1076 'amount': 5,1077 'signature': 'signature_three',1078 'hash': "transaction_hash_three"1079 }1080 transaction_four = {1081 'from': 'from',1082 'timestamp': 1498926800,1083 'to': 'address',1084 'amount': 7,1085 'signature': 'signature_four',1086 'hash': "transaction_hash_four"1087 }1088 block_one = Mock(Block)1089 block_one.transactions = [transaction_one]1090 block_one.index = 01091 block_two = Mock(Block)1092 block_two.transactions = [transaction_two]1093 block_two.index = 11094 block_three = Mock(Block)1095 block_three.transactions = [transaction_three, transaction_four]1096 block_three.index = 21097 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:1098 subject = Blockchain()1099 subject.blocks = [block_one, block_two, block_three]1100 resp = subject.find_duplicate_transactions("transaction_hash_five")1101 self.assertFalse(resp)1102 def test_validate_chain_whenAllBlocksValid_thenReturnTrue(self):1103 mock_block = Mock(Block)1104 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \1105 patch.object(Blockchain, 'validate_block', return_value=True) as patched_validate_block:1106 subject = Blockchain()1107 subject.blocks = [mock_block, mock_block, mock_block]1108 resp = subject.validate_chain()1109 self.assertTrue(resp)1110 def test_validate_chain_whenInvalidBlockPresent_thenRaiseException(self):1111 mock_block = Mock(Block)1112 with patch.object(Blockchain, '__init__', return_value=None) as patched_init, \1113 patch.object(Blockchain, 'validate_block', side_effect=InvalidHash(2, "Invalid Hash")) as patched_validate_block:1114 subject = Blockchain()1115 subject.blocks = [mock_block, mock_block, mock_block]1116 with self.assertRaises(InvalidHash):1117 subject.validate_chain()1118 def test_get_reward_whenGivenIndex_thenReturnsProperReward(self):1119 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:1120 subject = Blockchain()1121 reward_one = subject.get_reward(0)1122 reward_two = subject.get_reward(999)1123 reward_three = subject.get_reward(1000)1124 reward_four = subject.get_reward(1999)1125 reward_five = subject.get_reward(2000)1126 reward_six = subject.get_reward(3000)1127 reward_seven = subject.get_reward(4000)1128 reward_eight = subject.get_reward(5000)1129 reward_nine = subject.get_reward(5999)1130 reward_ten = subject.get_reward(6000)1131 self.assertEqual(reward_one, 50)1132 self.assertEqual(reward_two, 50)1133 self.assertEqual(reward_three, 25)1134 self.assertEqual(reward_four, 25)1135 self.assertEqual(reward_five, 12)1136 self.assertEqual(reward_six, 6)1137 self.assertEqual(reward_seven, 3)1138 self.assertEqual(reward_eight, 1)1139 self.assertEqual(reward_nine, 1)1140 self.assertEqual(reward_ten, 0)1141 def test_get_size_whenBlocksExist_thenReturnsProperLength(self):1142 mock_block = Mock(Block)1143 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:1144 subject = Blockchain()1145 subject.blocks = [mock_block, mock_block, mock_block]1146 size = subject.get_size()1147 self.assertEqual(3, size)1148 def test_get_size_whenNoBlocksExist_thenReturnsZero(self):1149 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:1150 subject = Blockchain()1151 size = subject.get_size()1152 self.assertEqual(0, size)1153 def test_get_latest_block_whenBlocksExist_thenReturnLatestBlock(self):1154 mock_block = Mock(Block)1155 latest_block = Mock(Block)1156 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:1157 subject = Blockchain()1158 subject.blocks = [mock_block, mock_block, mock_block, latest_block]1159 block = subject.get_latest_block()1160 self.assertEqual(block, latest_block)1161 def test_get_latest_block_whenNoBlocksExist_thenReturnNone(self):1162 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:1163 subject = Blockchain()1164 block = subject.get_latest_block()1165 self.assertIsNone(block)1166 def test_get_block_by_index_whenBlockExists_thenReturnCorrectBlock(self):1167 mock_block_one = Mock(Block)1168 mock_block_two = Mock(Block)1169 mock_block_three = Mock(Block)1170 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:1171 subject = Blockchain()1172 subject.blocks = [mock_block_one, mock_block_two, mock_block_three]1173 block = subject.get_block_by_index(1)1174 self.assertEqual(block, mock_block_two)1175 def test_get_block_by_index_whenBlockDoesNotExist_thenReturnNone(self):1176 mock_block_one = Mock(Block)1177 mock_block_two = Mock(Block)1178 mock_block_three = Mock(Block)1179 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:1180 subject = Blockchain()1181 subject.blocks = [mock_block_one, mock_block_two, mock_block_three]1182 block = subject.get_block_by_index(3)1183 self.assertIsNone(block)1184 def test_get_blocks_range_whenBlocksExists_thenReturnCorrectBlocks(self):1185 mock_block_one = Mock(Block)1186 mock_block_two = Mock(Block)1187 mock_block_three = Mock(Block)1188 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:1189 subject = Blockchain()1190 subject.blocks = [mock_block_one, mock_block_two, mock_block_three]1191 blocks = subject.get_blocks_range(0, 2)1192 self.assertEqual(blocks, subject.blocks)1193 blocks = subject.get_blocks_range(0, 1)1194 self.assertEqual(blocks, [mock_block_one, mock_block_two])1195 def test_get_blocks_range_whenBlocksOutOfRange_thenReturnsListOfBlocksWithinRange(self):1196 mock_block_one = Mock(Block)1197 mock_block_two = Mock(Block)1198 mock_block_three = Mock(Block)1199 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:1200 subject = Blockchain()1201 subject.blocks = [mock_block_one, mock_block_two, mock_block_three]1202 blocks = subject.get_blocks_range(4, 6)1203 self.assertEqual(blocks, [])1204 blocks = subject.get_blocks_range(1, 5)1205 self.assertEqual(blocks, [mock_block_two, mock_block_three])1206 def test_pop_next_unconfirmed_transaction_whenTransactionsExist_thenPopsAndReturnsFirstTransaction(self):1207 transaction_one = {1208 'from': 'from',1209 'timestamp': 1498923800,1210 'to': 'to',1211 'amount': 1,1212 'signature': 'signature_one',1213 'hash': "transaction_hash_one"1214 }1215 transaction_two = {1216 'from': 'from',1217 'timestamp': 1498924800,1218 'to': 'to',1219 'amount': 3,1220 'signature': 'signature_two',1221 'hash': "transaction_hash_two"1222 }1223 transaction_three = {1224 'from': 'from',1225 'timestamp': 1498925800,1226 'to': 'to',1227 'amount': 5,1228 'signature': 'signature_three',1229 'hash': "transaction_hash_three"1230 }1231 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:1232 subject = Blockchain()1233 subject.unconfirmed_transactions_lock = threading.Lock()1234 subject.unconfirmed_transactions = [transaction_one, transaction_two, transaction_three]1235 transaction = subject.pop_next_unconfirmed_transaction()1236 self.assertEqual(transaction, transaction_one)1237 self.assertEqual(len(subject.unconfirmed_transactions), 2)1238 self.assertTrue(transaction_one not in subject.unconfirmed_transactions)1239 def test_pop_next_unconfirmed_transaction_whenNoTransactionsExist_thenReturnsNone(self):1240 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:1241 subject = Blockchain()1242 subject.unconfirmed_transactions_lock = threading.Lock()1243 transaction = subject.pop_next_unconfirmed_transaction()1244 self.assertIsNone(transaction)1245 def test_push_unconfirmed_transaction_thenPushesTransactionAndReturnsNone(self):1246 transaction_one = {1247 'from': 'from',1248 'timestamp': 1498923800,1249 'to': 'to',1250 'amount': 1,1251 'signature': 'signature_one',1252 'hash': "transaction_hash_one"1253 }1254 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:1255 subject = Blockchain()1256 subject.unconfirmed_transactions_lock = threading.Lock()1257 resp = subject.push_unconfirmed_transaction(transaction_one)1258 self.assertTrue(resp)1259 self.assertEqual(len(subject.unconfirmed_transactions), 1)1260 self.assertTrue(transaction_one in subject.unconfirmed_transactions)1261 def test_verify_signature_whenSignatureAndMessageAndPublicKeyMatch_thenReturnsTrue(self):1262 signature = '304502202d009c9b97385189d23600ae480435ea5b68786dbdba184c80e0fb6e58d8c5520221009c25f5cdf659f33ce04f683e14f355b3db5524a289feb9efa4c6879342a81648'1263 message = 'hello world'1264 public_key = '04496ee863ef587f55b911987c0b0e88b73e840440b834c50ff774677dde49468dafe07868452635e986c35b62244b4739a8db5e27750ff172a9e52ea7278e93c6'1265 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:1266 subject = Blockchain()1267 resp = subject.verify_signature(1268 signature,1269 message,1270 public_key1271 )1272 self.assertTrue(resp)1273 def test_verify_signature_whenSignatureAndMessageAndPublicKeyMisMatch_thenReturnsFalse(self):1274 signature = '304502202d009c9b97385189d23600ae480435ea5b68786dbdba184c80e0fb6e58d8c5520221009c25f5cdf659f33ce04f683e14f355b3db5524a289feb9efa4c6879342a81648'1275 message = 'invalid message'1276 public_key = '04496ee863ef587f55b911987c0b0e88b73e840440b834c50ff774677dde49468dafe07868452635e986c35b62244b4739a8db5e27750ff172a9e52ea7278e93c6'1277 with patch.object(Blockchain, '__init__', return_value=None) as patched_init:1278 subject = Blockchain()1279 resp = subject.verify_signature(1280 signature,1281 message,1282 public_key1283 )...

Full Screen

Full Screen

test_node.py

Source:test_node.py Github

copy

Full Screen

1import unittest2from mock import patch, Mock, MagicMock, call3from crankycoin.node import *4class TestNode(unittest.TestCase):5 def test_request_nodes_whenValidNode_thenRequestsNodes(self):6 mock_response = Mock()7 mock_response.status_code = 2008 mock_response.json.return_value = {"full_nodes": ["127.0.0.2", "127.0.0.1", "127.0.0.3"]}9 with patch.object(FullNode, '__init__', return_value=None) as patched_init, \10 patch("crankycoin.requests.get", return_value=mock_response) as patched_requests:11 node = FullNode("127.0.0.1", "reward_address")12 nodes = node.request_nodes("127.0.0.2", "30013")13 self.assertIsNotNone(nodes)14 self.assertEqual(nodes, {"full_nodes": ["127.0.0.2", "127.0.0.1", "127.0.0.3"]})15 patched_requests.assert_called_once_with('http://127.0.0.2:30013/nodes')16 def test_request_nodes_whenNon200Status_thenReturnsNone(self):17 mock_response = Mock()18 mock_response.status_code = 40419 with patch.object(FullNode, '__init__', return_value=None) as patched_init, \20 patch("crankycoin.requests.get", return_value=mock_response) as patched_requests:21 node = FullNode("127.0.0.1", "reward_address")22 nodes = node.request_nodes("127.0.0.2", "30013")23 self.assertIsNone(nodes)24 patched_requests.assert_called_once_with('http://127.0.0.2:30013/nodes')25 def test_request_nodes_whenRequestError_thenReturnsNone(self):26 with patch.object(FullNode, '__init__', return_value=None) as patched_init, \27 patch("crankycoin.requests.get", side_effect=requests.exceptions.RequestException()) as patched_requests:28 node = FullNode("127.0.0.1", "reward_address")29 nodes = node.request_nodes("127.0.0.2", "30013")30 self.assertIsNone(nodes)31 patched_requests.assert_called_once_with('http://127.0.0.2:30013/nodes')32 def test_request_nodes_from_all_SetsFullNodesPropertyOnClass(self):33 nodes_one = {"full_nodes": ["127.0.0.2", "127.0.0.1", "127.0.0.4"]}34 nodes_two = {"full_nodes": ["127.0.0.2", "127.0.0.3", "127.0.0.5"]}35 nodes_three = {"full_nodes": ["127.0.0.1", "127.0.0.3", "127.0.0.4"]}36 with patch.object(FullNode, '__init__', return_value=None) as patched_init, \37 patch.object(FullNode, 'request_nodes', side_effect=[nodes_one, nodes_two, nodes_three]) as patched_request_nodes:38 node = FullNode("127.0.0.1", "reward_address")39 node.full_nodes = {"127.0.0.1", "127.0.1.1", "127.0.1.2"}40 node.request_nodes_from_all()41 self.assertEqual(node.full_nodes, {"127.0.0.2", "127.0.0.1", "127.0.0.3", "127.0.0.4", "127.0.0.5", "127.0.1.1", "127.0.1.2"})42 def test_broadcast_transaction_thenBroadcastsToAllNodes(self):43 transaction = {}44 with patch.object(FullNode, '__init__', return_value=None) as patched_init, \45 patch.object(FullNode, 'request_nodes_from_all') as patched_request_nodes_from_all, \46 patch("crankycoin.requests.post") as patched_requests:47 node = FullNode("127.0.0.1", "reward_address")48 node.full_nodes = {"127.0.0.1", "127.0.0.2", "127.0.0.3"}49 node.broadcast_transaction(transaction)50 patched_request_nodes_from_all.assert_called_once()51 patched_requests.assert_has_calls([52 call("http://127.0.0.1:30013/transactions", json={'transaction': {}}),53 call("http://127.0.0.2:30013/transactions", json={'transaction': {}}),54 call("http://127.0.0.3:30013/transactions", json={'transaction': {}})55 ], True)56 def test_broadcast_transaction_whenRequestException_thenFailsGracefully(self):57 transaction = {}58 with patch.object(FullNode, '__init__', return_value=None) as patched_init, \59 patch.object(FullNode, 'request_nodes_from_all') as patched_request_nodes_from_all, \60 patch("crankycoin.requests.post", side_effect=requests.exceptions.RequestException()) as patched_requests:61 node = FullNode("127.0.0.1", "reward_address")62 node.full_nodes = {"127.0.0.1", "127.0.0.2", "127.0.0.3"}63 node.broadcast_transaction(transaction)64 patched_request_nodes_from_all.assert_called_once()65 patched_requests.assert_has_calls([66 call("http://127.0.0.1:30013/transactions", json={'transaction': {}}),67 call("http://127.0.0.2:30013/transactions", json={'transaction': {}}),68 call("http://127.0.0.3:30013/transactions", json={'transaction': {}})69 ], True)70 def test_request_block_whenIndexIsLatest_thenRequestsLatestBlockFromNode(self):71 mock_response = Mock()72 mock_response.status_code = 20073 mock_response.json.return_value = '{"nonce": 12345, "index": 35, "transactions": [], "timestamp": 1234567890, "current_hash": "current_hash", "previous_hash": "previous_hash"}'74 with patch.object(FullNode, '__init__', return_value=None) as patched_init, \75 patch("crankycoin.requests.get", return_value=mock_response) as patched_requests:76 node = FullNode("127.0.0.1", "reward_address")77 block = node.request_block("127.0.0.2", "30013", "latest")78 self.assertIsNotNone(block)79 self.assertEqual(block.index, 35)80 self.assertEqual(block.transactions, [])81 self.assertEqual(block.previous_hash, "previous_hash")82 self.assertEqual(block.current_hash, "current_hash")83 self.assertEqual(block.timestamp, 1234567890)84 self.assertEqual(block.nonce, 12345)85 patched_requests.assert_called_once_with('http://127.0.0.2:30013/block/latest')86 def test_request_block_whenIndexIsNumeric_thenRequestsCorrectBlockFromNode(self):87 mock_response = Mock()88 mock_response.status_code = 20089 mock_response.json.return_value = '{"nonce": 12345, "index": 29, "transactions": [], "timestamp": 1234567890, "current_hash": "current_hash", "previous_hash": "previous_hash"}'90 with patch.object(FullNode, '__init__', return_value=None) as patched_init, \91 patch("crankycoin.requests.get", return_value=mock_response) as patched_requests:92 node = FullNode("127.0.0.1", "reward_address")93 block = node.request_block("127.0.0.2", "30013", 29)94 self.assertIsNotNone(block)95 self.assertEqual(block.index, 29)96 self.assertEqual(block.transactions, [])97 self.assertEqual(block.previous_hash, "previous_hash")98 self.assertEqual(block.current_hash, "current_hash")99 self.assertEqual(block.timestamp, 1234567890)100 self.assertEqual(block.nonce, 12345)101 patched_requests.assert_called_once_with('http://127.0.0.2:30013/block/29')102 def test_request_block_whenRequestException_thenReturnsNone(self):103 with patch.object(FullNode, '__init__', return_value=None) as patched_init, \104 patch("crankycoin.requests.get", side_effect=requests.exceptions.RequestException()) as patched_requests:105 node = FullNode("127.0.0.1", "reward_address")106 block = node.request_block("127.0.0.2", "30013", "latest")107 self.assertIsNone(block)108 patched_requests.assert_called_once_with('http://127.0.0.2:30013/block/latest')109 def test_request_block_from_all_whenIndexIsLatest_thenReturnsLatestBlockFromAll(self):110 block = Mock(Block)111 with patch.object(FullNode, '__init__', return_value=None) as patched_init, \112 patch.object(FullNode, 'request_block', side_effect=[block, block, block]) as patched_request_block:113 node = FullNode("127.0.0.1", "reward_address")114 node.full_nodes = {"127.0.0.1", "127.0.0.2", "127.0.0.3"}115 blocks = node.request_block_from_all("latest")116 self.assertEqual(blocks, [block, block, block])117 patched_request_block.assert_has_calls([118 call("127.0.0.1", "30013", "latest"),119 call("127.0.0.2", "30013", "latest"),120 call("127.0.0.3", "30013", "latest")121 ], True)122 def test_request_blocks_range(self):123 pass124 def test_request_blockchain(self):125 pass126 def test_mine(self):127 pass128 def test_broadcast_block(self):129 pass130 def test_add_node(self):131 pass132 def test_broadcast_node(self):133 pass134 def test_load_blockchain(self):135 pass136 def test_synchronize(self):137 pass138 def test_generate_ecc_instance(self):139 pass140 def test_get_pubkey(self):141 pass142 def test_get_privkey(self):143 pass144 def test_sign(self):145 pass146 def test_verify(self):147 pass148 def test_get_balance(self):149 pass150 def test_create_transaction(self):151 pass152 def test_calculate_transaction_hash(self):153 pass154 def test_generate_signable_transaction(self):...

Full Screen

Full Screen

test_backends.py

Source:test_backends.py Github

copy

Full Screen

1"""Mostly copied from django-warrant's tests.py."""2from django.conf import settings3from django.test import override_settings4from django.test import TestCase5from lizard_auth_server import backends6from unittest import mock7def get_user(cls, *args, **kwargs):8 user = {9 "user_status": kwargs.pop("user_status", "CONFIRMED"),10 "username": kwargs.pop("access_token", "testuser"),11 "email": kwargs.pop("email", "test@email.com"),12 "given_name": kwargs.pop("given_name", "FirstName"),13 "family_name": kwargs.pop("family_name", "LastName"),14 "UserAttributes": [15 {"Name": "sub", "Value": "c7d890f6-eb38-498d-8f85-7a6c4af33d7a"},16 {"Name": "email_verified", "Value": "true"},17 {"Name": "gender", "Value": "male"},18 {"Name": "name", "Value": "FirstName LastName"},19 {"Name": "preferred_username", "Value": "testuser"},20 {"Name": "given_name", "Value": "FirstName"},21 {"Name": "family_name", "Value": "LastName"},22 {"Name": "email", "Value": "test@email.com"},23 {"Name": "custom:api_key", "Value": "abcdefg"},24 {"Name": "custom:api_key_id", "Value": "ab-1234"},25 ],26 }27 user_metadata = {28 "username": user.get("Username"),29 "id_token": cls.id_token,30 "access_token": cls.access_token,31 "refresh_token": cls.refresh_token,32 "api_key": user.get("custom:api_key", None),33 "api_key_id": user.get("custom:api_key_id", None),34 }35 return cls.get_user_obj(36 username=cls.username,37 attribute_list=user.get("UserAttributes"),38 metadata=user_metadata,39 )40@override_settings(41 AUTHENTICATION_BACKENDS=[42 "lizard_auth_server.backends.CognitoBackend",43 "django.contrib.auth.backends.ModelBackend",44 ],45 AWS_ACCESS_KEY_ID="something"46)47@mock.patch("lizard_auth_server.backends.CognitoUser.__init__")48class TestCognitoUser(TestCase):49 @mock.patch("lizard_auth_server.signal_handlers.CognitoUser")50 def test_smoke(self, CognitoUser_m, patched_init):51 """Quick test52 The code has been mostly been copied from django-warrant and has been53 tested there, so I'm not going to re-build the entire test54 infrastructure here, especially as calls to amazon are being made.55 """56 patched_init.return_value = None57 # Example user is mostly copied from django-warrant's tests.58 example_user = {59 "user_status": "CONFIRMED",60 "username": "testuser",61 "email": "test@email.com",62 "given_name": "FirstName",63 "family_name": "LastName",64 "UserAttributes": [65 {"Name": "sub", "Value": "c7d890f6-eb38-498d-8f85-7a6c4af33d7a"},66 {"Name": "email_verified", "Value": "true"},67 {"Name": "gender", "Value": "male"},68 {"Name": "name", "Value": "FirstName LastName"},69 {"Name": "preferred_username", "Value": "testuser"},70 {"Name": "given_name", "Value": "FirstName"},71 {"Name": "family_name", "Value": "LastName"},72 {"Name": "email", "Value": "test@email.com"},73 {"Name": "custom:api_key", "Value": "abcdefg"},74 {"Name": "custom:api_key_id", "Value": "ab-1234"},75 ],76 }77 attribute_list = example_user["UserAttributes"]78 cognito_user = backends.CognitoUser()79 django_user1 = cognito_user.get_user_obj(80 username="test", attribute_list=attribute_list81 )82 self.assertEqual(django_user1.email, "test@email.com")83 self.assertTrue(django_user1.user_profile.migrated_at)84 self.assertFalse(85 CognitoUser_m.from_username.return_value.admin_user_exists.called86 )87 # Doing it a second time reuses the exisiting user.88 django_user2 = cognito_user.get_user_obj(89 username="test", attribute_list=attribute_list90 )91 self.assertEqual(django_user2.id, django_user1.id)92 def test_admin_set_password(self, patched_init):93 patched_init.return_value = None94 cognito_user = backends.CognitoUser()95 cognito_user.client = mock.Mock() # the boto3 client96 cognito_user.username = "testuser"97 cognito_user.user_pool_id = "foo"98 cognito_user.admin_set_user_password("bar")99 # AdminSetUserPassword should be called as documented100 args, kwargs = cognito_user.client.admin_set_user_password.call_args101 expected = {102 "UserPoolId": "foo",103 "Username": "testuser",104 "Password": "bar",105 "Permanent": True,106 }107 self.assertDictEqual(expected, kwargs)108 def test_admin_user_exists(self, patched_init):109 patched_init.return_value = None110 cognito_user = backends.CognitoUser()111 cognito_user.client = mock.Mock() # the boto3 client112 cognito_user.username = "testuser"113 cognito_user.user_pool_id = "foo"114 cognito_user.admin_user_exists()115 # AdminGetUser should be called as documented116 args, kwargs = cognito_user.client.admin_get_user.call_args117 expected = {118 "UserPoolId": "foo",119 "Username": "testuser",120 }...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run responses automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful