def test_remaining_principle_calculator(self):
        debts, expected_results, discretionary = loadDebtsfromFile(
            os.path.join('TestFiles', 'heloc_vs_amortized.csv'), "avalanche")

        print(debts)
        heloc = debts[0]
        amortized = debts[1]

        print('\nresults')
        print(expected_results)

        actual_amortized, _ = main([amortized],
                                   0.0,
                                   actionMonths=12,
                                   method="avalanche")

        print(actual_amortized)
        self.assertAlmostEqual(expected_results[1][0],
                               actual_amortized[0][5],
                               delta=5.0)
        self.assertEqual(expected_results[1][2], actual_amortized[0][3])

        actual_heloc, _ = main([heloc],
                               0.0,
                               actionMonths=12,
                               method="avalanche")
        print(actual_heloc)
        self.assertAlmostEqual(expected_results[0][0],
                               actual_heloc[0][5],
                               delta=125.0)
        self.assertEqual(expected_results[0][2], actual_heloc[0][3])
Пример #2
0
def demo_status():
    # global video_camera
    # if video_camera == None:
    #     video_camera = VideoCamera()

    json = request.get_json()

    status = json['status']

    print('kms!', file=sys.stderr)
    sys.stderr.flush()

    if status == "true":
        # app.logger.warning('A warning occurred (%d apples)', 42)
        # app.logger.error('An error occurred')

        # video_camera.start_record()
        print("testing INFO", file=sys.stderr)
        sys.stderr.flush()
        sys.stdout.flush()
        lib_processing.main()
        return jsonify(result="started")
    else:
        print("rip in pieces", file=sys.stderr)
        sys.stderr.flush()
        # video_camera.stop_record()
        return jsonify(result="stopped")
Пример #3
0
 def test_main_exits_with_code_1_if_config_validation_fails(self, config_validator_mock, exit_stub):
     mock_validator = Mock()
     mock_validator.is_valid = Mock(return_value=False)
     config_validator_mock.return_value = mock_validator
     with self.assertRaises(SystemExit) as sys_exit:
         main.main()
     self.assertEqual(sys_exit.exception.code, 1)
Пример #4
0
def batch_main():
    """Executes main function in a batch"""
    for year in (2015, 2016, 2017, 2018, 2019):
        SETTINGS['cutoff_value'] = year
        SETTINGS['log_name'] = f'{year}_log.txt'
        SETTINGS['csv_name'] = f'{year}_firepoints.csv'
        main(**SETTINGS)
Пример #5
0
def solution_works(test, a):
    with mock.patch('__builtin__.raw_input', side_effect=[a]):
        captured_output = StringIO.StringIO()
        sys.stdout = captured_output

        main()
        sys.stdout = sys.__stdout__

        test.assertTrue((len(captured_output.getvalue()) > 0),
                        msg="You did not print anything!")

        test.assertTrue(
            ("is " in captured_output.getvalue()),
            msg=
            "You should output \"Number INPUT is odd/even\" to print the result. You printed: "
            + captured_output.getvalue())

        test_result = captured_output.getvalue(
        )[captured_output.getvalue().index('is ') + len('is '):]

        if a % 2 == 0:
            correct_answer = 'even'

        else:
            correct_answer = 'odd'

        test.assertTrue(correct_answer in captured_output.getvalue(),
                        msg="Number " + str(a) + " is " + str(correct_answer) +
                        " you proposed: " + test_result)
