コード例 #1
0
ファイル: misc_utils_test.py プロジェクト: zhzy0077/beancount
    def test_log_time(self):
        with test_utils.capture() as stdout:
            with misc_utils.log_time('test-op', None):
                time.sleep(0.1)
        self.assertEqual("", stdout.getvalue())

        with test_utils.capture() as stdout:
            with misc_utils.log_time('test-op', sys.stdout.write):
                time.sleep(0.1)
        self.assertRegex(stdout.getvalue(), "Operation")
        self.assertRegex(stdout.getvalue(), "Time")
コード例 #2
0
    def test_parse_arguments__insufficient(self):
        # Test with insufficient arguments.
        parser = scripts_utils.create_arguments_parser("Test script")
        with test_utils.capture('stdout', 'stderr') as (stdout, stderr):
            with self.assertRaises(SystemExit):
                scripts_utils.parse_arguments(parser, argv=[])

        with test_utils.capture('stdout', 'stderr') as (stdout, stderr):
            with self.assertRaises(SystemExit):
                scripts_utils.parse_arguments(
                    parser, argv=[path.join(self.tempdir, 'test.import')])
コード例 #3
0
ファイル: doctor_test.py プロジェクト: emowen4/beancount
 def test_linked_explicit_link(self, filename):
     with test_utils.capture() as stdout:
         test_utils.run_with_args(doctor.main, ['linked', filename, '^abc'])
     self.assertRegex(stdout.getvalue(), 'Apples')
     self.assertRegex(stdout.getvalue(), 'Oranges')
     self.assertEqual(2, len(list(re.finditer(r'/(tmp|var/folders)/.*:\d+:',
                                              stdout.getvalue()))))
コード例 #4
0
ファイル: file_test.py プロジェクト: emowen4/beancount
    def test_file_examples(self):
        config_filename = path.join(test_utils.find_repository_root(__file__),
                                    'examples', 'ingest', 'office',
                                    'example.import')

        # For some reason via Bazel this isn't active from beancount.__init__.
        warnings.filterwarnings('ignore',
                                module='html5lib',
                                category=DeprecationWarning,
                                message='Using or importing the ABCs from')

        with test_utils.capture('stdout', 'stderr') as (_, stderr):
            result = test_utils.run_with_args(file_main, [
                config_filename,
                path.join(self.tempdir, 'Downloads'), '--output={}'.format(
                    self.tempdir)
            ], file.__file__)
        self.assertEqual(0, result)
        self.assertEqual("", stderr.getvalue())

        filed_files = []
        for root, dirs, files in os.walk(self.tempdir):
            filed_files.extend(files)
        self.assertEqual(5, len(filed_files))
        self.assertEqual(
            set(filed_files),
            set([
                'test.import', 'ofxdownload.ofx', 'bank.csv', 'readme.txt',
                'testimport.py'
            ]))
コード例 #5
0
    def test_tags_links(self, filename):
        """
          2019-01-25 open Assets:A
          2019-01-25 open Assets:B

          2019-01-25 * "Test tags" #foo ^link2 #bar #baz ^link1
            Assets:A                       10.00 EUR
            Assets:B                      -10.00 EUR
        """
        with test_utils.capture() as stdout:
            result = test_utils.run_with_args(report.main,
                                              [filename, 'hledger'])
        self.assertEqual(0, result)
        self.assertLines(
            """
          ;; Open: 2019/01/25 close Assets:A

          ;; Open: 2019/01/25 close Assets:B

          2019/01/25 * Test tags
            ; bar:, baz:, foo:
            ; Link: link1 link2
            Assets:A                       10.00 EUR
            Assets:B                      -10.00 EUR
        """, stdout.getvalue())
コード例 #6
0
ファイル: report_test.py プロジェクト: wzyboy/beancount
    def test_success(self, filename):
        """
        2013-01-01 open Assets:Account1
        2013-01-01 open Assets:Account2
        2013-01-01 open Assets:Account3
        2013-01-01 open Equity:Unknown

        2013-04-05 *
          Equity:Unknown
          Assets:Account1     5000 USD

        2013-04-05 *
          Assets:Account1     -3000 USD
          Assets:Account2     30 BOOG {100 USD}

        2013-04-05 *
          Assets:Account1     -1000 USD
          Assets:Account3     800 EUR @ 1.25 USD
        """
        with test_utils.capture() as stdout:
            test_utils.run_with_args(report.main, [filename, 'holdings'])
        output = stdout.getvalue()
        self.assertTrue(
            test_utils.search_words('Assets:Account1 1,000.00 USD', output))
        self.assertTrue(
            test_utils.search_words('Assets:Account2    30.00 BOOG', output))
        self.assertTrue(
            test_utils.search_words('Assets:Account3   800.00 EUR', output))
