Example #1
0
def test_flash_cannot_find_microbit():
    """
    Ensure an IOError is raised if it is not possible to find the micro:bit.
    """
    with mock.patch('uflash.find_microbit', return_value=None):
        with pytest.raises(IOError) as ex:
            uflash.flash()
        expected = 'Unable to find micro:bit. Is it plugged in?'
    assert ex.value.args[0] == expected
Example #2
0
def test_flash_wrong_python():
    """
    Ensures a call to flash will fail if it's not reported that we're using
    Python 3.
    """
    with mock.patch('sys.version_info', (2, 7, 9)):
        with pytest.raises(RuntimeError) as ex:
            uflash.flash()
    assert ex.value.args[0] == 'Will only run on Python 3.3 or later.'
Example #3
0
def test_flash_cannot_find_microbit():
    """
    Ensure an IOError is raised if it is not possible to find the micro:bit.
    """
    with mock.patch('uflash.find_microbit', return_value=None):
        with pytest.raises(IOError) as ex:
            uflash.flash()
        expected = 'Unable to find micro:bit. Is it plugged in?'
    assert ex.value.args[0] == expected
Example #4
0
def test_flash_wrong_python():
    """
    Ensures a call to flash will fail if it's not reported that we're using
    Python 3.
    """
    for version in [(2, 6, 3), (3, 2, 0)]:
        with pytest.raises(RuntimeError) as ex:
            with mock.patch('sys.version_info', version):
                uflash.flash()
            assert 'Will only run on Python ' in ex.value.args[0]
Example #5
0
def test_flash_wrong_python():
    """
    Ensures a call to flash will fail if it's not reported that we're using
    Python 3.
    """
    for version in [(2, 6, 3), (3, 2, 0)]:
        with mock.patch('sys.version_info', version):
            with pytest.raises(RuntimeError) as ex:
                uflash.flash()
            assert 'Will only run on Python ' in ex.value.args[0]
Example #6
0
def test_flash_with_python_script():
    """
    If a byte representation of a Python script is passed into the function it
    should hexlify that.
    """
    python_script = b'import this'
    with mock.patch('uflash.save_hex'):
        with mock.patch('uflash.find_microbit', return_value='bar'):
            with mock.patch('uflash.hexlify') as mock_hexlify:
                uflash.flash(python_script=python_script)
                mock_hexlify.assert_called_once_with(python_script, False)
Example #7
0
def test_main_keepname_message(capsys):
    """
    Ensure that the correct message appears when called as from py2hex.
    """
    uflash.flash('tests/example.py',
                 paths_to_microbits=['tests'],
                 keepname=True)
    stdout, stderr = capsys.readouterr()
    expected = 'Hexifying example.py as: {}'.format(
        os.path.join('tests', 'example.hex'))
    assert (expected in stdout) or (expected in stderr)
Example #8
0
def flash_io_runtime():
    """Flashes MicroPython with the default IO .hex"""
    try:
        microbit_path = uflash.find_microbit()
        if microbit_path:
            _BITIO_RUNTIME = os.path.join(os.path.dirname(__file__), "res",
                                          "bitio.hex")
            uflash.flash(path_to_runtime=_BITIO_RUNTIME)
            showinfo("Flashing micro:bit",
                     "Flashing the I/O .hex to micro:bit")
    except Exception:
        error_msg = traceback.format_exc(0) + '\n'
        showerror("Error", error_msg)
Example #9
0
 def run(self):
     """
     Flash the device.
     """
     try:
         uflash.flash(paths_to_microbits=self.paths_to_microbits,
                      python_script=self.python_script,
                      path_to_runtime=self.path_to_runtime)
     except Exception as ex:
         # Catch everything so Mu can recover from all of the wide variety
         # of possible exceptions that could happen at this point.
         logger.error(ex)
         self.on_flash_fail.emit(str(ex))
