Example #1
0
def test_help_output_is_generated(capsys):
    sys.argv = ['cli.py', '-h']
    with pytest.raises(SystemExit):
        cli.main()
    out, err = capsys.readouterr()
    assert 'usage: cli [-h] [--foo FOO]' in out
    assert '--foo FOO   the foo option!' in out
def test_main(mocker):

    environ = mocker.patch("os.environ", {"LANG": "fr-FR.UTF-8"})
    mocker.patch("{{ cookiecutter.package_name }}.cli.cli")
    cli.main()

    assert environ == {"LANG": "fr-FR.UTF-8", "LC_ALL": "C.UTF-8"}
Example #3
0
    def test_no_security_data(self):
        self.user_input.append(app.MenuOptions.ADD_SECURITIES)
        self.user_input.append('AMZN')
        self.user_input.append(app.MenuOptions.VIEW_SECURITIES)
        self.user_input.append('1')  # View AMZN security data
        self.user_input.append('0')  # Return to Main Menu
        self.user_input.append(app.MenuOptions.QUIT)

        sys.argv = ['./cli.py', self.database]
        app.main()

        self.expected_output.append(app.Messages.add_security_input())
        self.expected_output.append(app.Messages.security_added('AMZN'))

        self.expected_output.append(app.Messages.main_menu())
        self.expected_output.append(app.Messages.option_input())

        self.expected_output.append(app.Messages.view_securities(['AMZN']))
        self.expected_output.append(app.Messages.option_input())
        self.expected_output.append(app.Messages.no_security_data('AMZN'))
        self.expected_output.append(app.Messages.view_securities(['AMZN']))
        self.expected_output.append(app.Messages.option_input())

        self.expected_output.append(app.Messages.main_menu())
        self.expected_output.append(app.Messages.option_input())
        self.expected_output.append(app.Messages.quit())

        check_output(self.actual_output, self.expected_output)
Example #4
0
    def test_shouldNotSwitchToInteractiveMode(self, mock_function):
        args.interactive = False

        with mock.patch('cli.InteractiveModeHandler.run') as int_int_run:

            cli.main('')

            self.assertFalse(int_int_run.called)
Example #5
0
def main():
    interface = select_interface()
    db = database.Database()
    db.configuration_check(interface)
    os.chdir(db.database_location)
    if interface == "1":
        cli.main(db)
    else:
        gui.main(db)
Example #6
0
def pprotect(monkeypatch, tmpdir):
    os.chdir(str(tmpdir))
    # fake_stdin = io.StringIO('[email protected]\n')
    monkeypatch.setattr('sys.stdin', io.StringIO('[email protected]\n'))
    monkeypatch.setattr('getpass.getpass', lambda x: 'pass')
    os.environ['PPROTECT_USER'] = '******'
    os.environ['PPROTECT_PASS'] = '******'
    cli.main(['testing', 'init'])
    return PProtect(path=tmpdir, )
Example #7
0
    def test_quit_option_selected_exits_app(self):
        self.user_input.append(app.MenuOptions.QUIT)

        sys.argv = ['./cli.py', self.database]
        app.main()

        self.expected_output.append(app.Messages.quit())

        check_output(self.actual_output, self.expected_output)
Example #8
0
def main():
    print("Hello")
    arguments = [
        "-b 10", "-o outpout", "*****@*****.**", "-pAB6hzKSXYBf7",
        "-kef5beb9c47ff5e3abb1b9975", "-l0105c94f69e6edc0921827ca"
    ]
    args = gaanBreederCli.handle_args(arguments)

    print("Calling main")
    gaanBreederCli.main(arguments)
Example #9
0
    def test_shouldPassOriginalCommandLineToInteractiveMode(self,
                                                            mock_function):
        args.interactive = True
        expected = "--interactive -D"
        with mock.patch('cli.InteractiveModeHandler') as int_int:

            cli.main(expected.split())

            int_int.assert_called_once_with(expected, progname=cli.progname,
                                            progver=cli.progver)
Example #10
0
 def runCLI(self, args):
     orig_stdout = sys.stdout
     orig_stderr = sys.stderr
     try:
         sys.stdout = io.StringIO()
         sys.stderr = io.StringIO()
         cli.main('artool', args)
         return sys.stdout.getvalue(), sys.stderr.getvalue()
     finally:
         sys.stdout = orig_stdout
         sys.stderr = orig_stderr