コード例 #7
0
    def test_simple(self, filename):
        """
          ;; All supported features exhibited here.

          2013-01-01 open Expenses:Restaurant
          2013-01-01 open Assets:Cash         USD,CAD

          2014-02-15 price HOOL 500.00 USD

          2014-03-02 * "Something"
            Expenses:Restaurant   50.02 USD
            Assets:Cash

          2015-01-01 custom "budget" Expenses:Food  "yearly"  34.43 HRK
        """
        with test_utils.capture() as stdout:
            result = test_utils.run_with_args(report.main,
                                              [filename, 'ledger'])
        self.assertEqual(0, result)
        self.assertLines(
            """

          account Expenses:Restaurant

          account Assets:Cash
            assert commodity == "USD" | commodity == "CAD"

          P 2014/02/15 00:00:00 HOOL                   500.00 USD

          2014/03/02 * Something
            Expenses:Restaurant                                                     50.02 USD
            Assets:Cash                                                            -50.02 USD

        """, stdout.getvalue())
コード例 #8
0
    def test_parent_with_assets(self, filename):
        """
        2010-01-01 open Assets:Investments:Brokerage
        2010-01-01 open Assets:Bank

        2010-01-01 commodity BNDLOCAL
         asset_allocation_bond_local: 100

        2010-01-01 commodity BONDS
         asset_allocation_bond: 100

        2011-03-02 * "Buy stock"
         Assets:Investments:Brokerage 2 BNDLOCAL {200 USD}
         Assets:Bank

        2011-01-02 * "Buy stock"
         Assets:Investments:Brokerage 2 BONDS {200 USD}
         Assets:Bank

        2011-03-02 price BNDLOCAL 200 USD
        2011-03-02 price BONDS 200 USD
        """
        with test_utils.capture('stdout', 'stderr') as (stdout, _):
            result = test_utils.run_with_args(
                asset_allocation.main,
                [filename, '--accounts_patterns', 'Assets:Investments'])
        self.assertEqual(0, result)
        self.assertRegex(stdout.getvalue(), " bond *800 *100.0% *")
        self.assertRegex(stdout.getvalue(), "  local *400 *50.0% *")
コード例 #9
0
 def test_file_main__default_output_dir(self, file_mock):
     with test_utils.capture('stdout', 'stderr') as (stdout, stderr):
         test_utils.run_with_args(file.main, [
             '--dry-run',
             path.join(self.tempdir, 'test.import'),
             self.tempdir])
     self.assertEqual(self.tempdir, file_mock.call_args[0][2])
コード例 #10
0
    def test_context_multiple_files(self, filename):
        """
            2013-01-01 open Expenses:Movie
            2013-01-01 open Assets:Cash

            2014-03-03 * "Something"
              Expenses:Restaurant   50.02 USD
              Expenses:Movie        25.00 USD
              Assets:Cash

            2014-04-04 * "Something"
              Expenses:Alcohol      10.30 USD
              Expenses:Movie        25.00 USD
              Assets:Cash
        """

        with tempfile.NamedTemporaryFile('w') as topfile:
            topfile.write(textwrap.dedent("""
                include "{}"
            """.format(filename)))
            topfile.flush()
            with test_utils.capture() as stdout:
                test_utils.run_with_args(doctor.main, ['context', topfile.name,
                                                       '{}:6'.format(filename)])
            self.assertRegex(stdout.getvalue(), 'Location:')
            self.assertRegex(stdout.getvalue(), '50.02')
コード例 #11
0
ファイル: doctor_test.py プロジェクト: quangkr/beancount
    def test_missing_open(self, filename):
        """
            2013-01-01 open Expenses:Movie
            2013-01-01 open Assets:Cash

            2014-03-03 * "Something"
              Expenses:Restaurant   50.02 USD
              Expenses:Movie        25.00 USD
              Assets:Cash

            2014-04-04 * "Something"
              Expenses:Alcohol      10.30 USD
              Expenses:Movie        25.00 USD
              Assets:Cash
        """
        with test_utils.capture() as stdout:
            test_utils.run_with_args(doctor.main, ['missing-open', filename])

        self.assertEqualEntries(
            """

            2014-03-03 open Expenses:Restaurant
            2014-04-04 open Expenses:Alcohol

        """, stdout.getvalue())
