示例#1
0
def filepath(importer, filepath: str) -> str:
    """Compute filing path for a document.

    The path mirrors the structure of the accounts associated to the
    documents and with a file name composed by the document date and
    document name returned by the importer.

    Args:
      importer: The importer instance to handle the document.
      filepath: Filesystem path to the document.

    Returns:
      Filing tree location where to store the document.

    Raises:
      beangulp.exceptions.Error: The canonical file name returned by
      the importer contains a path separator charachter or seems to
      contain a date.

    """
    file = cache.get_file(filepath)

    # Get the account corresponding to the file.
    account = importer.file_account(file)
    filename = importer.file_name(file) or os.path.basename(file.name)
    date = importer.file_date(file) or utils.getmdate(file.name)

    # The returned filename cannot contain the file path separator character.
    if os.sep in filename:
        raise Error("The filename contains path separator character.")

    if re.match(r'\d\d\d\d-\d\d-\d\d', filename):
        raise Error("The filename contains what looks like a date.")

    # Remove whitespace and other funny characters from the filename.
    # TODO(dnicolodi): This should probably be importer responsibility.
    filename = misc_utils.idify(filename)

    # Prepend account directory and date prefix.
    filename = os.path.join(account.replace(':', os.sep),
                            f'{date:%Y-%m-%d}.{filename:}')

    return filename
示例#2
0
def filepath(importer, filepath: str) -> str:
    """Compute filing path for a document.

    The path mirrors the structure of the accounts associated to the
    documents and with a file name composed by the document date and
    document name returned by the importer.

    Args:
      importer: The importer instance to handle the document.
      filepath: Filesystem path to the document.

    Returns:
      Filing tree location where to store the document.

    Raises:
      beangulp.exceptions.Error: The canonical file name returned by
      the importer contains a path separator charachter or seems to
      contain a date.

    """
    # Get the account corresponding to the file.
    account = importer.account(filepath)
    filename = importer.filename(filepath) or os.path.basename(filepath)
    date = importer.date(filepath) or utils.getmdate(filepath)

    # The returned filename cannot contain the file path separator character.
    if os.sep in filename:
        raise Error("The filename contains path separator character.")

    if re.match(r'\d\d\d\d-\d\d-\d\d\.', filename):
        raise Error("The filename contains what looks like a date.")

    # Prepend account directory and date prefix.
    filename = os.path.join(account.replace(':', os.sep), f'{date:%Y-%m-%d}.{filename:}')

    return filename
示例#3
0
def _run(ctx,
         documents: List[str],
         expected: str,
         verbose: int,
         quiet: int,
         generate: bool = False,
         failfast: bool = False,
         force: bool = False):
    """Implement the test and generate commands."""

    assert len(ctx.importers) == 1
    importer = ctx.importers[0]

    verbosity = verbose - quiet
    log = utils.logger(verbosity)
    failures = 0

    for doc in utils.walk(documents):
        if doc.endswith('.beancount'):
            continue

        # Unless verbose mode is enabled, do not output a newline so
        # the test result is printed on the same line as the test
        # document filename.
        log(f'* {doc}', nl=verbosity > 0)

        # Compute the path to the expected output file.
        expected_filename = f"{doc}.beancount"
        if expected:
            expected_filename = path.join(expected,
                                          path.basename(expected_filename))

        # Run the importer's identify() method.
        if importer.identify(doc):
            account, date, name, entries = run_importer(importer, doc)
            log(f'  {expected_filename}', 1)
            if account is None:
                failures += 1
                log('  ERROR', fg='red')
                log('  ValueError: account() should not return None')
                continue
            log(
                '  {}/{:%Y-%m-%d}-{}'.format(account.replace(":", "/"), date
                                             or utils.getmdate(doc), name
                                             or path.basename(doc)), 1)
            if generate:
                try:
                    write_expected_file(expected_filename,
                                        account,
                                        date,
                                        name,
                                        entries,
                                        force=force)
                except FileExistsError as ex:
                    failures += 1
                    log('  ERROR', fg='red')
                    log('  FileExistsError: {}'.format(ex.filename))
                    continue
                log('  OK', fg='green')
                continue
            try:
                diff = compare_expected(expected_filename, account, date, name,
                                        entries)
            except FileNotFoundError:
                # The importer has positively identified a document
                # for which there is no expecred output file.
                failures += 1
                log('  ERROR', fg='red')
                log('  ExpectedOutputFileNotFound')
                continue
            if diff:
                # Test failure. Log an error.
                failures += 1
                log('  ERROR', fg='red')
                if verbosity >= 0:
                    sys.stdout.writelines(diff)
                    sys.stdout.write(os.linesep)
                    continue
            log('  PASSED', fg='green')

        elif path.exists(expected_filename):
            # The importer has not identified a document it should have.
            failures += 1
            log('  ERROR', fg='red')
            log('  DocumentNotIdentified')

        else:
            # Ignore files that are not positively identified by the
            # importer and for which there is no expected output file.
            log('  IGNORED')

        if failfast and failures:
            break

    if failures:
        sys.exit(1)
示例#4
0
 def test_getmdate(self):
     self.assertIsInstance(utils.getmdate(__file__), datetime.date)