コード例 #1
0
ファイル: __init__.py プロジェクト: yan-lang/ycc-grader
    def grade_single(self, stu_out, gold_out) -> BaseReport:
        formatter = formatting.DiffFormatter()
        diff_text = main.diff_files(stu_out, gold_out, formatter=formatter, diff_options={'F': 0.5})

        # Compute similarity

        # InsertNode, DeleteNode, MoveNode,
        # InsertAttrib, DeleteAttrib, RenameAttrib, UpdateAttrib,
        # UpdateTextIn, UpdateTextAfter

        diff = main.diff_files(stu_out, gold_out, diff_options={'F': 0.5})

        return ParserReport(os.path.basename(stu_out), diff_text, 0)
コード例 #2
0
    def test_api_diff_files(self):
        # diff_files can take filenames
        result1 = main.diff_files(LEFT_FILE, RIGHT_FILE)

        # Or open file streams:
        with open(LEFT_FILE, "rb") as linfile:
            with open(RIGHT_FILE, "rb") as rinfile:
                result2 = main.diff_files(linfile, rinfile)

        self.assertEqual(result1, result2)

        # Give something else, and it fails:
        with self.assertRaises(IOError):
            main.diff_files("<xml1/>", "<xml2/>")
コード例 #3
0
    def test_serialize_xml(self):
        for nfe in self.nfe_list:
            nfe_id = nfe["record_id"]

            self.prepare_test_nfe(nfe_id)

            xml_path = os.path.join(
                l10n_br_nfe.__path__[0],
                "tests",
                "nfe",
                "v4_00",
                "leiauteNFe",
                nfe["xml_file"],
            )
            financial_vals = nfe_id._prepare_amount_financial(
                "0", "01", nfe_id.amount_financial_total)
            nfe_id.nfe40_detPag = [(5, 0, 0), (0, 0, financial_vals)]
            nfe_id.action_document_confirm()
            nfe_id.document_date = datetime.strptime("2020-01-01T11:00:00",
                                                     "%Y-%m-%dT%H:%M:%S")
            nfe_id.date_in_out = datetime.strptime("2020-01-01T11:00:00",
                                                   "%Y-%m-%dT%H:%M:%S")
            nfe_id.nfe40_cNF = "06277716"
            nfe_id.with_context(lang="pt_BR")._document_export()
            output = os.path.join(
                config["data_dir"],
                "filestore",
                self.cr.dbname,
                nfe_id.send_file_id.store_fname,
            )
            _logger.info("XML file saved at %s" % (output, ))
            nfe_id.company_id.country_id.name = "Brazil"  # clean mess
            diff = main.diff_files(output, xml_path)
            _logger.info("Diff with expected XML (if any): %s" % (diff, ))
            assert len(diff) == 0
コード例 #4
0
def main():
  device_params=None
  if aargs.devicetype in ['j','c','n','h','junos','csr','nexus','huawei']:
    device_params={'name':aargs.devicetype} if len(aargs.devicetype)>1 else None
    device_params={'name':'junos'} if not device_params and aargs.devicetype=='j' else None
    device_params={'name':'csr'} if not device_params and aargs.devicetype=='c' else None
    device_params={'name':'nexus'} if not device_params and aargs.devicetype=='n' else None
    device_params={'name':'huawei'} if not device_params and aargs.devicetype=='h' else None
  ### READ YAML NETCONF AUTH FILE ----------------------------------------------
  with open('./netconf_auth_data.yaml', 'r') as stream: netconf_auth_data = yaml.load(stream)
  if netconf_auth_data:
    with manager.connect_ssh(host=netconf_auth_data.get('netconf_ipaddress'),
                             port=netconf_auth_data.get('netconf_ssh_port'),
                             username=netconf_auth_data.get('netconf_user'),
                             password=netconf_auth_data.get('netconf_password'),
                             device_params=device_params,
                             hostkey_verify=False ) as m:
        if aargs.verbose:
          print('CONNECTED:',m.connected,'\nCAPABILITIES:')
          for c in m.server_capabilities: print(c)

        ### GET RUNNING CONFIG =================================================
        if aargs.getrunningconfig:
          running_config = m.get_config('running').data_xml
          if aargs.verbose: print('\nRUNNING_CONFIG:\n',xml.dom.minidom.parseString(str(running_config)).toprettyxml())
          now = datetime.datetime.now()
          timestring='%04d%02d%02d_%02d%02d%02d'%(now.year,now.month,now.day,now.hour,now.minute,now.second)
          file_name='running_config_'+timestring+'.xml'
          with open(file_name, 'w', encoding='utf8') as outfile:
            outfile.write(xml.dom.minidom.parseString(str(running_config)).toprettyxml())
            print('Writing running-config to file:',file_name)
          #exit(0)
          if aargs.comparewithfile:
            diff = xdmain.diff_files(aargs.comparewithfile, file_name, formatter=formatting.XMLFormatter())
            print(diff)
