Best Python code snippet using autotest_python
test_sonic_installer.py
Source:test_sonic_installer.py  
1import os2from contextlib import contextmanager3from sonic_installer.main import sonic_installer4from click.testing import CliRunner5from unittest.mock import patch, Mock, call6@patch("sonic_installer.main.SWAPAllocator")7@patch("sonic_installer.main.get_bootloader")8@patch("sonic_installer.main.run_command_or_raise")9@patch("sonic_installer.main.run_command")10def test_install(run_command, run_command_or_raise, get_bootloader, swap, fs):11    """ This test covers the execution of "sonic-installer install" command. """12    sonic_image_filename = "sonic.bin"13    current_image_version = "image_1"14    new_image_version = "image_2"15    new_image_folder = f"/images/{new_image_version}"16    image_docker_folder = os.path.join(new_image_folder, "docker")17    mounted_image_folder = f"/tmp/image-{new_image_version}-fs"18    dockerd_opts = ["--iptables=false", "--bip=1.1.1.1/24"]19    # Setup mock files needed for our test scenario20    fs.create_file(sonic_image_filename)21    fs.create_dir(image_docker_folder)22    fs.create_dir(os.path.join(mounted_image_folder, "usr/lib/docker/docker.sh"))23    fs.create_file("/var/run/docker.pid", contents="15")24    fs.create_file("/proc/15/cmdline", contents="\x00".join(["dockerd"] + dockerd_opts))25    # Setup bootloader mock26    mock_bootloader = Mock()27    mock_bootloader.get_binary_image_version = Mock(return_value=new_image_version)28    mock_bootloader.get_installed_images = Mock(return_value=[current_image_version])29    mock_bootloader.get_image_path = Mock(return_value=new_image_folder)30    @contextmanager31    def rootfs_path_mock(path):32        yield mounted_image_folder33    mock_bootloader.get_rootfs_path = rootfs_path_mock34    get_bootloader.return_value=mock_bootloader35    # Invoke CLI command36    runner = CliRunner()37    result = runner.invoke(sonic_installer.commands["install"], [sonic_image_filename, "-y"])38    print(result.output)39    assert result.exit_code == 040    # Assert bootloader install API was called41    mock_bootloader.install_image.assert_called_with(f"./{sonic_image_filename}")42    # Assert all below commands were called, so we ensure that43    #   1. update SONiC environment works44    #   2. package migration works45    expected_call_list = [46        call(["mkdir", "-p", mounted_image_folder]),47        call(["mount", "-t", "squashfs", mounted_image_folder, mounted_image_folder]),48        call(["sonic-cfggen", "-d", "-y", f"{mounted_image_folder}/etc/sonic/sonic_version.yml", "-t", f"{mounted_image_folder}/usr/share/sonic/templates/sonic-environment.j2"]),49        call(["umount", "-r", "-f", mounted_image_folder], raise_exception=True),50        call(["rm", "-rf", mounted_image_folder], raise_exception=True),51        call(["mkdir", "-p", mounted_image_folder]),52        call(["mount", "-t", "squashfs", mounted_image_folder, mounted_image_folder]),53        call(["mkdir", "-p", f"{new_image_folder}/rw"]),54        call(["mkdir", "-p", f"{new_image_folder}/work"]),55        call(["mkdir", "-p", mounted_image_folder]),56        call(["mount", "overlay", "-t", "overlay", "-o", f"rw,relatime,lowerdir={mounted_image_folder},upperdir={new_image_folder}/rw,workdir={new_image_folder}/work", mounted_image_folder]),57        call(["mkdir", "-p", f"{mounted_image_folder}/var/lib/docker"]),58        call(["mount", "--bind", f"{new_image_folder}/docker", f"{mounted_image_folder}/var/lib/docker"]),59        call(["chroot", mounted_image_folder, "mount", "proc", "/proc", "-t", "proc"]),60        call(["chroot", mounted_image_folder, "mount", "sysfs", "/sys", "-t", "sysfs"]),61        call(["cp", f"{mounted_image_folder}/etc/default/docker", f"{mounted_image_folder}/tmp/docker_config_backup"]),62        call(["sh", "-c", f"echo 'DOCKER_OPTS=\"$DOCKER_OPTS {' '.join(dockerd_opts)}\"' >> {mounted_image_folder}/etc/default/docker"]), # dockerd started with added options as host dockerd63        call(["chroot", mounted_image_folder, "/usr/lib/docker/docker.sh", "start"]),64        call(["cp", "/var/lib/sonic-package-manager/packages.json", f"{mounted_image_folder}/tmp/packages.json"]),65        call(["touch", f"{mounted_image_folder}/tmp/docker.sock"]),66        call(["mount", "--bind", "/var/run/docker.sock", f"{mounted_image_folder}/tmp/docker.sock"]),67        call(["chroot", mounted_image_folder, "sh", "-c", "command -v sonic-package-manager"]),68        call(["chroot", mounted_image_folder, "sonic-package-manager", "migrate", "/tmp/packages.json", "--dockerd-socket", "/tmp/docker.sock", "-y"]),69        call(["chroot", mounted_image_folder, "/usr/lib/docker/docker.sh", "stop"], raise_exception=False),70        call(["umount", "-f", "-R", mounted_image_folder], raise_exception=False),71        call(["umount", "-r", "-f", mounted_image_folder], raise_exception=False),72        call(["rm", "-rf", mounted_image_folder], raise_exception=False),73    ]74    assert run_command_or_raise.call_args_list == expected_call_list75@patch("sonic_installer.main.get_bootloader")76def test_set_fips(get_bootloader):77    """ This test covers the execution of "sonic-installer set-fips/get-fips" command. """78    image = "image_1"79    next_image = "image_2"80    # Setup bootloader mock81    mock_bootloader = Mock()82    mock_bootloader.get_next_image = Mock(return_value=next_image)83    mock_bootloader.get_installed_images = Mock(return_value=[image, next_image])84    mock_bootloader.set_fips = Mock()85    mock_bootloader.get_fips = Mock(return_value=False)86    get_bootloader.return_value=mock_bootloader87    runner = CliRunner()88    # Test set-fips command options: --enable-fips/--disable-fips89    result = runner.invoke(sonic_installer.commands["set-fips"], [next_image, '--enable-fips'])90    assert 'Set FIPS' in result.output91    result = runner.invoke(sonic_installer.commands["set-fips"], ['--disable-fips'])92    assert 'Set FIPS' in result.output93    # Test command get-fips options94    result = runner.invoke(sonic_installer.commands["get-fips"])95    assert "FIPS is disabled" in result.output96    mock_bootloader.get_fips = Mock(return_value=True)97    result = runner.invoke(sonic_installer.commands["get-fips"], [next_image])...emulator.py
Source:emulator.py  
...5# from computer.io.screen import Screen6from computer.opcodes import *7from computer.utility.numbers import bin_to_dec, dec_to_bin8from computer.utility.status import print_status9def get_bootloader():10    # program_start = dec_to_bin(14)11    # start_of_loop = dec_to_bin(6)12    # instructions = [move_opcode + a_address + constant_address,13    #                 program_start,14    #                 move_opcode + b_address + constant_address,15    #                 dec_to_bin(0),16    #                 # Read length of bootloader17    #                 hdd_opcode + hdd_read + c_address + b_address,18    #                 alu_opcode + alu_inc + b_address + unused_opcode,19    #                 # Start of loop20    #                 hdd_opcode + hdd_read + ap_address + b_address,21    #                 alu_opcode + alu_inc + a_address + unused_opcode,22    #                 alu_opcode + alu_inc + b_address + unused_opcode,23    #                 # Check if entire bootloader is loaded24    #                 alu_no_move_opcode + alu_sub + c_address + b_address,25    #                 # Jump to program start if so26    #                 jump_zero_opcode + unused_opcode + constant_address,27    #                 program_start,28    #                 # If not jump back to start of loop29    #                 jump_opcode + unused_opcode + constant_address,30    #                 start_of_loop,31    #                 ]32    path = r'D:\Programmering\python\computer\computer\assembler\bootloader.bin'33    bootloader = bitarray()34    with open(path, 'rb') as file:35        bootloader.fromfile(file)36    return bootloader37class Emulator:38    def __init__(self, cpu, verbose=False):39        self.cpu = cpu40        self.verbose = verbose41        self.shutdown = False42    def load_instructions(self, instructions):43        for i, instruction in enumerate(instructions):44            address = dec_to_bin(i)45            self.cpu.ram(instruction, address[1:], 1)46        self.cpu.ram.tick()47    def load_binary(self, binary):48        size = int(len(binary) / 16)49        for i in range(size):50            instruction = binary[i*16:(i+1)*16]51            address = dec_to_bin(i)52            self.cpu.ram(instruction, address, 1)53        self.cpu.ram.tick()54    def run(self):55        while not self.shutdown:56            self.tick()57    def tick(self):58        if not self.shutdown:59            self.shutdown = self.cpu()60            if self.verbose:61                print_status(self.cpu)62            self.cpu.tick()63    def reset(self):64        self.cpu(reset=1)65        self.shutdown = False66        self.cpu.tick()67def main():68    emulator = make_emulator('ball.bin', verbose=True)69    emulator.run()70    print('Emulation completed')71def make_emulator(binary_file, verbose=False):72    ram = CombinedRAM()73    hdd = get_hdd_with_loaded_program(binary_file)74    cpu = CPU(ram, hdd)75    emulator = Emulator(cpu, verbose)76    bootloader = get_bootloader()77    emulator.load_binary(bootloader)78    return emulator79def get_hdd_with_loaded_program(file_name='test.bin'):80    hdd = HardDisk()81    file_path = os.path.join(r'D:\Programmering\python\computer\computer\assembler',82                             file_name)83    hdd.load_data(file_path)84    return hdd85if __name__ == '__main__':...bootloader.py
Source:bootloader.py  
...17        except serial.SerialException as e:18            print(e)19            raise ValueError("Port {} is NOT a valid COM Port.".format(port.device))20    @staticmethod21    def get_bootloader(port):22        try:23            bootloader = Bootloader(port)24            return bootloader25        except ValueError:26            return None27    @staticmethod28    def get_all():29        ports = [port for port in serial.tools.list_ports.comports() if port[2] != 'n/a']30        if len(ports):31            with Pool(len(ports)) as p:32                bootloaders = [bootloader for bootloader in p.map(Bootloader.get_bootloader, ports) if33                               bootloader is not None]34            if bootloaders:35                print("Flora bootloaders detected: {}".format([bootloader.port.device for bootloader in bootloaders]))...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
