Example #1
0
    def test_cron_status_multiple_jobs(self):
        (mock_api, mock_scheduler_proxy) = self.create_mock_api()
        with contextlib.nested(
            patch("time.sleep"),
            patch("apache.aurora.client.api.SchedulerProxy", return_value=mock_scheduler_proxy),
            patch("apache.aurora.client.factory.CLUSTERS", new=self.TEST_CLUSTERS),
            patch("apache.aurora.client.cli.context.AuroraCommandContext.print_out"),
        ) as (_, _, _, mock_print):
            response = self.create_simple_success_response()
            response.result = Mock()
            response.result.getJobsResult = Mock()
            mockjob1 = Mock()
            mockjob1.cronSchedule = "* * * * *"
            mockjob1.key = Mock()
            mockjob1.key.environment = "test"
            mockjob1.key.name = "hello2"
            mockjob1.key.role = "bozo"
            mockjob2 = Mock()
            mockjob2.cronSchedule = "* * * * *"
            mockjob2.key = Mock()
            mockjob2.key.environment = "test"
            mockjob2.key.name = "hello"
            mockjob2.key.role = "bozo"
            response.result.getJobsResult.configs = [mockjob1, mockjob2]
            mock_scheduler_proxy.getJobs.return_value = response

            cmd = AuroraCommandLine()
            result = cmd.execute(["cron", "show", "west/bozo/test/hello"])

            assert result == EXIT_OK
            mock_scheduler_proxy.getJobs.assert_called_once_with("bozo")
            mock_print.assert_called_with("west/bozo/test/hello\t * * * * *")
Example #2
0
    def test_on_snapshot_loaded(self):
        m_response = Mock()

        endpoint_on_host = Mock()
        endpoint_on_host.key = "/calico/v1/host/hostname/workload/" "orch/wlid/endpoint/epid"
        endpoint_on_host.value = ENDPOINT_STR

        bad_endpoint_on_host = Mock()
        bad_endpoint_on_host.key = "/calico/v1/host/hostname/workload/" "orch/wlid/endpoint/epid2"
        bad_endpoint_on_host.value = ENDPOINT_STR[:10]

        endpoint_not_on_host = Mock()
        endpoint_not_on_host.key = "/calico/v1/host/other/workload/" "orch/wlid/endpoint/epid"
        endpoint_not_on_host.value = ENDPOINT_STR

        still_ready = Mock()
        still_ready.key = "/calico/v1/Ready"
        still_ready.value = "true"

        m_response.children = [endpoint_on_host, bad_endpoint_on_host, endpoint_not_on_host, still_ready]
        with patch.object(self.watcher, "clean_up_endpoint_statuses") as m_clean:
            self.watcher._on_snapshot_loaded(m_response)

        # Cleanup should only get the endpoints on our host.
        m_clean.assert_called_once_with(set([EndpointId("hostname", "orch", "wlid", "epid")]))
    def test_should_return_number_of_cores_when_in_resources(self):
        resource_1 = Mock()
        resource_1.key = "weLoveCamelCase"
        resource_2 = Mock()
        resource_2.key = "numCpuCores"
        resource_2.value = 42
        resource_3 = Mock()
        resource_3.key = "someOtherKey"

        resources = [resource_1, resource_2, resource_3]
        self.raw_esx.licensableResource.resource = resources

        self.assertEquals(self.wrapped_esx.get_number_of_cores(), 42)
    def test_repo_groups(self):
        line_evaluator = Mock()
        line_evaluator.key = "line"
        line_evaluator.matches = Mock(return_value=True)

        rule = Mock()
        rule.name = "os_code_exec::python"
        rule.evaluators = [line_evaluator]

        junk_repo = Mock()
        junk_repo.name = "junk"
        local_repo = Mock()
        local_repo.name = "tooling"

        repo_groups = {"skipped_repos": ["junk"], "local_repos": ["tooling"]}
        rules_to_groups = {
            "skipped_repos": [{"except": ".*"}],
            "local_repos": [{"match": ".*"}, {"except": "os_code_exec::.*"}],
        }

        code_checker = CodeChecker(
            context_processors=[], rules=[rule], repo_groups=repo_groups, rules_to_groups=rules_to_groups
        )
        check_context = {"filename": "macbeth.txt"}

        self.assertEquals(code_checker.check(lines=self.code, context=check_context, repo=junk_repo), [])
        self.assertEquals(code_checker.check(lines=self.code, context=check_context, repo=local_repo), [])