コード例 #5
0
ファイル: test_formatting.py プロジェクト: toyg/xmldiff
    def test_all_actions(self):
        here = os.path.split(__file__)[0]
        lfile = os.path.join(here, "test_data", "all_actions.left.xml")
        rfile = os.path.join(here, "test_data", "all_actions.right.xml")

        formatter = formatting.XmlDiffFormatter()
        result = main.diff_files(lfile, rfile, formatter=formatter)
        expected = (
            "[move-after, /document/node[2], /document/tag[1]]\n"
            "[insert-comment, /document[1], 0,  Insert a new comment ]\n"
            '[update, /document/node[1]/@name, "was updated"]\n'
            "[remove, /document/node[1]/@attribute]\n"
            "[insert, /document/node[1], \n"
            "<@newtribute>\n"
            "renamed\n"
            "</@newtribute>]\n"
            "[insert, /document/node[1], \n"
            "<@this>\n"
            "is new\n"
            "</@this>]\n"
            "[remove, /document/node[1]/@attr]\n"
            '[update, /document/node[1]/text()[1], "\\n    Modified\\n  "]\n'
            '[update, /document/node[1]/text()[2], "\\n    '
            'New tail content\\n  "]\n'
            "[rename, /document/node[2], nod]\n"
            "[insert-after, /document/tail[1], \n"
            "<new/>]\n"
            "[remove, /document/tail[1]]")
        self.assertEqual(result, expected)
コード例 #6
0
ファイル: XMLCom.py プロジェクト: RuidongZhang/XMLCompare
def compare_xmls(observed, expected):
    formatter = formatting.DiffFormatter()
    # FYI: https://xmldiff.readthedocs.io/en/stable
    #
    # diff_options: A dictionary containing options that will be passed into the Differ(): F: A value between 0 and 1
    # that determines how similar two XML nodes must be to match as the same in both trees. Defaults to 0.5.
    #
    # A higher value requires a smaller difference between two nodes for them to match. Set the value high,
    # and you will see more nodes inserted and deleted instead of being updated. Set the value low, and you will get
    # more updates instead of inserts and deletes.
    #
    # uniqueattrs: A list of XML node attributes that will uniquely identify a node. See Unique Attributes for more
    # info.
    #
    # Defaults to ['{http://www.w3.org/XML/1998/namespace}id'].
    #
    # ratio_mode:
    #
    # The ratio_mode determines how accurately the similarity between two nodes is calculated. The choices are
    # 'accurate', 'fast' and 'faster'. Defaults to 'fast'.
    #
    # Using 'faster' often results in less optimal edits scripts, in other words, you will have more actions to
    # achieve the same result. Using 'accurate' will be significantly slower, especially if your nodes have long
    # texts or many attributes.
    diff = main.diff_files(observed,
                           expected,
                           diff_options={
                               'F': 0.5,
                               'ratio_mode': 'accurate',
                               'uniqueattrs': [('RuleEvaluation', 'Name')]
                           },
                           formatter=formatter)
    return diff
コード例 #7
0
ファイル: type.py プロジェクト: yan-lang/ycc-grader
 def grade_single(self, stu_out, gold_out) -> BaseReport:
     formatter = formatting.DiffFormatter()
     diff = main.diff_files(stu_out,
                            gold_out,
                            formatter=formatter,
                            diff_options={'F': 0.5})
     return TypeCheckReport(os.path.basename(stu_out), diff)
