def main():
    p = arg_parser()
    options = p.parse_args()
    if options.cmd == "list":
        print("Available rules are :")
        for rule in _RULES:
            print("\t" + rule.__name__ + " - " + rule.__doc__.split("\n")[0])
        return
    elif options.cmd == "validate":
        rules_to_check = []
        if options.i:
            rules_to_check = options.i
        elif options.e:
            rules_to_check = [
                x.__name__ for x in _RULES if x.__name__ not in options.e
            ]
        else:
            rules_to_check = [x.__name__ for x in _RULES]
        rule_options = {}
        if options.g:
            rule_options.setdefault("ElectoralDistrictOcdId", []).append(
                base.RuleOption("check_github", False))
            rule_options.setdefault("GpUnitOcdId", []).append(
                base.RuleOption("check_github", False))
        if options.c:
            rule_options.setdefault("ElectoralDistrictOcdId", []).append(
                base.RuleOption("country_code", options.c))
            rule_options.setdefault("GpUnitOcdId", []).append(
                base.RuleOption("country_code", options.c))
        if options.ocdid_file:
            rule_options.setdefault("ElectoralDistrictOcdId", []).append(
                base.RuleOption("local_file", options.ocdid_file))
            rule_options.setdefault("GpUnitOcdId", []).append(
                base.RuleOption("local_file", options.ocdid_file))
        rule_classes_to_check = [
            x for x in _RULES if x.__name__ in rules_to_check
        ]
        registry = base.RulesRegistry(
            election_file=options.election_file,
            schema_file=options.xsd,
            rule_classes_to_check=rule_classes_to_check,
            rule_options=rule_options)
        found_errors = registry.check_rules()
        registry.print_exceptions(options.severity, options.verbose)
        # TODO other error codes?
        return found_errors
示例#2
0
    def _TestFile(self,
                  filename,
                  rules_to_check,
                  expected_errors=0,
                  expected_warnings=0):
        sample_file = os.path.join(
            FLAGS.test_srcdir,
            'google3/third_party/py/election_results_xml_validator/'
            'samples/' + filename)
        schema_file = os.path.join(
            FLAGS.test_srcdir,
            'google3/third_party/py/election_results_xml_validator/'
            'election_data_spec.xsd')
        registry = base.RulesRegistry(election_file=sample_file,
                                      schema_file=schema_file,
                                      rule_options={},
                                      rule_classes_to_check=rules_to_check)

        registry.check_rules()
        self.assertEqual(expected_errors,
                         registry.exception_counts[base.ElectionError])
        self.assertEqual(expected_warnings,
                         registry.exception_counts[base.ElectionWarning])
 def setUp(self):
   super(RulesRegistryTest, self).setUp()
   self.registry = base.RulesRegistry("test.xml", "schema.xsd", [], [])
   root_string = """
     <ElectionReport>
       <PartyCollection>
         <Party objectId="par0001">
           <Name>
             <Text language="en">Republican</Text>
           </Name>
         </Party>
         <Party objectId="par0002">
           <Name>
             <Text language="en">Democratic</Text>
           </Name>
         </Party>
       </PartyCollection>
       <PersonCollection>
         <Person objectId="p1">
           <PartyId>par0001</PartyId>
         </Person>
         <Person objectId="p2" />
         <Person objectId="p3" />
       </PersonCollection>
       <CandidateCollection>
         <Candidate>
           <PartyId>par0003</PartyId>
         </Candidate>
       </CandidateCollection>
       <OfficeCollection>
         <Office><OfficeHolderPersonIds>p1 p2</OfficeHolderPersonIds></Office>
         <Office><OfficeHolderPersonIds>p3</OfficeHolderPersonIds></Office>
       </OfficeCollection>
       <GpUnitCollection>
         <GpUnit objectId="ru0002">
           <ComposingGpUnitIds>abc123</ComposingGpUnitIds>
           <Name>Virginia</Name>
           <Type>state</Type>
         </GpUnit>
         <GpUnit objectId="ru0003">
           <ComposingGpUnitIds></ComposingGpUnitIds>
           <Name>Massachusetts</Name>
           <Type>state</Type>
         </GpUnit>
         <GpUnit>
           <ComposingGpUnitIds>xyz987</ComposingGpUnitIds>
           <Name>New York</Name>
           <Type>state</Type>
         </GpUnit>
       </GpUnitCollection>
       <ContestCollection>
         <Contest objectId="cc11111">
          Test
         </Contest>
         <Contest objectId="cc22222">
          Test1
         </Contest>
         <Contest objectId="cc33333">
          Test2
         </Contest>
       </ContestCollection>
     </ElectionReport>
   """
   self.registry.election_tree = etree.fromstring(root_string)
def main():
    p = arg_parser()
    options = p.parse_args()
    if options.cmd == "list":
        print("Available rules are :")
        for rule in sorted(rules.ALL_RULES, key=lambda x: x.__name__):
            print("\t" + rule.__name__ + " - " + rule.__doc__.split("\n")[0])
        return
    elif options.cmd == "validate":
        if options.rule_set == rules.RuleSet.ELECTION:
            rule_names = [x.__name__ for x in rules.ELECTION_RULES]
        elif options.rule_set == rules.RuleSet.OFFICEHOLDER:
            rule_names = [x.__name__ for x in rules.OFFICEHOLDER_RULES]
        else:
            raise AssertionError("Invalid rule_set: " + options.rule_set)

        if options.i:
            rule_names = options.i
        elif options.e:
            rule_names = set(rule_names) - set(options.e)

        rule_options = {}
        if options.g:
            rule_options.setdefault("ElectoralDistrictOcdId", []).append(
                base.RuleOption("check_github", False))
            rule_options.setdefault("GpUnitOcdId", []).append(
                base.RuleOption("check_github", False))
        if options.c:
            rule_options.setdefault("ElectoralDistrictOcdId", []).append(
                base.RuleOption("country_code", options.c))
            rule_options.setdefault("GpUnitOcdId", []).append(
                base.RuleOption("country_code", options.c))
        if options.ocdid_file:
            rule_options.setdefault("ElectoralDistrictOcdId", []).append(
                base.RuleOption("local_file", options.ocdid_file))
            rule_options.setdefault("GpUnitOcdId", []).append(
                base.RuleOption("local_file", options.ocdid_file))
        if options.required_languages:
            rule_options.setdefault("AllLanguages", []).append(
                base.RuleOption("required_languages",
                                str.split(options.required_languages, ",")))
        rule_classes_to_check = [
            x for x in rules.ALL_RULES if x.__name__ in rule_names
        ]

        if isinstance(options.election_files, list):
            xml_files = options.election_files
        else:
            xml_files = [options.election_files]

        errors = []

        for election_file in xml_files:
            print("\n--------- Results after validating file: {0} ".format(
                election_file))

            if (not election_file.endswith(".xml")
                    or not os.stat(election_file).st_size):
                print("{0} is not a valid XML file.".format(election_file))
                errors.append(3)
                continue

            print_metadata(election_file)
            registry = base.RulesRegistry(
                election_file=election_file,
                schema_file=options.xsd,
                rule_classes_to_check=rule_classes_to_check,
                rule_options=rule_options)
            registry.check_rules()
            registry.print_exceptions(options.severity, options.verbose)
            if registry.exception_counts[base.ElectionError]:
                errors.append(3)
            elif registry.exception_counts[base.ElectionWarning]:
                errors.append(2)
            elif registry.exception_counts[base.ElectionInfo]:
                errors.append(1)
            else:
                errors.append(0)
        return max(errors)