예제 #1
0
 def test_compose_preseed_for_commissioning_node_produces_yaml(self):
     rack_controller = factory.make_RackController()
     node = factory.make_Node(interface=True,
                              status=NODE_STATUS.COMMISSIONING)
     nic = node.get_boot_interface()
     nic.vlan.dhcp_on = True
     nic.vlan.primary_rack = rack_controller
     nic.vlan.save()
     request = make_HttpRequest()
     apt_proxy = get_apt_proxy(request, node.get_boot_rack_controller())
     preseed = yaml.safe_load(
         compose_preseed(request, PRESEED_TYPE.COMMISSIONING, node))
     self.assertIn("datasource", preseed)
     self.assertIn("MAAS", preseed["datasource"])
     self.assertThat(
         preseed["datasource"]["MAAS"],
         KeysEqual("metadata_url", "consumer_key", "token_key",
                   "token_secret"),
     )
     self.assertThat(
         preseed["reporting"]["maas"],
         KeysEqual("consumer_key", "endpoint", "token_key", "token_secret",
                   "type"),
     )
     self.assertThat(preseed["rsyslog"]["remotes"], KeysEqual("maas"))
     self.assertAptConfig(preseed, apt_proxy)
예제 #2
0
 def test_compose_preseed_for_commissioning_node_produces_yaml(self):
     rack_controller = factory.make_RackController()
     node = factory.make_Node(interface=True,
                              status=NODE_STATUS.COMMISSIONING)
     nic = node.get_boot_interface()
     nic.vlan.dhcp_on = True
     nic.vlan.primary_rack = rack_controller
     nic.vlan.save()
     apt_proxy = get_apt_proxy(node.get_boot_rack_controller())
     preseed = yaml.safe_load(
         compose_preseed(PRESEED_TYPE.COMMISSIONING, node))
     self.assertIn('datasource', preseed)
     self.assertIn('MAAS', preseed['datasource'])
     self.assertThat(
         preseed['datasource']['MAAS'],
         KeysEqual('metadata_url', 'consumer_key', 'token_key',
                   'token_secret'))
     self.assertEqual(apt_proxy, preseed['apt_proxy'])
     self.assertThat(
         preseed['reporting']['maas'],
         KeysEqual('consumer_key', 'endpoint', 'token_key', 'token_secret',
                   'type'))
     self.assertThat(preseed['rsyslog']['remotes'], KeysEqual('maas'))
     self.assertSystemInfo(preseed)
     self.assertAptConfig(preseed, apt_proxy)
예제 #3
0
파일: test_api.py 프로젝트: rmyers/reddwarf
class RpcMsgMatcher(mockito.matchers.Matcher):
    def __init__(self, method, *args_dict):
        self.wanted_method = method
        self.wanted_dict = KeysEqual('version', 'method', 'args')
        self.args_dict = KeysEqual(*args_dict)

    def matches(self, arg):
        if self.wanted_method != arg['method']:
            return False
        if self.wanted_dict.match(arg) or self.args_dict.match(arg['args']):
            return False
        return True

    def __repr__(self):
        return "<Dict: %s>" % self.wanted_dict
예제 #4
0
    def test_teams_for_distro_with_bug_super(self):
        self._setup_teams(self.user)
        context = self.factory.makeDistribution(
            owner=self.user, members=self.bug_super_team)
        with person_logged_in(self.user):
            context.bug_supervisor = self.bug_super_team

        expose_user_administered_teams_to_js(self.request, self.user, context,
            absoluteURL=fake_absoluteURL)

        # The team information should have been added to the request.
        self.assertThat(self.request.objects, Contains('administratedTeams'))
        team_info = self._sort(self.request.objects['administratedTeams'])

        # Since the distro only returns teams that are members of the bug
        # supervisor team, we only expect two.
        expected_number_teams = 2
        self.assertThat(len(team_info), Equals(expected_number_teams))
        # The items info consist of a dictionary with link and title keys.
        for i in range(expected_number_teams):
            self.assertThat(
                team_info[i],
                KeysEqual('has_preferredemail', 'link', 'title', 'url'))
        # The link is the title of the team.
        self.assertThat(
            team_info[0]['title'],
            Equals(u'\u201cBug Supervisor Sub Team\u201d team'))
        self.assertThat(
            team_info[1]['title'],
            Equals(u'\u201cBug Supervisor Team\u201d team'))
        # The link is the API link to the team.
        self.assertThat(team_info[0]['link'],
            Equals(u'http://example.com/\u201cBugSupervisorSubTeam\u201dteam'))