コード例 #8
0
ファイル: test_a1001.py プロジェクト: blshao84/zzbj
def diff_xml(busi_data_type, operation_type, xml_file_name, file_number):
    today_dash = datetime.today().strftime('%Y-%m-%d')
    parent_dir, template_path, attachment_path, zip_file, zip_xml_file, utils.CONFIG_PATH_NAME \
        = test_utils.config(busi_data_type, operation_type)
    original_xml_path = os.path.join(
        parent_dir,
        template_path + xml_file_name.replace('file_number', file_number))
    original_xml = utils.xml_to_dict(original_xml_path)
    original_xml['Root']['Header']['SendDate'] = today_dash
    del original_xml['Root']['Body']['MasterAgrmt']['ExceID']
    zip_xml_path = os.path.join(
        parent_dir,
        template_path + zip_xml_file.replace('file_number', file_number))
    zip_xml = utils.xml_to_dict(zip_xml_path)
    del zip_xml['Root']['Body']['MasterAgrmt']['ExceID']

    diff_result = utils.convert_dict(original_xml) == utils.convert_dict(
        zip_xml)

    if not diff_result:
        print("XML比对失败!", diff_files(original_xml_path, zip_xml_path))
        return 0
    else:
        print("XML比对成功!")
        return 1
コード例 #9
0
    def test_nfse_ginfes(self):
        """ Test NFS-e same state. """

        self.nfse_same_state._onchange_document_serie_id()
        self.nfse_same_state._onchange_fiscal_operation_id()
        self.nfse_same_state._onchange_company_id()
        self.nfse_same_state.rps_number = 50
        self.nfse_same_state.date = datetime.strptime('2020-06-04T11:58:46',
                                                      '%Y-%m-%dT%H:%M:%S')

        for line in self.nfse_same_state.line_ids:
            line._onchange_product_id_fiscal()
            line._onchange_commercial_quantity()
            line._onchange_ncm_id()
            line._onchange_fiscal_operation_id()
            line._onchange_fiscal_operation_line_id()
            line._onchange_fiscal_taxes()

        self.nfse_same_state.action_document_confirm()

        xml_path = os.path.join(l10n_br_nfse_ginfes.__path__[0], 'tests',
                                'nfse', '001_50_nfse.xml')
        output = os.path.join(config['data_dir'], 'filestore', self.cr.dbname,
                              self.nfse_same_state.file_xml_id.store_fname)
        _logger.info("XML file saved at %s" % (output, ))

        diff = main.diff_files(xml_path, output)
        _logger.info("Diff with expected XML (if any): %s" % (diff, ))
        assert len(diff) == 0
コード例 #10
0
 def _upsert_jenkins_job(server: Jenkins, full_job_name: str, xml_job_config: str):
     if server.job_exists(full_job_name):
         job = server.get_job_info(full_job_name)
     else:
         print(f'Jenkins job {full_job_name} doesn''t exist.')
         job = None
     config_xml_string = canonicalize_jenkins_xml(xml_job_config)
     if job is None and writeback:
         print(f'Creating new job {full_job_name}')
         try:
             server.create_job(full_job_name, config_xml_string)
         except JenkinsException as e:
             print(f'Failed creating job:\n{e}')
     elif job is not None:
         current_xml_string = canonicalize_jenkins_xml(server.get_job_config(full_job_name))
         diffs = diff_files(BytesIO(bytearray(current_xml_string, encoding='utf-8')),
                            BytesIO(bytearray(config_xml_string, encoding='utf-8')))
         if len(diffs) > 0:
             print(f'Jenkins job {full_job_name} needs update')
             if writeback:
                 print(json.dumps(diffs, indent=4))
                 if input(f'Are you sure you want to update configuration for {full_job_name} (y/n) ? ') == 'y':
                     print(f'Updating job configuration for {full_job_name}')
                     try:
                         server.reconfig_job(full_job_name, config_xml_string)
                     except JenkinsException as e:
                         print(f'Failed updating job:\n{e}')
コード例 #11
0
ファイル: lexicon_tests.py プロジェクト: waxd/progenconlang
 def test_save_config(self):
     self.conlang.save("temp_lexicon_save.xml")
     self.assertFalse(
         main.diff_files("temp_lexicon_save.xml",
                         "testdata/basic_lexicon.xml"))
     # Cleanup
     os.remove("temp_lexicon_save.xml")
