Exemplo n.º 1
0
def test_main_first_arg_help():
    """
    If there is a single argument of "--help", it prints some help.
    """
    with mock.patch('uflash.argparse.ArgumentParser') as mock_ap:
        uflash.main(argv=['--help'])
        mock_ap.assert_called_once_with(description=uflash._HELP_TEXT)
Exemplo n.º 2
0
def test_main_first_arg_help():
    """
    If there is a single argument of "help", it prints some help.
    """
    with mock.patch('builtins.print') as mock_print:
        uflash.main(argv=['help'])
        assert mock_print.called_once_with(uflash._HELP_TEXT)
Exemplo n.º 3
0
def test_main_first_arg_help():
    """
    If there is a single argument of "--help", it prints some help.
    """
    with mock.patch('uflash.argparse.ArgumentParser') as mock_ap:
        uflash.main(argv=['--help'])
        mock_ap.assert_called_once_with(description=uflash._HELP_TEXT)
Exemplo n.º 4
0
def test_extract_command():
    """
    Test the command-line script extract feature
    """
    with mock.patch('uflash.extract') as mock_extract:
        uflash.main(argv=['-e', 'hex.hex', 'foo.py'])
        mock_extract.assert_called_once_with('hex.hex', ['foo.py'])
Exemplo n.º 5
0
def test_extract_command():
    """
    Test the command-line script extract feature
    """
    with mock.patch('uflash.extract') as mock_extract:
        uflash.main(argv=['-e', 'hex.hex', 'foo.py'])
        mock_extract.assert_called_once_with('hex.hex', ['foo.py'])
Exemplo n.º 6
0
def test_extract_command_source_only():
    """
    If there is no target file the extract command should write to stdout
    """
    with mock.patch('uflash.extract') as mock_extract:
        uflash.main(argv=['hex.hex'])
        assert mock_extract.called_once_with('hex.hex')
Exemplo n.º 7
0
def test_main_first_arg_version():
    """
    If there is a single argument of "--version", it prints the version.
    """
    with mock.patch('uflash.get_version') as mock_ver:
        uflash.main(argv=['--version'])
        assert mock_ver.call_count == 1
Exemplo n.º 8
0
def test_main_first_arg_python():
    """
    If there is a single argument that ends with ".py", it calls flash with
    it as the path to the source Python file.
    """
    with mock.patch('uflash.flash') as mock_flash:
        uflash.main(argv=['foo.py'])
        assert mock_flash.called_once_with('foo.py')
Exemplo n.º 9
0
def test_main_keepname_message(capsys):
    """
    Ensure that the correct filename appears in output message.
    """
    uflash.main(argv=['tests/example.py', '--keepname'])
    stdout, stderr = capsys.readouterr()
    expected = 'example.hex'
    assert (expected in stdout) or (expected in stderr)
Exemplo n.º 10
0
def test_extract_not_implemented(capsys):
    """
    Raises a NotImplementedError when trying to use the extract flag.
    """
    with pytest.raises(NotImplementedError):
        uflash.main(argv=["--extract", "test.py"])
        _, stderr = capsys.readouterr()
        assert "The 'extract' flag is no longer supported." in stderr
Exemplo n.º 11
0
def test_runtime_not_implemented(capsys):
    """
    Raises a NotImplementedError when trying to use the runtime flag.
    """
    with pytest.raises(NotImplementedError):
        uflash.main(argv=["--runtime", "test.hex"])
        _, stderr = capsys.readouterr()
        assert "The 'runtime' flag is no longer supported." in stderr
Exemplo n.º 12
0
def test_main_two_args():
    """
    If there are two arguments passed into main, then it should pass them onto
    the flash() function.
    """
    with mock.patch('uflash.flash') as mock_flash:
        uflash.main(argv=['foo.py', '/media/foo/bar'])
        assert mock_flash.called_once_with('foo.py', '/media/foo/bar')
Exemplo n.º 13
0
def test_main_first_arg_not_python():
    """
    If the first argument does not end in ".py" then it should display a useful
    error message.
    """
    with mock.patch('builtins.print') as mock_print:
        uflash.main(argv=['foo.bar'])
        expected = ValueError('Python files must end in ".py".')
        assert mock_print.called_once_with(expected)
Exemplo n.º 14
0
def test_main_no_args():
    """
    If there are no args into the main function, it simply calls flash with
    no arguments.
    """
    with mock.patch('sys.argv', ['uflash', ]):
        with mock.patch('uflash.flash') as mock_flash:
            uflash.main()
            assert mock_flash.called_once_with(None, None)
