def test_previously_migrated_blobs_do_not_migrate(self):
    blob_info = _write_blob('1')

    # drive a blob through the migration
    self.call_migrate_blob(blob_info)
    self.assertNumberOfRealBlobs(1)
    self.assertNumberOfGcsSimulationBlobs(1)

    # drive it through a second time
    inline_patcher = mock.patch('app.migrator.migrate_single_blob_inline')
    pipeline_patcher = mock.patch(
        'app.migrator.MigrateSingleBlobPipeline.start')
    inline_mock = inline_patcher.start()
    pipeline_mock = pipeline_patcher.start()
    try:
      self.call_migrate_blob(blob_info)
    finally:
      inline_patcher.stop()
      pipeline_mock.stop()

    # ensure that neither of the copying routines were invoked
    self.assertEquals(0, inline_mock.call_count)
    self.assertEquals(0, pipeline_mock.call_count)

    # ensure that no new GCS simulations have appeared
    self.assertNumberOfRealBlobs(1)
    self.assertNumberOfGcsSimulationBlobs(1)
    async def test_transaction_found(self):
        """
        A transaction is found with the inputs. A transaction object is
        returned
        """
        with mock.patch(
                'iota.commands.core.find_transactions.FindTransactionsCommand.'
                '_execute',
                mock.Mock(return_value=async_return(
                    {'hashes': [
                        self.transaction_hash,
                    ]})),
        ):
            with mock.patch(
                    'iota.commands.core.get_trytes.GetTrytesCommand._execute',
                    mock.Mock(
                        return_value=async_return({'trytes': [
                            self.trytes,
                        ]})),
            ):
                response = await self.command(addresses=[self.address])

        self.assertEqual(len(response['transactions']), 1)
        transaction = response['transactions'][0]
        self.assertIsInstance(transaction, Transaction)
        self.assertEqual(transaction.address, self.address)
예제 #3
0
    async def test_non_tail(self):
        """
        Called with a non-tail transaction.
        """
        # For mocking GetTrytesCommand call
        self.adapter.seed_response(
            'getTrytes',
            {
                # Tx with ID=1
                'trytes': [self.three_tx_bundle[1].as_tryte_string()]
            })

        # For mocking FindTransactionObjectsCommand call
        self.adapter.seed_response(
            'findTransactions',
            {'hashes': [tx.hash for tx in self.three_tx_bundle]})

        self.adapter.seed_response(
            'getTrytes',
            {'trytes': [tx.as_tryte_string() for tx in self.three_tx_bundle]})

        with mock.patch(
                'iota.commands.extended.get_latest_inclusion.GetLatestInclusionCommand.__call__',
                MagicMock(return_value=async_return({
                    'states': {
                        self.three_tx_bundle.tail_transaction.hash: True
                    }
                }))) as mocked_glis:
            with mock.patch(
                    'iota.commands.extended.get_bundles.GetBundlesCommand.__call__',
                    MagicMock(return_value=async_return(
                        {'bundles': [
                            self.three_tx_bundle,
                        ]}))) as mocked_get_bundles:
                response = await get_bundles_from_transaction_hashes(
                    adapter=self.adapter,
                    transaction_hashes=[self.three_tx_bundle[1].hash],
                    inclusion_states=True,
                )

                self.assertListEqual(
                    response,
                    [
                        self.three_tx_bundle,
                    ],
                )

                self.assertTrue(response[0].is_confirmed)

                mocked_glis.assert_called_once_with(
                    hashes=[self.three_tx_bundle.tail_transaction.hash])

                mocked_get_bundles.assert_called_once_with(
                    transactions=[self.three_tx_bundle.tail_transaction.hash])
예제 #4
0
    def test_happy_path(self):
        """
    Loading account data for an account.
    """

        # noinspection PyUnusedLocal
        def mock_iter_used_addresses(adapter, seed, start):
            """
      Mocks the ``iter_used_addresses`` function, so that we can
      simulate its functionality without actually connecting to the
      Tangle.

      References:
        - :py:func:`iota.commands.extended.utils.iter_used_addresses`
      """
            yield self.addy1, [self.hash1]
            yield self.addy2, [self.hash2]

        mock_get_balances = mock.Mock(return_value={'balances': [42, 0]})

        # Not particularly realistic, but good enough to prove that the
        # mocked function was invoked correctly.
        bundles = [Bundle(), Bundle()]
        mock_get_bundles_from_transaction_hashes = mock.Mock(
            return_value=bundles)

        with mock.patch(
                'iota.commands.extended.get_account_data.iter_used_addresses',
                mock_iter_used_addresses,
        ):
            with mock.patch(
                    'iota.commands.extended.get_account_data.get_bundles_from_transaction_hashes',
                    mock_get_bundles_from_transaction_hashes,
            ):
                with mock.patch(
                        'iota.commands.core.get_balances.GetBalancesCommand._execute',
                        mock_get_balances,
                ):
                    response = self.command(seed=Seed.random())

        self.assertDictEqual(
            response,
            {
                'addresses': [self.addy1, self.addy2],
                'balance': 42,
                'bundles': bundles,
            },
        )
예제 #5
0
    async def test_start_parameter_is_given(self):
        """
        The correct address is returned if a start parameter is given.
        """
        # Address 1
        self.adapter.seed_response('findTransactions', {
            'hashes': ['T' * 81],
        })

        # Address 2
        self.seed_unused_address()

        with mock.patch(
                'iota.crypto.addresses.AddressGenerator.create_iterator',
                self.mock_address_generator,
        ):
            self.assertEqual([self.address1], await
                             self.get_all_used_addresses(start=1))

        self.assertListEqual(self.adapter.requests, [
            {
                'command': 'findTransactions',
                'addresses': [self.address1],
            },
            {
                'command': 'findTransactions',
                'addresses': [self.address2],
            },
            {
                'command': 'wereAddressesSpentFrom',
                'addresses': [self.address2],
            },
        ])
예제 #6
0
    def test_happy_path(self):
        """
    Successfully promoting a bundle.
    """

        self.adapter.seed_response('checkConsistency', {
            'state': True,
        })

        result_bundle = Bundle.from_tryte_strings([
            TransactionTrytes(self.trytes1),
            TransactionTrytes(self.trytes2),
        ])
        mock_send_transfer = mock.Mock(return_value={
            'bundle': result_bundle,
        })

        with mock.patch(
                'iota.commands.extended.send_transfer.SendTransferCommand._execute',
                mock_send_transfer,
        ):

            response = self.command(
                transaction=self.hash1,
                depth=3,
                minWeightMagnitude=16,
            )

        self.assertDictEqual(response, {
            'bundle': result_bundle,
        })
예제 #7
0
    def test_no_stop_threshold_not_met(self):
        """
    No ``stop`` provided, balance does not meet ``threshold``.
    """
        self.adapter.seed_response('getBalances', {
            'balances': [42, 29, 0],
        })

        # To keep the unit test nice and speedy, we will mock the address
        # generator.  We already have plenty of unit tests for that
        # functionality, so we can get away with mocking it here.
        # noinspection PyUnusedLocal
        def mock_address_generator(ag, start, step=1):
            for addy in [self.addy0, self.addy1, self.addy2][start::step]:
                yield addy

        # When ``stop`` is None, the command uses a generator internally.
        with mock.patch(
                'iota.crypto.addresses.AddressGenerator.create_iterator',
                mock_address_generator,
        ):
            with self.assertRaises(BadApiResponse):
                self.command(
                    seed=Seed.random(),
                    threshold=72,
                )