Example #11
0
    def test_app_creates_database_on_database_not_found(self):
        with patch('cli.process_user_input', autospec=True) as mock_proc:
            mock_proc.return_value = False
            sys.argv = ['./cli.py', self.database]
            app.main()

        msg = app.Messages.new_database_created(self.database)
        self.expected_output.append(msg)
        self.expected_output.append(app.Messages.main_menu())

        check_output(self.actual_output, self.expected_output)
        self.assertTrue(os.path.isfile(self.database))
Example #12
0
def main():
    print("Starting program")
    keysList = ["1664c75e5b4856155775f062", "9556db302ee5a7b2c04907ea"]
    durations = [1, 1]

    # Calculating frame number from transition duration
    frameNumberPerDuration = []
    for duration in durations:
        frameNumberPerDuration.append(int(movieFrameRate * duration))

    folderNames = []
    secretData = loadSecretData()
    arguments = [
        "-u%s" % secretData["username"],
        "-p%s" % secretData["password"], "--no-loop", "-o" + workdir
    ]
    i = 0

    # Appel de la fonction sur chaque objet
    for key in keysList:

        # Creating arguments
        # print(frameNumberPerDuration[i])
        if i == len(keysList) - 1:
            # arguments.append("-k '" + key + "' '" + keysList[0] + "'")
            arguments.append("-k" + key)
            arguments.append("-l" + keysList[0])
            arguments.append("-n" + str(frameNumberPerDuration[i]))
            # arguments.append("-o"+folderNames[i])
        else:
            # arguments.append("-k" + key + " " + keysList[i+1])
            arguments.append("-k" + key)
            arguments.append("-l" + keysList[i + 1])
            arguments.append("-n" + str(frameNumberPerDuration[i]))
            # arguments = ["-o outpout", "*****@*****.**", "-pAB6hzKSXYBf7", "-k" + key , "-l" + keysList[i+1]]
        # arguments.append("-o"+folderNames[i])
        arguments.append("-P" + str(i).zfill(4))
        i += 1
        # print(arguments)
        # # Vérification des arguments
        # args = ganBreederCli.handle_args(arguments)
        # print(args)
        # Appel de la fonction principale
        ganBreederCli.main(arguments)

    ## Saving as movie
    stream = ffmpeg.input(workdir + '/*.png',
                          pattern_type='glob',
                          framerate=movieFrameRate)
    #stream = ffmpeg.framerate(24)
    stream = ffmpeg.output(stream, outputVideo)
    ffmpeg.run(stream)
Example #13
0
    def test_invalid_menu_option_selected(self):
        self.user_input.append('-1')
        self.user_input.append(app.MenuOptions.QUIT)

        sys.argv = ['./cli.py', self.database]
        app.main()

        self.expected_output.append(app.Messages.invalid_option())
        self.expected_output.append(app.Messages.main_menu())
        self.expected_output.append(app.Messages.option_input())
        self.expected_output.append(app.Messages.quit())

        check_output(self.actual_output, self.expected_output)
Example #14
0
    def test_app_loads_existing_database(self, mock_print):
        open(self.database, 'w').close()
        self.assertTrue(os.path.isfile(self.database))

        with patch('cli.process_user_input', autospec=True) as mock_proc:
            mock_proc.return_value = False
            sys.argv = ['./cli.py', self.database]
            app.main()

        msg = app.Messages.load_existing_database(self.database)
        self.expected_output.append(msg)
        self.expected_output.append(app.Messages.main_menu())

        check_output(self.actual_output, self.expected_output)
Example #15
0
    def test_add_securities(self):
        self.user_input.append(app.MenuOptions.ADD_SECURITIES)
        self.user_input.append('AMZN')
        self.user_input.append(app.MenuOptions.QUIT)

        sys.argv = ['./cli.py', self.database]
        app.main()

        self.expected_output.append(app.Messages.add_security_input())
        self.expected_output.append(app.Messages.security_added('AMZN'))
        self.expected_output.append(app.Messages.main_menu())
        self.expected_output.append(app.Messages.option_input())
        self.expected_output.append(app.Messages.quit())

        check_output(self.actual_output, self.expected_output)
Example #16
0
def main():
  options, args = parseOptions()
  log.info(options)

  ais = loadAI(args)
  loadMap(options.map)
  settings.IGNORE_EXCEPTIONS = not options.whiny
  if options.save_images:
    settings.SAVE_IMAGES = True
  if options.cli:
    try:
      cli.main(ais)
    except KeyboardInterrupt, e:
      pass
    finally:
Example #17
0
    def test_update_security_data(self, mock_scraper):
        ticker, dt, expected_data = test_utils.get_expected_equity_data()
        mock_scraper.return_value = [(dt.date(), expected_data)], []

        self.user_input.append(app.MenuOptions.ADD_SECURITIES)
        self.user_input.append(ticker)
        self.user_input.append(app.MenuOptions.UPDATE_MARKET_DATA)
        self.user_input.append(app.MenuOptions.VIEW_SECURITIES)
        self.user_input.append('1')  # View AMZN security data
        self.user_input.append(
            '')  # Press any key to return to view securities
        self.user_input.append('0')  # Return to Main Menu
        self.user_input.append(app.MenuOptions.QUIT)

        sys.argv = ['./cli.py', self.database]
        app.main()

        # Add security
        self.expected_output.append(app.Messages.add_security_input())
        self.expected_output.append(app.Messages.security_added(ticker))

        # Update market data
        self.expected_output.append(app.Messages.main_menu())
        self.expected_output.append(app.Messages.option_input())
        self.expected_output.append(app.Messages.market_data_updated())

        # View securities in app
        self.expected_output.append(app.Messages.main_menu())
        self.expected_output.append(app.Messages.option_input())
        self.expected_output.append(app.Messages.view_securities([ticker]))
        self.expected_output.append(app.Messages.option_input())

        # View current security data in app
        self.expected_output.append(
            app.Messages.view_security_data(ticker, [(dt, expected_data)]))
        self.expected_output.append(app.Messages.any_key_to_return())
        self.expected_output.append(app.Messages.view_securities([ticker]))
        self.expected_output.append(app.Messages.option_input())

        # Return to main menu and quit app
        self.expected_output.append(app.Messages.main_menu())
        self.expected_output.append(app.Messages.option_input())
        self.expected_output.append(app.Messages.quit())

        check_output(self.actual_output, self.expected_output)

        # Check that scraper was called
        mock_scraper.assert_called_once()
Example #18
0
    def test_no_securities_loaded(self):
        self.user_input.append(app.MenuOptions.VIEW_SECURITIES)
        self.user_input.append('0')  # Return to Main Menu
        self.user_input.append(app.MenuOptions.QUIT)

        sys.argv = ['./cli.py', self.database]
        app.main()

        self.expected_output.append(app.Messages.view_securities([]))

        self.expected_output.append(app.Messages.option_input())
        self.expected_output.append(app.Messages.main_menu())
        self.expected_output.append(app.Messages.option_input())
        self.expected_output.append(app.Messages.quit())

        check_output(self.actual_output, self.expected_output)
Example #19
0
 def _check_info_before_first_backup(self):
     out = io.StringIO()
     cli.main(('info',), services=self.services, stdoutfile=out)
     outstr = out.getvalue()
     if outstr.startswith('Web ui started'):
         firstline, outstr = outstr.split('\n', 1)
     self.assertEqual(
         'Backup definitions:\n'
         '  backup home\n'
         '    collection local:/backups/home\n'
         '      (Does not exist)\n'
         '    collection local:/backups/second\n'
         '      (Does not exist)\n'
         '    source local:/home/me\n',
         outstr)
     self.assertRegex(firstline, r'^Web ui started on port \d+$')
Example #20
0
 def _check_info_after_initial_backup(self):
     out = io.StringIO()
     cli.main(('info',), services=self.services, stdoutfile=out)
     outstr = out.getvalue()
     if outstr.startswith('Web ui started'):
         firstline, outstr = outstr.split('\n', 1)
     if False: # FIXME: last-verified data is currently broken
      self.assertEqual(
         'Backup definitions:\n  backup home\n'
         '    collection local:/backups/home\n'
         '      Least recently verified: 1995-01-01 00:00:20\n'
         '      Total number of content files: 7\n'
         '    collection local:/backups/second\n'
         '      (Does not exist)\n'
         '    source local:/home/me\n',
         outstr)
     self.assertRegex(firstline, r'^Web ui started on port \d+$')
Example #21
0
    def test_shouldSwitchToInteractiveModeAndReturnZero(self, mock_function):
        args.interactive = True
        with mock.patch('cli.InteractiveModeHandler.run') as int_int_run:
            int_int_run.return_value = 0

            ret = cli.main('')

            self.assertTrue(int_int_run.called)
            self.assertEqual(0, ret)
Example #22
0
    def test_worker(self):
        self.result = None

        def callback(ch, method, properties, body):
            self.result = json.loads(body)

        thread = threading.Thread(target=worker.main, args=[callback])
        thread.daemon = True
        thread.start()

        config = {
            'publisher_class': pubsub.Publisher
        }
        while self.result is None:
            time.sleep(1)
            cli.main([self.temp.name], config)

        self.assertEqual(self.result['id'], self._id)