コード例 #12
0
    def test_linked(self, filename):
        """
            2013-01-01 open Expenses:Movie
            2013-01-01 open Assets:Cash

            2014-03-03 * "Apples" ^abc
              Expenses:Restaurant   50.02 USD
              Expenses:Movie        25.00 USD
              Assets:Cash

            2014-04-04 * "Something"
              Expenses:Alcohol      10.30 USD
              Expenses:Movie        25.00 USD
              Assets:Cash

            2014-05-05 * "Oranges" ^abc
              Expenses:Alcohol      10.30 USD
              Expenses:Movie        25.00 USD
              Assets:Cash
        """
        with test_utils.capture() as stdout:
            test_utils.run_with_args(doctor.main, ['linked', filename, '6'])
        self.assertRegex(stdout.getvalue(), 'Apples')
        self.assertRegex(stdout.getvalue(), 'Oranges')
        self.assertEqual(2, len(list(re.finditer(r'/(tmp|var/folders)/.*:\d+:',
                                                 stdout.getvalue()))))
コード例 #13
0
ファイル: export_test.py プロジェクト: droogmic/beancount
 def test_export_basic(self):
     rootdir = test_utils.find_repository_root(__file__)
     example_beancount = path.join(rootdir, 'examples', 'example.beancount')
     with test_utils.capture('stdout', 'stderr'):
         result = test_utils.run_with_args(export.main,
                                           [example_beancount, '-o-'])
         self.assertEqual(0, result)
コード例 #14
0
    def test_basic_filter_exclude_parent(self, filename):
        """
        2010-01-01 open Assets:Investments:Brokerage
        2010-01-01 open Assets:Investments:XTrade
        2010-01-01 open Assets:Bank
        2010-01-01 commodity BNCT
         asset_allocation_equity: 60
         asset_allocation_bond: 40

        2011-03-02 * "Buy stock"
         Assets:Investments:Brokerage 1 BNCT {200 USD}
         Assets:Bank

        2011-01-02 * "Buy stock"
         Assets:Investments:XTrade 2 BNCT {200 USD}
         Assets:Bank

        2011-01-02 * "Buy stock"
         Assets:Investments 7 BNCT {200 USD}
         Assets:Bank

        2011-03-02 price BNCT 200 USD
        """
        with test_utils.capture('stdout', 'stderr') as (stdout, _):
            result = test_utils.run_with_args(asset_allocation.main, [filename,
                '--accounts', 'Assets:Investments:Brokerage'])
        self.assertEqual(0, result)
        self.assertRegex(stdout.getvalue(), "equity *60.0% *120 *")
        self.assertRegex(stdout.getvalue(), "bond *40.0% *80")
コード例 #15
0
 def test_file_main__output_dir_does_not_exist(self):
     with test_utils.capture('stdout', 'stderr') as (stdout, stderr):
         with self.assertRaises(SystemExit):
             test_utils.run_with_args(file.main, [
                 '--output', path.join(self.documents, "Bogus"),
                 path.join(self.tempdir, 'test.import'),
                 self.tempdir])
コード例 #16
0
    def test_invocation(self, filename):
        """
            2013-01-01 open Expenses:Restaurant
            2013-01-01 open Expenses:Movie
            2013-01-01 open Expenses:Alcohol
            2013-01-01 open Assets:Cash

            2014-03-02 * "Something"
              Expenses:Restaurant   50.02 USD
              Expenses:Alcohol      10.30 USD
              Expenses:Movie        25.00 USD
              Assets:Cash
        """
        for directory in self.TEST_DIRECTORIES:
            os.makedirs(path.join(self.tmpdir, directory))

        with test_utils.capture() as stdout:
            test_utils.run_with_args(doctor.main, ['directories', filename, self.tmpdir])
        self.assertEqual(2, len(stdout.getvalue().splitlines()))
        matches = set(match.group(1) for match in re.finditer("'(.*?)'", stdout.getvalue()))
        clean_matches = set(match[len(self.tmpdir)+1:]
                            if match.startswith(self.tmpdir)
                            else match
                            for match in matches)
        self.assertEqual({'Expenses/Restaurant/Sub',
                          'Expenses:Restaurant:Sub',
                          'Assets:Extra',
                          'Assets/Extra'}, clean_matches)