Example #5
0
 def test_request_token_fake(self):
     """Try with a phony consumer key"""
     c = Mock()
     c.key = "yer"
     c.secret = "mom"
     r = client.get("oauth.request_token", c)
     eq_(r.content, "Invalid consumer.")
Example #6
0
 def test_request_token_fake(self):
     c = Mock()
     c.key = self.accepted_consumer.key
     c.secret = "mom"
     self.client = OAuthClient(c)
     res = self.client.get(self.url)
     eq_(res.status_code, 401)
 def create_getjobs_response(cls):
     result = cls.create_simple_success_response()
     result.result = Mock()
     result.result.getJobsResult = Mock()
     mock_job_one = Mock()
     mock_job_one.key = Mock()
     mock_job_one.key.role = "RoleA"
     mock_job_one.key.environment = "test"
     mock_job_one.key.name = "hithere"
     mock_job_two = Mock()
     mock_job_two.key = Mock()
     mock_job_two.key.role = "bozo"
     mock_job_two.key.environment = "test"
     mock_job_two.key.name = "hello"
     result.result.getJobsResult.configs = [mock_job_one, mock_job_two]
     return result
def mock_read_4_endpoints(path, recursive):
    assert path == ALL_ENDPOINTS_PATH
    assert recursive
    leaves = []

    specs = [
        (CALICO_V_PATH + "/host/TEST_HOST/bird_ip", "192.168.1.1"),
        (CALICO_V_PATH + "/host/TEST_HOST/bird6_ip", "fd80::4"),
        (CALICO_V_PATH + "/host/TEST_HOST/config/marker", "created"),
        (CALICO_V_PATH + "/host/TEST_HOST/workload/docker/1234/endpoint/567890abcdef", EP_56.to_json()),
        (CALICO_V_PATH + "/host/TEST_HOST/workload/docker/5678/endpoint/90abcdef1234", EP_90.to_json()),
        (CALICO_V_PATH + "/host/TEST_HOST2/bird_ip", "192.168.1.2"),
        (CALICO_V_PATH + "/host/TEST_HOST2/bird6_ip", "fd80::3"),
        (CALICO_V_PATH + "/host/TEST_HOST2/config/marker", "created"),
        (CALICO_V_PATH + "/host/TEST_HOST2/workload/docker/1234/endpoint/7890abcdef12", EP_78.to_json()),
        (CALICO_V_PATH + "/host/TEST_HOST2/workload/docker/5678/endpoint/1234567890ab", EP_12.to_json()),
    ]
    for spec in specs:
        leaf = Mock(spec=EtcdResult)
        leaf.key = spec[0]
        leaf.value = spec[1]
        leaves.append(leaf)

    result = Mock(spec=EtcdResult)
    result.leaves = iter(leaves)
    return result
Example #9
0
 def test_pinned_requirement(self):
     req = Mock()
     req.key = "django"
     req.is_pinned = True
     req.latest_version_within_specs = "1.10"
     req.version = "1.0"
     self.assertEqual(Update.get_commit_message(req), "Update django from 1.0 to 1.10")
Example #10
0
 def test_requirement_pinned(self):
     req = Mock()
     req.key = "django"
     req.is_pinned = True
     req.latest_version_within_specs = "1.10"
     req.version = "1.0"
     self.assertEqual(SequentialUpdate.get_branch(req), "pyup-update-django-1.0-to-1.10")
Example #11
0
 def fetch_access_token(self, *args, **kwargs):
     if self.error:
         raise self.error("")
     response = Mock(["key", "secret"])
     response.key = self.key
     response.secret = self.secret
     return response
 def create_mock_jobs(cls):
     jobs = []
     for name in ["foo", "bar", "baz"]:
         job = Mock()
         job.key = JobKey(role=cls.TEST_ROLE, environment=cls.TEST_ENV, name=name)
         jobs.append(job)
     return jobs
    def test_filter_nonmatching_file_rules(self):
        file_evaluator = Mock()
        file_evaluator.key = "file"
        file_evaluator.matches = Mock(return_value=False)
        line_evaluator = Mock()
        line_evaluator.key = "line"
        line_evaluator.matches = Mock(return_value=False)
        rule = Mock()
        rule.name = "test"
        rule.evaluators = [file_evaluator, line_evaluator]
        code_checker = CodeChecker([], [rule])

        alert = code_checker.check(self.code, {"filename": "macbeth.txt"})

        self.assertEquals(1, file_evaluator.matches.call_count)
        self.assertEquals(0, line_evaluator.matches.call_count)