예제 #8
0
  def test_no_stop_threshold_not_met(self):
    """
    No ``stop`` provided, balance does not meet ``threshold``.
    """
    self.adapter.seed_response('getBalances', {
      'balances': [42, 29, 0],
    })

    # To keep the unit test nice and speedy, we will mock the address
    # generator.  We already have plenty of unit tests for that
    # functionality, so we can get away with mocking it here.
    # noinspection PyUnusedLocal
    def mock_address_generator(ag, start, step=1):
      for addy in [self.addy0, self.addy1, self.addy2][start::step]:
        yield addy

    # When ``stop`` is None, the command uses a generator internally.
    with mock.patch(
        'iota.crypto.addresses.AddressGenerator.create_iterator',
        mock_address_generator,
    ):
      with self.assertRaises(BadApiResponse):
        self.command(
          seed      = Seed.random(),
          threshold = 72,
        )
예제 #9
0
    def test_stop_threshold_zero(self):
        """
    ``stop`` provided, ``threshold`` is 0.
    """
        # Note that the first address has a zero balance.
        self.adapter.seed_response('getBalances', {
            'balances': [0, 1],
        })

        # To keep the unit test nice and speedy, we will mock the address
        # generator.  We already have plenty of unit tests for that
        # functionality, so we can get away with mocking it here.
        mock_address_generator = mock.Mock(
            return_value=[self.addy0, self.addy1])

        with mock.patch(
                'iota.crypto.addresses.AddressGenerator.get_addresses',
                mock_address_generator,
        ):
            response = self.command(
                seed=Seed.random(),
                stop=2,
                threshold=0,
            )

        self.assertEqual(response['totalBalance'], 1)
        self.assertEqual(len(response['inputs']), 1)

        # Address 0 was skipped because it has a zero balance.
        input0 = response['inputs'][0]
        self.assertIsInstance(input0, Address)

        self.assertEqual(input0, self.addy1)
        self.assertEqual(input0.balance, 1)
        self.assertEqual(input0.key_index, 1)
예제 #10
0
    def test_generate_multiple_digests(self):
        """
    Generating multiple digests.
    """
        seed = Seed.random()

        mock_get_private_keys = \
            mock.Mock(return_value={'keys': [self.key1, self.key2]})

        with mock.patch(
                'iota.multisig.commands.get_private_keys.GetPrivateKeysCommand._execute',
                mock_get_private_keys
        ):
            # noinspection PyUnresolvedReferences
            with mock.patch.object(self.key1, 'get_digest') as mock_get_digest_1:  # type: mock.MagicMock
                mock_get_digest_1.return_value = self.digest1

                # noinspection PyUnresolvedReferences
                with mock.patch.object(self.key2, 'get_digest') as mock_get_digest_2:  # type: mock.MagicMock
                    mock_get_digest_2.return_value = self.digest2

                    result = self.command(seed=seed, index=0, count=2, securityLevel=1)

        self.assertDictEqual(result, {'digests': [self.digest1, self.digest2]})

        mock_get_private_keys.assert_called_once_with({
            'count': 2,
            'index': 0,
            'securityLevel': 1,
            'seed': seed,
        })
예제 #11
0
    def test_stdin_success(self):
        with self._capture_output_fixture() as stdout:
            with mock.patch("sys.stdin", mock.Mock(
                            read=mock.Mock(return_value="hello world ${x}"))):
                cmdline(["--var", "x=5", "-"])

        eq_(stdout.write.mock_calls[0][1][0], "hello world 5")
예제 #12
0
  def test_generate_multiple_digests(self):
    """
    Generating multiple digests.
    """
    seed = Seed.random()

    mock_get_private_keys =\
      mock.Mock(return_value={'keys': [self.key1, self.key2]})

    with mock.patch(
        'iota.multisig.commands.get_private_keys.GetPrivateKeysCommand._execute',
        mock_get_private_keys
    ):
      # noinspection PyUnresolvedReferences
      with mock.patch.object(self.key1, 'get_digest') as mock_get_digest_1: # type: mock.MagicMock
        mock_get_digest_1.return_value = self.digest1

        # noinspection PyUnresolvedReferences
        with mock.patch.object(self.key2, 'get_digest') as mock_get_digest_2: # type: mock.MagicMock
          mock_get_digest_2.return_value = self.digest2

          result = self.command(seed=seed, index=0, count=2, securityLevel=1)

    self.assertDictEqual(result, {'digests': [self.digest1, self.digest2]})

    mock_get_private_keys.assert_called_once_with({
      'count':          2,
      'index':          0,
      'securityLevel':  1,
      'seed':           seed,
    })
예제 #13
0
    def test_no_transactions(self):
        """
    There are no transactions for the specified seed.
    """

        # To speed up the test, we will mock the address generator.
        # :py:class:`iota.crypto.addresses.AddressGenerator` already has
        # its own test case, so this does not impact the stability of the
        # codebase.
        # noinspection PyUnusedLocal
        def create_generator(ag, start, step=1):
            for addy in [self.addy1][start::step]:
                yield addy

        self.adapter.seed_response(
            'findTransactions',
            {
                'duration': 1,
                'hashes': [],
            },
        )

        with mock.patch(
                'iota.crypto.addresses.AddressGenerator.create_iterator',
                create_generator,
        ):
            response = self.command(seed=Seed.random())

        self.assertDictEqual(response, {'bundles': []})
예제 #14
0
    async def test_first_address_is_not_used(self):
        """
        The very first address is not used. No address is returned.
        """
        # Address 0
        self.seed_unused_address()

        with mock.patch(
                'iota.crypto.addresses.AddressGenerator.create_iterator',
                self.mock_address_generator,
        ):
            self.assertEqual([], await self.get_all_used_addresses())

        self.assertListEqual(
            self.adapter.requests,
            [
                {
                    'command': 'findTransactions',
                    'addresses': [self.address0],
                },
                {
                    'command': 'wereAddressesSpentFrom',
                    'addresses': [self.address0],
                },
            ]
        )
예제 #15
0
    async def test_transactions_are_considered_used(self):
        """
        An address with a transaction is considered used.
        """
        # Address 0
        self.adapter.seed_response('findTransactions', {
            'hashes': ['T' * 81],
        })

        # Address 1
        self.seed_unused_address()

        with mock.patch(
                'iota.crypto.addresses.AddressGenerator.create_iterator',
                self.mock_address_generator,
        ):
            self.assertEqual([self.address0], await
                             self.get_all_used_addresses())

        self.assertListEqual(self.adapter.requests, [
            {
                'command': 'findTransactions',
                'addresses': [self.address0],
            },
            {
                'command': 'findTransactions',
                'addresses': [self.address1],
            },
            {
                'command': 'wereAddressesSpentFrom',
                'addresses': [self.address1],
            },
        ])
예제 #16
0
  def test_no_transactions(self):
    """
    There are no transactions for the specified seed.
    """
    # To speed up the test, we will mock the address generator.
    # :py:class:`iota.crypto.addresses.AddressGenerator` already has
    # its own test case, so this does not impact the stability of the
    # codebase.
    # noinspection PyUnusedLocal
    def create_generator(ag, start, step=1):
      for addy in [self.addy1][start::step]:
        yield addy

    self.adapter.seed_response(
      'findTransactions',

      {
        'duration': 1,
        'hashes':   [],
      },
    )

    with mock.patch(
        'iota.crypto.addresses.AddressGenerator.create_iterator',
        create_generator,
    ):
      response = self.command(seed=Seed.random())

    self.assertDictEqual(response, {'bundles': []})