Пример #6
0
    def test_main_exits_with_code_1_if_not_all_protected_playlists_exist(self, get_config_stub, config_validator_mock,
                                                                         setup_logger_mock, helper_mock, integrity_mgr_mock,
                                                                         cleaner_mock, moderate_playlists_mock, exit_stub):

        only_playlist = { 'uri': self.generate_playlist_uri() }
        get_config_stub.return_value = ({
            'PROTECT_ALL': False,
            'PROTECTED_PLAYLISTS': []
        }, {}, {
            'CLIENT_ID': 'spotifyclientid',
            'CLIENT_SECRET': 'spotifyclientsecret',
            'REDIRECT_URI': 'http://localhost:8080',
            'USERNAME': '******'
        })

        mock_validator = Mock()
        mock_validator.is_valid.return_value = True
        mock_validator.all_protected_playlists_exist.return_value = False
        config_validator_mock.return_value = mock_validator

        configure_api_stub = Mock()
        configure_api_stub.configure_api.return_value = spotipy.client.Spotify()
        helper_mock.return_value = configure_api_stub

        with self.assertRaises(SystemExit) as sys_exit:
            main.main()
        self.assertEqual(sys_exit.exception.code, 1)
        moderate_playlists_mock.assert_not_called()
Пример #7
0
 def test_second_of_the_year(self):
     answer = "31536000"
     captured_output = StringIO.StringIO()
     sys.stdout = captured_output
     main()
     sys.stdout = sys.__stdout__
     self.assertTrue((answer in captured_output.getvalue()),
                     msg="Printed value is not correct!")
Пример #8
0
    def test_plugin(self):

        projectName = "ImageJ filter sobel"
        self.logger.info(
            "Testing the op: {} with overloading option: {}".format(projectName, op)
        )

        method_call_types = {}

        supported_data_types = [
            "double",
            "float",
            "long",
            "int",
            "short",
            "char",
            "byte",
            "boolean",
        ]

        # Get WIPP and ImageJ data types
        _opName = op
        _in1_wipp_types = {"SobelRAI": "collection"}
        _in1_imagej_types = {"SobelRAI": "RandomAccessibleInterval"}
        if _in1_wipp_types.get(op, None) != "collection":
            method_call_types.update(
                {
                    method: dtype
                    for method, dtype in _in1_imagej_types.items()
                    if dtype in supported_data_types
                }
            )
        # Generate data for the inputs
        _in1 = self.generate_data(
            "in1", _in1_wipp_types.get(op, None), method_call_types.get(op, None)
        )
        # Handle the op output
        _out = self.output_handler("out", "collection")
        try:
            # Call the op
            main(_opName=_opName, _in1=_in1, _out=_out)
            self.logger.info(
                "SUCCESS: op: {} with option {} was successful\n".format(
                    projectName, op
                )
            )
            self.summary.info("1")
        except Exception:
            self.logger.info(
                "FAILURE: op: {} with option {} was NOT successful".format(
                    projectName, op
                )
                + "\n"
                + str(sys.exc_info())
            )
            self.logger.info(traceback.format_exc() + "\n")
            self.summary.info("0")
Пример #9
0
 def test_main(self, parser, syncend):
     parser.return_value.get_arguments.return_value = (
         self.collection_name,
         self.postman_api_key,
         self.trigger_interval,
         self.slack_channel,
         self.slack_token,
     )
     mn.main()
Пример #10
0
 def test_main_validates_configurations_before_setting_up_a_logger(self, config_validator_mock,
                                                                   load_config_stub, exit_stub):
     # The stubbed return value of (False) is_valid() allows main() to quit early
     mock_validator = Mock()
     mock_validator.is_valid = Mock(return_value=False)
     config_validator_mock.return_value = mock_validator
     with self.assertRaises(SystemExit) as sys_exit:
         main.main()
     mock_validator.is_valid.assert_called_once()
Пример #11
0
def run(hook, _config, c_stages, c_results, _run):

    logger = logging.getLogger("{{ cookiecutter.repo_name }}." +
                               os.path.basename(os.path.splitext(__file__)[0]))
    logger.info(_config["timestamp"])

    if c_stages["main"]:
        main(_config)

    ex.add_artifact(os.path.join(c_results["output_path"], "general.log"))