Example #23
0
 def __call__(self):
     output = cli.main(self.case['filter'], yaml.dump(self.case['input']))
     if 'output' in self.case:
         expected_list = [self.case['output']]
     else:
         expected_list = self.case['output_list']
     for expected in expected_list:
         actual = output.next()
         print 'Actual: %s\nExpected: %s' % (actual, expected)
         assert actual == expected
Example #24
0
    def test_update_security_data_on_invalid_date(self, mock_scraper):
        ticker = 'AMZN'
        dt = datetime.datetime.today()
        errors = [InvalidDateError(f'{dt}')]
        mock_scraper.return_value = errors

        self.user_input.append(app.MenuOptions.ADD_SECURITIES)
        self.user_input.append(ticker)
        self.user_input.append(app.MenuOptions.UPDATE_MARKET_DATA)
        self.user_input.append(app.MenuOptions.VIEW_SECURITIES)
        self.user_input.append('1')  # View AMZN security data
        self.user_input.append('0')  # Return to Main Menu
        self.user_input.append(app.MenuOptions.QUIT)

        sys.argv = ['./cli.py', self.database]
        app.main()

        # Add security
        self.expected_output.append(app.Messages.add_security_input())
        self.expected_output.append(app.Messages.security_added(ticker))

        # Update market data
        self.expected_output.append(app.Messages.main_menu())
        self.expected_output.append(app.Messages.option_input())
        self.expected_output.append(app.Messages.market_data_updated())

        # View securities in app
        self.expected_output.append(app.Messages.main_menu())
        self.expected_output.append(app.Messages.option_input())
        self.expected_output.append(app.Messages.view_securities([ticker]))
        self.expected_output.append(app.Messages.option_input())

        # View current security data in app
        self.expected_output.append(app.Messages.no_security_data(ticker))
        self.expected_output.append(app.Messages.view_securities([ticker]))
        self.expected_output.append(app.Messages.option_input())

        # Quit
        self.expected_output.append(app.Messages.main_menu())
        self.expected_output.append(app.Messages.option_input())
        self.expected_output.append(app.Messages.quit())

        check_output(self.actual_output, self.expected_output)
Example #25
0
 def __call__(self):
     output = cli.main(self.case["filter"], yaml.dump(self.case["input"]))
     if "output" in self.case:
         expected_list = [self.case["output"]]
     else:
         expected_list = self.case["output_list"]
     for expected in expected_list:
         actual = output.next()
         print "Actual: %s\nExpected: %s" % (actual, expected)
         assert actual == expected
Example #26
0
 def sync_backups(self):
     self.local_filesys._add_file(
         ('home', 'me', '.config', 'ebakup', 'config'),
         content=textwrap.dedent('''\
             backup home
                collection local:/backup/mine
                collection local:/backup/second
                source local:/home/me
                    targetpath home
                    path tmp
                        ignore
                        path Q.pdf
                            static
                    path Pictures
                        static
             ''').encode('utf-8'),
         mtime=datetime.datetime(2014, 8, 1, 12, 30, 24, 157031),
         mtime_ns = 157031603,
         update=True)
     self.advance_utcnow(seconds=1)
     oldstdout = self.stdout.getvalue()
     # backup/second does not exist, so it should be created and
     # everything from backup/mine copied there. Thus, backup/mine
     # should not be modified.
     self.local_filesys._clear_all_access_rules()
     self.local_filesys._allow_reading_subtree(
         ('home', 'me', '.config', 'ebakup'))
     self.local_filesys._allow_reading_subtree(('etc', 'xdg', 'ebakup'))
     self.local_filesys._allow_full_access_to_subtree(('backup', 'second'))
     self.local_filesys._allow_reading_subtree(('backup', 'mine'))
     cli.main(
         ('sync', '--create'),
         stdoutfile=self.stdout, services=self.services)
     self.advance_utcnow(seconds=1)
     self.assertTrue(self.stdout.getvalue().startswith(oldstdout))
     stdout = self.stdout.getvalue()[len(oldstdout):]
     match = re.match('^Web ui started on port \d+\n', stdout)
     if match:
         self.assertEqual(0, match.start())
         stdout = stdout[match.end():]
     self.assertEqual('', stdout)