コード例 #12
0
    def test_directory(self, path, set_output=False):

        files = os.listdir(path)
        files = sorted(files, key=str.lower)

        for filename in files:

            if filename.endswith(".src"):

                self.cnt_tests += 1

                # Execute parser.php
                file_to_parse = open(f"{path}{filename}")
                status = subprocess.run(
                    self.args,
                    stdin=file_to_parse,
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.STDOUT,
                ).returncode

                # Compare the return code
                with open(f"{path}{filename[:-4]}.rc", "r") as f:
                    line = f.readline()
                    if int(line) != status:
                        if set_output:
                            print(f"{filename} : Failed")

                        self.cnt_failed += 1
                        continue
                    else:
                        if set_output:
                            print(f"{filename} : OK")

                        if status != 0:
                            self.cnt_passed += 1
                            continue

                # Compare xml files
                result = main.diff_files(
                    "output.xml",
                    f"{path}{filename[:-4]}.out",
                    diff_options={"F": 0.5, "ratio_mode": "fast"},
                )

                if len(result) == 0:
                    if set_output:
                        print(f"{filename} : OK")

                    self.cnt_passed += 1
                else:
                    if set_output:
                        print(f"{filename} : {result}")

                    self.cnt_failed += 1

        print(
            f"Test folder : {path} Passed : {self.cnt_passed} Failed : {self.cnt_failed}"
        )
        print("----------------")
コード例 #13
0
    def testStdOutput(self):

        _t = time.time()

        result = main.diff_files(self.first_path, self.second_path)

        for x in result:
            print(x)
コード例 #14
0
def assert_documents_are_semantical_equal(old, new):
    changes = xmldiff.diff_files(str(old),
                                 str(new),
                                 diff_options={
                                     "F": 1.0,
                                     "ratio_mode": "accurate"
                                 })
    assert not changes, changes
コード例 #15
0
 def _expect_designspace(self, doc, expected_path):
     actual_path = self.write_to_tmp_path(doc, "generated.designspace")
     actual_diff = main.diff_files(
         actual_path, expected_path, formatter=formatting.DiffFormatter()
     )
     if len(actual_diff) != 0:
         expected_name = os.path.basename(expected_path)
         sys.stderr.write("%s discrepancies (per xmldiff):\n" % (expected_name))
         for line in actual_diff.split("\n"):
             sys.stderr.write("  %s" % (line))
         self.fail("*.designspace file is different from expected")
コード例 #16
0
ファイル: test_ccelib.py プロジェクト: akretion/ccelib
def test_in_out_leiauteCCe():
    path = 'tests/cce/v1_00/leiauteCCe'
    for filename in os.listdir(path):
        inputfile = '%s/%s' % (path, filename,)
        obj = cce.parse(inputfile)

        outputfile = 'tests/output.xml'
        with open(outputfile, 'w') as f:
            obj.export(f, level=0, name_='evento',
                namespacedef_='xmlns="http://www.portalfiscal.inf.br/nfe"')

        diff = main.diff_files(inputfile, outputfile)
        print(diff)
        assert len(diff) == 0
コード例 #17
0
ファイル: Blackbox_test.py プロジェクト: hanniballar/mazikeen
 def test_testsuitsNtestcases_report(self):
     testDir = "TestFiles/Blackbox_test/testsuitsNtestcases/"
     outDir = testDir + "TestOutput/report"
     rmtree(outDir)
     os.makedirs(outDir)
     with open(outDir + "/mazikenout.txt", "w") as of:
         subprocess.run(["mazikeen", "-r", "TestOutput/report/report.xml"], stdout=of, stderr=of, cwd = testDir)
     
     with open(outDir + "/report.xml", "r") as ifile:
         with open(outDir + "/report_diff.xml", "w") as ofile:
             for line in ifile:
                 line = re.sub(r"time=\".+?\"", "time=\"\"", line)
                 line = re.sub(r"\\", "/", line)
                 ofile.write(line)
     self.assertEqual(main.diff_files(testDir + "TestOutput/report/report_diff.xml", testDir + "TestExpected/report/report_diff.xml"), [])