Exemplo n.º 15
0
def test_main_watch_flag():
    """
    The watch flag cause a call the correct function.
    """
    with mock.patch("uflash.watch_file") as mock_watch_file:
        uflash.main(argv=["-w"])
        mock_watch_file.assert_called_once_with(
            None, uflash.flash, path_to_python=None, paths_to_microbits=[]
        )
Exemplo n.º 16
0
def test_main_named_args():
    """
    Ensure that named arguments are passed on properly to the flash() function.
    """
    with mock.patch('uflash.flash') as mock_flash:
        uflash.main(argv=['-r', 'baz.hex'])
        mock_flash.assert_called_once_with(path_to_python=None,
                                           paths_to_microbits=[],
                                           path_to_runtime='baz.hex')
Exemplo n.º 17
0
def test_main_named_args():
    """
    Ensure that named arguments are passed on properly to the flash() function.
    """
    with mock.patch('uflash.flash') as mock_flash:
        uflash.main(argv=['-r', 'baz.hex'])
        mock_flash.assert_called_once_with(path_to_python=None,
                                           paths_to_microbits=[],
                                           path_to_runtime='baz.hex')
Exemplo n.º 18
0
def test_main_runtime():
    """
    If there are three arguments passed into main, then it should pass them
    onto the flash() function.
    """
    with mock.patch('uflash.flash') as mock_flash:
        uflash.main(argv=['-r' 'baz.hex', 'foo.py', '/media/foo/bar'])
        mock_flash.assert_called_once_with(path_to_python='foo.py',
                                           path_to_microbit='/media/foo/bar',
                                           path_to_runtime='baz.hex')
Exemplo n.º 19
0
def test_main_first_arg_python():
    """
    If there is a single argument that ends with ".py", it calls flash with
    it as the path to the source Python file.
    """
    with mock.patch('uflash.flash') as mock_flash:
        uflash.main(argv=['foo.py'])
        mock_flash.assert_called_once_with(path_to_python='foo.py',
                                           paths_to_microbits=[],
                                           path_to_runtime=None)
Exemplo n.º 20
0
def test_main_first_arg_python():
    """
    If there is a single argument that ends with ".py", it calls flash with
    it as the path to the source Python file.
    """
    with mock.patch("uflash.flash") as mock_flash:
        uflash.main(argv=["foo.py"])
        mock_flash.assert_called_once_with(
            path_to_python="foo.py", paths_to_microbits=[], keepname=False
        )
Exemplo n.º 21
0
def test_main_two_args():
    """
    If there are two arguments passed into main, then it should pass them onto
    the flash() function.
    """
    with mock.patch('uflash.flash', return_value=None) as mock_flash:
        uflash.main(argv=['foo.py', '/media/foo/bar'])
        mock_flash.assert_called_once_with(path_to_python='foo.py',
                                           path_to_microbit='/media/foo/bar',
                                           path_to_runtime=None)
Exemplo n.º 22
0
def test_main_first_arg_not_python():
    """
    If the first argument does not end in ".py" then it should display a useful
    error message.
    """
    with mock.patch.object(builtins, 'print') as mock_print:
        uflash.main(argv=['foo.bar'])
        error = mock_print.call_args[0][0]
        assert isinstance(error, ValueError)
        assert error.args[0] == 'Python files must end in ".py".'
Exemplo n.º 23
0
def test_main_first_arg_not_python():
    """
    If the first argument does not end in ".py" then it should display a useful
    error message.
    """
    with mock.patch.object(builtins, 'print') as mock_print:
        uflash.main(argv=['foo.bar'])
        error = mock_print.call_args[0][0]
        assert isinstance(error, ValueError)
        assert error.args[0] == 'Python files must end in ".py".'
Exemplo n.º 24
0
def test_main_first_arg_python():
    """
    If there is a single argument that ends with ".py", it calls flash with
    it as the path to the source Python file.
    """
    with mock.patch('uflash.flash') as mock_flash:
        uflash.main(argv=['foo.py'])
        mock_flash.assert_called_once_with(path_to_python='foo.py',
                                           paths_to_microbits=[],
                                           path_to_runtime=None)
