示例#1
0
    def test_SetArgsBasic_sets_the_args_to_the_plugin(self):
        plugin = self._get_plugin_example()
        args = {"arg1": "val1", "arg2": "val2"}
        self.plugin_params.Args = args

        assert_that(self.plugin_params.SetArgsBasic(args, plugin), equal_to([args]))
        assert_that(plugin["Args"], matches_regexp(".*arg1=val1.*"))
        assert_that(plugin["Args"], matches_regexp(".*arg2=val2.*"))
示例#2
0
    def test_RunCommandList_runs_more_than_one_command_in_a_shell(self):
        output = self.interactive_shell.RunCommandList(['pwd', "echo 1234"])

        pwd_expected = self.get_abs_path(".")
        echo_expected = "1234"

        assert_that(output, matches_regexp(pwd_expected))
        assert_that(output, matches_regexp(echo_expected))
示例#3
0
    def test_SetArgsBasic_sets_the_args_to_the_plugin(self):
        plugin = self._get_plugin_example()
        args = {"arg1": "val1", "arg2": "val2"}
        self.plugin_params.Args = args

        assert_that(self.plugin_params.SetArgsBasic(args, plugin),
                    equal_to([args]))
        assert_that(plugin["Args"], matches_regexp(".*arg1=val1.*"))
        assert_that(plugin["Args"], matches_regexp(".*arg2=val2.*"))
示例#4
0
    def test_shell_exec_monitor_runs_a_command_logging_the_output(self):
        stream = StreamMock()
        self.redirect_logging_to_stream(stream)
        command = 'pwd'
        expected_command_output = self.get_abs_path(".")
        expected_time_logging_message = "Execution Start Date/Time"

        command_output = self.shell.shell_exec_monitor(command)

        assert_that(command_output, matches_regexp(expected_command_output))
        assert_that(stream.get_content(), matches_regexp(expected_time_logging_message))
        assert_that(stream.get_content(), matches_regexp(expected_command_output))
示例#5
0
    def test_get_image_info(self):
        datastore = self._find_configured_datastore_in_host_config()

        request = ImageInfoRequest(image_id="ttylinux",
                                   datastore_id=datastore.id)
        response = self.host_client.get_image_info(request)
        assert_that(response.result, is_(ImageInfoResultCode.OK))
        assert_that(response.image_info.tombstone, is_(False))
        if response.image_info.last_updated_time != NEVER_UPDATED:
            assert_that(response.image_info.last_updated_time, matches_regexp(
                self.REGEX_TIME)
            )
        assert_that(response.image_info.created_time, matches_regexp(
            self.REGEX_TIME)
        )
        assert_that(response.image_info.vm_ids, has_length(
            response.image_info.ref_count))
        assert_that(response.image_info.type, is_(ImageType.CLOUD))
        assert_that(response.image_info.replication, is_(
            ImageReplication.EAGER))

        vm_wrapper = VmWrapper(self.host_client)

        image = DiskImage("ttylinux", CloneType.COPY_ON_WRITE)
        disks = [
            Disk(new_id(), self.DEFAULT_DISK_FLAVOR.name, False, True,
                 image=image,
                 capacity_gb=0, flavor_info=self.DEFAULT_DISK_FLAVOR),
        ]

        reservation = \
            vm_wrapper.place_and_reserve(vm_disks=disks).reservation
        request = vm_wrapper.create_request(res_id=reservation)
        response = vm_wrapper.create(request=request)
        assert_that(response.vm, not_none())

        request = ImageInfoRequest(image_id="ttylinux",
                                   datastore_id=datastore.id)
        response = self.host_client.get_image_info(request)
        assert_that(response.result, is_(ImageInfoResultCode.OK))
        assert_that(response.image_info.tombstone, is_(False))
        assert_that(len(response.image_info.vm_ids),
                    is_(response.image_info.ref_count))

        assert_that(response.image_info.vm_ids, has_length(
            response.image_info.ref_count))
        vm_wrapper.delete(request=vm_wrapper.delete_request(disk_ids=[]))
    def _validate_datastore_id(self, datastore_id):
        """ Check if id is in one of the expected formats. """

        # standard uuids are 36 chars
        # vmfs volume uuids are 35 chars
        # nfs volume uuids are 17 chars
        assert_that(datastore_id, matches_regexp("^[0-9a-f-]+$"))
        assert_that(len(datastore_id),
                    any_of(equal_to(17), equal_to(35), equal_to(36)))