Пример #12
0
 def test_main_exits_with_code_1_if_an_exception_is_raised_when_setting_up_a_loger(self, config_validator_mock,
                                                                                   setup_logger_mock, load_config_stub,
                                                                                   exit_stub):
     mock_validator = Mock()
     # stubbing is_valid to return True allows the function to continue running beyond validation
     mock_validator.is_valid = Mock(return_value=True)
     config_validator_mock.return_value = mock_validator
     with self.assertRaises(SystemExit) as sys_exit:
         main.main()
     self.assertEqual(sys_exit.exception.code, 1)
Пример #13
0
 def test_gcode_interactive(self):
     """
     Test that the flag calls the function with the right argument
     :return:
     """
     with mock.patch('src.main.interactive_gcode') as mock_func:
         with pytest.raises(SystemExit) as cm:
             main(["--gi", "--ip=192.168.0.1", "--port=10002", "--vid=0x0403", "--pid=0x6001"])
         assert cm.value.code != EXIT_BAD_INPUT
         assert cm.value.code == EXIT_SUCCESS
         assert mock_func.called
Пример #14
0
 def test_demo_mode(self):
     """
     Test that the flag --demo calls the function with the right arguments
     :return:
     """
     with mock.patch('src.main.demo_mode') as mock_func:
         with pytest.raises(SystemExit) as cm:
             main(["--demo", "--ip=192.168.0.1", "--port=10002"])
         assert cm.value.code != EXIT_BAD_INPUT
         assert cm.value.code == EXIT_SUCCESS
         assert mock_func.called
Пример #15
0
    def test_main_returns_return_value_of_restore_config_if_rdc_option_in_args(self, restore_stub, exit_stub):
        with patch.object(sys, 'argv', ['--rdc']) as stubbed_args:
            restore_stub.return_value = 0
            with self.assertRaises(SystemExit) as sys_exit:
                main.main()
            self.assertEqual(sys_exit.exception.code, 0)

            restore_stub.return_value = 1
            with self.assertRaises(SystemExit) as sys_exit:
                main.main()
            self.assertEqual(sys_exit.exception.code, 1)
Пример #16
0
 def test_help(self, capsys, cmd):
     """
     Test that the different help options print the doc string of main
     :param capsys:
     :param cmd:
     :return:
     """
     with pytest.raises(SystemExit):
         main([cmd])
     captured = capsys.readouterr().out.strip("\n")
     stripped_doc = cli_doc.strip("\n")
     assert stripped_doc in captured
Пример #17
0
    def test_main_prints_help_info_and_exits_with_code_0_if_help_option_in_args(self, print_help_mock, exit_stub):
        with patch.object(sys, 'argv', [ '--help' ]) as stubbed_args:
            with self.assertRaises(SystemExit) as sys_exit:
                main.main()
        print_help_mock.assert_called_once()
        self.assertEqual(sys_exit.exception.code, 0)

        with patch.object(sys, 'argv', ['-h']) as stubbed_args:
            with self.assertRaises(SystemExit) as sys_exit:
                main.main()
        self.assertEqual(print_help_mock.call_count, 2)
        self.assertEqual(sys_exit.exception.code, 0)
Пример #18
0
 def do_POST(self):
     content_length = int(
         self.headers['Content-Length'])  # <--- Gets the size of data
     post_data = self.rfile.read(
         content_length)  # <--- Gets the data itself
     logger.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n",
                 str(self.path), str(self.headers),
                 post_data.decode('utf-8'))
     main(json.loads(post_data.decode('utf-8')))
     self._set_response()
     self.wfile.write("POST request for {}".format(
         self.path).encode('utf-8'))
Пример #19
0
 def test_validate_gcode(self, cmd):
     """
     Test that the flags call the function with the right arguments
     :param cmd:
     :return:
     """
     with mock.patch('src.main.check_trajectory') as mock_func:
         with pytest.raises(SystemExit) as cm:
             main([cmd, 'test.gcode', 'config.ini'])
         print(cm)
         assert cm.value.code != EXIT_BAD_INPUT
         assert cm.value.code == EXIT_SUCCESS
         assert mock_func.called