예제 #5
0
    def test_teams_for_non_distro(self):
        # The expose_user_administered_teams_to_js function loads some data
        # about the teams the requesting user administers into the response to
        # be made available to JavaScript.

        context = self.factory.makeProduct(owner=self.user)
        self._setup_teams(self.user)

        expose_user_administered_teams_to_js(self.request, self.user, context,
            absoluteURL=fake_absoluteURL)

        # The team information should have been added to the request.
        self.assertThat(self.request.objects, Contains('administratedTeams'))
        team_info = self._sort(self.request.objects['administratedTeams'])
        # Since there are three teams, there should be three items in the
        # list of team info.
        expected_number_teams = 3
        self.assertThat(len(team_info), Equals(expected_number_teams))
        # The items info consist of a dictionary with link and title keys.
        for i in range(expected_number_teams):
            self.assertThat(
                team_info[i],
                KeysEqual('has_preferredemail', 'link', 'title', 'url'))
        # The link is the title of the team.
        self.assertThat(
            team_info[0]['title'],
            Equals(u'\u201cBug Supervisor Sub Team\u201d team'))
        self.assertThat(
            team_info[1]['title'],
            Equals(u'\u201cBug Supervisor Team\u201d team'))
        self.assertThat(
            team_info[2]['title'], Equals(u'\u201cUnrelated Team\u201d team'))
        # The link is the API link to the team.
        self.assertThat(team_info[0]['link'],
            Equals(u'http://example.com/\u201cBugSupervisorSubTeam\u201dteam'))
예제 #6
0
    def test_only_addError_once(self):
        # Even if the reactor is unclean and the test raises an error and the
        # cleanups raise errors, we only called addError once per test.
        reactor = self.make_reactor()

        class WhenItRains(TestCase):
            def it_pours(self):
                # Add a dirty cleanup.
                self.addCleanup(lambda: 3 / 0)
                # Dirty the reactor.
                from twisted.internet.protocol import ServerFactory
                reactor.listenTCP(0, ServerFactory(), interface='127.0.0.1')
                # Unhandled error.
                defer.maybeDeferred(lambda: 2 / 0)
                # Actual error.
                raise RuntimeError("Excess precipitation")

        test = WhenItRains('it_pours')
        runner = self.make_runner(test)
        result = self.make_result()
        runner.run(result)
        self.assertThat([event[:2] for event in result._events],
                        Equals([('startTest', test), ('addError', test),
                                ('stopTest', test)]))
        error = result._events[1][2]
        self.assertThat(
            error,
            KeysEqual(
                'traceback',
                'traceback-1',
                'traceback-2',
                'twisted-log',
                'unhandled-error-in-deferred',
            ))
예제 #7
0
 def test_run_200(self):
     # A request that returns 200 is a success.
     with CaptureOops() as oopses:
         job, reqs = self.makeAndRunJob(response_status=200)
     self.assertThat(
         job,
         MatchesStructure(
             status=Equals(JobStatus.COMPLETED),
             pending=Is(False),
             successful=Is(True),
             date_sent=Not(Is(None)),
             error_message=Is(None),
             json_data=ContainsDict(
                 {'result': MatchesAll(
                     KeysEqual('request', 'response'),
                     ContainsDict(
                         {'response': ContainsDict(
                             {'status_code': Equals(200)})}))})))
     self.assertEqual(1, len(reqs))
     self.assertEqual([
         ('POST', 'http://example.com/ep',
          {'Content-Type': 'application/json',
           'User-Agent': 'launchpad.dev-Webhooks/r%s' % (
               versioninfo.revision),
           'X-Launchpad-Event-Type': 'test',
           'X-Launchpad-Delivery': str(job.job_id)}),
         ], reqs)
     self.assertEqual([], oopses.oopses)