コード例 #17
0
    def test_linked_multiple_files(self, filename):
        """
            2013-01-01 open Expenses:Movie
            2013-01-01 open Assets:Cash

            2014-03-03 * "Apples" ^abc
              Expenses:Restaurant   50.02 USD
              Expenses:Movie        25.00 USD
              Assets:Cash

            2014-04-04 * "Something"
              Expenses:Alcohol      10.30 USD
              Expenses:Movie        25.00 USD
              Assets:Cash

            2014-05-05 * "Oranges" ^abc
              Expenses:Alcohol      10.30 USD
              Expenses:Movie        25.00 USD
              Assets:Cash
        """
        with tempfile.NamedTemporaryFile('w') as topfile:
            topfile.write(textwrap.dedent("""
                include "{}"
            """.format(filename)))
            topfile.flush()
            with test_utils.capture() as stdout:
                test_utils.run_with_args(doctor.main, ['linked', topfile.name,
                                                       '{}:6'.format(filename)])
            self.assertRegex(stdout.getvalue(), 'Apples')
            self.assertRegex(stdout.getvalue(), 'Oranges')
            self.assertEqual(2, len(list(re.finditer(r'/(tmp|var/folders)/.*:\d+:',
                                                     stdout.getvalue()))))
コード例 #18
0
    def test_align_posting_starts(self, filename):
        """
          2014-03-01 * "Something"
            Expenses:Restaurant   50.01 USD
            Assets:Cash

          2014-03-02 * "Something"
           Expenses:Restaurant    50.02 USD
              Assets:Cash

          2014-03-03 * "Something"
            Expenses:Restaurant   50.03 USD
            Assets:Cash
        """
        with test_utils.capture() as stdout:
            result = test_utils.run_with_args(format.main, [filename])
        self.assertEqual(0, result)
        self.assertEqual(textwrap.dedent("""
          2014-03-01 * "Something"
            Expenses:Restaurant  50.01 USD
            Assets:Cash

          2014-03-02 * "Something"
            Expenses:Restaurant  50.02 USD
            Assets:Cash

          2014-03-03 * "Something"
            Expenses:Restaurant  50.03 USD
            Assets:Cash
        """), stdout.getvalue())
コード例 #19
0
    def test_extract_examples(self):
        example_dir = path.join(
            test_utils.find_repository_root(__file__), 'examples', 'ingest')
        config_filename = path.join(example_dir, 'office', 'example.import')
        with test_utils.capture('stdout', 'stderr') as (stdout, stderr):
            result = test_utils.run_with_args(extract_main, [
                '--existing={}'.format(path.join(example_dir, 'example.beancount')),
                config_filename,
                path.join(example_dir, 'Downloads')],
                                              extract.__file__)
        self.assertEqual(0, result)
        errors = stderr.getvalue()
        self.assertTrue(not errors or re.search('ERROR.*pdf2txt', errors))

        output = stdout.getvalue()

        self.assertRegex(output, r';; -\*- mode: org; mode: beancount; coding: utf-8; -\*-')

        self.assertRegex(output, 'Downloads/UTrade20160215.csv')
        self.assertRegex(output, 'ORDINARY DIVIDEND~CSKO')
        self.assertRegex(output, 'Income:US:UTrade:CSKO:Gains')
        self.assertRegex(output, '2016-02-08 balance Assets:US:UTrade:Cash .*4665.89 USD')

        self.assertRegex(output, 'Downloads/ofxdownload.ofx')
        self.assertRegex(output, r'2013-12-16 \* "LES CAFES 400 LAFAYENEW YORK /')
コード例 #20
0
 def test_implicit_invocation(self):
     with test_utils.capture('stdout', 'stderr') as (stdout, stderr):
         test_utils.run_with_args(extract.main, [
             path.join(self.tempdir, 'test.import'),
             path.join(self.tempdir, 'Downloads')
         ])
     self.assertRegex(stdout.getvalue(), r'\*.*ofxdownload.ofx')
     self.assertFalse(stderr.getvalue())
コード例 #21
0
 def test_renamed_plugin_warnings(self, warn):
     with test_utils.capture('stderr'):
         entries, errors, options_map = loader.load_string("""
           plugin "beancount.ops.auto_accounts"
         """,
                                                           dedent=True)
     self.assertTrue(warn.called)
     self.assertFalse(errors)
コード例 #22
0
 def test_parse_arguments__invalid(self):
     parser = scripts_utils.create_arguments_parser("Test script")
     with test_utils.capture('stdout', 'stderr') as (stdout, stderr):
         with self.assertRaises(SystemExit):
             scripts_utils.parse_arguments(parser, [
                 path.join(self.tempdir, 'test.import'),
                 path.join(self.tempdir, 'Non-existent'),
             ])