示例#7
0
def correctly_ordered(ordering, docs_by_name):
    seen = set()
    elems = []
    is_rev = matches_regexp(r"(\d+)-[a-fA-F0-9]{32}")
    for name in ordering:
        if name not in seen:
            docid = docs_by_name[name]["_id"]
            elems.append(has_entries({"id": docid, "rev": is_rev}))
            seen.add(name)
        else:
            elems.append(has_entry("error", "conflict"))
    return contains(*tuple(elems))
示例#8
0
    def test_get_vm_path(self):
        vm_wrapper = VmWrapper(self.host_client)

        # create a vm without disk
        reservation = vm_wrapper.place_and_reserve().reservation
        request = vm_wrapper.create_request(res_id=reservation)
        vm_wrapper.create(request=request)

        find_response = vm_wrapper.find()
        vm_id = vm_wrapper.id
        assert_that(find_response.path,
                    matches_regexp("\[.*\] vms/%s/%s/%s\.vmx" %
                                   (vm_id[0:2], vm_id, vm_id)))
 def test_get_host_config(self):
     """Test that the agent responds with Host configuration"""
     request = Host.GetConfigRequest()
     response = self.host_client.get_host_config(request)
     assert_that(response.hostConfig.agent_id,
                 matches_regexp("[0-9a-f-]{36}"))
     datastores = response.hostConfig.datastores
     assert_that(datastores, has_length(len(self.get_all_datastores())))
     for datastore in datastores:
         assert_that(self.get_all_datastores(), has_item(datastore.name))
         assert_that(datastore.type, not_none())
     self._validate_datastore_id(datastores[0].id)
     assert_that(response.hostConfig.networks, not_none())
     vm_networks = [network for network in response.hostConfig.networks
                    if NetworkType.VM in network.types]
     assert_that(len(vm_networks), greater_than_or_equal_to(1))
示例#10
0
    def test_Run_command_in_a_shell(self):
        output = self.interactive_shell.Run('pwd')

        expected = self.get_abs_path(".")
        assert_that(output, matches_regexp(expected))
示例#11
0
    def test_get_abs_path(self):
        relative_path = "test_cases/resources"  # Relative to owtf/tests directory
        abs_path = self.get_abs_path(relative_path)

        assert_that(abs_path, matches_regexp("/(.+/)*" + relative_path + "/?"))
示例#12
0
 def assert_that_output_matches_more_than(self, regex, times):
     """Assert that the output matches a given regular expression a specified number of times."""
     assert_that(self.owtf_output, matches_regexp(regex))
     if times is not None:
         times_replaced = self._get_number_of_occurences_for(regex)
         assert_that(times_replaced, greater_than_or_equal_to(times))
def is_timestamp():
    return match_equality(matches_regexp(TIMESTAMP_PATTERN))
示例#14
0
 def assert_that_output_matches_more_than(self, regex, times):
     """Assert that the output matches a given regular expression a specified number of times."""
     assert_that(self.owtf_output, matches_regexp(regex))
     if times is not None:
         times_replaced = self._get_number_of_occurences_for(regex)
         assert_that(times_replaced, greater_than_or_equal_to(times))
示例#15
0
    def test_get_abs_path(self):
        relative_path = "test_cases/resources"  # Relative to owtf/tests directory
        abs_path = self.get_abs_path(relative_path)

        assert_that(abs_path, matches_regexp("/(.+/)*" + relative_path + "/?"))