コード例 #18
0
ファイル: Blackbox_test.py プロジェクト: hanniballar/mazikeen
 def test_testsuitsNtestcases_waitNfail_parallel(self):
     testDir = "TestFiles/Blackbox_test/testsuitsNtestcases_waitNfail/"
     outDir = testDir + "TestOutput/parallel/"
     rmtree(outDir)
     os.makedirs(outDir)
     with open(outDir + "/mazikenout.txt", "w") as of:
         subprocess.run(["mazikeen", "-r", "TestOutput/parallel/report.xml", "-j", "2"], stdout=of, stderr=of, cwd = testDir)
     
     with open(outDir + "/report.xml", "r") as ifile:
         with open(outDir + "/report_diff.xml", "w") as ofile:
             for line in ifile:
                 line = re.sub(r"time=\".+?\"", "time=\"\"", line)
                 line = re.sub(r"\\", "/", line)
                 ofile.write(line)
     self.assertEqual(main.diff_files(outDir + "/report_diff.xml", outDir + "/report_diff.xml"), [])
     self.assertTrue(diff(testDir + "TestOutput/parallel/mazikenout.txt", testDir + "TestExpected/parallel/mazikenout.txt", ignore = ["process time: .*"]))
コード例 #19
0
def test_designspace_generation_italic_same_family_name(tmpdir, ufo_module):
    ufo_Lt = ufo_module.Font()
    ufo_Lt.info.familyName = "CoolFoundry Examplary Serif"
    ufo_Lt.info.styleName = "Light Italic"
    ufo_Lt.info.openTypeOS2WeightClass = 300
    ufo_Lt.info.italicAngle = -11

    ufo_Rg = ufo_module.Font()
    ufo_Rg.info.familyName = "CoolFoundry Examplary Serif"
    ufo_Rg.info.styleName = "Regular Italic"
    ufo_Rg.info.openTypeOS2WeightClass = 400
    ufo_Rg.info.italicAngle = -11

    ufo_Md = ufo_module.Font()
    ufo_Md.info.familyName = "CoolFoundry Examplary Serif"
    ufo_Md.info.styleName = "Medium Italic"
    ufo_Md.info.openTypeOS2WeightClass = 500
    ufo_Md.info.italicAngle = -11

    ufo_Bd = ufo_module.Font()
    ufo_Bd.info.familyName = "CoolFoundry Examplary Serif"
    ufo_Bd.info.styleName = "Bold Italic"
    ufo_Bd.info.openTypeOS2WeightClass = 700
    ufo_Bd.info.italicAngle = -11

    ufo_ExBd = ufo_module.Font()
    ufo_ExBd.info.familyName = "CoolFoundry Examplary Serif"
    ufo_ExBd.info.styleName = "XBold Italic"
    ufo_ExBd.info.openTypeOS2WeightClass = 800
    ufo_ExBd.info.italicAngle = -11

    font = to_glyphs([ufo_Lt, ufo_Rg, ufo_Md, ufo_Bd, ufo_ExBd])
    designspace = to_designspace(font, ufo_module=ufo_module)

    path = os.path.join(str(tmpdir), "actual.designspace")
    designspace.write(path)

    expected_path = os.path.join(
        os.path.dirname(__file__), "..", "data", "DesignspaceGenTestItalic.designspace"
    )

    assert (
        len(main.diff_files(path, expected_path, formatter=formatting.DiffFormatter()))
        == 0
    )
コード例 #20
0
def execute_test(path, servico):
    for filename in os.listdir(path):
        subtree = parsexml_('%s/%s' % (
            path,
            filename,
        ))
        inputfile = 'input.xml'
        subtree.write(inputfile, encoding='utf-8')

        obj = parse(inputfile, servico)

        outputfile = 'output.xml'
        with open(outputfile, 'w') as f:
            obj.export(f, 0, namespaceprefix_='')

        diff = main.diff_files(inputfile, outputfile)
        print(diff)
        assert len(diff) == 0
コード例 #21
0
    def testHtmlOutput(self):

        _t = time.time()

        formatter = HTMLFormatter(text_tags=('p', 'h1', 'h2', 'h3', 'h4', 'h5',
                                             'h6', 'li'),
                                  formatting_tags=('b', 'u', 'i', 'strike',
                                                   'em', 'super', 'sup', 'sub',
                                                   'link', 'a', 'span'))

        result = main.diff_files(self.first_path,
                                 self.second_path,
                                 formatter=formatter)

        print(time.time() - _t)

        with open('{}\\output.html'.format(self.path), "w") as f:
            f.write(result)