Example #10
0
def test_flash_with_python_script():
    """
    If a byte representation of a Python script is passed into the function it
    should hexlify that.
    """
    python_script = b"import this"
    with mock.patch("uflash.save_hex"):
        with mock.patch("uflash.find_microbit", return_value="bar"):
            with mock.patch("uflash.embed_fs_uhex") as mock_embed_fs_uhex:
                uflash.flash(python_script=python_script)
                mock_embed_fs_uhex.assert_called_once_with(
                    uflash._RUNTIME, python_script
                )
Example #11
0
def test_flash_no_args():
    """
    The good case with no arguments to the flash() function. When it's
    possible to find a path to the micro:bit.

    If no path to a Python script is supplied then just flash the unmodified
    MicroPython firmware onto the device.
    """
    with mock.patch('uflash.find_microbit', return_value='foo'):
        with mock.patch('uflash.save_hex') as mock_save:
            uflash.flash()
            assert mock_save.call_count == 1
            assert mock_save.call_args[0][0] == uflash._RUNTIME
            expected_path = os.path.join('foo', 'micropython.hex')
            assert mock_save.call_args[0][1] == expected_path
Example #12
0
def test_flash_no_args():
    """
    The good case with no arguments to the flash() function. When it's
    possible to find a path to the micro:bit.

    If no path to a Python script is supplied then just flash the unmodified
    MicroPython firmware onto the device.
    """
    with mock.patch('uflash.find_microbit', return_value='foo'):
        with mock.patch('uflash.save_hex') as mock_save:
            uflash.flash()
            assert mock_save.call_count == 1
            assert mock_save.call_args[0][0] == uflash._RUNTIME
            expected_path = os.path.join('foo', 'micropython.hex')
            assert mock_save.call_args[0][1] == expected_path
Example #13
0
def test_flash_with_path_to_microbit():
    """
    Flash the referenced path to the micro:bit with a hex file generated from
    the MicroPython firmware and the referenced Python script.
    """
    with mock.patch('uflash.save_hex') as mock_save:
        uflash.flash('tests/example.py', ['test_path'])
        assert mock_save.call_count == 1
        # Create the hex we're expecting to flash onto the device.
        with open('tests/example.py', 'rb') as py_file:
            python = uflash.hexlify(py_file.read())
        assert python
        expected_hex = uflash.embed_hex(uflash._RUNTIME, python)
        assert mock_save.call_args[0][0] == expected_hex
        expected_path = os.path.join('test_path', 'micropython.hex')
        assert mock_save.call_args[0][1] == expected_path
Example #14
0
def test_flash_with_path_to_microbit():
    """
    Flash the referenced path to the micro:bit with a hex file generated from
    the MicroPython firmware and the referenced Python script.
    """
    with mock.patch("uflash.save_hex") as mock_save:
        uflash.flash("tests/example.py", ["test_path"])
        assert mock_save.call_count == 1
        # Create the hex we're expecting to flash onto the device.
        with open("tests/example.py", "rb") as py_file:
            py_code = py_file.read()
        assert py_code
        expected_hex = uflash.embed_fs_uhex(uflash._RUNTIME, py_code)
        assert mock_save.call_args[0][0] == expected_hex
        expected_path = os.path.join("test_path", "micropython.hex")
        assert mock_save.call_args[0][1] == expected_path
Example #15
0
def test_flash_with_path_to_runtime():
    """
    Use the referenced runtime hex file when building the hex file to be
    flashed onto the device.
    """
    mock_o = mock.mock_open(read_data=b'script')
    with mock.patch.object(builtins, 'open', mock_o) as mock_open:
        with mock.patch('uflash.embed_hex', return_value='foo') as em_h:
            with mock.patch('uflash.find_microbit', return_value='bar'):
                with mock.patch('uflash.save_hex') as mock_save:
                    uflash.flash('tests/example.py',
                                 path_to_runtime='tests/fake.hex')
                    assert mock_open.call_args[0][0] == 'tests/fake.hex'
                    assert em_h.call_args[0][0] == b'script'
                    expected_hex_path = os.path.join('bar', 'micropython.hex')
                    mock_save.assert_called_once_with('foo', expected_hex_path)