Пример #20
0
    def test_main_exits_with_code_1_if_redirect_uri_is_in_use(self, get_config_stub, config_validator_mock,
                                                              setup_logger_mock, helper_mock, exit_stub):
        mock_validator = Mock()
        # stubbing is_valid to return True allows the function to continue running beyond validation
        mock_validator.is_valid = Mock(return_value=True)
        config_validator_mock.return_value = mock_validator

        configure_api_stub = Mock()
        # an OSError is raised when the redirect URI is already in use
        configure_api_stub.configure_api.side_effect = OSError('Address already in use')
        helper_mock.return_value = configure_api_stub
        with self.assertRaises(SystemExit) as sys_exit:
            main.main()
        self.assertEqual(sys_exit.exception.code, 1)
Пример #21
0
    def test_gcode_execution(self):
        """
        Test that the flag calls the function with the right argument
        :return:
        """
        current_file_path = Path(os.path.dirname(os.path.realpath(__file__)))
        gcode_file = Path(current_file_path, "cartesian_violation.gcode")

        with mock.patch('src.main.execute_gcode') as mock_func:
            with pytest.raises(SystemExit) as cm:
                main(["--gi", "--ip=192.168.0.1", "--port=10002", "--vid=0x0403", "--pid=0x6001",
                      f"--f={gcode_file}"])
            assert cm.value.code != EXIT_BAD_INPUT
            assert cm.value.code == EXIT_SUCCESS
            assert mock_func.called
Пример #22
0
                def OnClick():
                    input_parameters["config_file"] = "GUI"
                    for param in simulation_parameters:
                        if param.choices == ["True", "False"]:
                            input_parameters[param.name] = "True" if int(
                                getattr(self,
                                        param.name).get()) == 1 else "False"
                        elif param.name == "grating":
                            input_parameters["grating"] = str(
                                self.grating.get()).split("[")[0].strip()
                        else:
                            input_parameters[param.name] = param.type(
                                getattr(self, param.name).get())

                    from src.main import main
                    main(input_parameters)
Пример #23
0
def process(dirname):
    filename = datetime.now().isoformat()
    f = open(dirname + '/' + filename, 'w')
    for file in os.listdir(dirname):
        results = main.main(dirname + '/' + file)
        f.write(file + " : " + results + "\n")
    f.close()
Пример #24
0
    def test_0(self):
        db = Database(self.TMPDIR, DataItem)
        html = HtmlOutput(self.TMPDIR / "out.html", ["secret", "_id", "detail"])
        search = SearchSim()
        
        for loop in range(4):
            LOG.info("-------- LOOP %d -------", loop)
            main(db, search, html)
            cat_file(html.filename)
        
        to_check = { 
            "table_new"  : ["ID0019","ID0021"],
            "table_gone" : ["ID0009","ID0011"],
            "table_existing" : ["ID0013","ID0015", "ID0017"],
        }

        self.check_file( html.filename, to_check )
Пример #25
0
def test_cli_args_noxmit():
    x0 = 232323e-6
    b = 3.8
    text = 'hi'
    argv = f'{x0} {b} {text}'.split()
    response = main.main(argv)
    nums = [int(_) for _ in response.split(',')]
    assert nums == [2077, 5]