예제 #17
0
    async def test_generate_single_digest(self):
        """
    Generating a single digest.
    """
        seed = Seed.random()

        mock_get_private_keys = mock.Mock(
            return_value=async_return({'keys': [self.key1]}))

        with mock.patch(
                'iota.multisig.commands.get_private_keys.GetPrivateKeysCommand._execute',
                mock_get_private_keys):
            with mock.patch.object(
                    self.key1,
                    'get_digest') as mock_get_digest_1:  # type: mock.MagicMock
                mock_get_digest_1.return_value = self.digest1

                result = await self.command(seed=seed,
                                            index=0,
                                            count=1,
                                            securityLevel=1)

        self.assertDictEqual(result, {'digests': [self.digest1]})

        mock_get_private_keys.assert_called_once_with({
            'count': 1,
            'index': 0,
            'securityLevel': 1,
            'seed': seed,
        })
예제 #18
0
  def test_stop_threshold_zero(self):
    """
    ``stop`` provided, ``threshold`` is 0.
    """
    # Note that the first address has a zero balance.
    self.adapter.seed_response('getBalances', {
      'balances': [0, 1],
    })

    # To keep the unit test nice and speedy, we will mock the address
    # generator.  We already have plenty of unit tests for that
    # functionality, so we can get away with mocking it here.
    mock_address_generator = mock.Mock(return_value=[self.addy0, self.addy1])

    with mock.patch(
        'iota.crypto.addresses.AddressGenerator.get_addresses',
        mock_address_generator,
    ):
      response = self.command(
        seed      = Seed.random(),
        stop      = 2,
        threshold = 0,
      )

    self.assertEqual(response['totalBalance'], 1)
    self.assertEqual(len(response['inputs']), 1)

    # Address 0 was skipped because it has a zero balance.
    input0 = response['inputs'][0]
    self.assertIsInstance(input0, Address)

    self.assertEqual(input0, self.addy1)
    self.assertEqual(input0.balance, 1)
    self.assertEqual(input0.key_index, 1)
예제 #19
0
  def test_happy_path(self):
    """
    Loading account data for an account.
    """
    # noinspection PyUnusedLocal
    def mock_iter_used_addresses(adapter, seed, start):
      """
      Mocks the ``iter_used_addresses`` function, so that we can
      simulate its functionality without actually connecting to the
      Tangle.

      References:
        - :py:func:`iota.commands.extended.utils.iter_used_addresses`
      """
      yield self.addy1, [self.hash1]
      yield self.addy2, [self.hash2]

    mock_get_balances = mock.Mock(return_value={'balances': [42, 0]})

    # Not particularly realistic, but good enough to prove that the
    # mocked function was invoked correctly.
    bundles = [Bundle(), Bundle()]
    mock_get_bundles_from_transaction_hashes = mock.Mock(return_value=bundles)

    with mock.patch(
        'iota.commands.extended.get_account_data.iter_used_addresses',
        mock_iter_used_addresses,
    ):
      with mock.patch(
        'iota.commands.extended.get_account_data.get_bundles_from_transaction_hashes',
        mock_get_bundles_from_transaction_hashes,
      ):
        with mock.patch(
          'iota.commands.core.get_balances.GetBalancesCommand._execute',
          mock_get_balances,
        ):
          response = self.command(seed=Seed.random())

    self.assertDictEqual(
      response,

      {
        'addresses':  [self.addy1, self.addy2],
        'balance':    42,
        'bundles':    bundles,
      },
    )
예제 #20
0
    def test_start(self):
        """
    Using ``start`` to offset the key range.
    """

        # ``getInputs`` uses ``findTransactions`` and
        # ``wereAddressesSpentFrom`` to identify unused addresses.
        # noinspection SpellCheckingInspection
        self.adapter.seed_response(
            'findTransactions', {
                'hashes': [
                    TransactionHash(
                        b'TESTVALUE9DONTUSEINPRODUCTION99999YFXGOD'
                        b'GISBJAX9PDJIRDMDV9DCRDCAEG9FN9KECCBDDFZ9H'),
                ],
            })

        self.adapter.seed_response('findTransactions', {
            'hashes': [],
        })

        self.adapter.seed_response('wereAddressesSpentFrom', {
            'states': [False],
        })

        self.adapter.seed_response('getBalances', {
            'balances': [86],
        })

        # To keep the unit test nice and speedy, we will mock the address
        # generator.  We already have plenty of unit tests for that
        # functionality, so we can get away with mocking it here.
        # noinspection PyUnusedLocal
        def mock_address_generator(ag, start, step=1):
            # If ``start`` has the wrong value, return garbage to make the
            # test asplode.
            for addy in [None, self.addy1, self.addy2][start::step]:
                yield addy

        # When ``stop`` is None, the command uses a generator internally.
        with mock.patch(
                'iota.crypto.addresses.AddressGenerator.create_iterator',
                mock_address_generator,
        ):
            response = self.command(
                seed=Seed.random(),
                start=1,
            )

        self.assertEqual(response['totalBalance'], 86)
        self.assertEqual(len(response['inputs']), 1)

        input0 = response['inputs'][0]
        self.assertIsInstance(input0, Address)

        self.assertEqual(input0, self.addy1)
        self.assertEqual(input0.balance, 86)
        self.assertEqual(input0.key_index, 1)
예제 #21
0
    async def test_multiple_addresses_return(self):
        """
        A larger test that combines multiple cases and more than one address
        should be returned.
        Address 0: Was spent from
        Address 1: Has a transaction
        Address 2: Is not used. Should not be returned
        """

        # Address 0
        self.adapter.seed_response('findTransactions', {
            'hashes': [],
        })
        self.adapter.seed_response('wereAddressesSpentFrom', {
            'states': [True],
        })

        # Address 1
        self.adapter.seed_response('findTransactions', {
            'hashes': ['T' * 81],
        })

        # Address 2
        self.seed_unused_address()

        with mock.patch(
                'iota.crypto.addresses.AddressGenerator.create_iterator',
                self.mock_address_generator,
        ):
            self.assertEqual([self.address0, self.address1],
                             await self.get_all_used_addresses())

        self.assertListEqual(
            self.adapter.requests,
            [
                {
                    'command': 'findTransactions',
                    'addresses': [self.address0],
                },
                {
                    'command': 'wereAddressesSpentFrom',
                    'addresses': [self.address0],
                },
                {
                    'command': 'findTransactions',
                    'addresses': [self.address1],
                },
                {
                    'command': 'findTransactions',
                    'addresses': [self.address2],
                },
                {
                    'command': 'wereAddressesSpentFrom',
                    'addresses': [self.address2],
                },
            ]
        )
예제 #22
0
    def test_stdin_success(self):
        with self._capture_output_fixture() as stdout:
            with mock.patch(
                "sys.stdin",
                mock.Mock(read=mock.Mock(return_value="hello world ${x}")),
            ):
                cmdline(["--var", "x=5", "-"])

        eq_(stdout.write.mock_calls[0][1][0], "hello world 5")
예제 #23
0
    def test_stdin_rt_err(self):
        with mock.patch("sys.stdin",
                        mock.Mock(read=mock.Mock(return_value="${q}"))):
            with self._capture_output_fixture("stderr") as stderr:
                with raises(SystemExit):
                    cmdline(["--var", "x=5", "-"])

            assert "NameError: Undefined" in stderr.write.mock_calls[0][1][0]
            assert "Traceback" in stderr.write.mock_calls[0][1][0]
예제 #24
0
    def test_stdin_rt_err(self):
        with mock.patch("sys.stdin", mock.Mock(
                            read=mock.Mock(return_value="${q}"))):
            with self._capture_output_fixture("stderr") as stderr:
                with raises(SystemExit):
                    cmdline(["--var", "x=5", "-"])

            assert "NameError: Undefined" in stderr.write.mock_calls[0][1][0]
            assert "Traceback" in stderr.write.mock_calls[0][1][0]