Example #27
0
 def make_first_backup(self):
     self.build_initial_filesystem()
     self.advance_utcnow(seconds=1)
     self.local_filesys._allow_reading_subtree(('home', 'me'))
     self.local_filesys._allow_reading_path(
         ('etc', 'xdg', 'ebakup', 'config'))
     self.local_filesys._allow_full_access_to_subtree(('backup', 'mine'))
     self.local_filesys._allow_reading_subtree(
         ('home', 'me', '.config', 'ebakup'))
     self.local_filesys._allow_full_access_to_subtree(
         ('home', 'me', '.local', 'share', 'ebakup'))
     self.local_filesys._allow_full_access_to_subtree(
         ('home', 'me', '.cache', 'ebakup'))
     self.local_filesys._add_file(
         ('home', 'me', '.config', 'ebakup', 'config'),
         content=textwrap.dedent('''\
             backup home
                collection local:/backup/mine
                source local:/home/me
                    targetpath home
                    path tmp
                        ignore
                        path Q.pdf
                            static
                    path Pictures
                        static
             ''').encode('utf-8'),
         mtime=datetime.datetime(2014, 7, 14, 15, 11, 9, 912451),
         mtime_ns = 912451337,
         owner='the owner',
         group='the owning group',
         access=0o644)
     self.advance_utcnow(seconds=1)
     self.time_backup1_start = self._utcnow
     cli.main(
         ('backup', '--create', 'home'),
         stdoutfile=self.stdout, services=self.services)
     self.advance_utcnow(seconds=1)
     self.assertRegex(
         self.stdout.getvalue(), r'Web ui started on port \d+\n')
Example #28
0
def getLocation(data):
    '''
    output_file = "tweet.json"
    input_file = "tweetLocation.json"
    with open(output_file, 'w') as fo:
        json.dump(data, fo)
    '''
    ok, result = cli.main(data)
    if ok:
        #with open(input_file, 'r') as fi:
        #result = json.load(fi)
        return result['location']
    else:
        return {}
Example #29
0
    def test_cli(self):
        class Publisher(object):
            result = None

            def __init__(self, host):
                pass

            def __enter__(self):
                return self

            def __exit__(self, exc_type, exc_val, exc_tb):
                pass

            def publish(self, data):
                Publisher.result = data

        config = {
            'publisher_class': Publisher
        }

        cli.main([self.temp.name], config)

        self.assertEqual(Publisher.result['id'], self._id)
def main():
    parser = OptionParser()
    parser.add_option("-l", "--list", action="store_true", dest="list", help="List your saved minecraft worlds.")
    parser.add_option("-t", "--token", type="string", dest="token", help="Your sketchfab api token. Can be found on your dashboard.")
    parser.add_option("-w", "--world", type="string", dest="world", help="Name of minecraft world to export.")
    parser.add_option("-d", "--dimension", type="string", dest="dimension", default="0", help="Dimension number to export from world. Default is 0 for the overworld.")
    parser.add_option("-n", "--name", type="string", dest="title", help="Sketchfab model title.")
    parser.add_option("-a", "--area", type="string", dest="area", help="Box x, z limit coordinates of world selection. Format : xmin,xmax,zmin,zmax")
    parser.add_option("-y", "--height", type="string", dest="height", help="y coordinates limit. Format : ymin,ymax")
    (options, args) = parser.parse_args()

    gui_enabled = True

    # if arguments passed, switch to cli
    if not options.list is None or not options.world is None:
        gui_enabled = False

    if gui_enabled is True:
        import gui
        try:
            from PyQt4 import QtGui

            app = QtGui.QApplication(sys.argv)
            w = gui.Window()
            w.show()
            w.setFixedSize(w.size())

            sys.exit(app.exec_())
        except:
            print("Failed to initialize QtGui interface. Switching to cli.")

            # if gui failed to start fallback to cli
            gui_enabled = False

    if gui_enabled is False:
        import cli
        cli.main(options)
Example #31
0
def test_granule_selection(test_run):
    sys.argv = ['', test_run['json']]
    test_name = os.path.basename(test_run['json']).split('.')[0]
    print('Running {}...'.format(test_name))
    selected_granules = main()

    # Test that all expected granules exist in selected
    expected_granules = pd.read_csv(test_run['csv'])

    correctly_found_condition = selected_granules['hdf_filename'].isin(
        expected_granules['hdf_filename'])
    correctly_found_granules = selected_granules[correctly_found_condition]
    incorrectly_found_granules = selected_granules[~correctly_found_condition]
    missed_granules_condition = ~(expected_granules['hdf_filename'].isin(
        selected_granules['hdf_filename']))
    missed_granules = expected_granules[missed_granules_condition]

    num_correct = len(correctly_found_granules)
    num_expected = len(expected_granules)
    num_extra = len(incorrectly_found_granules)
    num_missed = len(missed_granules)

    # Report results
    if num_extra == 0 and num_missed == 0:
        print('Selected {}/{} expected granules and no extras.'.format(
            num_correct, num_expected))
    else:
        print('Selected {}/{} expected granules, {} unexpected, {} missed.'.
              format(num_correct, num_expected, num_extra, num_missed))

        if num_extra > 0:
            print('Unexpected granules:')
            print(incorrectly_found_granules)

        if num_missed > 0:
            print('Missed granules:')
            print(missed_granules)

    assert (num_correct == num_expected)
    assert (num_extra == 0)
    assert (num_missed == 0)