Пример #26
0
    def test_main_runs_playlist_moderation_until_user_wants_to_exit_if_loop_mode_enabled(self, get_config_stub, config_validator_mock,
                                                                                         setup_logger_mock, helper_mock, integrity_mgr_mock,
                                                                                         cleaner_mock, user_exit_mock, exit_stub):

        only_playlist = { 'uri': self.generate_playlist_uri() }
        get_config_stub.return_value = ({
            'PROTECT_ALL': False,
            'PROTECTED_PLAYLISTS': [ { 'playlistlabel': only_playlist } ],
            'DELAY_BETWEEN_SCANS': 1
        }, {}, {
            'CLIENT_ID': 'spotifyclientid',
            'CLIENT_SECRET': 'spotifyclientsecret',
            'REDIRECT_URI': 'http://localhost:8080',
            'USERNAME': '******'
        })

        mock_validator = Mock()
        mock_validator.is_valid.return_value = True
        mock_validator.all_protected_playlists_exist.return_value = True
        config_validator_mock.return_value = mock_validator

        helper_obj = Mock()
        helper_obj.configure_api.return_value = spotipy.client.Spotify()
        helper_mock.return_value = helper_obj

        integrity_mgr_obj = Mock()
        playlist_cleaner_obj = Mock()
        integrity_mgr_mock.return_value = integrity_mgr_obj
        cleaner_mock.return_value = playlist_cleaner_obj

        with self.assertRaises(SystemExit) as sys_exit:
            # run within SysExit context because main explicitly exits with code 0 after completion
            main.main()

        self.assertEqual(integrity_mgr_obj.run.call_count, 2)
        self.assertEqual(len(integrity_mgr_obj.run.call_args_list[0][0]), 1)
        self.assertEqual(integrity_mgr_obj.run.call_args_list[0][0][0], only_playlist)

        self.assertEqual(len(integrity_mgr_obj.run.call_args_list[1][0]), 1)
        self.assertEqual(integrity_mgr_obj.run.call_args_list[1][0][0], only_playlist)

        self.assertEqual(playlist_cleaner_obj.run.call_count, 2)
        self.assertEqual(playlist_cleaner_obj.run.call_args_list[0][0][0], only_playlist)
        self.assertEqual(len(playlist_cleaner_obj.run.call_args_list[0][0]), 1)
        self.assertEqual(playlist_cleaner_obj.run.call_args_list[1][0][0], only_playlist)
        self.assertEqual(len(playlist_cleaner_obj.run.call_args_list[1][0]), 1)
Пример #27
0
def text_reply(msg):
    global flag
    message = msg['Text']
    fromName = msg['FromUserName']
    toName = msg['ToUserName']

    # logging.error('# 收到命令: ' + message + ",From:" + fromName + ",to:" + toName)
    print('# 收到命令: ' + message + ",From:" + fromName + ",to:" + toName)

    if toName == 'filehelper':
        itchat.send(sendMsg, fromName)
        if message == "打卡":
            main()
            global driver
            chromedriver = r"D:\DevPlatform\chromedriver\chromedriver.exe"
            os.environ['webdriver.chromedriver'] = chromedriver
            driver = webdriver.Chrome(chromedriver)
Пример #28
0
    def test_main_exits_with_code_1_if_api_client_setup_fails(self, get_config_stub, config_validator_mock,
                                                             setup_logger_mock, helper_mock, exit_stub):
        mock_validator = Mock()
        # stubbing is_valid to return True allows the function to continue running beyond validation
        mock_validator.is_valid = Mock(return_value=True)
        config_validator_mock.return_value = mock_validator

        configure_api_stub = Mock()
        configure_api_stub.configure_api.side_effect = Exception('401 unauthorized')
        helper_mock.return_value = configure_api_stub
        with self.assertRaises(SystemExit) as sys_exit:
            main.main()
        self.assertEqual(sys_exit.exception.code, 1)

        configure_api_stub.configure_api.side_effect = [ None ]
        with self.assertRaises(SystemExit) as sys_exit:
            main.main()
        self.assertEqual(sys_exit.exception.code, 1)
Пример #29
0
def test_cli_args():
    x0 = 232323e-6
    b = 3.8
    text = 'hi'
    xmit = '--xmit .9'
    argv = f'{x0} {b} {text} {xmit}'.split()
    response = main.main(argv)
    nums = [int(_) for _ in response.split(',')]
    assert nums[0] >= 2077 and nums[1] >= 5