Example #16
0
def test_flash_with_path_to_runtime():
    """
    Use the referenced runtime hex file when building the hex file to be
    flashed onto the device.
    """
    mock_o = mock.mock_open(read_data=b'script')
    with mock.patch.object(builtins, 'open', mock_o) as mock_open:
        with mock.patch('uflash.embed_hex', return_value='foo') as em_h:
            with mock.patch('uflash.find_microbit', return_value='bar'):
                with mock.patch('uflash.save_hex') as mock_save:
                    uflash.flash('tests/example.py',
                                 path_to_runtime='tests/fake.hex')
                    assert mock_open.call_args[0][0] == 'tests/fake.hex'
                    assert em_h.call_args[0][0] == b'script'
                    expected_hex_path = os.path.join('bar', 'micropython.hex')
                    mock_save.assert_called_once_with('foo', expected_hex_path)
Example #17
0
def test_flash_with_path_to_microbit():
    """
    Flash the referenced path to the micro:bit with a hex file generated from
    the MicroPython firmware and the referenced Python script.
    """
    with mock.patch('uflash.save_hex') as mock_save:
        uflash.flash('tests/example.py', ['test_path'])
        assert mock_save.call_count == 1
        # Create the hex we're expecting to flash onto the device.
        with open('tests/example.py', 'rb') as py_file:
            python = uflash.hexlify(py_file.read())
        assert python
        expected_hex = uflash.embed_hex(uflash._RUNTIME, python)
        assert mock_save.call_args[0][0] == expected_hex
        expected_path = os.path.join('test_path', 'micropython.hex')
        assert mock_save.call_args[0][1] == expected_path
Example #18
0
def test_flash_has_python_no_path_to_microbit():
    """
    The good case with a path to a Python file. When it's possible to find a
    path to the micro:bit.

    The resulting payload should be a correctly created micropython.hex file.
    """
    with mock.patch('uflash.find_microbit', return_value='foo'):
        with mock.patch('uflash.save_hex') as mock_save:
            uflash.flash('tests/example.py')
            assert mock_save.call_count == 1
            # Create the hex we're expecting to flash onto the device.
            with open('tests/example.py', 'rb') as py_file:
                python = uflash.hexlify(py_file.read())
            assert python
            expected_hex = uflash.embed_hex(uflash._RUNTIME, python)
            assert mock_save.call_args[0][0] == expected_hex
            expected_path = os.path.join('foo', 'micropython.hex')
            assert mock_save.call_args[0][1] == expected_path
Example #19
0
def test_flash_with_path_to_runtime():
    """
    Use the referenced runtime hex file when building the hex file to be
    flashed onto the device.
    """
    mock_o = mock.MagicMock()
    mock_o.return_value.__enter__ = lambda s: s
    mock_o.return_value.__exit__ = mock.Mock()
    mock_o.return_value.read.return_value = 'script'
    with mock.patch.object(builtins, 'open', mock_o) as mock_open:
        with mock.patch('uflash.embed_hex', return_value='foo') as em_h:
            with mock.patch('uflash.find_microbit', return_value='bar'):
                with mock.patch('uflash.save_hex') as mock_save:
                    uflash.flash('tests/example.py',
                                 path_to_runtime='tests/fake.hex')
                    assert mock_open.call_args[0][0] == 'tests/fake.hex'
                    assert em_h.call_args[0][0] == 'script'
                    mock_save.assert_called_once_with('foo',
                                                      'bar/micropython.hex')
