当前位置: 首页>>代码示例>>Python>>正文


Python Validator.validate方法代码示例

本文整理汇总了Python中validator.Validator.validate方法的典型用法代码示例。如果您正苦于以下问题:Python Validator.validate方法的具体用法?Python Validator.validate怎么用?Python Validator.validate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在validator.Validator的用法示例。


在下文中一共展示了Validator.validate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_str

# 需要导入模块: from validator import Validator [as 别名]
# 或者: from validator.Validator import validate [as 别名]
    def test_str(self):

        hello_validator = Validator('hello')
        self.assertTrue(hello_validator.validate('hello').isEmpty())
        error_bucket = hello_validator.validate('Not hello')
        self.assertEquals(error_bucket.errors,
                          {'not_equal': {'': NotEqual('hello', 'Not hello')}})
开发者ID:devdoomari,项目名称:pyvalidator,代码行数:9,代码来源:test_comparable.py

示例2: test_and

# 需要导入模块: from validator import Validator [as 别名]
# 或者: from validator.Validator import validate [as 别名]
    def test_and(self):
        def always_true(data):
            return True

        def len_lt_7(data):
            return len(data) < 7

        def always_false(data):
            return False

        lt7_validator = Validator(And(always_true, len_lt_7))
        self.assertTrue(lt7_validator.validate('hello').isEmpty())
        errorbucket = lt7_validator.validate('solongmorethan7')
        self.assertEquals(
            errorbucket.errors,
            {'func_fail': {'': FuncFail(len_lt_7, 'solongmorethan7')}})
        lt7_falsy_validator = Validator(And(always_true, always_false,
                                            len_lt_7))
        errorbucket = lt7_falsy_validator.validate('solongmorethan7')
        self.assertEquals(errorbucket.errors, {
            'func_fail': {
                '': OrderedList(FuncFail(len_lt_7, 'solongmorethan7'),
                                FuncFail(always_false, 'solongmorethan7'))
            }
        })
开发者ID:devdoomari,项目名称:pyvalidator,代码行数:27,代码来源:test_and.py

示例3: install_service

# 需要导入模块: from validator import Validator [as 别名]
# 或者: from validator.Validator import validate [as 别名]
 def install_service(self, service_name, service_code):
     """
     Installs new service code in the execution environment.
     @type service_name: str
     @param service_name: The name of the service. This name must be on 
     the form name1.name2.name3, e.g., daimi.imaging.scale
     @type service_code: str
     @param service_code: The code of the service. The code will be validated
     by the Locusts code validator and thus must adhere to a lot of different 
     rules.
     @raise Exception: Raised if the code fails to validate.  
     """
     # Check the validity of the service name.
     if not Jailor.valid_service_name(service_name):
         self.__logger.info('Service with invalid name given (%s)'%service_name)
         raise Exception('Invalid service name.')
     
     # Check that the service is not already installed.
     if self.registry.has_service(service_name):
         self.__logger.info('Attempt to re-install service.')
         raise Exception('Service %s already installed.'%service_name)
     
     # Avoid malicious attempts to push __init__.py this way...
     if service_name[-8:] == '__init__':
         self.__logger.info('Attempt to hack by pushing __init__.py')
         raise Exception('Stop trying to hack me!')
     
     # Validate the code.
     v = Validator(service_code)
     try:
         v.validate()
     except ValidationError, error:
         self.__logger.info('Validation error: %s'%error.message)
         raise Exception(error.message)
开发者ID:Danaze,项目名称:scavenger-cf,代码行数:36,代码来源:jailor.py

示例4: test_simple

# 需要导入模块: from validator import Validator [as 别名]
# 或者: from validator.Validator import validate [as 别名]
    def test_simple(self):

        simple_validator = Validator({'test': 'hello'})
        simple_validator.validate({'test': 'hello'})

        simple_validator2 = Validator({'test': 'hello', 'wow so': 'doge'})
        simple_validator2.validate({'test': 'hello', 'wow so': 'doge'})
开发者ID:devdoomari,项目名称:pyvalidator,代码行数:9,代码来源:test_dict.py

示例5: test_always_true_callable

# 需要导入模块: from validator import Validator [as 别名]
# 或者: from validator.Validator import validate [as 别名]
    def test_always_true_callable(self):
        test_data = 'hello world'

        def return_true(input):
            return True

        always_true_validator = Validator(return_true)
        always_true_validator.validate(test_data)
开发者ID:devdoomari,项目名称:pyvalidator,代码行数:10,代码来源:test_callable.py

示例6: test_str

