Exemplo n.º 1
0
def parse_generator(configuration):
    """ Parses a configuration built from yaml and returns a generator
        Configuration should be a map
    """
    from py3resttest.utils import Parser
    configuration = Parser.lowercase_keys(Parser.flatten_dictionaries(configuration))
    gen_type = str(configuration.get(u'type')).lower()

    if gen_type not in GENERATOR_TYPES:
        raise ValueError(
            'Generator type given {0} is not valid '.format(gen_type))

    # Do the easy parsing, delegate more complex logic to parsing functions
    if gen_type == 'env_variable':
        return factory_env_variable(configuration['variable_name'])()
    elif gen_type == 'env_string':
        return factory_env_string(configuration['string'])()
    elif gen_type == 'number_sequence':
        start = int(configuration.get('start', 1))
        increment = int(configuration.get('increment', 1))
        return factory_generate_ids(start, increment)()
    elif gen_type == 'random_int':
        return generator_random_int32()
    elif gen_type == 'random_text':
        return parse_random_text_generator(configuration)
    elif gen_type in GENERATOR_TYPES:
        return GENERATOR_PARSING[gen_type](configuration)

    raise Exception("Unknown generator type: {0}".format('gen_type'))
Exemplo n.º 2
0
    def url(self, value):

        if isinstance(value, dict):
            # this is the templated url , we need to convert it into actual URL
            template_str = Parser.lowercase_keys(value)['template']
            self.set_template("url", Parser.coerce_to_string(template_str))
            self.__url = value
        else:
            self.__url = value
Exemplo n.º 3
0
    def parse(cls, config):
        validator = JsonSchemaValidator()
        config = Parser.lowercase_keys(config)
        if 'schema' not in config:
            raise ValueError(
                "Cannot create schema validator without a 'schema' configuration element!")
        validator.schema_context = ContentHandler.parse_content(config['schema'])

        return validator
Exemplo n.º 4
0
    def parse(config):
        from py3resttest.utils import Parser
        output = ExtractTestValidator()
        config = Parser.lowercase_keys(Parser.flatten_dictionaries(config))
        output.config = config
        extractor = _get_extractor(config)
        output.extractor = extractor

        test_name = config['test']
        output.test_name = test_name
        test_fn = VALIDATOR_TESTS[test_name]
        output.test_fn = test_fn
        return output
Exemplo n.º 5
0
    def parse(self,
              base_url: str,
              testcase_list: List,
              test_file=None,
              working_directory=None,
              variable_dict=None):

        if working_directory is None:
            working_directory = Path(os.path.abspath(os.getcwd()))
        else:
            working_directory = Path(working_directory)
        if variable_dict is None:
            self.config.variable_binds = variable_dict
        if test_file:
            self.__testcase_file.add(test_file)

        testcase_config_object = TestCaseConfig()
        for testcase_node in testcase_list:
            if not isinstance(testcase_node, dict):
                logger.warning("Skipping the configuration %s" % testcase_node)
                continue

            testcase_node = Parser.lowercase_keys(testcase_node)
            for key in testcase_node:
                sub_testcase_node = testcase_node[key]
                if key == YamlKeyWords.INCLUDE:
                    if not isinstance(sub_testcase_node, list):
                        raise ValueError("include should be list not %s" %
                                         type(sub_testcase_node))
                    for testcase_file_path in sub_testcase_node:
                        testcase_file_path = testcase_file_path.replace(
                            '.', '/')
                        testcase_file = str(
                            working_directory.joinpath(
                                "%s.yaml" % testcase_file_path).resolve())
                        if testcase_file not in self.__testcase_file:
                            self.__testcase_file.add(testcase_file)
                            import_testcase_list = read_testcase_file(
                                testcase_file)
                            with ChangeDir(working_directory):
                                self.parse(base_url,
                                           import_testcase_list,
                                           variable_dict=variable_dict)
                elif key == YamlKeyWords.IMPORT:
                    if sub_testcase_node not in self.__testcase_file:
                        testcase_file_path = sub_testcase_node
                        logger.debug("Importing testcase from %s",
                                     testcase_file_path)
                        testcase_file_path = str(
                            working_directory.joinpath(
                                "%s" % testcase_file_path).resolve())
                        self.__testcase_file.add(sub_testcase_node)
                        import_testcase_list = read_testcase_file(
                            testcase_file_path)
                        with ChangeDir(working_directory):
                            self.parse(base_url,
                                       import_testcase_list,
                                       variable_dict=variable_dict)
                elif key == YamlKeyWords.URL:
                    __group_name = TestCaseGroup.DEFAULT_GROUP
                    group_object = TestSet.__create_test(
                        __group_name, testcase_config_object)
                    testcase_object = TestCase(
                        base_url=base_url,
                        extract_binds=group_object.extract_binds,
                        variable_binds=group_object.variable_binds,
                        context=group_object.context,
                        config=group_object.config)
                    testcase_object.url = testcase_node[key]
                    group_object.testcase_list = testcase_object

                elif key == YamlKeyWords.TEST:
                    with ChangeDir(working_directory):
                        self.parse_test(base_url, sub_testcase_node,
                                        testcase_config_object)

                elif key == YamlKeyWords.CONFIG:
                    testcase_config_object.parse(sub_testcase_node)

        self.config = testcase_config_object
