Example #1
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])
Example #2
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)
Example #3
0
    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())
Example #4
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()))))
Example #5
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')
Example #6
0
 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()))))
Example #7
0
    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))
Example #8
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()))))
Example #9
0
 def test_bake_missing_input(self):
     with test_utils.tempdir() as tmpdir:
         with self.assertRaises(SystemExit):
             output = path.join(tmpdir, 'output')
             filename = path.join(tmpdir, 'does_not_exist.beancount')
             test_utils.run_with_args(bake.main,
                                      self.get_args() + [filename, output])
Example #10
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])
Example #11
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())
Example #12
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; -\*-')
Example #13
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()
Example #14
0
 def test_run_with_args(self):
     sentinel = []
     def main():
         sentinel.append(sys.argv)
     test_utils.run_with_args(main, ['a', 'b', 'c'])
     self.assertEqual(1, len(sentinel))
     sys_argv = sentinel[0]
     self.assertTrue(sys_argv[0].endswith('beancount/utils/test_utils_test.py'))
     self.assertEqual(['a', 'b', 'c'], sys_argv[1:])
Example #15
0
 def test_export_portfolio_on_example(self):
     rootdir = test_utils.find_repository_root(__file__)
     filename = path.join(rootdir, 'examples/example.beancount')
     with test_utils.capture() as stdout:
         test_utils.run_with_args(
             report.main, [filename, 'export_holdings', '--promiscuous'])
     output = stdout.getvalue()
     self.assertTrue(output)
     self.assertRegex(output, 'OFXHEADER:100')
     self.assertRegex(output, '<SIGNONMSGSRSV1>')
     self.assertRegex(output, '</OFX>')
Example #16
0
    def test_dump_roundtrip(self, filename):
        """
        2013-01-01 open Expenses:Restaurant
        2013-01-01 open Assets:Cash

        2014-03-02 * "Something"
          Expenses:Restaurant   50.02 USD
          Assets:Cash
        """
        with test_utils.capture('stdout', 'stderr'):
            test_utils.run_with_args(doctor.main, ['roundtrip', filename])
Example #17
0
    def test_implicit_invocation_with_ingest_call(self):
        with test_utils.capture('stdout', 'stderr') as (stdout, stderr):
            test_utils.run_with_args(extract.main, [
                path.join(self.tempdir, 'test2.import'),
                path.join(self.tempdir, 'Downloads')
            ])
        self.assertRegex(stdout.getvalue(), r'\*.*ofxdownload.ofx')
        self.assertFalse(stderr.getvalue())

        # Make sure the duplicates function was called.
        self.assertRegex(stdout.getvalue(),
                         r'{60248d66-f3f2-41c2-96af-039341eafd25}')
Example #18
0
 def test_file(self):
     with test_utils.capture('stdout', 'stderr') as (stdout, stderr):
         test_utils.run_with_args(file.main, [
             '--output', self.documents,
             path.join(self.tempdir, 'test.import'),
             path.join(self.tempdir, 'Downloads')])
     expected_res = [
         path.join(self.documents, x)
         for x in [r'Liabilities/CreditCard/\d\d\d\d-\d\d-\d\d\.bank\.csv',
                   r'Assets/Checking/\d\d\d\d-\d\d-\d\d\.ofxdownload\.ofx']]
     moved_files = list(file_utils.find_files([self.documents]))
     for regexp in expected_res:
         self.assertTrue(any(re.match(regexp, filename) for filename in moved_files))
Example #19
0
 def test_linked_multiple_files(self, filename):
     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()))))
    def test_success(self, filename):
        """
        Description,Amount
        Bla bla,1029.02 CR
        Bla bla,928.02 DB
        """
        with test_utils.capture('stdout', 'stderr') as (stdout, stderr):
            test_utils.run_with_args(remove_crdb.main, [filename])

        r = self.assertLines("""
        Description,Amount
        Bla bla,1029.02
        Bla bla,-928.02
        """, stdout.getvalue())
Example #21
0
    def run_split_reports(self, args):
        """Run the split_reports command.

        Args:
          args: A list of extra arguments (beyond the filename).
        """
        rootdir = test_utils.find_repository_root(__file__)
        filename = path.join(rootdir, 'examples', 'sharing', 'duxbury2015.beancount')
        with test_utils.capture() as stdout:
            test_utils.run_with_args(split_expenses.main, args + [filename])
        output = stdout.getvalue()
        self.assertRegex(output, "Participant")
        self.assertRegex(output, "Expenses:Food:Restaurant")
        self.assertRegex(output, "description")
        self.assertRegex(output, "balance")
Example #22
0
    def test_extract_with_previous_entries(self):
        existing_filename = path.join(self.tempdir, 'existing.beancount')
        with open(existing_filename, 'w') as file:
            file.write(
                textwrap.dedent("""\

              plugin "beancount.plugins.auto_accounts"

              2016-06-02 * "Rent"
                Assets:Checking          -1000.00 USD
                Expenses:Rent

              2016-06-08 * "Withdrawal"
                Assets:Checking           -300.00 USD
                Assets:Cash


              2016-06-01 * "Dinner"
                Liabilities:CreditCard     -47.34 USD
                Expenses:Restaurant

              2016-06-03 * "Groceries"
                Liabilities:CreditCard     -82.32 USD
                Expenses:Groceries

              2016-06-04 * "Drinks"
                Liabilities:CreditCard     -32.23 USD
                Expenses:Alcohol

            """))

        with test_utils.capture('stdout', 'stderr') as (stdout, stderr):
            test_utils.run_with_args(extract.main, [
                '--existing={}'.format(existing_filename),
                self.config_filename,
                path.join(self.tempdir, 'Downloads')
            ])
        output = stdout.getvalue()

        self.assertRegex(output, r'/checking.dl')
        self.assertRegex(output, r'; +Assets:Cash +300.00 USD')
        self.assertRegex(output, r'Expenses:Electricity +48.34 USD')
        self.assertRegex(output, r'Expenses:Internet +48.34 USD')

        self.assertRegex(output, r'/credit.dl')
        self.assertRegex(output, r'; +Expenses:Alcohol +32.23 USD')
        self.assertRegex(output, r'Expenses:Books +87.30 USD')
        self.assertRegex(output, r'Expenses:Clothing +87.30 USD')
Example #23
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 /')
Example #24
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())
Example #25
0
 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)
Example #26
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")
Example #27
0
    def test_bake_archive__unknown(self, filename):
        """
        2013-01-01 open Expenses:Restaurant
        2013-01-01 open Assets:Cash

        2014-03-02 * "Some basic transaction"
          Expenses:Restaurant   50.02 USD
          Assets:Cash
        """
        with test_utils.tempdir() as tmpdir:
            for archive_name in ('archive.tar.zip', 'archive.tar.xz'):
                with self.assertRaises(SystemExit):
                    outfile = path.join(tmpdir, archive_name)
                    test_utils.run_with_args(
                        bake.main,
                        self.get_args() + [filename, outfile])
Example #28
0
    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'
            ]))
Example #29
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())
Example #30
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())