예제 #8
0
    def test_unhandled_error_from_deferred_combined_with_error(self):
        # If there's a Deferred with an unhandled error, the test fails.  Each
        # unhandled error is reported with a separate traceback, and the error
        # is still reported.
        class SomeCase(TestCase):
            def test_cruft(self):
                # Note we aren't returning the Deferred so that the error will
                # be unhandled.
                defer.maybeDeferred(lambda: 1 / 0)
                2 / 0

        test = SomeCase('test_cruft')
        runner = self.make_runner(test)
        result = self.make_result()
        runner.run(result)
        error = result._events[1][2]
        result._events[1] = ('addError', test, None)
        self.assertThat(
            result._events,
            Equals([('startTest', test), ('addError', test, None),
                    ('stopTest', test)]))
        self.assertThat(
            error,
            KeysEqual(
                'traceback',
                'twisted-log',
                'unhandled-error-in-deferred',
            ))
예제 #9
0
    def test_compose_preseed_with_curtin_installer(self):
        rack_controller = factory.make_RackController(url="")
        node = factory.make_Node(interface=True, status=NODE_STATUS.DEPLOYING)
        nic = node.get_boot_interface()
        nic.vlan.dhcp_on = True
        nic.vlan.primary_rack = rack_controller
        nic.vlan.save()
        self.useFixture(RunningClusterRPCFixture())
        request = make_HttpRequest()
        expected_apt_proxy = get_apt_proxy(request,
                                           node.get_boot_rack_controller())
        preseed = yaml.safe_load(
            compose_preseed(request, PRESEED_TYPE.CURTIN, node))

        self.assertIn("datasource", preseed)
        self.assertIn("MAAS", preseed["datasource"])
        self.assertThat(
            preseed["datasource"]["MAAS"],
            KeysEqual("metadata_url", "consumer_key", "token_key",
                      "token_secret"),
        )
        self.assertDictEqual(
            {
                "delay": "now",
                "mode": "reboot",
                "timeout": 1800,
                "condition": "test ! -e /tmp/block-reboot",
            },
            preseed["power_state"],
        )
        self.assertEqual(
            request.build_absolute_uri(reverse("curtin-metadata")),
            preseed["datasource"]["MAAS"]["metadata_url"],
        )
        self.assertAptConfig(preseed, expected_apt_proxy)
예제 #10
0
    def test_yields_configuration_when_machine_install_rackd_true(self):
        node = factory.make_Node(osystem="ubuntu", netboot=False)
        node.install_rackd = True
        proxy = "http://proxy.example.com/"
        configuration = generate_rack_controller_configuration(
            node, proxy=proxy
        )
        secret = "1234"
        Config.objects.set_config("rpc_shared_secret", secret)
        channel = version.get_maas_version_track_channel()
        maas_url = "http://%s:5240/MAAS" % get_maas_facing_server_host(
            node.get_boot_rack_controller()
        )
        cmd = "/bin/snap/maas init --mode rack"

        self.assertThat(
            dict(configuration),
            KeysEqual(
                {
                    "runcmd": [
                        "snap set system proxy.http=%s proxy.https=%s"
                        % (proxy, proxy),
                        f"snap install maas --channel={channel}",
                        "%s --maas-url %s --secret %s"
                        % (cmd, maas_url, secret),
                    ]
                }
            ),
        )
