Beispiel #1
0
    def test_make_parsed_url_asserts_with_conflicting_port_numbers(self):
        with ExpectedException(AssertionError):
            netloc = "%s:%d" % (factory.make_hostname(), factory.pick_port())
            factory.make_parsed_url(netloc=netloc, port=factory.pick_port())

        with ExpectedException(AssertionError):
            netloc = "%s:%d" % (factory.make_hostname(), factory.pick_port())
            factory.make_parsed_url(netloc=netloc, port=True)
Beispiel #2
0
    def test_configuration_manager(self, mock_strategy):
        mock_strategy.count_revisions.return_value = 0
        manager = ConfigurationManager(Mock(), Mock(), Mock(), Mock())

        with ExpectedException(exception.DatastoreOperationNotSupported):
            manager.update_override({})

        with ExpectedException(exception.DatastoreOperationNotSupported):
            manager.remove_override()

        manager.set_override_strategy(mock_strategy, 1)

        self.assertEqual(1, manager.max_num_overrides)
        self.assertEqual(0, manager.current_revision)

        with ExpectedException(
                exception.UnprocessableEntity,
                "The maximum number of attached Configuration Groups cannot "
                "be negative."):
            manager.max_num_overrides = -1

        manager.max_num_overrides = 2

        self.assertEqual(2, manager.max_num_overrides)

        self.assertEqual(0, manager.current_revision)
        manager.update_override({})
        self.assertEqual(1, manager.current_revision)
        manager.update_override({})
        self.assertEqual(2, manager.current_revision)

        with ExpectedException(
                ConfigurationError, "This instance cannot have more than "
                "'2' Configuration Groups attached."):
            manager.update_override({})

        self.assertEqual(2, manager.current_revision)
        manager.remove_override()
        self.assertEqual(1, manager.current_revision)
        manager.update_override({})
        self.assertEqual(2, manager.current_revision)
        manager.remove_override()
        self.assertEqual(1, manager.current_revision)
        manager.remove_override()
        self.assertEqual(0, manager.current_revision)

        with ExpectedException(
                ConfigurationError,
                "This instance does not have a Configuration Group attached."):
            manager.remove_override()

        self.assertEqual(0, manager.current_revision)

        manager.override_strategy = None

        self.assertEqual(0, manager.max_num_overrides)
        self.assertEqual(0, manager.current_revision)
Beispiel #3
0
    def _test_rebuild(self, stgpol, data_size, broken_pos_list,
                      full_rebuild_pos):
        data = random_data(data_size)
        content, broken_chunks_info = self._new_content(
            stgpol, data, broken_pos_list)

        rebuild_pos, rebuild_idx = full_rebuild_pos
        rebuild_chunk_info = broken_chunks_info[rebuild_pos][rebuild_idx]
        content.rebuild_chunk(rebuild_chunk_info["id"])

        # get the new structure of the content
        rebuilt_content = self.content_factory.get(self.container_id,
                                                   content.content_id)
        self.assertEqual(type(rebuilt_content), DupContent)

        # find the rebuilt chunk
        for c in rebuilt_content.chunks.filter(pos=rebuild_pos):
            if len(content.chunks.filter(id=c.id)) > 0:
                # not the rebuilt chunk
                # if this chunk is broken, it must not have been rebuilt
                for b_c_i in broken_chunks_info[rebuild_pos].values():
                    if c.id == b_c_i["id"]:
                        with ExpectedException(NotFound):
                            _, _ = self.blob_client.chunk_get(c.url)
                continue
            meta, stream = self.blob_client.chunk_get(c.url)
            self.assertEqual(meta["chunk_id"], c.id)
            self.assertEqual(md5_stream(stream), rebuild_chunk_info["dl_hash"])
            self.assertEqual(c.hash, rebuild_chunk_info["hash"])
            self.assertThat(c.url, NotEquals(rebuild_chunk_info["url"]))
            del meta["chunk_id"]
            del rebuild_chunk_info["dl_meta"]["chunk_id"]
            self.assertEqual(meta, rebuild_chunk_info["dl_meta"])
 def test_pending_transaction(self):
     """When a transaction is pending before the operation, raise."""
     transaction.begin()
     with ExpectedException(AssertionError,
                            'Transaction open before operation'):
         with TransactionFreeOperation():
             pass