예제 #25
0
    def test_stdin_syntax_err(self):
        with mock.patch("sys.stdin", mock.Mock(
                            read=mock.Mock(return_value="${x"))):
            with self._capture_output_fixture("stderr") as stderr:
                with raises(SystemExit):
                    cmdline(["--var", "x=5", "-"])

            assert "SyntaxException: Expected" in \
                        stderr.write.mock_calls[0][1][0]
            assert "Traceback" in stderr.write.mock_calls[0][1][0]
예제 #26
0
    def test_stdin_syntax_err(self):
        with mock.patch("sys.stdin",
                        mock.Mock(read=mock.Mock(return_value="${x"))):
            with self._capture_output_fixture("stderr") as stderr:
                with raises(SystemExit):
                    cmdline(["--var", "x=5", "-"])

            assert "SyntaxException: Expected" in \
                        stderr.write.mock_calls[0][1][0]
            assert "Traceback" in stderr.write.mock_calls[0][1][0]
예제 #27
0
    async def test_happy_path_no_inclusion(self):
        """
        A bundle is successfully fetched without inclusion states.
        """
        self.adapter.seed_response(
                'getTrytes',
                {
                    'trytes': self.single_bundle.as_tryte_strings()
                }
        )

        with mock.patch(
                'iota.commands.core.get_inclusion_states.GetInclusionStatesCommand.__call__',
                MagicMock(return_value=async_return({'states': {
                    self.single_bundle.tail_transaction.hash: True
                }}))
        ) as mocked_glis:
            with mock.patch(
                'iota.commands.extended.get_bundles.GetBundlesCommand.__call__',
                MagicMock(return_value=async_return({'bundles': [self.single_bundle]}))
            ) as mocked_get_bundles:
                response = await get_bundles_from_transaction_hashes(
                        adapter=self.adapter,
                        transaction_hashes=[self.single_bundle.tail_transaction.hash],
                        inclusion_states=False,
                )

                self.assertListEqual(
                        response,
                        [self.single_bundle],
                )

                self.assertFalse(
                        mocked_glis.called
                )

                mocked_get_bundles.assert_called_once_with(
                        transactions=[self.single_bundle.tail_transaction.hash]
                )

                self.assertFalse(
                        response[0].is_confirmed
                )
예제 #28
0
    def setUp(self):
        """Create mock objects for HTTP Handler."""

        self._post = rpc.Handler.do_POST

        patcher = mock.patch('anaconda_mode.rpc.Handler', autospec=True)
        self.addCleanup(patcher.stop)
        self._handler = patcher.start()
        self._handler.rfile = mock.Mock()
        self._handler.wfile = mock.Mock()
예제 #29
0
  def test_start(self):
    """
    Using ``start`` to offset the key range.
    """
    self.adapter.seed_response('getBalances', {
      'balances': [86],
    })

    # ``getInputs`` uses ``findTransactions`` to identify unused
    # addresses.
    # noinspection SpellCheckingInspection
    self.adapter.seed_response('findTransactions', {
      'hashes': [
        TransactionHash(
          b'TESTVALUE9DONTUSEINPRODUCTION99999YFXGOD'
          b'GISBJAX9PDJIRDMDV9DCRDCAEG9FN9KECCBDDFZ9H'
        ),
      ],
    })

    self.adapter.seed_response('findTransactions', {
      'hashes': [],
    })

    # To keep the unit test nice and speedy, we will mock the address
    # generator.  We already have plenty of unit tests for that
    # functionality, so we can get away with mocking it here.
    # noinspection PyUnusedLocal
    def mock_address_generator(ag, start, step=1):
      # If ``start`` has the wrong value, return garbage to make the
      # test asplode.
      for addy in [None, self.addy1, self.addy2][start::step]:
        yield addy

    # When ``stop`` is None, the command uses a generator internally.
    with mock.patch(
        'iota.crypto.addresses.AddressGenerator.create_iterator',
        mock_address_generator,
    ):
      response = self.command(
        seed  = Seed.random(),
        start = 1,
      )

    self.assertEqual(response['totalBalance'], 86)
    self.assertEqual(len(response['inputs']), 1)

    input0 = response['inputs'][0]
    self.assertIsInstance(input0, Address)

    self.assertEqual(input0, self.addy1)
    self.assertEqual(input0.balance, 86)
    self.assertEqual(input0.key_index, 1)
예제 #30
0
    async def test_instance_attribute_timeout(self):
        # mock for returning dummy response
        mocked_request = mock.Mock(return_value=async_return(
            mock.Mock(text='{ "dummy": "payload"}', status_code=200)))

        # create adapter
        mock_payload = {'dummy': 'payload'}
        adapter = HttpAdapter('http://localhost:14265')

        # test with explicit attribute
        adapter.timeout = 77
        with mock.patch('iota.adapter.AsyncClient.request', mocked_request):
            await adapter.send_request(payload=mock_payload)
        _, kwargs = mocked_request.call_args
        self.assertEqual(kwargs['timeout'], 77)
예제 #31
0
    async def test_argument_overriding_init_timeout(self):
        # mock for returning dummy response
        mocked_request = mock.Mock(return_value=async_return(
            mock.Mock(text='{ "dummy": "payload"}', status_code=200)))

        # create adapter
        mock_payload = {'dummy': 'payload'}
        adapter = HttpAdapter('http://localhost:14265')

        # test with timeout at adapter creation
        adapter = HttpAdapter('http://localhost:14265', timeout=99)
        with mock.patch('iota.adapter.AsyncClient.request', mocked_request):
            await adapter.send_request(payload=mock_payload)
        _, kwargs = mocked_request.call_args
        self.assertEqual(kwargs['timeout'], 99)
예제 #32
0
    def test_generate_single_key(self):
        """
    Generating a single key.
    """
        keys = [PrivateKey(self.trytes1, 0)]

        mock_get_keys = mock.Mock(return_value=keys)
        with mock.patch('iota.crypto.signing.KeyGenerator.get_keys', mock_get_keys):
            result = self.command(seed=Seed.random(), securityLevel=2)

        self.assertDictEqual(result, {'keys': keys})
        mock_get_keys.assert_called_once_with(
            count=1,
            iterations=2,
            start=0,
        )
예제 #33
0
    async def test_default_timeout(self):
        # create adapter
        mock_payload = {'dummy': 'payload'}
        adapter = HttpAdapter('http://localhost:14265')

        # mock for returning dummy response
        mocked_request = mock.Mock(return_value=async_return(
            mock.Mock(text='{ "dummy": "payload"}', status_code=200)))

        with mock.patch('iota.adapter.AsyncClient.request', mocked_request):
            # test with default timeout
            await adapter.send_request(payload=mock_payload)

        # Was the default timeout correctly injected into the request?
        _, kwargs = mocked_request.call_args
        self.assertEqual(kwargs['timeout'], socket.getdefaulttimeout())
예제 #34
0
    def test_no_transactions_fround(self):
        """
        No transaction is found with the inputs. An empty list is returned
        """
        with mock.patch(
                'iota.commands.core.get_trytes.GetTrytesCommand._execute',
                mock.Mock(return_value={'trytes': []}),
        ):
            response = self.command(hashes=[self.transaction_hash])

        self.assertDictEqual(
            response,
            {
                'transactions': [],
            },
        )