예제 #11
0
    def test_teams_for_distro_with_no_bug_super(self):
        self._setup_teams(self.user)
        context = self.factory.makeDistribution(owner=self.user,
                                                members=self.bug_super_team)

        expose_user_administered_teams_to_js(self.request,
                                             self.user,
                                             context,
                                             absoluteURL=fake_absoluteURL)

        # The team information should have been added to the request.
        self.assertThat(self.request.objects, Contains('administratedTeams'))
        team_info = self.request.objects['administratedTeams']

        # Since the distro has no bug supervisor set, all administered teams
        # are returned.
        expected_number_teams = 3
        self.assertThat(len(team_info), Equals(expected_number_teams))
        # The items info consist of a dictionary with link and title keys.
        for i in range(expected_number_teams):
            self.assertThat(
                team_info[i],
                KeysEqual('has_preferredemail', 'link', 'title', 'url'))
        # The link is the unique display name of the team.
        self.assertThat(
            team_info[0]['title'],
            Equals(u'Bug Supervisor Sub Team (bug-supervisor-sub-team)'))
        self.assertThat(team_info[1]['title'],
                        Equals(u'Bug Supervisor Team (bug-supervisor-team)'))
        self.assertThat(team_info[2]['title'],
                        Equals(u'Unrelated Team (unrelated-team)'))
        # The link is the API link to the team.
        self.assertThat(team_info[0]['link'],
                        Equals(u'http://example.com/bug-supervisor-sub-team'))
예제 #12
0
 def test_makeService_not_in_debug(self):
     """
     Only the site service is created when no options are given.
     """
     self.patch(settings, "DEBUG", False)
     options = Options()
     service_maker = ProvisioningServiceMaker("Harry", "Hill")
     self.patch(service_maker, '_loadSettings')
     service = service_maker.makeService(options, clock=None)
     self.assertIsInstance(service, MultiService)
     expected_services = [
         "dhcp_probe",
         "networks_monitor",
         "image_download",
         "lease_socket_service",
         "node_monitor",
         "ntp",
         "rpc",
         "rpc-ping",
         "tftp",
         "http_image_service",
         "service_monitor",
     ]
     self.assertThat(service.namedServices, KeysEqual(*expected_services))
     self.assertEqual(len(service.namedServices), len(service.services),
                      "Not all services are named.")
     self.assertEqual(service, provisioningserver.services)
     self.assertThat(crochet.no_setup, MockCalledOnceWith())
     self.assertThat(
         logger.configure,
         MockCalledOnceWith(options["verbosity"],
                            logger.LoggingMode.TWISTD))
 def test_authenticate_default(self):
     """
     Verify that when we send a POST request to the authenticate endpoint
     with no username and password specified, we get a callback response,
     then when we respond to that with the callback filled in with the
     correct username and password, a response is returned with the tokenId
     """
     headers = {"Content-Type": "application/json"}
     response = requests.post(AUTHENTICATE_URI, headers=headers)
     self.assertThat(response.status_code, Equals(200))
     data = response.json()
     for idx, callback in enumerate(data['callbacks']):
         if callback['type'] == 'NameCallback':
             data['callbacks'][idx]['input'][0]['value'] = USERNAME
         if callback['type'] == 'PasswordCallback':
             data['callbacks'][idx]['input'][0]['value'] = PASSWORD
     response = requests.post(
         AUTHENTICATE_URI,
         data=json.dumps(data),
         headers=headers,
     )
     self.assertThat(response.status_code, Equals(200))
     self.assertThat(response.json(),
                     KeysEqual({
                         "successUrl": "",
                         "tokenId": "",
                     }))