# 需要导入模块: from validator import Validator [as 别名]
# 或者: from validator.Validator import validate [as 别名]
 def test_str(self):
     str_validator = Validator(str)
     test_data = 'hello'
     str_validator.validate(test_data)
     test_error_data = 1234
     self.assertErrorBucket(
         str_validator, test_error_data,
         errors={'wrong_type': _EBN([WrongType(int, str)])})
开发者ID:devdoomari,项目名称:pyvalidator,代码行数:10,代码来源:test_typeschema.py

示例7: test_simple

# 需要导入模块: from validator import Validator [as 别名]
# 或者: from validator.Validator import validate [as 别名]
    def test_simple(self):

        simple_validator = Validator({'test': 'hello'})
        self.assertTrue(simple_validator.validate({'test': 'hello'}).isEmpty())

        simple_validator2 = Validator({'test': 'hello', 'wow so': 'doge'})
        self.assertTrue(simple_validator2.validate(
            {'test': 'hello',
             'wow so': 'doge'}).isEmpty())
开发者ID:devdoomari,项目名称:pyvalidator,代码行数:11,代码来源:test_dict.py

示例8: generate

# 需要导入模块: from validator import Validator [as 别名]
# 或者: from validator.Validator import validate [as 别名]
    def generate(self, error_details={}):
        v = Validator(self.spec, self.schema)
        v.validate(error_details=error_details)
        self._leafs = v.leafs
        self._meta_schema_map = v.meta_schema_map
        self._re_integer_pattern = re.compile('^[0-9]+$')
        self._path_action = {}
        self._identify_path_actions(None, self.schema)
        self._excluded_selections = {}

        for expansion_node in self._traverse(None, self.spec,
                                             match_action="suppress"):
            path, named_chain, pattern = expansion_node
            for selection in self._permute_pattern(pattern):
                serialized_selection = self._serialize(selection)
                print "To be excluded", serialized_selection
                self._excluded_selections[serialized_selection] = True

        selection_index = -1
        for expansion_node in self._traverse(None, self.spec,
                                             match_action="generate"):
            path, named_chain, pattern = expansion_node
            for selection in self._permute_pattern(pattern):
                selection_index += 1
                serialized_selection = self._serialize(selection)
                if serialized_selection in self._excluded_selections:
                    print "Excluding", selection
                    continue
                print "Generating", selection
                extensions = self._leafs[path]["extensions"]
                extended_selection = self._extend(selection,
                                                  named_chain,
                                                  selection_index,
                                                  extensions)

                # When clause handler.
                when_rules = self._leafs[path]["when"]
                self._run_when_rules(when_rules, extended_selection)

                # The generate action.
                path_template = self._leafs[path]["path"]
                content_template = self._resolve_template(
                    self._leafs[path]["template"], extended_selection)
                file_path = self._produce(path_template,
                                          extended_selection,
                                          check_produces=False)
                content = self._produce(content_template,
                                        extended_selection,
                                        reference=self._leafs[path]["template"],
                                        check_produces=False)
                self.writer.write(file_path, content)
开发者ID:kristijanburnik,项目名称:wpt-testgen,代码行数:53,代码来源:generator.py

示例9: test_is_dict_callable

# 需要导入模块: from validator import Validator [as 别名]
# 或者: from validator.Validator import validate [as 别名]
    def test_is_dict_callable(self):
        ok_data = {'wow': 'so gukky'}
        nope_data = ['wow', 'so listy']

        def is_dict(input):
            return type(input) == dict

        is_dict_validator = Validator(is_dict)
        is_dict_validator.validate(ok_data)

        self.assertErrorBucket(
            is_dict_validator, nope_data,
            errors={'func_fail': _EBN([FuncFail(is_dict, nope_data)])},
            debug=True)
开发者ID:devdoomari,项目名称:pyvalidator,代码行数:16,代码来源:test_callable.py

示例10: validate

# 需要导入模块: from validator import Validator [as 别名]
# 或者: from validator.Validator import validate [as 别名]
 def validate(self):
     from validator import Validator
     
     v = Validator(self.ui)
     errors = v.validate()
     
     if errors:
         obj, msg = errors[0]
         QtGui.QMessageBox.critical(self, "Error", msg)
         try:
             obj.setFocus()
             obj.selectAll()
         except: pass
         return False
     else:
         iter = QtGui.QTreeWidgetItemIterator(self.ui.treeWidgetFiles)
         while iter.value():
             attachment = iter.value().attachment
             if attachment.size > self.current_account.max_size_bytes:
                 QtGui.QMessageBox.critical(self, 
                                            "Error", 
                                            "'%s' larger than %s %s" % (attachment.name, self.current_account.max_size, self.current_account.max_size_type))
                 return False
             iter += 1
             
         return True
开发者ID:flaramusician,项目名称:kurir,代码行数:28,代码来源:kurir_main.py