Exemplo n.º 6
0
    def parse(config):
        """ Create a validator that does an extract from body and applies a comparator,
            Then does comparison vs expected value
            Syntax sample:
              { jsonpath_mini: 'node.child',
                operator: 'eq',
                expected: 'myValue'
              }
        """
        from py3resttest.utils import Parser
        output = ComparatorValidator()
        config = Parser.lowercase_keys(Parser.flatten_dictionaries(config))
        output.config = config

        output.extractor = _get_extractor(config)

        if output.extractor is None:
            raise ValueError(
                "Extract function for comparison is not valid or not found!")

        if 'comparator' not in config:  # Equals comparator if unspecified
            output.comparator_name = 'eq'
        else:
            output.comparator_name = config['comparator'].lower()
        try:
            output.comparator = COMPARATORS[output.comparator_name]
        except KeyError:
            raise ValueError("Invalid comparator given! %s  "
                             "available options are %s" %
                             (output.comparator_name, COMPARATORS.keys()))
        if not output.comparator:
            raise ValueError("Invalid comparator given!")

        try:
            expected = config['expected']
        except KeyError:
            raise ValueError(
                "No expected value found in comparator validator config, one must be!"
            )

        # Expected value can be another extractor query, or a single value, or
        # a templated value

        if isinstance(expected, str) or isinstance(expected,
                                                   (int, float, complex)):
            output.expected = expected
        elif isinstance(expected, dict):

            expected = Parser.lowercase_keys(expected)
            template = expected.get('template')
            if template:  # Templated string
                if not isinstance(template, str):
                    raise ValueError(
                        "Can't template a comparator-validator unless template value is a string"
                    )
                output.is_template_expected = True
                output.expected = template
            else:  # Extractor to compare against
                output.expected = _get_extractor(expected)
                if not output.expected:
                    raise ValueError(
                        "Can't supply a non-template, non-extract dictionary to comparator-validator"
                    )

        return output
Exemplo n.º 7
0
    def parse_content(node):
        """ Parse content from input node and returns ContentHandler object
        it'll look like:

            - template:
                - file:
                    - temple: path

            or something

        """

        # Tread carefully, this one is a bit narly because of nesting
        output = ContentHandler()
        is_template_path = False
        is_template_content = False
        is_file = False
        is_done = False

        while node and not is_done:  # Dive through the configuration tree
            # Finally we've found the value!
            if isinstance(node, str):
                output.content = node
                output.setup(node, is_file=is_file, is_template_path=is_template_path,
                             is_template_content=is_template_content)
                return output
            elif not isinstance(node, dict) and not isinstance(node, list):
                raise TypeError(
                    "Content must be a string, dictionary, or list of dictionaries")

            is_done = True

            # Dictionary or list of dictionaries
            flat = Parser.lowercase_keys(Parser.flatten_dictionaries(node))
            for key, value in flat.items():
                if key == 'template':
                    if isinstance(value, str):
                        if is_file:
                            value = os.path.abspath(value)
                        output.content = value
                        is_template_content = is_template_content or not is_file
                        output.is_template_content = is_template_content
                        output.is_template_path = is_file
                        output.is_file = is_file
                        return output
                    else:
                        is_template_content = True
                        node = value
                        is_done = False
                        break

                elif key == 'file':
                    if isinstance(value, str):
                        output.content = os.path.abspath(value)
                        output.is_file = True
                        output.is_template_content = is_template_content
                        return output
                    else:
                        is_file = True
                        node = value
                        is_done = False
                        break

        raise Exception("Invalid configuration for content.")
Exemplo n.º 8
0
 def test_lowercase_keys(self):
     input_val = 23
     result_dict = Parser.lowercase_keys(input_val)
     self.assertEqual(23, result_dict)