示例#1
0
 def test_download_seed_to_folder(self,
                                  requests_get: unittest.mock.MagicMock):
     """
     Test if the Building process works.
     """
     chunks = [b"a", b"b", b"c"]
     md5_hash_chunk = "900150983cd24fb0d6963f7d28e17f72"  # The md5 hash of all the chunks saved together as string
     response_mock = unittest.mock.MagicMock()
     response_mock.iter_content.return_value = iter(chunks)
     requests_get.return_value = response_mock
     tmp_dir = "tmp/"
     if os.path.isdir(tmp_dir):
         shutil.rmtree(tmp_dir)
     os.mkdir(tmp_dir)
     download_link = "somerandomlink"  # Link not important, we have mocked the response
     filename = "Makefile"
     # This file should exists now:
     self.assertTrue(
         utils.download_seed_to_folder(download_link=download_link,
                                       to_directory=tmp_dir,
                                       filename=filename))
     self.assertTrue(os.path.isfile(tmp_dir + "/" + filename))
     self.assertEqual(utils.md5(tmp_dir + "/" + filename), md5_hash_chunk)
     # We are simulating a reponse that would be the exact same file again: Should not be downloaded.
     response_mock.iter_content.return_value = (chunks)
     self.assertFalse(
         utils.download_seed_to_folder(download_link=download_link,
                                       to_directory=tmp_dir,
                                       filename=filename + "_new"))
     self.assertFalse(os.path.exists(tmp_dir + "/" + filename + "_new"))
     shutil.rmtree(tmp_dir)
示例#2
0
    def test_try_filetype_with_coverage_via_afl_fail(
            self, subprocess_check_output: unittest.mock.MagicMock):
        binary_path = "tshark"
        repo_path = ""
        max_timeout = 2500
        memory_limit = "none"

        h = HeuristicConfigCreator(binary_path=binary_path,
                                   repo_path=repo_path,
                                   dummyfiles_path=os.getcwd())
        h.MAX_TIMEOUT = max_timeout
        h.memory_limit = memory_limit
        h.FAILED_INVOCATIONS_THRESHOLD = 2
        h.afl_cmin_path = "afl-cmin"
        mocked_return_value = "cmin-output"
        subprocess_check_output.return_value = bytes(mocked_return_value,
                                                     encoding="utf-8")
        subprocess_check_output.side_effect = subprocess.CalledProcessError(
            returncode=-1, cmd="alja")
        h.try_filetype_with_coverage_via_afl("-f",
                                             os.getcwd(),
                                             file_type=".test")
        with self.assertRaises(helpers.exceptions.NoCoverageInformation):
            h.try_filetype_with_coverage_via_afl("-g",
                                                 os.getcwd(),
                                                 file_type=".test")
示例#3
0
    def test_build_jobs(self, mock_cpu_count: unittest.mock.MagicMock) -> None:
        """Tests that the number of build jobs comes out correctly."""
        mock_cpu_count.return_value = 13
        cases = [
            # MAX_JOBS, USE_NINJA, IS_WINDOWS,         want
            ((     '8',      True,     False),          ['-j', '8']),  # noqa: E201,E241
            ((    None,      True,     False),                 None),  # noqa: E201,E241
            ((     '7',     False,     False),          ['-j', '7']),  # noqa: E201,E241
            ((    None,     False,     False),         ['-j', '13']),  # noqa: E201,E241
            ((     '6',      True,      True),          ['-j', '6']),  # noqa: E201,E241
            ((    None,      True,      True),                 None),  # noqa: E201,E241
            ((    '11',     False,      True), ['/p:CL_MPCount=11']),  # noqa: E201,E241
            ((    None,     False,      True), ['/p:CL_MPCount=13']),  # noqa: E201,E241
        ]
        for (max_jobs, use_ninja, is_windows), want in cases:
            with self.subTest(MAX_JOBS=max_jobs, USE_NINJA=use_ninja, IS_WINDOWS=is_windows):
                with contextlib.ExitStack() as stack:
                    stack.enter_context(env_var('MAX_JOBS', max_jobs))
                    stack.enter_context(unittest.mock.patch.object(tools.setup_helpers.cmake, 'USE_NINJA', use_ninja))
                    stack.enter_context(unittest.mock.patch.object(tools.setup_helpers.cmake, 'IS_WINDOWS', is_windows))

                    cmake = tools.setup_helpers.cmake.CMake()

                    with unittest.mock.patch.object(cmake, 'run') as cmake_run:
                        cmake.build({})

                    cmake_run.assert_called_once()
                    call, = cmake_run.mock_calls
                    build_args, _ = call.args

                if want is None:
                    self.assertNotIn('-j', build_args)
                else:
                    self.assert_contains_sequence(build_args, want)
