Best Python code snippet using localstack_python
build-image-incr.py
Source:build-image-incr.py  
...160    subprocess.run(["docker", "rm", "-f", id], stdout=subprocess.DEVNULL)161def count_image_layers(image: str) -> int:162    return int(scos(["docker", "inspect", image,163                     "--format", "{{len .RootFS.Layers}}"]))164def get_image_entrypoint(image: str) -> str:165    return json.dumps(json.loads(scos(["docker", "image", "inspect", image]))[166                      0]["Config"]["Entrypoint"])167def image_exists_locally(image: str) -> bool:168    output = scos(["docker", "image", "ls", "-q", image])169    return output != ""170def get_image_id(image: str) -> str:171    return scos(["docker", "inspect", "-f", "{{.Id}}", image])172def get_parent(image: str) -> str:173    """174    Returns the id of the parent of 'image'.  If 'image' does not have a175    parent the result will be a blank string.176    """177    return scos(["docker", "inspect", "-f", "{{.Parent}}", image])178def is_descendent_of(image1, image2):179    image2_id = get_image_id(image2)180    image = image1181    while True:182        parent = get_parent(image)183        if not parent:184            return False185        if parent == image2_id:186            return True187        image = parent188################################189def main():190    parser = argparse.ArgumentParser(191        description='Build a container image',192        formatter_class=argparse.ArgumentDefaultsHelpFormatter)193    parser.add_argument(194        'default_base_image',195        help='The base image to use if the one specified by --layer is not suitable')196    parser.add_argument('rsync_source',197                        help='The host directory to use as the rsync source')198    parser.add_argument(199        'rsync_dest',200        help='The container directory to use as the rsync destination')201    parser.add_argument('output_image',202                        help='The name of the output image to create')203    parser.add_argument(204        '--layer',205        help='The image to try to layer on top of.  This image must be one generated by this script')206    parser.add_argument(207        '--rsync-transfer-pct-max',208        help='The maximum rsync transfer percentage to accept when determining if the image specified by --layer is suitable',209        type=float,210        default=25)211    # Max layer count of 125 for overlayfs measured on Linux 4.19.0-14-amd64212    parser.add_argument(213        '--max-layers',214        help='The maximum number of layers that LAYER is allowed to have. If exceeded, the default base image will be used',215        type=int,216        default=125)217    parser.add_argument('--exclude',218                        metavar='PATTERN',219                        action='append',220                        help="Exclude files matching PATTERN")221    parser.add_argument('--include',222                        metavar='PATTERN',223                        action='append',224                        help="don't exclude files matching PATTERN")225    args = parser.parse_args()226    app = App(args)227    base_image = app.select_base_image()228    print("Using {} as the base image".format(base_image))229    # Save the original entrypoint of the base image since we override230    # it in the 'docker run' in run_build_container() and 'docker commit' saves that as231    # the entrypoint (if we don't do anything about it, but we do).232    original_entrypoint = get_image_entrypoint(base_image)233    stats = app.estimate_rsync(base_image)234    rsync_args = []235    if stats["regular_files_transferred"] + stats["files_deleted"] <= 100:236        rsync_args.append("-v")237    print("\n** rsync {} to container:{} **".format(app.rsync_source, app.rsync_dest))238    builder_id = app.run_rsync(base_image, rsync_args)239    try:240        print("\nCommit {}".format(args.output_image))241        subprocess.run(["docker", "commit",242                        "-c", "ENTRYPOINT {}".format(original_entrypoint),243                        builder_id, args.output_image],244                       check=True)245        print("{} has {} layers".format(args.output_image,246                                        count_image_layers(args.output_image)))...dockerutil.py
Source:dockerutil.py  
...78    try:79        return info['Config']['Cmd']80    except KeyError as ke:81        raise DockerError('Failed to inspect image: JSON result missing key {}'.format(ke))82def get_image_entrypoint(image):83    '''Gets the image entrypoint'''84    info = docker_inspect_or_pull(image)85    try:86        return info['Config']['Entrypoint']87    except KeyError as ke:88        raise DockerError('Failed to inspect image: JSON result missing key {}'.format(ke))89def make_vol_opt(hostdir, contdir, options=None):90    '''Generate a docker volume option'''91    vol = '--volume={}:{}'.format(hostdir, contdir)92    if options != None:93        if isinstance(options, str):94            options = (options,)95        vol += ':' + ','.join(options)96    return voltest_dockerutil.py
Source:test_dockerutil.py  
...65    # Now try to get the image's Command66    result = uut.get_image_command(image)67    # Should return a non-empty string68    assert result69def test_get_image_entrypoint():70    '''get_image_entrypoint works'''71    result = uut.get_image_entrypoint('scuba/entrypoint-test')72    assert result == ['/entrypoint.sh']73def test_get_image_entrypoint__none():74    '''get_image_entrypoint works for image with no entrypoint'''75    result = uut.get_image_entrypoint(DOCKER_IMAGE)76    assert result is None77def test_make_vol_opt_no_opts():78    assert uut.make_vol_opt('/hostdir', '/contdir') == '--volume=/hostdir:/contdir'79def test_make_vol_opt_one_opt():80    assert uut.make_vol_opt('/hostdir', '/contdir', 'ro') == '--volume=/hostdir:/contdir:ro'81def test_make_vol_opt_multi_opts():...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!!