示例#16
0
    def test_streaming_different_file_types(self):
        dir = self._new_tempdir()
        input = iter(WriteFilesTest.SIMPLE_COLLECTION)
        ts = (TestStream().advance_watermark_to(0).add_elements(
            [next(input), next(input)]).advance_watermark_to(10).add_elements(
                [next(input),
                 next(input)]).advance_watermark_to(20).add_elements([
                     next(input), next(input)
                 ]).advance_watermark_to(30).add_elements([
                     next(input), next(input)
                 ]).advance_watermark_to(40).advance_watermark_to_infinity())

        def no_colon_file_naming(*args):
            file_name = fileio.destination_prefix_naming()(*args)
            return file_name.replace(':', '_')

        with TestPipeline() as p:
            _ = (p
                 | ts
                 | beam.WindowInto(FixedWindows(10))
                 | beam.io.fileio.WriteToFiles(
                     path=dir,
                     destination=lambda record: record['foundation'],
                     sink=lambda dest:
                     (WriteFilesTest.CsvSink(WriteFilesTest.CSV_HEADERS)
                      if dest == 'apache' else WriteFilesTest.JsonSink()),
                     file_naming=no_colon_file_naming,
                     max_writers_per_bundle=0,
                 ))

        with TestPipeline() as p:
            cncf_files = (p
                          | fileio.MatchFiles(FileSystems.join(dir, 'cncf*'))
                          | "CncfFileNames" >> beam.Map(lambda fm: fm.path))

            apache_files = (p
                            | "MatchApache" >> fileio.MatchFiles(
                                FileSystems.join(dir, 'apache*'))
                            |
                            "ApacheFileNames" >> beam.Map(lambda fm: fm.path))

            assert_that(
                cncf_files,
                matches_all([
                    stringmatches.matches_regexp(
                        '.*cncf-1970-01-01T00_00_00-1970-01-01T00_00_10--.*'),
                    stringmatches.matches_regexp(
                        '.*cncf-1970-01-01T00_00_10-1970-01-01T00_00_20--.*'),
                    stringmatches.matches_regexp(
                        '.*cncf-1970-01-01T00_00_20-1970-01-01T00_00_30--.*'),
                    stringmatches.matches_regexp(
                        '.*cncf-1970-01-01T00_00_30-1970-01-01T00_00_40--.*')
                ]),
                label='verifyCNCFFiles')

            assert_that(
                apache_files,
                matches_all([
                    stringmatches.matches_regexp(
                        '.*apache-1970-01-01T00_00_00-1970-01-01T00_00_10--.*'
                    ),
                    stringmatches.matches_regexp(
                        '.*apache-1970-01-01T00_00_10-1970-01-01T00_00_20--.*'
                    ),
                    stringmatches.matches_regexp(
                        '.*apache-1970-01-01T00_00_20-1970-01-01T00_00_30--.*'
                    ),
                    stringmatches.matches_regexp(
                        '.*apache-1970-01-01T00_00_30-1970-01-01T00_00_40--.*')
                ]),
                label='verifyApacheFiles')
示例#17
0
    import sys

    sys.path.insert(0, "..")
    sys.path.insert(0, "../..")

import re
import unittest

from hamcrest.library.text.stringmatches import matches_regexp
from hamcrest_unit_test.matcher_test import MatcherTest

__author__ = "Chris Rose"
__copyright__ = "Copyright 2011 hamcrest.org"
__license__ = "BSD, see License.txt"

string_matcher = matches_regexp(r"--[a-z]+--")
compiled_matcher = matches_regexp(re.compile(r"--[a-z]+--"))


class StringMatchesTest(MatcherTest):
    def testMatchesWhenPatternIsFoundAtBeginning(self):
        self.assert_matches("pattern at beginning", string_matcher, "--a-----")

    def testMatchesWhenPatternIsFoundAtEnd(self):
        self.assert_matches("pattern at end", string_matcher, "-----a--")

    def testMatchesWhenPatternIsFoundInMiddle(self):
        self.assert_matches("pattern in the middle", string_matcher,
                            "-----a-----")

    def testMismatchesWhenPatternIsNotPresent(self):