예제 #35
0
    def test_transaction_found(self):
        """
        A transaction is found with the inputs. A transaction object is
        returned
        """
        with mock.patch(
                'iota.commands.core.get_trytes.GetTrytesCommand._execute',
                mock.Mock(return_value={'trytes': [
                    self.trytes,
                ]}),
        ):
            response = self.command(hashes=[self.transaction_hash])

        self.assertEqual(len(response['transactions']), 1)
        transaction = response['transactions'][0]
        self.assertIsInstance(transaction, Transaction)
        self.assertEqual(transaction.hash, self.transaction_hash)
예제 #36
0
    def test_no_transactions_fround(self):
        """
        No transaction is found with the inputs. An empty list is returned
        """
        with mock.patch(
            'iota.commands.core.find_transactions.FindTransactionsCommand.'
            '_execute',
            mock.Mock(return_value={'hashes': []}),
        ):
            response = self.command(addresses=[self.address])

        self.assertDictEqual(
            response,
            {
                'transactions': [],
            },
        )
예제 #37
0
    def test_start_stop(self):
        """
    Using ``start`` and ``stop`` at once.
    Checking if correct number of addresses is returned. Must be stop - start
    """

        # To keep the unit test nice and speedy, we will mock the address
        # generator.  We already have plenty of unit tests for that
        # functionality, so we can get away with mocking it here.
        # noinspection PyUnusedLocal

        def mock_address_generator(ag, start, step=1):
            # returning up to 3 addresses, depending on stop value
            for addy in [self.addy0, self.addy1, self.addy2][start::step]:
                yield addy

        self.adapter.seed_response('getBalances', {
            'balances': [11, 11],
        })

        with mock.patch(
                'iota_async.crypto.addresses.AddressGenerator.create_iterator',
                mock_address_generator,
        ):
            response = self.command(
                seed=Seed.random(),
                start=1,
                stop=3,
            )

        self.assertEqual(len(response['inputs']),
                         2)  # 3 - 1 = 2 addresses expected
        self.assertEqual(response['totalBalance'], 22)

        input0 = response['inputs'][0]
        self.assertIsInstance(input0, Address)
        self.assertEqual(input0, self.addy1)
        self.assertEqual(input0.balance, 11)
        self.assertEqual(input0.key_index, 1)

        input1 = response['inputs'][1]
        self.assertIsInstance(input1, Address)
        self.assertEqual(input1, self.addy2)
        self.assertEqual(input1.balance, 11)
        self.assertEqual(input1.key_index, 2)
예제 #38
0
    def test_happy_path(self):
        """
        Successfully checking promotability.
        """

        self.adapter.seed_response('checkConsistency', {
            'state': True,
        })
        self.adapter.seed_response('getTrytes',
                                   {'trytes': [self.trytes1, self.trytes2]})

        with mock.patch('iota.commands.extended.is_promotable.get_current_ms',
                        mock.MagicMock(return_value=self.valid_now)):
            response = self.command(tails=[self.hash1, self.hash2])

            self.assertDictEqual(response, {
                'promotable': True,
            })
예제 #39
0
    def test_no_transactions(self):
        """
    Loading account data for a seed that hasn't been used yet.
    """
        with mock.patch(
                'iota.commands.extended.get_account_data.iter_used_addresses',
                mock.Mock(return_value=[]),
        ):
            response = self.command(seed=Seed.random())

        self.assertDictEqual(
            response,
            {
                'addresses': [],
                'balance': 0,
                'bundles': [],
            },
        )
예제 #40
0
  def test_no_transactions(self):
    """
    Loading account data for a seed that hasn't been used yet.
    """
    with mock.patch(
        'iota.commands.extended.get_account_data.iter_used_addresses',
        mock.Mock(return_value=[]),
    ):
      response = self.command(seed=Seed.random())

    self.assertDictEqual(
      response,

      {
        'addresses':  [],
        'balance':    0,
        'bundles':    [],
      },
    )
예제 #41
0
    def test_stop_no_threshold(self):
        """
    ``stop`` provided, no ``threshold``.
    """
        self.adapter.seed_response('getBalances', {
            'balances': [42, 29],
        })

        # To keep the unit test nice and speedy, we will mock the address
        # generator.  We already have plenty of unit tests for that
        # functionality, so we can get away with mocking it here.
        mock_address_generator = mock.Mock(
            return_value=[self.addy0, self.addy1])

        with mock.patch(
                'iota.crypto.addresses.AddressGenerator.get_addresses',
                mock_address_generator,
        ):
            response = self.command(
                seed=Seed.random(),
                start=0,
                stop=2,
            )

        self.assertEqual(response['totalBalance'], 71)
        self.assertEqual(len(response['inputs']), 2)

        input0 = response['inputs'][0]
        self.assertIsInstance(input0, Address)

        self.assertEqual(input0, self.addy0)
        self.assertEqual(input0.balance, 42)
        self.assertEqual(input0.key_index, 0)

        input1 = response['inputs'][1]
        self.assertIsInstance(input1, Address)

        self.assertEqual(input1, self.addy1)
        self.assertEqual(input1.balance, 29)
        self.assertEqual(input1.key_index, 1)
예제 #42
0
  def test_stop_no_threshold(self):
    """
    ``stop`` provided, no ``threshold``.
    """
    self.adapter.seed_response('getBalances', {
      'balances': [42, 29],
    })

    # To keep the unit test nice and speedy, we will mock the address
    # generator.  We already have plenty of unit tests for that
    # functionality, so we can get away with mocking it here.
    mock_address_generator = mock.Mock(return_value=[self.addy0, self.addy1])

    with mock.patch(
        'iota.crypto.addresses.AddressGenerator.get_addresses',
        mock_address_generator,
    ):
      response = self.command(
        seed      = Seed.random(),
        start     = 0,
        stop      = 2,
      )

    self.assertEqual(response['totalBalance'], 71)
    self.assertEqual(len(response['inputs']), 2)

    input0 = response['inputs'][0]
    self.assertIsInstance(input0, Address)

    self.assertEqual(input0, self.addy0)
    self.assertEqual(input0.balance, 42)
    self.assertEqual(input0.key_index, 0)

    input1 = response['inputs'][1]
    self.assertIsInstance(input1, Address)

    self.assertEqual(input1, self.addy1)
    self.assertEqual(input1.balance, 29)
    self.assertEqual(input1.key_index, 1)
  def test_generate_multiple_keys(self):
    """
    Generating multiple keys.
    """
    keys = [PrivateKey(self.trytes1, 0), PrivateKey(self.trytes2, 1)]

    mock_get_keys = mock.Mock(return_value=keys)
    with mock.patch('iota_async.crypto.signing.KeyGenerator.get_keys', mock_get_keys):
      result =\
        self.command(
          count         = 2,
          index         = 0,
          securityLevel = 1,
          seed          = Seed.random(),
        )

    self.assertDictEqual(result, {'keys': keys})
    mock_get_keys.assert_called_once_with(
      count       = 2,
      iterations  = 1,
      start       = 0,
    )
예제 #44
0
  def test_stop_threshold_not_met(self):
    """
    ``stop`` provided, balance does not meet ``threshold``.
    """
    self.adapter.seed_response('getBalances', {
      'balances': [42, 29],
    })

    # To keep the unit test nice and speedy, we will mock the address
    # generator.  We already have plenty of unit tests for that
    # functionality, so we can get away with mocking it here.
    mock_address_generator = mock.Mock(return_value=[self.addy0, self.addy1])

    with mock.patch(
        'iota.crypto.addresses.AddressGenerator.get_addresses',
        mock_address_generator,
    ):
      with self.assertRaises(BadApiResponse):
        self.command(
          seed      = Seed.random(),
          stop      = 2,
          threshold = 72,
        )
예제 #45
0
 def test(self, date, timezone, sunday_offset, expected_result):
     self.set_timezone(timezone)
     with mock.patch("github_board.sunday_offset", mock.Mock(return_value=sunday_offset)):
         self.assertEqual(expected_result, board_origin(date))