示例11: main

# 需要导入模块: from validator import Validator [as 别名]
# 或者: from validator.Validator import validate [as 别名]
def main():
    import argparse

    parser = argparse.ArgumentParser(
        description='Check for common mistakes in LaTeX documents.')

    parser.add_argument('filenames', action='append',
                        help='List of filenames to check')

    args = parser.parse_args()

    # Count the total number of errors
    num_errors = 0

    for fname in args.filenames:
        with open(fname, 'r') as infile:
            validator = Validator()
            for lineno, line in enumerate(infile):
                for rule, span in validator.validate(line):
                    print_warning(fname, lineno, line.strip(), span, rule, args)
                    num_errors += 1

    if num_errors > 0:
        print '\nTotal of {0} mistakes found.'.format(num_errors)
        return 1
    else:
        print 'No mistakes found.'
        return 0
开发者ID:ebnn,项目名称:draftcheck,代码行数:30,代码来源:script.py

示例12: main

# 需要导入模块: from validator import Validator [as 别名]
# 或者: from validator.Validator import validate [as 别名]
def main(schema=None, output_dir=None, config_path=None):

    """

        Validate the schema file and output directory parameters.
        Build a tree from the schema file.
        Walk the tree, calling the registered callbacks on each node. 

    """

    validator = Validator(schema, output_dir=output_dir)
    if not validator.validate():
        click.echo(validator.error['msg'])
        sys.exit(1)

    directory_tree = Tree(
        indent_size = validator.indent_size,
        output_dir  = output_dir,
        base_path   = os.path.abspath(os.curdir)
    )
    directory_tree.load_data(schema)
    directory_tree.build_tree()

    callbacks = [ pprint_node ]

    if config_path:
        process_hooks = make_config_processor(config_path)
        callbacks.append(process_hooks)

    directory_tree.walk(callbacks=callbacks)
开发者ID:foundling,项目名称:scaffolder,代码行数:32,代码来源:superdir.py

示例13: main

# 需要导入模块: from validator import Validator [as 别名]
# 或者: from validator.Validator import validate [as 别名]
def main():
    """
    To run the CF model.
    """
    input_filename = sys.argv[1]
    user_bias = bool(int(sys.argv[2]))
    item_bias = bool(int(sys.argv[3]))
    nums = []
    with open(input_filename, 'r') as f:
        for line in f:
            nums.append(line.strip().split(" "))

    for city in nums[0]:
        # Filenames needed.
        ratings_filename = "../data/reviews" + city
        network_filename = "../data/network" + city + "b.csv"
        # Create the Validator object.
        # k: number of folds for cross validation.
        k = 10
        # Creating an object for my model
        val = Validator(ratings_filename, network_filename, k, 0.)
        for nfeat in map(int, nums[1]):
            for lrate in map(float, nums[2]):
                for rparam in map(float, nums[3]):
                    my_rec = Matrix_Factorization(n_features=nfeat,
                                        learn_rate=lrate,
                                        regularization_param=rparam,
                                        optimizer_pct_improvement_criterion=2,
                                        user_bias_correction=user_bias,
                                        item_bias_correction=item_bias)
                    (val_results, ratios) = val.validate(my_rec, run_all=True)
                    print 'validation results: '
                    print city, nfeat, lrate, rparam, ratios, val_results, \
                        np.mean(val_results)
开发者ID:suhanree,项目名称:network-recommender,代码行数:36,代码来源:run_cf.py

示例14: test_missing_custom_error

# 需要导入模块: from validator import Validator [as 别名]
# 或者: from validator.Validator import validate [as 别名]
 def test_missing_custom_error(self):
     validator = Validator(
         {'test': CustomMissingkeyError('MISSINGKEY!', 'hello')})
     error_bucket = validator.validate({})
     self.assertEquals(error_bucket.errors,
                       {'missing_key': {'': MissingKey('test', 'hello')}})
     self.assertEquals(error_bucket.custom_errors, ['MISSINGKEY!'])
开发者ID:devdoomari,项目名称:pyvalidator,代码行数:9,代码来源:test_dict.py

示例15: test_surplus

# 需要导入模块: from validator import Validator [as 别名]
# 或者: from validator.Validator import validate [as 别名]
 def test_surplus(self):
     simple_validator = Validator({'test': 'hello'})
     error_bucket = simple_validator.validate(
         {'test': 'hello',
          'wow so': 'doge'})
     self.assertEquals(error_bucket.errors,
                       {'surplus_key': {'': SurplusKey('wow so', 'doge')}})
开发者ID:devdoomari,项目名称:pyvalidator,代码行数:9,代码来源:test_dict.py


注:本文中的validator.Validator.validate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。