示例#4
0
    def test_try_to_query_status_from_reputation(
        self, reputation_checker_path: unittest.mock.MagicMock
    ) -> None:
        """
        Tests of the method that tries to define the status from the reputation
        checker.
        """

        self.checker.subject = "192.168.1.1"

        reputation_checker_path.return_value = ReputationCheckerStatus(
            subject="192.168.1.1",
            idna_subject="192.168.1.1",
            status="SANE",
            status_source="REPUTATION",
            tested_at=datetime.utcnow(),
        )

        self.checker.try_to_query_status_from_reputation()

        expected_status = None
        actual_status = self.checker.status.status

        self.assertEqual(expected_status, actual_status)

        reputation_checker_path.return_value = ReputationCheckerStatus(
            subject="192.168.1.1",
            idna_subject="192.168.1.1",
            status="MALICIOUS",
            status_source="REPUTATION",
            tested_at=datetime.utcnow(),
        )

        self.checker.try_to_query_status_from_reputation()

        expected_status = "ACTIVE"
        actual_status = self.checker.status.status

        self.assertEqual(expected_status, actual_status)

        expected_source = "REPUTATION"
        actual_source = self.checker.status.status_source

        self.assertEqual(expected_source, actual_source)
示例#5
0
    def test_get_current(self, getcwd_path: unittest.mock.MagicMock) -> None:
        """
        Tests the method which let us get the current directory.
        """

        getcwd_path.return_value = "/hello/world"

        expected = "/hello/world"
        actual = self.helper.get_current()

        self.assertEqual(expected, actual)
示例#6
0
 def test_invoke_afl_cmin(self, subprocess_check_output: unittest.mock.MagicMock):
     binary_path = "tshark"
     repo_path = ""
     max_timeout = 2500
     memory_limit = "none"
     h = HeuristicConfigCreator(binary_path=binary_path, repo_path=repo_path, dummyfile_path=__file__,
                                dummyfiles_path=os.getcwd())
     h.MAX_TIMEOUT = max_timeout
     h.memory_limit = memory_limit
     h.afl_cmin_path = "afl-cmin"
     mocked_return_value = "cmin-output"
     subprocess_check_output.return_value = bytes(mocked_return_value, encoding="utf-8")
     self.assertEqual(h.invoke_afl_cmin("-f", "tmp_dir"), mocked_return_value)
示例#7
0
    def test_query_dns_record_ptr(
            self, dns_query_patch: unittest.mock.MagicMock) -> None:
        """
        Tests the method that let us query the (right) DNS record of the given
        subject.
        """

        dns_query_patch.return_value = ["example.org"]
        given = "192.168.1.1"
        expected = {"PTR": ["example.org"]}

        self.checker.subject = given

        actual = self.checker.query_dns_record()

        self.assertEqual(expected, actual)