예제 #14
0
    def test_compose_preseed_with_curtin_installer(self):
        rack_controller = factory.make_RackController(url='')
        node = factory.make_Node(interface=True, status=NODE_STATUS.DEPLOYING)
        nic = node.get_boot_interface()
        nic.vlan.dhcp_on = True
        nic.vlan.primary_rack = rack_controller
        nic.vlan.save()
        self.useFixture(RunningClusterRPCFixture())
        request = make_HttpRequest()
        expected_apt_proxy = get_apt_proxy(request,
                                           node.get_boot_rack_controller())
        preseed = yaml.safe_load(
            compose_preseed(request, PRESEED_TYPE.CURTIN, node))

        self.assertIn('datasource', preseed)
        self.assertIn('MAAS', preseed['datasource'])
        self.assertThat(
            preseed['datasource']['MAAS'],
            KeysEqual('metadata_url', 'consumer_key', 'token_key',
                      'token_secret'))
        self.assertDictEqual(
            {
                'delay': 'now',
                'mode': 'reboot',
                'timeout': 1800,
                'condition': 'test ! -e /tmp/block-reboot',
            }, preseed['power_state'])
        self.assertEqual(
            request.build_absolute_uri(reverse('curtin-metadata')),
            preseed['datasource']['MAAS']['metadata_url'])
        self.assertAptConfig(preseed, expected_apt_proxy)
    def test_unhandled_error_from_deferred(self):
        # If there's a Deferred with an unhandled error, the test fails.  Each
        # unhandled error is reported with a separate traceback.

        # We're interested in the behavior when debugging is disabled. When
        # debugging is enabled, we get more stack traces.
        self.useFixture(DebugTwisted(False))

        class SomeCase(TestCase):
            def test_cruft(self):
                # Note we aren't returning the Deferred so that the error will
                # be unhandled.
                defer.maybeDeferred(lambda: 1 / 0)
                defer.maybeDeferred(lambda: 2 / 0)

        test = SomeCase('test_cruft')
        runner = self.make_runner(test)
        result = self.make_result()
        runner.run(result)
        error = result._events[1][2]
        result._events[1] = ('addError', test, None)
        self.assertThat(
            result._events,
            Equals([('startTest', test), ('addError', test, None),
                    ('stopTest', test)]))
        self.assertThat(
            error,
            KeysEqual(
                'twisted-log',
                'unhandled-error-in-deferred',
                'unhandled-error-in-deferred-1',
            ))
예제 #16
0
    def test_yields_configuration_with_ubuntu(self):
        tag = factory.make_Tag(name="wedge100")
        node = factory.make_Node(osystem="ubuntu", netboot=False)
        node.tags.add(tag)
        configuration = generate_rack_controller_configuration(
            node, proxy="http://proxy.example.com/"
        )
        secret = "1234"
        Config.objects.set_config("rpc_shared_secret", secret)
        channel = version.get_maas_version_track_channel()
        maas_url = "http://%s:5240/MAAS" % get_maas_facing_server_host(
            node.get_boot_rack_controller()
        )
        cmd = "/bin/snap/maas init --mode rack"

        self.assertThat(
            dict(configuration),
            KeysEqual(
                {
                    "runcmd": [
                        f"snap install maas --channel={channel}",
                        "%s --maas-url %s --secret %s"
                        % (cmd, maas_url, secret),
                    ]
                }
            ),
        )
예제 #17
0
class RpcMsgMatcher(mockito.matchers.Matcher):
    def __init__(self, method, *args_dict):
        self.wanted_method = method
        self.wanted_dict = KeysEqual("version", "method", "args", "namespace")
        self.args_dict = KeysEqual(*args_dict)

    def matches(self, arg):
        if self.wanted_method != arg["method"]:
            raise Exception("Method does not match: %s != %s" % (self.wanted_method, arg["method"]))
            # return False
        if self.wanted_dict.match(arg) or self.args_dict.match(arg["args"]):
            raise Exception("Args do not match: %s != %s" % (self.args_dict, arg["args"]))
            # return False
        return True

    def __repr__(self):
        return "<Dict: %s>" % self.wanted_dict
예제 #18
0
 def test_compose_preseed_for_commissioning_node_produces_yaml(self):
     node = factory.make_node(status=NODE_STATUS.COMMISSIONING)
     preseed = yaml.safe_load(compose_preseed(node))
     self.assertIn('datasource', preseed)
     self.assertIn('MAAS', preseed['datasource'])
     self.assertThat(
         preseed['datasource']['MAAS'],
         KeysEqual(
             'metadata_url', 'consumer_key', 'token_key', 'token_secret'))