コード例 #22
0
def compare(dir, xml1, xml2):
    file1 = os.path.join(dir, xml1)
    file2 = os.path.join(dir, xml2)
    diff = main.diff_files(file1, file2)
    if diff:
        out_file = os.path.join(
            report_folder,
            xml1.split('.')[0] + '_' + xml2.split('.')[0] + '.html')
        winmerge = '"%s\WinMerge\WinMergeU.exe"' % os.environ['ProgramFiles']
        cmd_line = '%s /e /ul /ur "%s" "%s" -minimize -noninteractive -u -or "%s"' % (
            winmerge, file1, file2, out_file)
        sp = subprocess.Popen(cmd_line,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE)
        while True:
            if sp.poll() != None:
                break
        return "Not identical", out_file
    else:
        return "identical", None
コード例 #23
0
def test_in_out_leiauteNFe():
    path = 'tests/nfe/v4_00/leiauteNFe'
    for filename in os.listdir(path):
        # primeiro filtramos a root tag e a possivel assinatura:
        subtree = nfe_sub.parsexml_('%s/%s' % (path, filename,))
        inputfile = 'tests/input.xml'
        subtree.write(inputfile, encoding='utf-8')

        # agora vamos importar o XML da nota e transforma-lo em objeto Python:
        obj = nfe_sub.parse(inputfile)#'%s/%s' % (path, filename,))
        # agora podemos trabalhar em cima do objeto e fazer operaçoes como:
        obj.infNFe.emit.CNPJ

        outputfile = 'tests/output.xml'
        with open(outputfile, 'w') as f:
            nfe_sub.export(obj, nfeProc=False, stream=f)

        diff = main.diff_files(inputfile, outputfile)
        print(diff)
        assert len(diff) == 0
コード例 #24
0
def test_in_out_leiauteInutNFe():
    path = 'tests/nfe/v4_00/leiauteInutNFe'
    for filename in os.listdir(path):
        inputfile = '%s/%s' % (
            path,
            filename,
        )
        obj = inut.parse(inputfile)

        outputfile = 'tests/output.xml'
        with open(outputfile, 'w') as f:
            obj.export(f,
                       level=0,
                       name_='inutNFe',
                       namespacedef_='xmlns='
                       '"http://www.portalfiscal.inf.br/nfe"')

        diff = main.diff_files(inputfile, outputfile)
        _logger.info(diff)
        assert len(diff) == 0
コード例 #25
0
def set_in_motion_find_diffs(file1name, file2name):
    diff = ''
    diff = main.diff_files(file1name, file2name, formatter=formatting.XMLFormatter())


    for i in diff.splitlines():
        if re.search(r'\bdiff:\w+', i) or i.startswith('</node') or i.startswith('<node'):
            if not cull_line(i, 'TRUE'):
                categorize_it(i)
    get_all_node_from_keyfile(file1name) #double check the missing and extra list
    get_all_node_from_studentfile(file2name)
    key_file(file1name)
    student_file(file2name)
    compare(print_list_for_key, print_list_for_student)
    double_check_moved() # double check the moved node using key and student links
    key_crosslink(file1name)
    student_crosslink(file2name)
    compare_crosslink(print_list_key_crosslink, print_list_student_crosslink)

    return
コード例 #26
0
    def test_nfse_issnet(self):
        """ Test NFS-e same state. """

        xml_path = os.path.join(l10n_br_nfse_issnet.__path__[0], "tests",
                                "nfse", "001_50_nfse.xml")

        self.nfse_same_state._onchange_document_serie_id()
        self.nfse_same_state._onchange_fiscal_operation_id()
        self.nfse_same_state._onchange_company_id()
        self.nfse_same_state.rps_number = "50"
        self.nfse_same_state.document_number = "50"

        for line in self.nfse_same_state.line_ids:
            line._onchange_product_id_fiscal()
            line._onchange_commercial_quantity()
            line._onchange_ncm_id()
            line._onchange_fiscal_operation_id()
            line._onchange_fiscal_operation_line_id()
            line._onchange_fiscal_taxes()

        self.nfse_same_state.action_document_confirm()

        self.nfse_same_state.document_date = datetime.strptime(
            "2020-06-04T11:58:46", "%Y-%m-%dT%H:%M:%S")
        self.nfse_same_state.date_in_out = datetime.strptime(
            "2020-06-04T11:58:46", "%Y-%m-%dT%H:%M:%S")

        self.nfse_same_state.with_context(lang="pt_BR")._document_export()

        output = os.path.join(
            config["data_dir"],
            "filestore",
            self.cr.dbname,
            self.nfse_same_state.send_file_id.store_fname,
        )
        _logger.info("XML file saved at %s" % (output, ))

        diff = main.diff_files(xml_path, output)
        _logger.info("Diff with expected XML (if any): %s" % (diff, ))

        assert len(diff) == 0