Example #32
0
File: __main__.py Project: 5y/flask
# -*- coding: utf-8 -*-
"""
    flask.__main__
    ~~~~~~~~~~~~~~

    Alias for flask.run for the command line.

    :copyright: (c) 2014 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""


if __name__ == '__main__':
    from cli import main
    main(as_module=True)
Example #33
0
# This file is needed to run the package
import os
import sys

from cli import main
#  from create_inputs import main

if __name__ == '__main__':
    main(obj={})
Example #34
0
import cli
cli.main()
Example #35
0
 def test_all(self):
     self.fs = fake_filesys.FakeFileSystem()
     self.services = {
         'utcnow': self.utcnow,
         'filesystem': self.get_filesys,
         '*': None,
         }
     fs = self.fs
     fs._set_utcnow(self.utcnow)
     self.make_initial_source_tree(fs)
     fs._allow_full_access_to_subtree(('backups', 'home'))
     fs._allow_full_access_to_subtree(('backups', 'second'))
     fs._allow_reading_subtree(('home', 'me'))
     fs._disallow_reading_subtree(('home', 'me', 'tmp'))
     fs._disallow_reading_subtree(('home', 'me', '.cache'))
     fs._disallow_reading_subtree(('home', 'me', 'tmp-data.txt'))
     fs._disallow_reading_subtree(('home', 'me', 'mount-fileserver'))
     fs._allow_reading_path(('etc', 'xdg', 'ebakup', 'config'))
     fs._add_file(
         ('home', 'me', '.config', 'ebakup', 'config'),
         content=self.get_initial_config_file_content(),
         mtime=datetime.datetime(1994, 12, 31, 23, 58),
         owner='fileowner', group='fileownergroup', access=0o644)
     self._check_info_before_first_backup()
     self.assertRaisesRegex(
         fake_filesys.ForbiddenActionError,
         "No listdir access.*'me', 'tmp'\)",
         self.fs.get_directory_listing, ('home', 'me', 'tmp'))
     self.assertRaisesRegex(
         fake_filesys.ForbiddenActionError,
         "No listdir access.*'squiggle'\)",
         self.fs.get_directory_listing, ('home', 'me', '.cache', 'squiggle'))
     self.assertRaisesRegex(
         fake_filesys.ForbiddenActionError,
         "No stat access.*'tmp-data.txt'\)",
         self.fs.get_item_at_path, ('home', 'me', 'tmp-data.txt'))
     self.assertRaisesRegex(
         fake_filesys.ForbiddenActionError,
         "No stat access.*'nosuchfile'\)",
         self.fs.get_item_at_path, ('home', 'me', 'tmp', 'nosuchfile'))
     out = io.StringIO()
     self.advance_utcnow(seconds=20)
     cli.main(
         ('backup', '--create', 'home'),
         services=self.services,
         stdoutfile=out)
     self.advance_utcnow(seconds=20)
     self.assertRegex(out.getvalue(), r'^Web ui started on port \d+$')
     self._check_result_of_initial_backup()
     self._check_info_after_initial_backup()
     self.advance_utcnow(days=4, seconds=2000)
     self._update_sources_before_second_backup()
     self.advance_utcnow(seconds=600)
     cli.main(('backup', 'home'), services=self.services, stdoutfile=out)
     self.advance_utcnow(seconds=80)
     self._check_result_of_second_backup(stdout=out.getvalue())
     self.advance_utcnow(seconds=32)
     self.assertRaisesRegex(
         FileNotFoundError, 'Backup collection does not exist.*second',
         cli.main, ('sync',), services=self.services, stdoutfile=out)
     self.advance_utcnow(seconds=17)
     out = io.StringIO()
     cli.main(('sync', '--create'), services=self.services, stdoutfile=out)
     self._check_result_of_sync(stdout=out.getvalue())
     self.advance_utcnow(seconds=27)
     out = io.StringIO()
     cli.main(('sync', '--create'), services=self.services, stdoutfile=out)
     # This should not have caused any changes, so just do the same check
     self._check_result_of_sync(stdout=out.getvalue())
     out = io.StringIO()
     fs._allow_full_access_to_subtree(('backup', 'shadow'))
     cli.main(
         ('shadowcopy', '--target', '/backup/shadow', '1995-01-01T00:00'),
         services=self.services, stdoutfile=out)
     fs._drop_all_access_to_subtree(('backup', 'shadow'))
     self.assertRegex(out.getvalue(), r'^Web ui started on port \d+$')
Example #36
0
    def test_app_terminates_if_no_database_provided(self):
        sys.argv = ['./cli.py']
        app.main()

        self.expected_output.append(app.Messages.no_database_specified())
        check_output(self.actual_output, self.expected_output)
Example #37
0
# 
#     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
#     OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
#     MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
#     NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
#     DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
#     OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
#     USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
Trivial example, placing a 8-pin DIP package.

"""