示例#8
0
    def test_get_current_with_sep(
            self, getcwd_path: unittest.mock.MagicMock) -> None:
        """
        Tests the method which let us get the current directory for the case
        that we want to have the directory separator at  the end.
        """

        getcwd_path.return_value = "/hello/world"

        if PlatformUtility.is_windows():
            expected = "/hello/world\\"
        else:
            expected = "/hello/world/"

        actual = self.helper.get_current(with_end_sep=True)

        self.assertEqual(expected, actual)
    def test_get_problem(self, requests_get_mock: unittest.mock.MagicMock):
        page = unittest.mock.MagicMock()
        page.status_code = 200
        inputs = ["5 4\n3 2", "111 222\n555 2 -1 -7", "999 221\n22 1 0\n5 5 5"]
        outpus = ["1", "2\n", "2\n1 5 8\n2 5 6"]
        content = """
        <div class="sample-test">
            <div class="input">
                <div class="title">Input</div>
                <pre>{0}</pre>
            </div>
            <div class="output">
                <div class="title">Output</div>
                <pre>{1}</pre>
            </div>
            <div class="input">
                <div class="title">Input</div>
                <pre>{2}</pre>
            </div>
            <div class="output">
                <div class="title">Output</div>
                <pre>{3}</pre>
            </div>
            <div class="input">
                <div class="title">Input</div>
                <pre>{4}</pre>
            </div>
            <div class="output">
                <div class="title">Output</div>
                <pre>{5}</pre>
            </div>
        </div>
        """.format(*[pre_contents.replace("\n", "<br>") for input_output_pair in zip(inputs, outpus)
                                                        for pre_contents in input_output_pair])
        page.content = content.encode()
        requests_get_mock.return_value = page

        link = "http://codeforces.com/contest/839/problem/A"
        problem = fetch_cf_examples.Codeforces.get_problem(link)
        assert link == problem.problem_link
        assert len(problem.examples) == 3
        assert problem.examples == [
            fetch_cf_examples.Example(inputs[0], outpus[0]),
            fetch_cf_examples.Example(inputs[1], outpus[1]),
            fetch_cf_examples.Example(inputs[2], outpus[2])]
示例#10
0
    def test_query_dns_record_not_valid_subject(
            self, dns_query_patch: unittest.mock.MagicMock) -> None:
        """
        Tests the method that let us query the (right) DNS record of the given
        subject.

        Here we test the case that the given subject is not correct.
        """

        dns_query_patch.return_value = []
        given = "a1"
        expected = dict()  # pylint: disable=use-dict-literal

        self.checker.subject = given

        actual = self.checker.query_dns_record()

        self.assertEqual(expected, actual)
示例#11
0
    def test_query_dns_record_no_response(
            self, dns_query_patch: unittest.mock.MagicMock) -> None:
        """
        Tests the method that let us query the (right) DNS record of the given
        subject.

        Here we test the case that there is systematically no (valid) response.
        """

        dns_query_patch.return_value = []
        given = "example.net"
        expected = dict()  # pylint: disable=use-dict-literal

        self.checker.subject = given

        actual = self.checker.query_dns_record()

        self.assertEqual(expected, actual)
示例#12
0
    def test_build_jobs(self, mock_cpu_count: unittest.mock.MagicMock) -> None:
        """Tests that the number of build jobs comes out correctly."""
        mock_cpu_count.return_value = 13
        cases = [
            # MAX_JOBS, USE_NINJA, IS_WINDOWS,         want
            (("8", True, False), ["-j", "8"]),  # noqa: E201,E241
            ((None, True, False), None),  # noqa: E201,E241
            (("7", False, False), ["-j", "7"]),  # noqa: E201,E241
            ((None, False, False), ["-j", "13"]),  # noqa: E201,E241
            (("6", True, True), ["-j", "6"]),  # noqa: E201,E241
            ((None, True, True), None),  # noqa: E201,E241
            (("11", False, True), ["/p:CL_MPCount=11"]),  # noqa: E201,E241
            ((None, False, True), ["/p:CL_MPCount=13"]),  # noqa: E201,E241
        ]
        for (max_jobs, use_ninja, is_windows), want in cases:
            with self.subTest(MAX_JOBS=max_jobs,
                              USE_NINJA=use_ninja,
                              IS_WINDOWS=is_windows):
                with contextlib.ExitStack() as stack:
                    stack.enter_context(env_var("MAX_JOBS", max_jobs))
                    stack.enter_context(
                        unittest.mock.patch.object(tools.setup_helpers.cmake,
                                                   "USE_NINJA", use_ninja))
                    stack.enter_context(
                        unittest.mock.patch.object(tools.setup_helpers.cmake,
                                                   "IS_WINDOWS", is_windows))

                    cmake = tools.setup_helpers.cmake.CMake()

                    with unittest.mock.patch.object(cmake, "run") as cmake_run:
                        cmake.build({})

                    cmake_run.assert_called_once()
                    (call, ) = cmake_run.mock_calls
                    build_args, _ = call.args

                if want is None:
                    self.assertNotIn("-j", build_args)
                else:
                    self.assert_contains_sequence(build_args, want)