Example #14
0
 def create_mock_scheduled_tasks(cls):
     jobs = []
     for name in ["foo", "bar", "baz"]:
         job = Mock()
         job.key = JobKey(role=cls.TEST_ROLE, environment=cls.TEST_ENV, name=name)
         job.failure_count = 0
         job.assignedTask = Mock(spec=AssignedTask)
         job.assignedTask.slaveHost = "slavehost"
         job.assignedTask.task = Mock(spec=TaskConfig)
         job.assignedTask.task.maxTaskFailures = 1
         job.assignedTask.task.executorConfig = Mock(spec=ExecutorConfig)
         job.assignedTask.task.executorConfig.data = Mock()
         job.assignedTask.task.packages = []
         job.assignedTask.task.owner = Identity(role="mchucarroll")
         job.assignedTask.task.environment = "test"
         job.assignedTask.task.jobName = "woops"
         job.assignedTask.task.numCpus = 2
         job.assignedTask.task.ramMb = 2
         job.assignedTask.task.diskMb = 2
         job.assignedTask.instanceId = 4237894
         job.assignedTask.assignedPorts = None
         job.status = ScheduleStatus.RUNNING
         mockEvent = Mock(spec=TaskEvent)
         mockEvent.timestamp = 28234726395
         mockEvent.status = ScheduleStatus.RUNNING
         mockEvent.message = "Hi there"
         job.taskEvents = [mockEvent]
         jobs.append(job)
     return jobs
Example #15
0
 def test_request_token_fake(self):
     c = Mock()
     c.key = self.access.key
     c.secret = "mom"
     res = self.auth.is_authenticated(self.call(client=OAuthClient(c)))
     eq_(res.status_code, 401)
     eq_(json.loads(res.content)["reason"], errors["headers"])
Example #16
0
 def test_exec_config_with_set_workspaces(self):
     """Test exec config with set workspaces subcommand."""
     args = Mock()
     args.action = "set"
     args.key = "workspaces"
     args.value = False
     self.assertFalse(self.subcommand.execute(args))
Example #17
0
 def test_request_token_fake(self):
     c = Mock()
     c.key = self.access.key
     c.secret = "mom"
     self.client = OAuthClient(c)
     res = self.client.get(self.url)
     eq_(res.status_code, 401)
     eq_(json.loads(res.content)["reason"], errors["headers"])
Example #18
0
 def create_getjobs_response(cls):
     result = Mock(spec=Response)
     result.responseCode = ResponseCode.OK
     result.result = Mock(spec=Result)
     result.result.getJobsResult = Mock(spec=GetJobsResult)
     mock_job_one = Mock(spec=JobConfiguration)
     mock_job_one.key = Mock(spec=JobKey)
     mock_job_one.key.role = "RoleA"
     mock_job_one.key.environment = "test"
     mock_job_one.key.name = "hithere"
     mock_job_two = Mock(spec=JobConfiguration)
     mock_job_two.key = Mock(spec=JobKey)
     mock_job_two.key.role = "bozo"
     mock_job_two.key.environment = "test"
     mock_job_two.key.name = "hello"
     result.result.getJobsResult.configs = [mock_job_one, mock_job_two]
     return result
Example #19
0
    def test_get_stack_parameters_dict_returns_proper_dict(self, _, get_stack_mock):
        cfn = CloudFormation()

        parameter_1 = Mock()
        parameter_1.key = "myKey1"
        parameter_1.value = "myValue1"
        parameter_2 = Mock()
        parameter_2.key = "myKey2"
        parameter_2.value = "myValue2"

        stack_mock = Mock()
        stack_mock.parameters = [parameter_1, parameter_2]
        get_stack_mock.return_value = stack_mock

        result = cfn.get_stack_parameters_dict("foo")

        self.assertDictEqual({"myKey1": "myValue1", "myKey2": "myValue2"}, result)
Example #20
0
 def test_cover_no_match(self):
     m_result = Mock(spec=etcd.EtcdResult)
     m_result.key = "/a"
     m_result.action = "unknown"
     self.dispatcher.handle_event(m_result)
     for handlers in self.handlers.itervalues():
         for key, handler in handlers.iteritems():
             self.assertFalse(handler.called, msg="Unexpected handler called: %s" % key)
Example #21
0
 def test_exec_config_with_set(self):
     """Test exec config with set subcommand."""
     args = Mock()
     args.action = "set"
     args.key = "logfile"
     args.value = "/tmp/yoda.log"
     self.subcommand.execute(args)
     self.assertEqual("/tmp/yoda.log", self.config["logfile"])