예제 #19
0
 def test_create_no_name(self):
     user = factory.make_User()
     handler = TokenHandler(user, {}, None)
     new_token = handler.create({})
     self.assertThat(new_token, KeysEqual("id", "key", "secret",
                                          "consumer"))
     event = Event.objects.get(type__level=AUDIT)
     self.assertIsNotNone(event)
     self.assertEqual(event.description, "Created token.")
예제 #20
0
 def test_includes_system_information_if_default_user(self):
     owner = factory.make_User()
     node = factory.make_Node(owner=owner, default_user=owner)
     vendor_data = get_vendor_data(node)
     self.assertThat(vendor_data, ContainsDict({
         "system_info": MatchesDict({
             "default_user": KeysEqual("name", "gecos"),
         }),
     }))
예제 #21
0
class RpcMsgMatcher(mockito.matchers.Matcher):
    def __init__(self, method, *args_dict):
        self.wanted_method = method
        self.wanted_dict = KeysEqual('version', 'method', 'args', 'namespace')
        self.args_dict = KeysEqual(*args_dict)

    def matches(self, arg):
        if self.wanted_method != arg['method']:
            raise Exception("Method does not match: %s != %s" %
                            (self.wanted_method, arg['method']))
            #return False
        if self.wanted_dict.match(arg) or self.args_dict.match(arg['args']):
            raise Exception("Args do not match: %s != %s" %
                            (self.args_dict, arg['args']))
            #return False
        return True

    def __repr__(self):
        return "<Dict: %s>" % self.wanted_dict
예제 #22
0
 def test_get(self):
     representation = self.webservice.get(self.webhook_url,
                                          api_version='devel').jsonBody()
     self.assertThat(
         representation,
         KeysEqual('active', 'date_created', 'date_last_modified',
                   'deliveries_collection_link', 'delivery_url',
                   'event_types', 'http_etag', 'registrant_link',
                   'resource_type_link', 'self_link', 'target_link',
                   'web_link'))
예제 #23
0
    def test_rpc_info_from_running_ipc_master(self):
        # Run the IPC master, IPC worker, and RPC service so the endpoints
        # are updated in the database.
        region = factory.make_RegionController()
        self.useFixture(MAASIDFixture(region.system_id))
        region.owner = factory.make_admin()
        region.save()
        # `workers` is only included so ipc-master will not actually get the
        # workers service because this test runs in all-in-one mode.
        self.useFixture(
            RegionEventLoopFixture(
                "ipc-master", "ipc-worker", "rpc", "workers"
            )
        )

        eventloop.start(master=True, all_in_one=True).wait(5)
        self.addCleanup(lambda: eventloop.reset().wait(5))

        getServiceNamed = eventloop.services.getServiceNamed
        ipcMaster = getServiceNamed("ipc-master")

        @wait_for(5)
        @inlineCallbacks
        def wait_for_startup():
            # Wait for the service to complete startup.
            yield ipcMaster.starting
            yield getServiceNamed("ipc-worker").starting
            yield getServiceNamed("rpc").starting
            # Force an update, because it's very hard to track when the
            # first iteration of the ipc-master service has completed.
            yield ipcMaster.update()

        wait_for_startup()

        response = self.client.get(reverse("rpc-info"))

        self.assertEqual("application/json", response["Content-Type"])
        info = json.loads(response.content.decode("unicode_escape"))
        self.assertThat(info, KeysEqual("eventloops"))
        self.assertThat(
            info["eventloops"],
            MatchesDict(
                {
                    # Each entry in the endpoints dict is a mapping from an
                    # event loop to a list of (host, port) tuples. Each tuple is
                    # a potential endpoint for connecting into that event loop.
                    eventloop.loop.name: MatchesSetwise(
                        *(
                            MatchesListwise((Equals(addr), is_valid_port))
                            for addr, _ in ipcMaster._getListenAddresses(5240)
                        )
                    )
                }
            ),
        )