import component
import cli

ic1 = component.DualInlinePackage("IC1", 8)

board = component.StripBoard((5, 5))

nets = (
    (ic1.terminals[0], ic1.terminals[7]),
    (ic1.terminals[1], ic1.terminals[6]),
    (ic1.terminals[2] ,ic1.terminals[5]),
    (ic1.terminals[3] ,ic1.terminals[4]),
)

cli.main(board, (ic1,), nets)

Example #38
0
def main():
    config.configure()
    cli.main()
Example #39
0
def test_add_secret(pprotect, monkeypatch):
    monkeypatch.setattr('sys.stdin', io.StringIO('mydomain\n'))
    cli.main(['testing', 'add-domain'])
Example #40
0
def main(argv=sys.argv):
 return cli.main(argv)
Example #41
0
#!/usr/bin/python
from cli import main
import sys

sys.exit(main())
Example #42
0
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
#     The above copyright notice and this permission notice shall be included
#     in all copies or substantial portions of the Software.
#
#     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
#     OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
#     MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
#     NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
#     DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
#     OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
#     USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
Trivial example, placing a single resistor on a 1x2 strip board.

"""

import component
import cli

r1 = component.Resistor("R1", 1)

board = component.StripBoard((1, 2))

nets = ((r1.terminals[0],), (r1.terminals[1],))

cli.main(board, (r1,), nets)
Example #43
0
from cli import main


if __name__ == '__main__':
    main()
Example #44
0
name = "xlsx2pdf"

if __name__ == '__main__':
    from cli import main

    exit(main())
Example #45
0
# -*- coding: utf-8 -*-
'''Entrypoint module, in case you use `python -m {{parent}}.{{project}}`.'''

import sys

from {{parent}}.{{project}} import cli

if '__main__' == __name__:
    cli.main(sys.argv[1:])
Example #46
0
    if rc is None:
        logger.info("Config file not found.")
        konch.main(konch_args)
    else:
        konchrc = konch.use_file(rc, trust=True)
        DBG(dir(konchrc))
        DBG(f"{dir(konchrc.konch)}")
        DBG(f"konch_args: {konch_args}")
        konch.start(konch_args)
    return


def touch_files():
    files = [
        Path.home() / '.ptpython' / 'history',
    ]
    for file in files:
        Path(file).parent.mkdir(parents=True, exist_ok=True)
        Path(file).touch()


if __name__ == "__main__":
    from cli import main

    # DBG("bonked, (__main__)")
    sys.exit(main())  # pragma: no cover
"""
# TODO:
    tmux integration?