예제 #46
0
  def test_no_stop_no_threshold(self):
    """
    No ``stop`` provided, no ``threshold``.
    """
    self.adapter.seed_response('getBalances', {
      'balances': [42, 29],
    })

    # ``getInputs`` uses ``findTransactions`` to identify unused
    # addresses.
    # noinspection SpellCheckingInspection
    self.adapter.seed_response('findTransactions', {
      'hashes': [
        TransactionHash(
          b'TESTVALUE9DONTUSEINPRODUCTION99999WBL9KD'
          b'EIZDMEDFPEYDIIA9LEMEUCC9MFPBY9TEVCUGSEGGN'
        ),
      ],
    })

    # noinspection SpellCheckingInspection
    self.adapter.seed_response('findTransactions', {
      'hashes': [
        TransactionHash(
          b'TESTVALUE9DONTUSEINPRODUCTION99999YFXGOD'
          b'GISBJAX9PDJIRDMDV9DCRDCAEG9FN9KECCBDDFZ9H'
        ),
      ],
    })

    self.adapter.seed_response('findTransactions', {
      'hashes': [],
    })

    # To keep the unit test nice and speedy, we will mock the address
    # generator.  We already have plenty of unit tests for that
    # functionality, so we can get away with mocking it here.
    # noinspection PyUnusedLocal
    def mock_address_generator(ag, start, step=1):
      for addy in [self.addy0, self.addy1, self.addy2][start::step]:
        yield addy

    # When ``stop`` is None, the command uses a generator internally.
    with mock.patch(
        'iota.crypto.addresses.AddressGenerator.create_iterator',
        mock_address_generator,
    ):
      response = self.command(
        seed = Seed.random(),
      )

    self.assertEqual(response['totalBalance'], 71)
    self.assertEqual(len(response['inputs']), 2)

    input0 = response['inputs'][0]
    self.assertIsInstance(input0, Address)

    self.assertEqual(input0, self.addy0)
    self.assertEqual(input0.balance, 42)
    self.assertEqual(input0.key_index, 0)

    input1 = response['inputs'][1]
    self.assertIsInstance(input1, Address)

    self.assertEqual(input1, self.addy1)
    self.assertEqual(input1.balance, 29)
    self.assertEqual(input1.key_index, 1)
예제 #47
0
 def test(self, template):
     with mock.patch("github_board.open", mock.mock_open(read_data=template), create=True):
         with mock.patch("github_board.pygit2.Repository.create_commit", mock.Mock()) as m:
             main("test@test", self.repo.path, template, None)
             self.assertEquals(sum([int(i) for i in template if i.isdigit()]), len(m.mock_calls))
예제 #48
0
 def test(self, data, expected_result):
     with mock.patch("github_board.url_request.urlopen", mock.Mock(return_value=BytesIO(data))):
         self.assertSequenceEqual(expected_result, min_max_for_user("some_github_user"))
예제 #49
0
  def test_get_inclusion_states(self):
    """
    Fetching inclusion states with transactions.
    """
    # noinspection PyUnusedLocal
    def create_generator(ag, start, step=1):
      for addy in [self.addy1][start::step]:
        yield addy

    # The first address received IOTA.
    self.adapter.seed_response(
      'findTransactions',

      {
        'duration': 42,

        'hashes': [
          'TESTVALUEFIVE9DONTUSEINPRODUCTION99999VH'
          'YHRHJETGYCAFZGABTEUBWCWAS9WF99UHBHRHLIOFJ',
        ],
      },
    )

    # For this test, we have to generate a real TryteString.
    transaction_trytes =\
      TryteString(
        b'KMYUMNEUAYODAQSNGWTAERRRHNZBZCOLMVVOBTVWLOFYCJKYMGRAMH9RQ9MTZOSZMH'
        b'QNZFHFEJEDFQ99HSUNVOTULDJGXEDULS9ZHABVDZODJUMCNWVCPNSCUVKVYWCEXBHW'
        b'RBZBSWFPQLWZWMUPGQIGAEGOVE9DDXBVCIPKQYCFZFBELTSMVFSIXLPTACTKAFMCTK'
        b'CPYD9BWDJMLKWAOBDSJNQYAHS9GFIQKZCROLFZJVUEIVXVNBRRLEIWTYVHURUXHSCG'
        b'DKEIEGPOCXKCYWIBUG9ABYCALYJVFLBNGMS9ARHGTQXBZFLENXCJVKHPVKD9KSAEOL'
        b'FFVAJCNKLDVHOCDARWUNKARDYMVKFKRSMUTYOUXSBFFYTKRREBDJZTLVUROQFCBXQN'
        b'SXDDYTZTEBRSXOBMLXHJKSJAVOOVCXATOWNQDWHT9CCUAAJUJKDOQLMAEZACSNFKXZ'
        b'IGWDQEUEFRZYAOSDNVMSXWYLVDAUXZSHNHAIBEMNPFUGORYUETNJK9UCEMSUJYBBDK'
        b'BHIPKEINQCGOVYCPKUPJMUCUVZOJSIWYRFMFXYUVSMOUALAQBWIMXBUBXSAETGKJRP'
        b'AHVAXHQJDMEVSRFYEXUSIEBKMGYCUKFD9JPGUV9AIYUVCRUURKMYUHMVE9OJCYYWTQ'
        b'WUWFMTBZYFXASHHVCMSWXKBRQFHHQVEQMEULJRWZKLWFFSGGKEHUZZFNDNITSRAUH9'
        b'PQK9OGLYMVBSHXQLLZHOBBIM9KVUWDLHZRDKQQVLQXGWYXEEVQPDZUO9PVXMALOMRQ'
        b'VCTHGIZLILSCFKTBRESYZGBZKHXEODNDJZ9GK9ROWYXNGFHZCCBHHZEYEOGWXRGSUD'
        b'SUZFUAUBXVXZHCUVJSYBWTCYCEDYKZNGWFZYKSQLW9FUYMWDVXKZEWT9SCVMQCODZK'
        b'DRNKTINTPNOJOLGQJDAJMFWRFSWZJLYZGSTSIDSXLUJBZRZNLEDNBKAUNGTCYUPDRW'
        b'JOCEBQ9YG9IZLLRMJITISJOTLQMOGXVQIZXHMTJVMMWM9FOIOT9KFZMANEPOEOV9HX'
        b'JNEGURUKRWDGYNPVGAWMWQVABIJNL9MDXKONEPMYACOZ9BE9UZMAFTKYWPFWIQWAPK'
        b'GUXQTOQVWYYVZYGQDLBIQDVOZIWGOMGOBAUARICQZVNXD9UVEFBBAJKQBHRHXTBUOW'
        b'VBFKYQWZWTMMXVKZRIZUBVPQ9XHLJHFHWFZUIZVSNAKBDHDFGJCYQETOMEDTOXIUT9'
        b'OAJVIHWAGTCNPEZTERMMN9EZEWSJHKQAUMXPBZTNQOEQCVXIMAAYO9NIUFLTCFIMK9'
        b'9AFAGWJFA9VOFPUDJLRAMORGSUDBLWWKXEDZ9XPQUZSGANGESHKKGGQSGSYDCRLHZD'
        b'PKA9HKYBKLKKCXYRQQIPXCFETJJDZYPCLUNHGBKEJDRCIHEXKCQQNOV9QFHLGFXOCR'
        b'HPAFCUTPMY9NOZVQHROYJSCMGRSVMOBWADAZNFIAHWGIQUUZBOVODSFAUNRTXSDU9W'
        b'EIRBXQNRSJXFRAQGHA9DYOQJGLVZUJKAQ9CTUOTT9ZKQOQNNLJDUPDXZJYPRCVLRZT'
        b'UCZPNBREYCCKHK9FUWGITAJATFPUOFLZDHPNJYUTXFGNYJOBRD9BVHKZENFXIUYDTL'
        b'CE9JYIIYMXMCXMWTHOLTQFKFHDLVPGMQNITEUXSYLAQULCZOJVBIPYP9M9X9QCNKBX'
        b'W9DVJEQFFY9KQVMKNVTAHQVRXUKEM9FZOJLHAGEECZBUHOQFZOSPRXKZOCCKAOHMSV'
        b'QCFG9CWAHKVWNA9QTLYQI9NKOSHWJCNGPJBLEQPUIWJBIOAWKLBXUCERTSL9FVCLYN'
        b'ADPYTPKJOIEMAQGWBVGSRCZINXEJODUDCT9FHOUMQM9ZHRMBJYSOMPNMEAJGEHICJI'
        b'PVXRKCYX9RZVT9TDZIMXGZJAIYJRGIVMSOICSUINRBQILMJOUQYXCYNJ9WGGJFHYTU'
        b'LWOIPUXXFNTIFNOJRZFSQQNAWBQZOLHHLVGHEPWTKKQEVIPVWZUN9ZBICZ9DZZBVII'
        b'BF9EPHARZJUFJGBQXQFQIBUECAWRSEKYJNYKNSVBCOWTFBZ9NAHFSAMRBPEYGPRGKW'
        b'WTWACZOAPEOECUO9OTMGABJVAIICIPXGSXACVINSYEQFTRCQPCEJXZCY9XZWVWVJRZ'
        b'CYEYNFUUBKPWCHICGJZXKE9GSUDXZYUAPLHAKAHYHDXNPHENTERYMMBQOPSQIDENXK'
        b'LKCEYCPVTZQLEEJVYJZV9BWU999999999999999999999999999FFL999999999999'
        b'9999999999999RJQGVD99999999999A99999999USGBXHGJUEWAUAKNPPRHJXDDMQV'
        b'YDSYZJSDWFYLOQVFGBOSLE9KHFDLDYHUYTXVSFAFCOCLQUHJXTEIQRNBTLHEGJFGVF'
        b'DJCE9IKAOCSYHLCLWPVVNWNESKLYAJG9FGGZOFXCEYOTWLVIJUHGY9QCU9FMZJY999'
        b'9999HYBUYQKKRNAVDPVGYBTVDZ9SVQBLCCVLJTPEQWWOIG9CQZIFQKCROH9YHUCNJT'
        b'SYPBVZVBNESX999999D9TARGPQTNIYRZURQGVHCAWEDRBJIIEJIUZYENVE9LLJQMXH'
        b'GSUUYUCPSOWBCXVFDCHHAZUDC9LUODYWO'
      )

    self.adapter.seed_response(
      'getTrytes',

      {
        'duration': 99,
        'trytes':   [binary_type(transaction_trytes)],
      },
    )

    transaction = Transaction.from_tryte_string(transaction_trytes)

    mock_get_bundles = mock.Mock(return_value={
      'bundles': [Bundle([transaction])],
    })

    mock_get_latest_inclusion = mock.Mock(return_value={
      'states': {
        transaction.hash: True,
      },
    })

    with mock.patch(
        'iota.crypto.addresses.AddressGenerator.create_iterator',
        create_generator,
    ):
      with mock.patch(
          'iota.commands.extended.get_bundles.GetBundlesCommand._execute',
          mock_get_bundles,
      ):
        with mock.patch(
          'iota.commands.extended.get_latest_inclusion.GetLatestInclusionCommand._execute',
          mock_get_latest_inclusion,
        ):
          response = self.command(
            seed = Seed.random(),

            inclusionStates = True,

            # To keep the test focused, only retrieve a single
            # transaction.
            start = 0,
            stop  = 1,
          )

    bundle = response['bundles'][0] # type: Bundle
    self.assertTrue(bundle[0].is_confirmed)