예제 #24
0
파일: test_api.py 프로젝트: B-Rich/trove
class RpcMsgMatcher(object):
    def __init__(self, method, *args_dict):
        self.wanted_method = method
        self.wanted_dict = KeysEqual('version', 'method', 'args', 'namespace')
        args_dict = args_dict or [{}]
        self.args_dict = KeysEqual(*args_dict)

    def __eq__(self, arg):
        if self.wanted_method != arg['method']:
            raise Exception("Method does not match: %s != %s" %
                            (self.wanted_method, arg['method']))
            #return False
        if self.wanted_dict.match(arg) or self.args_dict.match(arg['args']):
            raise Exception("Args do not match: %s != %s" %
                            (self.args_dict, arg['args']))
            #return False
        return True

    def __repr__(self):
        return "<Dict: %s>" % self.wanted_dict
예제 #25
0
class TestKeysEqual(TestCase, TestMatchersInterface):

    matches_matcher = KeysEqual('foo', 'bar')
    matches_matches = [
        {
            'foo': 0,
            'bar': 1
        },
    ]
    matches_mismatches = [
        {},
        {
            'foo': 0
        },
        {
            'bar': 1
        },
        {
            'foo': 0,
            'bar': 1,
            'baz': 2
        },
        {
            'a': None,
            'b': None,
            'c': None
        },
    ]

    str_examples = [
        ("KeysEqual('foo', 'bar')", KeysEqual('foo', 'bar')),
    ]

    describe_examples = [
        ("['bar', 'foo'] does not match {'baz': 2, 'foo': 0, 'bar': 1}: "
         "Keys not equal", {
             'foo': 0,
             'bar': 1,
             'baz': 2
         }, KeysEqual('foo', 'bar')),
    ]
예제 #26
0
 def test_update(self):
     user = factory.make_User()
     handler = TokenHandler(user, {}, None)
     name = factory.make_name("name")
     token = create_auth_token(user, name)
     new_name = factory.make_name("name")
     updated_token = handler.update({"id": token.id, "name": new_name})
     self.assertThat(updated_token,
                     KeysEqual("id", "key", "secret", "consumer"))
     self.assertEqual(new_name, updated_token["consumer"]["name"])
     event = Event.objects.get(type__level=AUDIT)
     self.assertIsNotNone(event)
     self.assertEqual(event.description, "Modified consumer name of token.")
예제 #27
0
    def test_deferred_error(self):
        class SomeTest(TestCase):
            def test_something(self):
                return defer.maybeDeferred(lambda: 1 / 0)

        test = SomeTest('test_something')
        runner = self.make_runner(test)
        result = self.make_result()
        runner.run(result)
        self.assertThat([event[:2] for event in result._events],
                        Equals([('startTest', test), ('addError', test),
                                ('stopTest', test)]))
        error = result._events[1][2]
        self.assertThat(error, KeysEqual('traceback', 'twisted-log'))
예제 #28
0
    def test_compose_preseed_with_curtin_installer(self):
        node = factory.make_node(status=NODE_STATUS.READY)
        node.use_fastpath_installer()
        preseed = compose_preseed(node)

        preseed = yaml.safe_load(compose_preseed(node))
        self.assertIn('datasource', preseed)
        self.assertIn('MAAS', preseed['datasource'])
        self.assertThat(
            preseed['datasource']['MAAS'],
            KeysEqual(
                'metadata_url', 'consumer_key', 'token_key', 'token_secret'))
        self.assertEqual(
            absolute_reverse('curtin-metadata'),
            preseed['datasource']['MAAS']['metadata_url'])
예제 #29
0
    def test_log_in_details(self):
        class LogAnError(TestCase):
            def test_something(self):
                log.msg("foo")
                1 / 0

        test = LogAnError('test_something')
        runner = self.make_runner(test)
        result = self.make_result()
        runner.run(result)
        self.assertThat([event[:2] for event in result._events],
                        Equals([('startTest', test), ('addError', test),
                                ('stopTest', test)]))
        error = result._events[1][2]
        self.assertThat(error, KeysEqual('traceback', 'twisted-log'))