Beispiel #5
0
    def _rebuild_and_check(self, content, broken_chunks_info, full_rebuild_pos,
                           allow_frozen_container=False):
        rebuild_pos, rebuild_idx = full_rebuild_pos
        rebuild_chunk_info = broken_chunks_info[rebuild_pos][rebuild_idx]
        content.rebuild_chunk(rebuild_chunk_info["id"],
                              allow_frozen_container=allow_frozen_container)

        # get the new structure of the content
        rebuilt_content = self.content_factory.get(self.container_id,
                                                   content.content_id)

        # find the rebuilt chunk
        for c in rebuilt_content.chunks.filter(pos=rebuild_pos):
            if len(content.chunks.filter(id=c.id)) > 0:
                # not the rebuilt chunk
                # if this chunk is broken, it must not have been rebuilt
                for b_c_i in broken_chunks_info[rebuild_pos].values():
                    if c.id == b_c_i["id"]:
                        with ExpectedException(NotFound):
                            _, _ = self.blob_client.chunk_get(c.url)
                continue
            meta, stream = self.blob_client.chunk_get(c.url)
            self.assertEqual(meta["chunk_id"], c.id)
            self.assertEqual(md5_stream(stream),
                             rebuild_chunk_info["dl_hash"])
            self.assertEqual(c.checksum, rebuild_chunk_info["hash"])
            self.assertThat(c.url, NotEquals(rebuild_chunk_info["url"]))
            del meta["chunk_id"]
            del rebuild_chunk_info["dl_meta"]["chunk_id"]
            self.assertEqual(meta, rebuild_chunk_info["dl_meta"])
Beispiel #6
0
    def test_cannot_be_acquired_twice(self):
        """
        `SystemLock` and its kin do not suffer from a bug that afflicts
        ``lockfile`` (https://pypi.python.org/pypi/lockfile):

          >>> from lockfile import FileLock
          >>> with FileLock('foo'):
          ...     with FileLock('foo'):
          ...         print("Hello!")
          ...
          Hello!
          Traceback (most recent call last):
            File "<stdin>", line 3, in <module>
            File ".../dist-packages/lockfile.py", line 230, in __exit__
              self.release()
            File ".../dist-packages/lockfile.py", line 271, in release
              raise NotLocked
          lockfile.NotLocked

        """
        lock = self.make_lock()
        with lock:
            with ExpectedException(self.locktype.NotAvailable, lock.path):
                with lock:
                    pass
Beispiel #7
0
 def test_connection_raises_NoRabbit_if_cannot_connect(self):
     # Attempt to connect to a RabbitMQ on the local "discard"
     # service.  The connection will be refused.
     self.patch(settings, 'RABBITMQ_HOST', 'localhost:9')
     session = RabbitSession()
     with ExpectedException(NoRabbit):
         session.connection
Beispiel #8
0
 def test_list_boot_images_passes_on_other_exceptions(self):
     # OSError(EACCESS) is transmogrified, by Python itself, into
     # PermissionError. It's a subclass of OSError.
     error = OSError(errno.EACCES, "Deliberate error for testing.")
     self.patch(tftppath, 'list_subdirs', Mock(side_effect=error))
     with ExpectedException(PermissionError):
         list_boot_images(factory.make_string())
Beispiel #9
0
    def test_utf8_container(self):
        backend = AccountBackend({}, self.conn)
        account_id = 'test'
        self.assertEqual(backend.create_account(account_id), account_id)
        name = u'La fête à la maison'
        mtime = Timestamp(time()).normal

        # create container
        backend.update_container(account_id, name, mtime, 0, 0, 0, 0, 0)
        res = self.conn.zrangebylex('containers:%s' % account_id, '-', '+')
        self.assertEqual(unicode(res[0], 'utf8'), name)

        # ensure it appears in listing
        listing = backend.list_containers(account_id,
                                          marker='',
                                          delimiter='',
                                          limit=100)
        self.assertIn(name, [entry[0] for entry in listing])

        # delete container
        sleep(.00001)
        dtime = Timestamp(time()).normal
        backend.update_container(account_id, name, 0, dtime, 0, 0, 0, 0)
        res = self.conn.zrangebylex('containers:%s' % account_id, '-', '+')
        self.assertEqual(len(res), 0)
        self.assertTrue(
            self.conn.ttl('container:%s:%s' % (account_id, name)) >= 1)

        # ensure it has been removed
        with ExpectedException(Conflict):
            backend.update_container(account_id, name, 0, dtime, 0, 0, 0, 0)
        res = self.conn.zrangebylex('containers:%s' % account_id, '-', '+')
        self.assertEqual(len(res), 0)
        self.assertTrue(
            self.conn.ttl('container:%s:%s' % (account_id, name)) >= 1)
Beispiel #10
0
 def test__raises_when_inner_encapsulation_is_not_bson(self):
     self.write_secret()
     payload = fernet_encrypt_psk(compress(b"\n\n"), raw=True)
     packet = _make_beacon_payload(payload=payload)
     with ExpectedException(InvalidBeaconingPacket,
                            ".*beacon payload is not BSON.*"):
         read_beacon_payload(packet)