예제 #50
0
  def test_stop(self):
    """
    Scanning the Tangle for all transfers, with stop index.
    """
    # noinspection PyUnusedLocal
    def create_generator(ag, start, step=1):
      # Inject an invalid value into the generator, to ensure it is
      # skipped.
      for addy in [self.addy1, None][start::step]:
        yield addy

    # The first address received IOTA.
    self.adapter.seed_response(
      'findTransactions',

      {
        'duration': 42,

        'hashes': [
          'TESTVALUEFIVE9DONTUSEINPRODUCTION99999VH'
          'YHRHJETGYCAFZGABTEUBWCWAS9WF99UHBHRHLIOFJ',
        ],
      },
    )

    self.adapter.seed_response(
      'getTrytes',

      {
        'duration': 99,
        'trytes':   [''],
      },
    )

    bundle = Bundle([
      Transaction(
        address = self.addy1,
        timestamp = 1483033814,

        # These values are not relevant to the test.
        hash_ = None,
        signature_message_fragment = None,
        value = 42,
        tag = Tag(b''),
        current_index = 0,
        last_index = 0,
        bundle_hash = None,
        trunk_transaction_hash = None,
        branch_transaction_hash = None,
        attachment_timestamp = 1483033814,
        attachment_timestamp_lower_bound = 12,
        attachment_timestamp_upper_bound = 0,
        nonce = None,
      )
    ])

    mock_get_bundles = mock.Mock(return_value={
      'bundles': [bundle],
    })

    with mock.patch(
        'iota.crypto.addresses.AddressGenerator.create_iterator',
        create_generator,
    ):
      with mock.patch(
          'iota.commands.extended.get_bundles.GetBundlesCommand._execute',
          mock_get_bundles,
      ):
        response = self.command(seed=Seed.random(), stop=1)

    self.assertDictEqual(
      response,

      {
        'bundles': [bundle],
      },
    )