Exemplo n.º 25
0
def test_watch_raises(capsys):
    """
    If the watch system goes wrong, it should say that's what happened
    """
    with mock.patch("uflash.watch_file", side_effect=RuntimeError("boom")):
        with pytest.raises(SystemExit):
            uflash.main(argv=["--watch", "test.py"])

    _, stderr = capsys.readouterr()
    expected = "Error watching test.py"
    assert expected in stderr
Exemplo n.º 26
0
def test_main_no_args():
    """
    If there are no args into the main function, it simply calls flash with
    no arguments.
    """
    with mock.patch('sys.argv', ['uflash', ]):
        with mock.patch('uflash.flash') as mock_flash:
            uflash.main()
            mock_flash.assert_called_once_with(path_to_python=None,
                                               paths_to_microbits=[],
                                               path_to_runtime=None)
Exemplo n.º 27
0
def test_extract_raises(capsys):
    """
    If the extract system goes wrong, it should say that's what happened
    """
    with mock.patch('uflash.extract', side_effect=RuntimeError("boom")):
        with pytest.raises(SystemExit):
            uflash.main(argv=['--extract', 'test.py'])

    _, stderr = capsys.readouterr()
    expected = 'Error extracting test.py'
    assert expected in stderr
Exemplo n.º 28
0
def test_main_first_arg_not_python(capsys):
    """
    If the first argument does not end in ".py" then it should display a useful
    error message.
    """
    with pytest.raises(SystemExit):
        uflash.main(argv=['foo.bar'])

    _, stderr = capsys.readouterr()
    expected = 'Python files must end in ".py".'
    assert expected in stderr
Exemplo n.º 29
0
def test_main_runtime():
    """
    If there are three arguments passed into main, then it should pass them
    onto the flash() function.
    """
    with mock.patch('uflash.flash') as mock_flash:
        uflash.main(argv=['-r' 'baz.hex', 'foo.py', '/media/foo/bar'])
        mock_flash.assert_called_once_with(
            path_to_python='foo.py',
            paths_to_microbits=['/media/foo/bar'],
            path_to_runtime='baz.hex')
Exemplo n.º 30
0
def test_main_two_args():
    """
    If there are two arguments passed into main, then it should pass them onto
    the flash() function.
    """
    with mock.patch('uflash.flash', return_value=None) as mock_flash:
        uflash.main(argv=['foo.py', '/media/foo/bar'])
        mock_flash.assert_called_once_with(
            path_to_python='foo.py',
            paths_to_microbits=['/media/foo/bar'],
            path_to_runtime=None)
Exemplo n.º 31
0
def test_main_keepname_args():
    """
    Ensure that keepname is passed properly.
    """
    with mock.patch('uflash.flash') as mock_flash:
        uflash.main(argv=['tests/example.py', '--keepname'])
        mock_flash.assert_called_once_with(path_to_python='tests/example.py',
                                           paths_to_microbits=[],
                                           path_to_runtime=None,
                                           minify=False,
                                           keepname=True)
Exemplo n.º 32
0
def test_main_first_arg_help(capsys):
    """
    If there is a single argument of "--help", it prints some help and exits.
    """
    with pytest.raises(SystemExit):
        uflash.main(argv=['--help'])

    stdout, _ = capsys.readouterr()
    # argparse manipulates the help text (e.g. changes line wrap)
    # so it isn't trivial to compare the output to uflash._HELP_TEXT.
    expected = 'Flash Python onto the BBC micro:bit'
    assert expected in stdout
Exemplo n.º 33
0
def test_main_no_args():
    """
    If there are no args into the main function, it simply calls flash with
    no arguments.
    """
    with mock.patch('sys.argv', ['uflash', ]):
        with mock.patch('uflash.flash') as mock_flash:
            uflash.main()
            mock_flash.assert_called_once_with(path_to_python=None,
                                               paths_to_microbits=[],
                                               path_to_runtime=None,
                                               minify=False)
Exemplo n.º 34
0
def test_main_two_args():
    """
    If there are two arguments passed into main, then it should pass them onto
    the flash() function.
    """
    with mock.patch("uflash.flash", return_value=None) as mock_flash:
        uflash.main(argv=["foo.py", "/media/foo/bar"])
        mock_flash.assert_called_once_with(
            path_to_python="foo.py",
            paths_to_microbits=["/media/foo/bar"],
            keepname=False,
        )