Beispiel #11
0
 def test__raises_when_inner_encapsulation_does_not_decompress(self):
     self.write_secret()
     packet = _make_beacon_payload(
         payload=fernet_encrypt_psk('\n\n', raw=True))
     with ExpectedException(InvalidBeaconingPacket,
                            ".*Failed to decompress.*"):
         read_beacon_payload(packet)
Beispiel #12
0
 def test__raises_when_inner_payload_does_not_decrypt(self):
     self.write_secret()
     packet = _make_beacon_payload(payload=b"\xfe")
     with ExpectedException(
         InvalidBeaconingPacket, ".*Failed to decrypt.*"
     ):
         read_beacon_payload(packet)
Beispiel #13
0
 def test__requires_input_file(self):
     parser = ArgumentParser()
     add_arguments(parser)
     args = parser.parse_args([])
     with ExpectedException(ActionScriptError,
                            ".*Required argument: interface.*"):
         run(args)
Beispiel #14
0
    def test_passes_on_dissimilar_errors(self):
        class DeliberateError(Exception):
            """Deliberately induced error for testing."""

        with ExpectedException(DeliberateError):
            with report_missing_config_dir():
                raise DeliberateError("This exception propagates unchanged.")
Beispiel #15
0
 def test_raises_last_exception_after_all_retries_fail(self):
     wait_time = [random.randrange(1, 10) for _ in range(3)]
     driver = make_power_driver(wait_time=wait_time)
     exception_types = list(
         factory.make_exception_type((PowerError, )) for _ in wait_time)
     self.patch(driver, "power_query").side_effect = exception_types
     with ExpectedException(exception_types[-1]):
         yield driver.query(sentinel.system_id, sentinel.context)
    def test_install_agent(self):
        blueprint_path = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            "resources/blueprints/test-install-agent-blueprint.yaml")

        with ExpectedException(ValueError,
                               "'install_agent': true is not supported*"):
            self.env = local.init_env(blueprint_path)
Beispiel #17
0
 def test__discover_requires_client_to_have_vm_support(self):
     context = self.make_parameters_context()
     driver = LXDPodDriver()
     Client = self.patch(lxd_pod_module, "Client")
     client = Client.return_value
     client.has_api_extension.return_value = False
     with ExpectedException(lxd_pod_module.LXDError):
         yield driver.discover(None, context)
Beispiel #18
0
 def test_pauses_between_retries(self):
     wait_time = [random.randrange(1, 10) for _ in range(3)]
     driver = make_power_driver(wait_time=wait_time)
     self.patch(driver, 'power_query').side_effect = PowerError
     with ExpectedException(PowerError):
         yield driver.query(sentinel.system_id, sentinel.context)
     self.assertThat(power.pause, MockCallsMatch(
         *(call(wait, reactor) for wait in wait_time)))
 def test_secrecy_change_unprivileged(self):
     """Unprivileged users cannot change information_type."""
     policy = SpecificationSharingPolicy.PUBLIC_OR_PROPRIETARY
     product = self.factory.makeProduct(specification_sharing_policy=policy)
     spec = self.factory.makeSpecification(product=product)
     person = self.factory.makePerson()
     with ExpectedException(Unauthorized):
         self.set_secrecy(spec, person)
     self.assertEqual(InformationType.PUBLIC, spec.information_type)
Beispiel #20
0
 def test_validates_mtu(self):
     vlan = factory.make_VLAN()
     vlan.mtu = self.mtu
     if self.valid:
         # No exception.
         self.assertIsNone(vlan.save())
     else:
         with ExpectedException(ValidationError):
             vlan.save()
Beispiel #21
0
 def test_handles_non_fatal_error(self):
     system_id = factory.make_name("system_id")
     context = {"context": factory.make_name("context")}
     driver = make_power_driver(wait_time=[0])
     mock_on = self.patch(driver, self.action_func)
     mock_on.side_effect = PowerError()
     method = getattr(driver, self.action)
     with ExpectedException(PowerError):
         yield method(system_id, context)
Beispiel #22
0
 def test_power_query_raises_error_on_unknown_state(self):
     context = self.make_parameters_context()
     pod_id = factory.make_name("pod_id")
     driver = lxd_module.LXDPodDriver()
     mock_machine = self.patch(driver, "get_machine").return_value
     mock_machine.status_code = 106
     error_msg = f"Pod {pod_id}: Unknown power status code: {mock_machine.status_code}"
     with ExpectedException(lxd_module.LXDPodError, error_msg):
         yield driver.power_query(pod_id, context)
Beispiel #23
0
 def test_get_client_raises_error_when_cannot_connect(self):
     context = self.make_parameters_context()
     pod_id = factory.make_name("pod_id")
     Client = self.patch(lxd_module, "Client")
     Client.side_effect = lxd_module.ClientConnectionFailed()
     driver = lxd_module.LXDPodDriver()
     error_msg = f"Pod {pod_id}: Failed to connect to the LXD REST API."
     with ExpectedException(lxd_module.LXDPodError, error_msg):
         yield driver.get_client(pod_id, context)