Пример #30
0
def run(args):
    """Run the package's main script. All arguments are passed to it."""
    # The main script expects to get the called executable's name as
    # argv[0]. However, paver doesn't provide that in args. Even if it did (or
    # we dove into sys.argv), it wouldn't be useful because it would be paver's
    # executable. So we just pass the package name in as the executable name,
    # since it's close enough. This should never be seen by an end user
    # installing through Setuptools anyway.
    from src.main import main
    raise SystemExit(main([CODE_DIRECTORY] + args))
Пример #31
0
    def test_invalid_regex_input(self):

        error_message_for_invalid_regex = sys.argv[0].split('\\')[-1]
        error_message_for_invalid_regex += ': error: argument -r/--regex: Error in function validate_regex: The regex expression is not valid'
        sys.argv.append('-f')
        sys.argv.append('/project/tests/dummy_input1.txt')
        sys.argv.append('-r')
        sys.argv.append('+')
        sys.argv.append('-m')
        temp_strout = StringIO()
        try:
            with contextlib.redirect_stderr(temp_strout):
                main()
        except:
            error_line = temp_strout.getvalue().strip().splitlines()[-1]
            # bring back the original sys.argv
            for par in sys.argv[1:]:
                sys.argv.remove(par)
            self.assertEqual(error_line, error_message_for_invalid_regex)
Пример #32
0
#! /usr/bin/env python

from src import main
main.main()
Пример #33
0
    "\tlegoJson2Pickle: BJ4\n"
  )))

if __name__ == '__main__':
  # import pdb; pdb.set_trace()
  args = sys.argv[1:]
  # args[0] = RUN_SHORT_CUT
  if not args:
    print_usage()
    sys.exit(-1)

  if args[0] == "help":
    print_usage()

  elif args[0] == "run":
    main()

  elif args[0] == "resizeImageCollectioneDir":
    if len(args) < 2:
      print_usage()
      print('Not enough argments')
      sys.exit(-1)
    resizeImageCollectioneDir(args[1], "output/")

  elif args[0] == "coverImageDirToJSON":
    if len(args) < 2:
      print_usage()
      print('Not enough argments')
      sys.exit(-1)
    coverImageDirToJSON(args[1], "output/alldata.json")    
  elif args[0] == "legoJson2Pickle":
Пример #34
0
 def test_main_bootstrap(self):
     "json is written to stdout"
     results = main.main(self.small_doc) # writes article json to stdout
     results = json.loads(results)
     self.assertTrue('article' in results)
     self.assertTrue('journal' in results)
Пример #35
0
#!/usr/bin/env python3
import sys
from src.main import main

if __name__ == "__main__":
    #Check dependencies
    main(sys.argv[1:])
        # If update_bloomfilter > 0, then every so many seconds an introduction request will be sent
        # Introduction request contains the Dispersy address
        self._community.create_candidate(address, True, address, address, u"unknown")
        
    def do_callback(self, key, *args, **kwargs):
        if self._api_callback is not None:
            self._api_callback(key, *args, **kwargs)
        
def verify_addresses_are_free(addrs):    
    if not addrs: # None or []
        logger.warning("No address to return!")
        return addrs
    l = set() # No doubles!
    for addr in addrs:
        if not addr.resolve_interface():
            logger.debug("Interface for %s does not exist", addr)
        elif not try_sockets([addr]):
            logger.debug("Port %s is not available for %s on %s", addr.port, addr.ip, addr.interface.name)
            addr.set_port(0) # Let the system decide
            l.add(addr)
        else:
            l.add(addr)
    logger.debug("Swift will listen to %s", [str(a) for a in l])        
    return list(l)
    
if __name__ == '__main__':
    from src.main import main
    args, kwargs = main()
    d = DispersyInstance(*args, **kwargs)
    d.start()