Exemplo n.º 35
0
def test_extract_command_source_only():
    """
    If there is no target file the extract command should write to stdout.
    """
    mock_e = mock.MagicMock(return_value=b'print("hello, world!")')
    mock_o = mock.mock_open(read_data='script')
    with mock.patch('uflash.extract_script', mock_e) as mock_extract_script, \
            mock.patch.object(builtins, 'open', mock_o) as mock_open, \
            mock.patch.object(builtins, 'print') as mock_print:
        uflash.main(argv=['-e', 'hex.hex'])
        mock_open.assert_any_call('hex.hex', 'r')
        mock_extract_script.assert_called_once_with('script')
        mock_print.assert_any_call(b'print("hello, world!")')
Exemplo n.º 36
0
def test_main_first_arg_version(capsys):
    """
    If there is a single argument of "--version", it prints the version
    and exits.
    """
    with pytest.raises(SystemExit):
        uflash.main(argv=['--version'])

    stdout, stderr = capsys.readouterr()
    expected = uflash.get_version()
    # On python 2 --version prints to stderr. On python 3 to stdout.
    # https://bugs.python.org/issue18920
    assert (expected in stdout) or (expected in stderr)
Exemplo n.º 37
0
def test_minify_arg(capsys):
    """
    Test a the minify flag print an error but doesn't raise an exception.
    """
    with mock.patch("uflash.flash") as mock_flash:
        uflash.main(argv=["tests/example.py", "-m"])
        _, stderr = capsys.readouterr()
        assert "The 'minify' flag is no longer supported, ignoring" in stderr
        mock_flash.assert_called_once_with(
            path_to_python="tests/example.py",
            paths_to_microbits=[],
            keepname=False,
        )
Exemplo n.º 38
0
def test_extract_command_source_only():
    """
    If there is no target file the extract command should write to stdout.
    """
    mock_e = mock.MagicMock(return_value=b'print("hello, world!")')
    mock_o = mock.mock_open(read_data='script')
    with mock.patch('uflash.extract_script', mock_e) as mock_extract_script, \
            mock.patch.object(builtins, 'open', mock_o) as mock_open, \
            mock.patch.object(builtins, 'print') as mock_print:
        uflash.main(argv=['-e', 'hex.hex'])
        mock_open.assert_any_call('hex.hex', 'r')
        mock_extract_script.assert_called_once_with('script')
        mock_print.assert_any_call(b'print("hello, world!")')
Exemplo n.º 39
0
def test_main_no_args():
    """
    If there are no args into the main function, it simply calls flash with
    no arguments.
    """
    with mock.patch(
        "sys.argv",
        [
            "uflash",
        ],
    ):
        with mock.patch("uflash.flash") as mock_flash:
            uflash.main()
            mock_flash.assert_called_once_with(
                path_to_python=None, paths_to_microbits=[], keepname=False
            )
Exemplo n.º 40
0
def test_main_multiple_microbits():
    """
    If there are more than two arguments passed into main, then it should pass
    them onto the flash() function.
    """
    with mock.patch('uflash.flash', return_value=None) as mock_flash:
        uflash.main(argv=[
            'foo.py', '/media/foo/bar', '/media/foo/baz', '/media/foo/bob'
        ])
        mock_flash.assert_called_once_with(path_to_python='foo.py',
                                           paths_to_microbits=[
                                               '/media/foo/bar',
                                               '/media/foo/baz',
                                               '/media/foo/bob'
                                           ],
                                           path_to_runtime=None,
                                           minify=False,
                                           keepname=False)
Exemplo n.º 41
0
def test_flash_raises_with_info(capsys):
    """
    When flash goes wrong it should mention everything you tell it
    """
    with mock.patch("uflash.flash", side_effect=RuntimeError("boom")):
        with pytest.raises(SystemExit):
            uflash.main(argv=["test.py"])

    _, stderr = capsys.readouterr()
    expected = "Error flashing test.py to microbit: boom\n"
    assert stderr == expected

    with mock.patch("uflash.flash", side_effect=RuntimeError("boom")):
        with pytest.raises(SystemExit):
            uflash.main(argv=["test.py", "D:\\"])

    _, stderr = capsys.readouterr()
    expected = "Error flashing test.py to " + repr(["D:\\"]) + ": boom\n"
    assert stderr == expected

    with mock.patch("uflash.flash", side_effect=RuntimeError("boom")):
        with pytest.raises(SystemExit):
            uflash.main(argv=["test.py", "D:\\"])

    _, stderr = capsys.readouterr()
    expected = "Error flashing test.py to " + repr(["D:\\"]) + ": boom\n"
    assert stderr == expected