コード例 #23
0
 def test_extract_find_dups_once_only_with_many_files(self, mock):
     with test_utils.capture('stdout', 'stderr') as (stdout, stderr):
         test_utils.run_with_args(extract_main,
                                  [self.config_filename,
                                   path.join(self.tempdir, 'Downloads')],
                                  extract.__file__)
     output = stdout.getvalue()
     mock.assert_called_once()
コード例 #24
0
 def convert_to_sql(self, filename):
     dbfile = tempfile.NamedTemporaryFile('w', suffix='.db')
     with test_utils.capture('stdout', 'stderr'):
         result = test_utils.run_with_args(sql.main,
                                           [filename, dbfile.name])
     self.assertEqual(0, result)
     self.assertNotEqual(0, path.getsize(dbfile.name))
     return dbfile
コード例 #25
0
    def test_version(self):
        parser = version.ArgumentParser()
        self.assertIsInstance(parser, argparse.ArgumentParser)

        with test_utils.capture('stdout') as stdout, self.assertRaises(
                SystemExit):
            parser.parse_args(['--version'])
        self.assertRegex(stdout.getvalue(), r'Beancount \d+\.\d+\.\d+')
コード例 #26
0
 def test_extract_no_files(self):
     emptydir = path.join(self.tempdir, 'Empty')
     os.makedirs(emptydir)
     with test_utils.capture('stdout', 'stderr') as (stdout, stderr):
         test_utils.run_with_args(extract_main, [self.config_filename, emptydir],
                                  extract.__file__)
     output = stdout.getvalue()
     self.assertRegex(output, r';; -\*- mode: org; mode: beancount; coding: utf-8; -\*-')
コード例 #27
0
 def test_expressions(self):
     with test_utils.capture('stderr'):
         args, jobs, _, __ = test_utils.run_with_args(
             price.process_args, ['--no-cache', '-e', 'USD:yahoo/AAPL'])
         self.assertEqual(
             [price.DatedPrice(
                 'AAPL', 'USD', None,
                 [price.PriceSource(yahoo, 'AAPL', False)])], jobs)
コード例 #28
0
 def test_function(self):
     def loadfun():
         return entries, errors, options_map
     with test_utils.capture('stdout') as stdout:
         shell_obj = shell.BQLShell(False, loadfun, sys.stdout)
         shell_obj.on_Reload()
         shell_obj.onecmd(function.__doc__)
     return function(self, stdout.getvalue())
コード例 #29
0
def main():
    logging.basicConfig(level=logging.INFO,
                        format='%(levelname)-8s: %(message)s')
    parser = version.ArgumentParser(description=__doc__.strip())
    parser.add_argument('filename', help='Beancount filename')
    parser.add_argument('output_directory',
                        help='Output directory for the tutorial files')
    args = parser.parse_args()
    rootdir = test_utils.find_repository_root(__file__)

    for report_name, command_template in COMMANDS:
        logging.info('Generating %s: %s', report_name, command_template)
        rootdir = test_utils.find_repository_root(__file__)
        output_filename = path.join(args.output_directory,
                                    '{}.output'.format(report_name))
        errors_filename = path.join(args.output_directory,
                                    '{}.errors'.format(report_name))
        command = command_template.format(args.filename)
        command_args = command.split()[1:]
        with test_utils.capture('stdout') as stdout:
            with test_utils.capture('stderr') as stderr:
                try:
                    returncode = report.main(command_args)
                except SystemExit as exc:
                    returncode = exc.code
                if returncode != 0:
                    with open(errors_filename) as efile:
                        errors = efile.read()
                    raise RuntimeError(
                        "Error running '{}': exit with {}; errors: {}".format(
                            command, returncode, errors))

        # NOTE(blais): This could be removed by improving the capture() function.
        output_filename = path.join(args.output_directory,
                                    '{}.output'.format(report_name))
        with open(output_filename, 'w') as outfile:
            outfile.write(stdout.getvalue())

        if stderr.getvalue():
            errors_filename = path.join(args.output_directory,
                                        '{}.errors'.format(report_name))
            with open(errors_filename, 'w') as outfile:
                outfile.write(stderr.getvalue())

    return 0
コード例 #30
0
 def test_explicit_file__badcontents(self, filename):
     """
     2015-01-01 open Assets:Invest
     2015-01-01 open USD ;; Error
     """
     with test_utils.capture('stderr'):
         args, jobs, _, __ = test_utils.run_with_args(
             price.process_args, ['--no-cache', filename])
         self.assertEqual([], jobs)