"""
Example #47
0
        # and then transmit it
        ANDI(r.data, r.result, 0xFF),
        JAL(r.lr, "uart_tx"),
        SRLI(r.data, r.result, 8),
        JAL(r.lr, "uart_tx"),


        # and do it all again
        J("main"),

    L("uart_tx"),
        LDXA(r.wait_status, 2),
        ANDI(r.wait_status, r.wait_status, 1),
        BNZ("uart_tx"),
        STXA(r.data, 2),
        JR(r.lr, 0),
    ])

    return fw

if __name__ == "__main__":
    from cli import main
    def make(simulating):
        raise Exception("this is code only!")

    def fw():
        return firmware()

    main(maker=make, fw=fw, build_args={"synth_opts": "-abc9"})
Example #48
0
    def test_cli_called_with_wrong_arg(self, capsys):
        sys.argv = ['cli.py', 'foo']
        with pytest.raises(SystemExit):
            cli.main()

        assert 'Unknown' in capsys.readouterr()[0]
Example #49
0
#!/usr/bin/python3.6

if __name__ == '__main__':
    from cli import main

    main()
Example #50
0
    def test_update_security_data_on_multiple_dates(self, mock_scraper):
        # Load test data
        dataset = test_utils.load_test_data()
        ticker = 'AMZN'
        dt1 = datetime.datetime(2019, 8, 23)
        expected_data_dt1 = test_utils.get_test_data(dataset, ticker, dt1)
        dt2 = datetime.datetime(2019, 8, 26)
        expected_data_dt2 = test_utils.get_test_data(dataset, ticker, dt2)
        dt3 = datetime.datetime(2019, 8, 27)
        expected_data_dt3 = test_utils.get_test_data(dataset, ticker, dt3)
        data_series = [(dt3, expected_data_dt3), (dt2, expected_data_dt2),
                       (dt1, expected_data_dt1)]

        # Create an existing database with data already in the database
        self.da.create_test_database()
        data = self.da.connect(self.database)
        data.insert_securities([ticker])

        data.update_market_data(ticker, (dt1, expected_data_dt1))
        data.close()

        sys.argv = ['./cli.py', self.database]
        self.expected_output = []
        self.expected_output.append(
            app.Messages.load_existing_database(self.database))
        self.expected_output.append(app.Messages.main_menu())
        self.expected_output.append(app.Messages.option_input())

        ret_data = [(dt2.date(), expected_data_dt2),
                    (dt3.date(), expected_data_dt3)]
        mock_scraper.return_value = ret_data, []

        self.user_input.append(app.MenuOptions.UPDATE_MARKET_DATA)
        self.expected_output.append(app.Messages.market_data_updated())
        self.expected_output.append(app.Messages.main_menu())
        self.expected_output.append(app.Messages.option_input())

        self.user_input.append(app.MenuOptions.VIEW_SECURITIES)
        self.expected_output.append(app.Messages.view_securities(['AMZN']))
        self.expected_output.append(app.Messages.option_input())

        self.user_input.append('1')
        self.expected_output.append(
            app.Messages.view_security_data(ticker, data_series))
        self.expected_output.append(app.Messages.any_key_to_return())

        self.user_input.append('')
        self.expected_output.append(app.Messages.view_securities(['AMZN']))
        self.expected_output.append(app.Messages.option_input())
        self.user_input.append('0')
        self.expected_output.append(app.Messages.main_menu())
        self.expected_output.append(app.Messages.option_input())
        self.user_input.append(app.MenuOptions.QUIT)
        self.expected_output.append(app.Messages.quit())

        app.main()

        check_output(self.actual_output, self.expected_output)

        # Check that scraper was called
        mock_scraper.assert_called_once()
Example #51
0
#     OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
#     USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
A 555 astable circuit.

"""

import component
import cli

ic555 = component.DualInlinePackage("555", 8)
r1 = component.Resistor("R1", 4)
r2 = component.Resistor("R2", 4)
c1 = component.Capacitor("C1", 4)
c2 = component.Capacitor("C2", 4)
components = (ic555, r1, r2, c1, c2)

board = component.StripBoard((7, 7))

nets = (
    (r1.terminals[0], ic555.terminals[3], ic555.terminals[7]),
    (r1.terminals[1], ic555.terminals[6], r2.terminals[0]),
    (r2.terminals[1], ic555.terminals[5], ic555.terminals[1], c1.terminals[0]),
    (c1.terminals[1], ic555.terminals[0], c2.terminals[1]),
    (c2.terminals[0], ic555.terminals[4]),
    (ic555.terminals[2],),
)

cli.main(board, components, nets)
Example #52
0
    def test_cli_called_without_args(self, capsys):
        sys.argv = ['cli.py']
        with pytest.raises(SystemExit):
            cli.main()

        assert 'cli.py' in capsys.readouterr()[0]
Example #53
0
import sys
import re

if "-r" in sys.argv:
    pass  # TODO MAKE RESTART PROCESSING
else:
    import cli

    cli.main()
Example #54
0
# permissions and limitations under the License.
#
# When distributing Covered Code, include this CDDL
# HEADER in each file and include the License file at
# LICENSE.txt  If applicable,
# add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your
# own identifying information: Portions Copyright [yyyy]
# [name of copyright owner]
#
# CDDL HEADER END

# Copyright 2014-2017 Extreme Networks, Inc.  All rights reserved.
# Use is subject to license terms.

# This file is part of e2x (translate EOS switch configuration to ExtremeXOS)

"""Entry point for the e2x.py binary (which is a ZIP archive)."""

import sys

import cli


if __name__ == '__main__':
    cmdlineArgs = sys.argv[1:]
    ret = cli.main(cmdlineArgs)
    sys.exit(ret)

# vim:filetype=python:expandtab:shiftwidth=4:tabstop=4