Exemplo n.º 42
0
def test_flash_raises_with_info(capsys):
    """
    When flash goes wrong it should mention everything you tell it
    """
    with mock.patch('uflash.flash', side_effect=RuntimeError("boom")):
        with pytest.raises(SystemExit):
            uflash.main(argv=['test.py'])

    _, stderr = capsys.readouterr()
    expected = 'Error flashing test.py to microbit: boom\n'
    assert stderr == expected

    with mock.patch('uflash.flash', side_effect=RuntimeError("boom")):
        with pytest.raises(SystemExit):
            uflash.main(argv=['test.py', 'D:\\'])

    _, stderr = capsys.readouterr()
    expected = 'Error flashing test.py to ' + repr(['D:\\']) + ': boom\n'
    assert stderr == expected

    with mock.patch('uflash.flash', side_effect=RuntimeError("boom")):
        with pytest.raises(SystemExit):
            uflash.main(argv=['-r', 'foo.hex', 'test.py', 'D:\\'])

    _, stderr = capsys.readouterr()
    expected = 'Error flashing test.py to ' + repr(['D:\\']) + \
               'with runtime foo.hex: boom\n'
    assert stderr == expected
Exemplo n.º 43
0
def flash():
    import uflash
    micropython_hex = os.path.join(project_root, 'vagrant_shared',
                                   'micropython', 'build', 'firmware.hex')
    if os.path.isfile(micropython_hex):
        uflash_args = sys.argv[2:]
        uflash_args.append('--runtime=%s' % micropython_hex)
        # Print useful information about the MicroPython hex time stamp
        file_timestamp = os.path.getmtime(micropython_hex)
        print('Flashing MicroPython modified on %s (%s ago):\n\t%s' %
              (datetime.fromtimestamp(file_timestamp).strftime("%Y-%m-%d %H:%M:%S"),
               timedelta(seconds=int(time.time() - file_timestamp)),
               micropython_hex))
        # If flashing with a Python script print the info
        if len(sys.argv) > 2:
            print('With Python script: %s\n' % sys.argv[2])
        # print(uflash_args)
        uflash.main(uflash_args)
    else:
        print('The file %s does not exists' % micropython_hex +
              'are you sure the MicroPython build was successful?')
        sys.exit(1)
Exemplo n.º 44
0
from __future__ import (absolute_import, division,
                        print_function, unicode_literals)
import sys
import os
import time
from datetime import datetime, timedelta

sys.path.append(os.path.join('vagrant_shared', 'uflash'))
import uflash


if __name__ == '__main__':
    micropython_hex = os.path.join('vagrant_shared', 'micropython', 'build',
                                   'bbc-microbit-classic-gcc-nosd', 'source',
                                   'microbit-micropython.hex')
    if os.path.isfile(micropython_hex):
        #sys.argv.append('--runtime=%s' % micropython_hex)
        sys.argv[0] = '--runtime=%s' % micropython_hex
        file_timestamp = os.path.getmtime(micropython_hex)
        print('Flashing MicroPython modified on %s (%s ago):\n\t%s' %
              (datetime.fromtimestamp(file_timestamp).strftime("%Y-%m-%d %H:%M:%S"),
               timedelta(seconds=int(time.time() - file_timestamp)),
               micropython_hex))
        if len(sys.argv) > 1:
            print('With Python script: %s\n' % sys.argv[1])
        uflash.main(sys.argv)
        #print(sys.argv)
    else:
        print('The file %s does not exists' % micropython_hex +
              'are you sure you have built micropython successfully?')
Exemplo n.º 45
0
    install_only = True
else:
    install_only = False
try:
    import uflash
except:
    install = True

if __name__ == '__main__':
    if install:
        uflash_link = "https://raw.githubusercontent.com/ntoll/uflash/e3eeb6504089963683f4cc141bba8901752cef8d/uflash.py"
        try:
            from urllib.request import urlopen
        except:
            from urllib import urlopen
        resp = urlopen(uflash_link)
        text = resp.read()
        install_dir = os.path.join(base_path, 'python')
        if not os.path.isdir(install_dir):
            os.mkdir(install_dir)
        with open(os.path.join(install_dir, 'uflash.py'), 'wb') as f:
            f.write(text)
            f.flush()
        print('Local uflash installed')
        try:
            import uflash
        except:
            pass
    if not install_only:
        uflash.main(sys.argv[1:])