Example #20
0
def test_flash_has_python_no_path_to_microbit():
    """
    The good case with a path to a Python file. When it's possible to find a
    path to the micro:bit.

    The resulting payload should be a correctly created micropython.hex file.
    """
    with mock.patch('uflash.find_microbit', return_value='foo'):
        with mock.patch('uflash.save_hex') as mock_save:
            uflash.flash('tests/example.py')
            assert mock_save.call_count == 1
            # Create the hex we're expecting to flash onto the device.
            with open('tests/example.py', 'rb') as py_file:
                python = uflash.hexlify(py_file.read())
            assert python
            expected_hex = uflash.embed_hex(uflash._RUNTIME, python)
            assert mock_save.call_args[0][0] == expected_hex
            expected_path = os.path.join('foo', 'micropython.hex')
            assert mock_save.call_args[0][1] == expected_path
Example #21
0
def test_flash_has_python_no_path_to_microbit():
    """
    The good case with a path to a Python file. When it's possible to find a
    path to the micro:bit.

    The resulting payload should be a correctly created micropython.hex file.
    """
    with mock.patch("uflash.find_microbit", return_value="foo"):
        with mock.patch("uflash.save_hex") as mock_save:
            uflash.flash("tests/example.py")
            assert mock_save.call_count == 1
            # Create the hex we're expecting to flash onto the device.
            with open("tests/example.py", "rb") as py_file:
                py_code = py_file.read()
            assert py_code
            expected_hex = uflash.embed_fs_uhex(uflash._RUNTIME, py_code)
            assert mock_save.call_args[0][0] == expected_hex
            expected_path = os.path.join("foo", "micropython.hex")
            assert mock_save.call_args[0][1] == expected_path
Example #22
0
    def deployToMicrobit(self):
        # Temporarily redirecting stdout because there are some print statements in uflash library
        fake_stdout = open(os.devnull, "w")
        _stdout = sys.stdout
        sys.stdout = fake_stdout

        try:
            uflash.flash(path_to_python=self.file_path)
            message = {"type": "complete"}
        except RuntimeError:
            message = {"type": "low-python-version"}
        except IOError:
            self.error_message = CONSTANTS.NO_MICROBIT_DETECTED_ERROR_TITLE
            print(
                self.error_message, file=sys.stderr, flush=True,
            )
            message = {"type": "no-device"}

        sys.stdout = _stdout
        return message
Example #23
0
import os, uflash, sys

# 1. uflash empty python environment
print('Flashing sub-node runtime...')
try:
    uflash.flash(os.path.join(os.path.dirname(__file__), 'slave.py'))
except Exception as e:
    sys.stderr.write('\n%s: %s' % (type(e).__name__, str(e)))
    sys.exit(1)
print('Done...')
Example #24
0
import os, uflash, microfs, sys

# 1. uflash empty python environment
try:
    uflash.flash()
except Exception as e:
    sys.stderr.write('\n%s: %s' % (type(e).__name__, str(e)))
    sys.exit(1)

# 2. find & put required files
dxk_folder = os.path.abspath(
    os.path.join(os.path.dirname(__file__), '..', 'dxk_ext'))

commands = []
for file in os.listdir(dxk_folder):
    if file.endswith('.py'):
        commands.append("fd = open('{}', 'wb')".format(file))
        commands.append("f = fd.write")
        with open(os.path.join(dxk_folder, file), 'rb') as local:
            content = local.read()
        while content:
            line = content[:64]
            if microfs.PY2:
                commands.append('f(b' + repr(line) + ')')
            else:
                commands.append('f(' + repr(line) + ')')
            content = content[64:]
        commands.append('fd.close()')
print('Flashing modules...')
microfs.execute(commands)
print('Done.')
Example #25
0
import sys
import uflash

if len(sys.argv) > 1:
	filename = sys.argv[1]
else:
	print "Missing filename on command line."
	sys.exit(1)

print "File: " + filename

print "Looking for micro:bit..."

microbitPath = uflash.find_microbit()

if microbitPath == None:
	print "Cannot find micro:bit. Check that it is plugged in via USB."
	sys.exit(1)

print "micro:bit found @ " + microbitPath

print "uflash version " + uflash.get_version()

uflash.flash(filename, microbitPath)