예제 #51
0
  def test_happy_path(self):
    """
    Sending a transfer successfully.
    """
    # noinspection SpellCheckingInspection
    transaction1 =\
      TransactionTrytes(
          b'GYPRVHBEZOOFXSHQBLCYW9ICTCISLHDBNMMVYD9JJHQMPQCTIQAQTJNNNJ9IDXLRCC'
          b'OYOXYPCLR9PBEY9ORZIEPPDNTI9CQWYZUOTAVBXPSBOFEQAPFLWXSWUIUSJMSJIIIZ'
          b'WIKIRH9GCOEVZFKNXEVCUCIIWZQCQEUVRZOCMEL9AMGXJNMLJCIA9UWGRPPHCEOPTS'
          b'VPKPPPCMQXYBHMSODTWUOABPKWFFFQJHCBVYXLHEWPD9YUDFTGNCYAKQKVEZYRBQRB'
          b'XIAUX9SVEDUKGMTWQIYXRGSWYRK9SRONVGTW9YGHSZRIXWGPCCUCDRMAXBPDFVHSRY'
          b'WHGB9DQSQFQKSNICGPIPTRZINYRXQAFSWSEWIFRMSBMGTNYPRWFSOIIWWT9IDSELM9'
          b'JUOOWFNCCSHUSMGNROBFJX9JQ9XT9PKEGQYQAWAFPRVRRVQPUQBHLSNTEFCDKBWRCD'
          b'X9EYOBB9KPMTLNNQLADBDLZPRVBCKVCYQEOLARJYAGTBFR9QLPKZBOYWZQOVKCVYRG'
          b'YI9ZEFIQRKYXLJBZJDBJDJVQZCGYQMROVHNDBLGNLQODPUXFNTADDVYNZJUVPGB9LV'
          b'PJIYLAPBOEHPMRWUIAJXVQOEM9ROEYUOTNLXVVQEYRQWDTQGDLEYFIYNDPRAIXOZEB'
          b'CS9P99AZTQQLKEILEVXMSHBIDHLXKUOMMNFKPYHONKEYDCHMUNTTNRYVMMEYHPGASP'
          b'ZXASKRUPWQSHDMU9VPS99ZZ9SJJYFUJFFMFORBYDILBXCAVJDPDFHTTTIYOVGLRDYR'
          b'TKHXJORJVYRPTDH9ZCPZ9ZADXZFRSFPIQKWLBRNTWJHXTOAUOL9FVGTUMMPYGYICJD'
          b'XMOESEVDJWLMCVTJLPIEKBE9JTHDQWV9MRMEWFLPWGJFLUXI9BXPSVWCMUWLZSEWHB'
          b'DZKXOLYNOZAPOYLQVZAQMOHGTTQEUAOVKVRRGAHNGPUEKHFVPVCOYSJAWHZU9DRROH'
          b'BETBAFTATVAUGOEGCAYUXACLSSHHVYDHMDGJP9AUCLWLNTFEVGQGHQXSKEMVOVSKQE'
          b'EWHWZUDTYOBGCURRZSJZLFVQQAAYQO9TRLFFN9HTDQXBSPPJYXMNGLLBHOMNVXNOWE'
          b'IDMJVCLLDFHBDONQJCJVLBLCSMDOUQCKKCQJMGTSTHBXPXAMLMSXRIPUBMBAWBFNLH'
          b'LUJTRJLDERLZFUBUSMF999XNHLEEXEENQJNOFFPNPQ9PQICHSATPLZVMVIWLRTKYPI'
          b'XNFGYWOJSQDAXGFHKZPFLPXQEHCYEAGTIWIJEZTAVLNUMAFWGGLXMBNUQTOFCNLJTC'
          b'DMWVVZGVBSEBCPFSM99FLOIDTCLUGPSEDLOKZUAEVBLWNMODGZBWOVQT9DPFOTSKRA'
          b'BQAVOQ9RXWBMAKFYNDCZOJGTCIDMQSQQSODKDXTPFLNOKSIZEOY9HFUTLQRXQMEPGO'
          b'XQGLLPNSXAUCYPGZMNWMQWSWCKAQYKXJTWINSGPPZG9HLDLEAWUWEVCTVRCBDFOXKU'
          b'ROXH9HXXAXVPEJFRSLOGRVGYZASTEBAQNXJJROCYRTDPYFUIQJVDHAKEG9YACV9HCP'
          b'JUEUKOYFNWDXCCJBIFQKYOXGRDHVTHEQUMHO999999999999999999999999999999'
          b'999999999999999999999999999999999999999999999999999999999999999999'
          b'999999999999999999999999999999999999999999999999999999999999999999'
          b'999999999999999999999999999999999999999999999999999999999999999999'
          b'999999999999999999999999999999999999999999999999999999999999999999'
          b'999999999999999999999999999999999999999999999999999999999999999999'
          b'999999999999999999999999999999999999999999999999999999999999999999'
          b'999999999999999999999999999999999999999999999999999999999999999999'
          b'999999999999999999999999999999999999999999999999999999999999999999'
          b'999999999999999999999999999999999999999999999999999999999999999999'
          b'999999999999999999999999999999999999999999999999999999999999999999'
          b'999999999999RKWEEVD99A99999999A99999999NFDPEEZCWVYLKZGSLCQNOFUSENI'
          b'XRHWWTZFBXMPSQHEDFWZULBZFEOMNLRNIDQKDNNIELAOXOVMYEI9PGTKORV9IKTJZQ'
          b'UBQAWTKBKZ9NEZHBFIMCLV9TTNJNQZUIJDFPTTCTKBJRHAITVSKUCUEMD9M9SQJ999'
          b'999TKORV9IKTJZQUBQAWTKBKZ9NEZHBFIMCLV9TTNJNQZUIJDFPTTCTKBJRHAITVSK'
          b'UCUEMD9M9SQJ999999999999999999999999999999999999999999999999999999'
          b'999999999999999999999999999999999'
        )

    mock_prepare_transfer =\
      mock.Mock(return_value={
        'trytes': [transaction1],
      })

    mock_send_trytes =\
      mock.Mock(return_value={
        'trytes': [transaction1],
      })

    with mock.patch(
        'iota.commands.extended.prepare_transfer.PrepareTransferCommand._execute',
        mock_prepare_transfer,
    ):
      with mock.patch(
          'iota.commands.extended.send_trytes.SendTrytesCommand._execute',
          mock_send_trytes,
      ):
        response = self.command(
          depth               = 100,
          minWeightMagnitude  = 18,
          seed                = Seed.random(),

          transfers = [
            ProposedTransaction(
              address =
                Address(
                  b'9999999999999999999999999999999999999999'
                  b'99999999999999999999999999999999999999999'
                ),

              value = 0,
            ),
          ],
        )

    bundle = response['bundle'] # type: Bundle
    self.assertEqual(len(bundle), 1)
    self.assertEqual(bundle[0].as_tryte_string(), transaction1)
예제 #52
0
  def test_full_scan(self):
    """
    Scanning the Tangle for all transfers.
    """
    # To speed up the test, we will mock the address generator.
    # :py:class:`iota.crypto.addresses.AddressGenerator` already has
    # its own test case, so this does not impact the stability of the
    # codebase.
    # noinspection PyUnusedLocal
    def create_generator(ag, start, step=1):
      for addy in [self.addy1, self.addy2][start::step]:
        yield addy

    # The first address received IOTA.
    self.adapter.seed_response(
      'findTransactions',

      {
        'duration': 42,

        'hashes': [
          'TESTVALUEFIVE9DONTUSEINPRODUCTION99999VH'
          'YHRHJETGYCAFZGABTEUBWCWAS9WF99UHBHRHLIOFJ',
        ],
      },
    )

    # The second address is unused.
    self.adapter.seed_response(
      'findTransactions',

      {
        'duration': 1,
        'hashes':   [],
      },
    )

    self.adapter.seed_response(
      'getTrytes',

      {
        'duration': 99,

        # Thankfully, we do not have to seed a realistic response for
        # ``getTrytes``, as we will be mocking the ``getBundles``
        # command that uses on it.
        'trytes': [''],
      },
    )

    bundle = Bundle([
      Transaction(
        address = self.addy1,
        timestamp = 1483033814,

        # These values are not relevant to the test.
        hash_ = None,
        signature_message_fragment = None,
        value = 42,
        tag = Tag(b''),
        current_index = 0,
        last_index = 0,
        bundle_hash = None,
        trunk_transaction_hash = None,
        branch_transaction_hash = None,
        attachment_timestamp = 1483033814,
        attachment_timestamp_lower_bound = 12,
        attachment_timestamp_upper_bound = 0,
        nonce = None,
      )
    ])

    mock_get_bundles =\
      mock.Mock(return_value={
        'bundles': [bundle],
      })

    with mock.patch(
        'iota.crypto.addresses.AddressGenerator.create_iterator',
        create_generator,
    ):
      with mock.patch(
          'iota.commands.extended.get_bundles.GetBundlesCommand._execute',
          mock_get_bundles,
      ):
        response = self.command(seed=Seed.random())

    self.assertDictEqual(
      response,

      {
        'bundles': [bundle],
      },
    )
예제 #53
0
 def _capture_output_fixture(self, stream="stdout"):
     with mock.patch("sys.%s" % stream) as stdout:
         yield stdout