| 1 | import pytest |
| 2 | import subprocess |
| 3 | import tempfile |
| 4 | import attr |
| 5 | import os |
| 6 | from pathlib import Path |
| 7 | from labgrid.driver.flashscriptdriver import FlashScriptDriver |
| 8 | from labgrid.resource.common import ManagedResource |
| 9 | from labgrid import target_factory |
| 10 | |
| 11 | |
| 12 | @target_factory.reg_resource |
| 13 | @attr.s(eq=False) |
| 14 | class MockFlashableDevice(ManagedResource): |
| 15 | def __attrs_post_init__(self): |
| 16 | super().__attrs_post_init__() |
| 17 | self.avail = True |
| 18 | |
| 19 | @property |
| 20 | def prop(self): |
| 21 | return "test" |
| 22 | |
| 23 | |
| 24 | @pytest.fixture(scope="function") |
| 25 | def resource(target): |
| 26 | r = MockFlashableDevice(target, name=None) |
| 27 | assert isinstance(r, MockFlashableDevice) |
| 28 | target.activate(r) |
| 29 | return r |
| 30 | |
| 31 | |
| 32 | @pytest.fixture(scope="function") |
| 33 | def driver(target, mocker, resource): |
| 34 | mocker.patch.dict( |
| 35 | FlashScriptDriver.bindings, |
| 36 | { |
| 37 | "device": { |
| 38 | "MockFlashableDevice", |
| 39 | }, |
| 40 | }, |
| 41 | ) |
| 42 | |
| 43 | d = FlashScriptDriver(target, name=None) |
| 44 | assert isinstance(d, FlashScriptDriver) |
| 45 | target.activate(d) |
| 46 | return d |
| 47 | |
| 48 | |
| 49 | def capture_argument_expansion(d, var): |
| 50 | with tempfile.NamedTemporaryFile() as f: |
| 51 | d.flash("/bin/sh", args=["-c", "echo -n {%s} > %s" % (var, f.name)]) |
| 52 | return f.read().decode("utf-8") |
| 53 | |
| 54 | |
| 55 | @pytest.mark.skipif(not Path("/bin/true").exists(), reason="true not available") |
| 56 | def test_script_success(target, driver): |
| 57 | driver.flash("/bin/true") |
| 58 | |
| 59 | |
| 60 | @pytest.mark.skipif(not Path("/bin/false").exists(), reason="false not available") |
| 61 | def test_script_failure(target, driver): |
| 62 | with pytest.raises(subprocess.CalledProcessError): |
| 63 | driver.flash("/bin/false") |
| 64 | |
| 65 | |
| 66 | def test_argument_device_expansion(target, resource, driver): |
| 67 | value = capture_argument_expansion(driver, "device.prop") |
| 68 | assert value == resource.prop |
| 69 | |
| 70 | |
| 71 | def test_argument_file_expansion(target, driver): |
| 72 | value = capture_argument_expansion(driver, "file.local_path") |
| 73 | assert os.path.samefile(value, "/bin/sh") |