Beispiel #24
0
 def test_atomic_write_does_not_leak_temp_file_on_failure(self):
     # If the overwrite fails, atomic_write does not leak its
     # temporary file.
     self.patch(fs_module, "rename", Mock(side_effect=OSError()))
     filename = self.make_file()
     with ExpectedException(OSError):
         atomic_write(factory.make_bytes(), filename)
     self.assertEqual([os.path.basename(filename)],
                      os.listdir(os.path.dirname(filename)))
Beispiel #25
0
    def test_connection_propagates_exceptions(self):

        def fail(*args, **kwargs):
            raise socket.error("Connection not refused, but failed anyway.")

        self.patch(amqp, 'Connection', fail)
        session = RabbitSession()
        with ExpectedException(socket.error):
            session.connection
Beispiel #26
0
 def test_probe_and_enlist_login_failure(self):
     user = factory.make_name('user')
     poweraddr = factory.make_name('poweraddr')
     mock_login = self.patch(virsh.VirshSSH, 'login')
     mock_login.return_value = False
     with ExpectedException(virsh.VirshError):
         yield deferToThread(virsh.probe_virsh_and_enlist,
                             user,
                             poweraddr,
                             password=factory.make_string())
Beispiel #27
0
 def test_refuses_EMBARGOED(self):
     """Packaging cannot be created for EMBARGOED productseries"""
     product = self.factory.makeProduct(
         information_type=InformationType.EMBARGOED)
     sp = self.makeSourcePackage()
     series = self.factory.makeProductSeries(product=product)
     with ExpectedException(CannotPackageProprietaryProduct,
         'Only Public project series can be packaged, not Embargoed.'):
         series.setPackaging(
             sp.distroseries, sp.sourcepackagename, series.owner)
Beispiel #28
0
 def test_raises_integrity_error_if_reconnecting_fails(self):
     # Here we test a corner case: we test that the DB refuses to
     # leave an interface without a VLAN in case the reconnection
     # fails when a VLAN is deleted.
     vlan = factory.make_VLAN()
     # Break 'manage_connected_interfaces'.
     self.patch(vlan, 'manage_connected_interfaces')
     factory.make_Interface(INTERFACE_TYPE.PHYSICAL, vlan=vlan)
     with ExpectedException(ProtectedError):
         vlan.delete()
Beispiel #29
0
    def test_delete_container(self):
        account_id = 'test'
        self.assertEqual(self.backend.create_account(account_id), account_id)
        name = 'c'
        old_mtime = Timestamp(time() - 1).normal
        mtime = Timestamp(time()).normal

        # initial container
        self.backend.update_container(account_id, name, mtime, 0, 0, 0, 0, 0)
        res = self.backend.conn.zrangebylex('containers:%s' % account_id, '-',
                                            '+')
        self.assertEqual(res[0], name)

        # delete event
        sleep(.00001)
        dtime = Timestamp(time()).normal
        self.backend.update_container(account_id, name, mtime, dtime, 0, 0, 0,
                                      0)
        res = self.backend.conn.zrangebylex('containers:%s' % account_id, '-',
                                            '+')
        self.assertEqual(len(res), 0)
        self.assertTrue(
            self.backend.conn.ttl('container:%s:%s' % (account_id, name)) >= 1)

        # same event
        with ExpectedException(Conflict):
            self.backend.update_container(account_id, name, mtime, dtime, 0, 0,
                                          0, 0)
        res = self.backend.conn.zrangebylex('containers:%s' % account_id, '-',
                                            '+')
        self.assertEqual(len(res), 0)
        self.assertTrue(
            self.backend.conn.ttl('container:%s:%s' % (account_id, name)) >= 1)

        # old event
        with ExpectedException(Conflict):
            self.backend.update_container(account_id, name, old_mtime, 0, 0, 0,
                                          0, 0)
        res = self.backend.conn.zrangebylex('containers:%s' % account_id, '-',
                                            '+')
        self.assertEqual(len(res), 0)
        self.assertTrue(
            self.backend.conn.ttl('container:%s:%s' % (account_id, name)) >= 1)
Beispiel #30
0
 def test_handles_fails_to_complete_power_action_in_time(self):
     system_id = factory.make_name("system_id")
     context = {"context": factory.make_name("context")}
     driver = make_power_driver(wait_time=[0])
     self.patch(driver, self.action_func)
     mock_query = self.patch(driver, "power_query")
     mock_query.return_value = self.bad_state
     method = getattr(driver, self.action)
     with ExpectedException(PowerError):
         yield method(system_id, context)