Example #22
0
    def test_clean_up_endpoint_status(self):
        self.m_config.REPORT_ENDPOINT_STATUS = True
        ep_id = EndpointId("foo", "openstack", "workloadid", "endpointid")

        empty_dir = Mock()
        empty_dir.key = "/calico/felix/v1/host/foo/workload/" "openstack/foobar"
        empty_dir.dir = True

        missing_ep = Mock()
        missing_ep.key = "/calico/felix/v1/host/foo/workload/" "openstack/aworkload/endpoint/anendpoint"

        self.m_client.read.return_value.leaves = [empty_dir, missing_ep]
        with patch.object(self.rep, "_mark_endpoint_dirty") as m_mark:
            self.rep.clean_up_endpoint_statuses(async=True)
            self.step_actor(self.rep)

            # Missing endpoint should have been marked for cleanup.
            m_mark.assert_called_once_with(EndpointId("foo", "openstack", "aworkload", "anendpoint"))
Example #23
0
 def dispatch(self, key, action, value=None):
     """
     Send an EtcdResult to the watcher's dispatcher.
     """
     m_response = Mock(spec=EtcdResult)
     m_response.key = key
     m_response.action = action
     m_response.value = value
     self.watcher.dispatcher.handle_event(m_response)
 def mock_read_get_endpoint(path, recursive=None):
     assert recursive
     assert path == TEST_ENDPOINT_PATH
     leaf = Mock(spec=EtcdResult)
     leaf.key = TEST_ENDPOINT_PATH
     leaf.value = ep.to_json()
     result = Mock(spec=EtcdResult)
     result.leaves = iter([leaf])
     return result
Example #25
0
    def test_clean_up_endpoint_status(self):
        self.m_config.REPORT_ENDPOINT_STATUS = True
        ep_id = EndpointId("hostname", "openstack", "workloadid", "endpointid")

        empty_dir = Mock()
        empty_dir.key = "/calico/felix/v1/host/hostname/workload/" "openstack/foobar"
        empty_dir.dir = True

        missing_ep = Mock()
        missing_ep.key = "/calico/felix/v1/host/hostname/workload/" "openstack/aworkload/endpoint/anendpoint"

        self.client.read.return_value.leaves = [empty_dir, missing_ep]
        self.watcher.clean_up_endpoint_statuses(set([ep_id]))

        # Missing endpoint should have been marked for cleanup.
        self.m_status_rep.mark_endpoint_dirty.assert_called_once_with(
            EndpointId("hostname", "openstack", "aworkload", "anendpoint"), async=True
        )
Example #26
0
 def test_add_with_empty(self):
     update = Update([])
     req_file = Mock()
     req = Mock()
     req.key = "django"
     req.is_pinned = False
     req.latest_version_within_specs = "1.10"
     update.add(req, req_file)
     self.assertEqual("django-pin" in update, True)
     self.assertEqual(len(update["django-pin"]), 1)
    def test_evaluators_called(self):
        evaluator = Mock()
        evaluator.key = "line"
        evaluator.matches = Mock(return_value=False)
        rule = Mock()
        rule.name = "test"
        rule.evaluators = [evaluator]
        code_checker = CodeChecker([], [rule])

        alert = code_checker.check(self.code, {"filename": "macbeth.txt"})

        self.assertEquals(len(self.code), evaluator.matches.call_count)
Example #28
0
 def _create_getjobs_response(cls):
     response = cls.create_simple_success_response()
     response.result = Mock()
     response.result.getJobsResult = Mock()
     mockjob = Mock()
     mockjob.cronSchedule = "* * * * *"
     mockjob.key = Mock()
     mockjob.key.environment = "test"
     mockjob.key.name = "hello"
     mockjob.key.role = "bozo"
     response.result.getJobsResult.configs = [mockjob]
     return response
    def test_long_lines(self):
        line_evaluator = Mock()
        line_evaluator.key = "line"
        line_evaluator.matches = Mock(return_value=True)
        rule = Mock()
        rule.name = "test"
        rule.evaluators = [line_evaluator]
        code_checker = CodeChecker([], [rule])
        code = ["l0", "X" * 513, "l2"]

        alerts = code_checker.check(code, {"filename": "macbeth.txt"})

        self.assertEquals(len(code) - 1, len(alerts))
Example #30
0
    def setUp(self):
        # mock request object
        request = Request()
        request.method = "GET"
        request.url = "http://example.com/"
        request.headers = {}
        request.params = {}
        request.data = {}
        request.params_and_data = {}
        self.request = request

        # mock consumer object
        consumer = Mock()
        consumer.key = "123"
        consumer.secret = "456"
        self.consumer = consumer

        # mock token object
        token = Mock()
        token.key = "321"
        token.secret = "456"
        self.token = token