コード例 #27
0
ファイル: test_nfelib.py プロジェクト: vanderleiromera/nfelib
def test_in_out_leiauteInutNFe():
    path = 'tests/nfe/v4_00/leiauteInutNFe'
    for filename in os.listdir(path):
        inputfile = '%s/%s' % (
            path,
            filename,
        )
        doc = retInutNFe.parsexml_(inputfile, None)
        obj = retInutNFe.TInutNFe.factory().build(doc.getroot())

        outputfile = 'tests/output.xml'
        with open(outputfile, 'w') as f:
            obj.export(
                f,
                level=0,
                name_='inutNFe',
                namespacedef_='xmlns="http://www.portalfiscal.inf.br/nfe"')

        diff = main.diff_files(inputfile, outputfile)
        print(diff)
        assert len(diff) == 0
コード例 #28
0
    def diff_xml_files(self, desired_filepath: str,
                       actual_filepath: str) -> List[str]:
        print("DesiredDoc: " + desired_filepath)
        print("ActualDoc: " + actual_filepath)
        diff = diff_files(desired_filepath, actual_filepath)
        marked_for_removal = list()
        for difference in list(diff):
            if (isinstance(difference, UpdateAttrib) and difference.name ==
                    '{http://www.w3.org/2001/XMLSchema-instance}schemaLocation'
                    and difference.node == '/*[1]'):
                marked_for_removal.append(difference)

        for difference in marked_for_removal:
            diff.remove(difference)

        if len(diff) > 0:
            rval = list()
            for val in diff:
                rval.append(str(val))
            return rval

        return None
コード例 #29
0
def test_single_csv_parser(tmp_dir):
    resources_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                 "resources")
    input_dir = os.path.join(resources_dir, "input")
    golden_dir = os.path.join(resources_dir, "golden")
    # output_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "output")  # For debugging purposes
    output_dir = tmp_dir

    input_statements_csv = load_csv(open(os.path.join(input_dir, "test.csv")))
    process(input_dir, output_dir, ["csv"], False)

    output_statements_csv = load_csv(
        open(os.path.join(output_dir, "statements.csv")))

    diff = compare(input_statements_csv, output_statements_csv)
    assert_csv_diff(diff)

    golden = load_csv(open(os.path.join(golden_dir, "app8-part4-1.csv")))
    output = load_csv(open(os.path.join(output_dir, "app8-part4-1.csv")))

    diff = compare(golden, output)
    assert_csv_diff(diff)

    golden = load_csv(open(os.path.join(golden_dir, "app8-part1.csv")))
    output = load_csv(open(os.path.join(output_dir, "app8-part1.csv")))

    diff = compare(golden, output)
    assert_csv_diff(diff)

    golden = load_csv(open(os.path.join(golden_dir, "app5-table2.csv")))
    output = load_csv(open(os.path.join(output_dir, "app5-table2.csv")))

    diff = compare(golden, output)
    assert_csv_diff(diff)

    golden = os.path.join(golden_dir, "dec50_2020_data.xml")
    output = os.path.join(output_dir, "dec50_2020_data.xml")

    assert len(main.diff_files(golden, output)) == 0
コード例 #30
0
ファイル: test_nfelib.py プロジェクト: netosjb/l10n-brazil
def test_in_out_leiauteInutNFe():
    path = "tests/nfe/v4_00/leiauteInutNFe"
    for filename in os.listdir(path):
        inputfile = "%s/%s" % (
            path,
            filename,
        )
        obj = inut.parse(inputfile)

        outputfile = "tests/output.xml"
        with open(outputfile, "w") as f:
            obj.export(
                f,
                level=0,
                name_="inutNFe",
                namespacedef_="xmlns="
                '"http://www.portalfiscal.inf.br/nfe"',
            )

        diff = main.diff_files(inputfile, outputfile)
        _logger.info(diff)
        assert len(diff) == 0