예제 #30
0
 def test_JsonModel_custom_cache(self):
     # Adding an item to the cache in the initialize method results in it
     # being in the cache.
     class ProductModelTestView(BaseProductModelTestView):
         def initialize(self):
             request = get_current_browser_request()
             target_info = {}
             target_info['title'] = "The Title"
             cache = IJSONRequestCache(request).objects
             cache['target_info'] = target_info
     lp.services.webapp.tests.ProductModelTestView = \
         ProductModelTestView
     self.configZCML()
     browser = self.getUserBrowser(self.url)
     cache = loads(browser.contents)
     self.assertThat(
         cache, KeysEqual('related_features', 'context', 'target_info'))
 def test_authenticate_default(self):
     """
     Verify that the correct username and password combination
     gives a succesful response with the correct fields.
     """
     headers = {
         OPENAM_USERNAME_HEADER: USERNAME,
         OPENAM_PASSWORD_HEADER: PASSWORD,
         "Content-Type": "application/json",
     }
     response = requests.post(AUTHENTICATE_URI, headers=headers)
     self.assertThat(response.status_code, Equals(200))
     # verify that the response has the right fields
     self.assertThat(response.json(),
                     KeysEqual({
                         "successUrl": "",
                         "tokenId": "",
                     }))
예제 #32
0
 def assertRecipientsEqual(self, expected, changes, blamer, maintainer,
                           changer, purpose=ArchivePurpose.PRIMARY):
     distribution = self.factory.makeDistribution()
     archive = self.factory.makeArchive(
         distribution=distribution, purpose=purpose)
     distroseries = self.factory.makeDistroSeries(distribution=distribution)
     # Now set the uploaders.
     component = getUtility(IComponentSet).ensure('main')
     if component not in distroseries.components:
         self.factory.makeComponentSelection(
             distroseries=distroseries, component=component)
     distribution.main_archive.newComponentUploader(maintainer, component)
     distribution.main_archive.newComponentUploader(changer, component)
     info = fetch_information(None, None, changes)
     observed, _ = PackageUploadMailer.getRecipientsForAction(
         'accepted', info, blamer, None, [], archive, distroseries,
         PackagePublishingPocket.RELEASE)
     self.assertThat(observed, KeysEqual(*expected))
예제 #33
0
    def test_clean_reactor(self):
        # If there's cruft left over in the reactor, the test fails.
        reactor = self.make_reactor()
        timeout = self.make_timeout()

        class SomeCase(TestCase):
            def test_cruft(self):
                reactor.callLater(timeout * 10.0, lambda: None)

        test = SomeCase('test_cruft')
        runner = self.make_runner(test, timeout)
        result = self.make_result()
        runner.run(result)
        self.assertThat([event[:2] for event in result._events],
                        Equals([('startTest', test), ('addError', test),
                                ('stopTest', test)]))
        error = result._events[1][2]
        self.assertThat(error, KeysEqual('traceback', 'twisted-log'))
예제 #34
0
파일: test_api.py 프로젝트: B-Rich/trove
 def __init__(self, method, *args_dict):
     self.wanted_method = method
     self.wanted_dict = KeysEqual('version', 'method', 'args', 'namespace')
     args_dict = args_dict or [{}]
     self.args_dict = KeysEqual(*args_dict)
예제 #35
0
파일: test_api.py 프로젝트: rmyers/reddwarf
 def __init__(self, method, *args_dict):
     self.wanted_method = method
     self.wanted_dict = KeysEqual('version', 'method', 'args')
     self.args_dict = KeysEqual(*args_dict)
예제 #36
0
 def __init__(self, method, *args_dict):
     self.wanted_method = method
     self.wanted_dict = KeysEqual("version", "method", "args", "namespace")
     self.args_dict = KeysEqual(*args_dict)