Best Python code snippet using localstack_python
commands.py
Source:commands.py  
1#!/usr/bin/env python32# coding: utf-83import typer4import subprocess5import platform6from pathlib import Path7app = typer.Typer()8USE_DOCKER = False9DEBUG = True  # print what commands get executed10def echo(11    message: str,12    fg_color: str = typer.colors.WHITE,13    bg_color: str = typer.colors.BLACK,14    bold: bool = False15    ):16    """colors:17        "bright_" + black, red, green, yellow, blue, magenta, cyan, white18    """19    typer.echo(20        typer.style(21            message,22            fg=fg_color,23            bg=bg_color,24            bold=bold,25        )26    )27def run_command(command, debug=False, cwd='./backend', env=None, managepy=False, docker=False):28    if managepy:29        command = f"python manage.py {command}"30    if docker:31        cwd = '.'32        command = f"docker-compose run django {command}"33    if debug:34        echo(f">>> Running command: {command}")35    try:36        subprocess.run(command, cwd=cwd, env=env)37    except FileNotFoundError:38        echo(f'The command {command} threw a FileNotFoundError', fg_color=typer.colors.RED)39def run_docker_compose_command(command, debug=False, cwd='.', env=None, docker=False):40    if not docker:41        echo(f">>> {command} requires a dockerized project")42        return43    if debug:44        echo(f">>> Running command: {command}")45    try:46        subprocess.run(command, cwd=cwd, env=env)47    except FileNotFoundError:48        echo(f'The command {command} threw a FileNotFoundError', fg_color=typer.colors.RED)49def delete_folder(path: Path):50    for element in path.iterdir():51        if element.is_dir():52            delete_folder(element)53        else:54            element.unlink()55    path.rmdir()56def clean_build():57    echo(f"Unlinking build-files: build/; dist/ *.egg-info; __pycache__;", fg_color=typer.colors.RED)58    cwd = Path('.')59    [delete_folder(p) for p in cwd.rglob('build')]60    [delete_folder(p) for p in cwd.rglob('dist')]61    [delete_folder(p) for p in cwd.rglob('*.egg-info')]62    [delete_folder(p) for p in cwd.rglob('__pycache__')]63def clean_pyc():64    echo(f"Unlinking caches: *.pyc; *pyo; *~;", fg_color=typer.colors.RED)65    [p.unlink() for p in Path('.').rglob('*.py[co]')]66    [p.unlink() for p in Path('.').rglob('*~')]67@app.command()68def clean():69    clean_build()70    clean_pyc()71@app.command()72def manage(command: str, second: str = typer.Argument(None)):73    if second:74        echo(f'Commands with arguments are not supported via this interface yet', fg_color=typer.colors.RED)75        return76    run_command(f'{command}', debug=DEBUG, managepy=True, docker=USE_DOCKER)77@app.command()78def compose(command: str, second: str = typer.Argument(None)):79    if second:80        echo(f'Commands with arguments are not supported via this interface yet', fg_color=typer.colors.RED)81        return82    run_docker_compose_command(f'{command}', debug=DEBUG, docker=USE_DOCKER)83@app.command()84def build(nocache: bool = False):85    command = "docker-compose build"86    if nocache:87        command = f"{command} --no-cache"88    run_docker_compose_command(command, debug=DEBUG, docker=USE_DOCKER)89@app.command()90def up(orphans: bool = False):91    command = "docker-compose up"92    if orphans:93        command = f"{command} --remove-orphans"94    run_docker_compose_command(command, debug=DEBUG, docker=USE_DOCKER)95@app.command()96def down():97    command = "docker-compose down"98    run_docker_compose_command(command, debug=DEBUG, docker=USE_DOCKER)99@app.command()100def pytest(test_path: str = typer.Argument(None)):101    command = "pytest"102    if test_path is not None:103        command = f"{command} {test_path}"104    run_command(command, debug=DEBUG, docker=USE_DOCKER)105@app.command()106def test(test_path: str = typer.Argument(None)):107    pytest(test_path)108@app.command()109def black(path: str = typer.Argument(None)):110    command = "black"111    if path is not None:112        command = f"{command} {path}"113    run_command(command, debug=DEBUG, docker=USE_DOCKER)114@app.command()115def coverage():116    commands = [117        "coverage run --source='.' manage.py test",118        "coverage report"119    ]120    for command in commands:121        run_command(command, debug=DEBUG, docker=USE_DOCKER)122@app.command()123def docs(doc_path: Path = Path('./backend/docs')):124    [p.unlink(missing_ok=True) for p in doc_path.rglob('*.rst') if not p.name == 'index.rst']125    run_command("sphinx-apidoc -o . .. --ext-autodoc", debug=DEBUG, cwd=doc_path)126    if not platform.system() == "Windows":127        run_command("make html", debug=DEBUG, cwd=doc_path)128        when = "now"129    else:130        echo(f"Make failed (Windows) run it manually with:\n{doc_path.resolve()}\make html", fg_color=typer.colors.RED)131        when = "then"132    file_url = f'file://{Path("docs/_build/html/index.html").resolve()}'133    echo(f"Docs are {when} available at: {file_url}", fg_color=typer.colors.BLACK, bg_color=typer.colors.WHITE)134@app.command()135def poetryinstall():136    run_command(f'poetry install', debug=DEBUG, managepy=True, docker=False)137@app.command()138def rebuild(nocache: bool = False):139    poetryinstall()140    build(nocache=nocache)141    initialize()142@app.command()143def makemigrations():144    run_command('makemigrations', debug=DEBUG, managepy=True, docker=USE_DOCKER)145@app.command()146def migrate():147    run_command('migrate', debug=DEBUG, managepy=True, docker=USE_DOCKER)148@app.command()149def resetschema():150    run_command('reset_schema --noinput', debug=DEBUG, managepy=True, docker=USE_DOCKER)151@app.command()152def deletemigrations(apps_path: Path = Path('.')):  # it's usally APPS_DIR 'apps/' !153    if not apps_path.exists():154        echo(f'Directory {apps_path.resolve()} does not exist', fg_color=typer.colors.RED)155        return156    app_dirs = [157        app_dir158        for app_dir in apps_path.iterdir()159        if app_dir.is_dir() and app_dir.name != "__pycache__"160    ]161    for d in app_dirs:162        migrations = Path(d) / "migrations"163        if migrations.exists():164            for f in [m for m in migrations.iterdir() if not m.is_dir()]:165                if not '__init__' in f.name:166                    echo(f"Deleting migration: {f.parent}/{f.name}", fg_color=typer.colors.RED)167                    f.unlink()168@app.command()169def initialize():170    echo(f'Reset the database schema...', fg_color=typer.colors.RED)171    resetschema()172    echo(f'Deleting migrations...', fg_color=typer.colors.RED)173    deletemigrations()174    echo(f'Makemigrations...', fg_color=typer.colors.GREEN)175    makemigrations()176    echo(f'Migrate...', fg_color=typer.colors.GREEN)177    migrate()178    echo(f'Creating pytest DB...', fg_color=typer.colors.GREEN)179    run_command("pytest --quiet --create-db", debug=DEBUG, docker=USE_DOCKER)180    echo(f'Successfully initialized the project...', fg_color=typer.colors.GREEN)181@app.command()182def init():183    initialize()184@app.command()185def mm():186    makemigrations()187@app.command()188def mig():189    migrate()190if __name__ == "__main__":...app.py
Source:app.py  
1#!/usr/bin/env python32# -*- coding: utf-8 -*-3# Copyright (C) 2020 jessedp4#5# Permission is hereby granted, free of charge, to any person obtaining6# a copy of this software and associated documentation files (the7# "Software"),  to deal in the Software without restriction, including8# without limitation the rights to use, copy, modify, merge, publish,9# distribute, sublicense, and/or sell copies of the Software, and to10# permit persons to whom the Software is furnished to do so, subject to11# the following conditions:12#13# The above copyright notice and this permission notice shall be14# included in all copies or substantial portions of the Software.15#16# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,17# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF18# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND19# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS20# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN21# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN22# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE23# SOFTWARE.24"""Makes bulk adding DNS blocklists and allowlists to Pi-hole 5 a breeze"""25import os26import sys27import sqlite328from ph5lt import constants29from ph5lt import prompts30from ph5lt import allowlists31from ph5lt import blocklists32from ph5lt import utils33from ph5lt import banner34from ph5lt import stats35def main():36    """main method"""37    conn = None38    try:39        utils.clear()40        banner.display()41        use_docker = False42        docker = utils.find_docker()43        if docker[0] is True:44            utils.success(f"+ Found Running Docker config: {docker[1]}")45            use_docker = prompts.confirm("Use Docker-ized config?", "n")46            if use_docker:47                db_file = docker[1]48        if not use_docker:49            print()50            db_file = prompts.ask_db()51        # ask_db validates the db, pass this connection round for easy access & "global" mgmt52        conn = sqlite3.connect(db_file)53        cur = conn.cursor()54        default = constants.BLOCKLIST55        option = ""56        any_save = False57        while option != constants.EXIT:58            stats.stat_bar(cur)59            option = prompts.main_menu(default)60            save = False61            if option == constants.BLOCKLIST:62                save = blocklists.manage_blocklists(cur)63            if option == constants.ALLOWLIST:64                save = allowlists.manage_allowlists(cur)65            if option == constants.STATS:66                stats.header(cur)67            if save:68                any_save = True69                default = constants.EXIT70                conn.commit()71                if option == constants.ALLOWLIST:72                    stats.allow_header(cur)73                if option == constants.BLOCKLIST:74                    stats.block_header(cur)75                if prompts.confirm("Are you finished?"):76                    break77        conn.close()78        if any_save:79            update_gravity(use_docker)80        utils.info("\n\tBye!\n")81    except (KeyboardInterrupt, KeyError):82        if conn:83            conn.close()84        sys.exit(0)85def update_gravity(use_docker):86    """ various ways of updating the gravity db """87    if prompts.confirm("Update Gravity for immediate effect?"):88        print()89        if use_docker:90            os.system('docker exec pihole bash "/usr/local/bin/pihole" "-g"')91        else:92            os.system("pihole -g")93    else:94        print()95        if use_docker:96            utils.info(97                "Update Gravity through the web interface or by running:\n\t"98                + '# docker exec pihole bash "/usr/local/bin/pihole" "-g"'99            )100        else:101            utils.info(102                "Update Gravity through the web interface or by running:\n\t# pihole -g"103            )104if __name__ == "__main__":105    try:106        main()107    except sqlite3.OperationalError as err:108        utils.danger("\n\tDatabase error!")109        utils.danger(f"\t{err}")110    except (KeyboardInterrupt, KeyError):...test_utils.py
Source:test_utils.py  
...3    use_docker.cache_clear()4    rc = mocker.Mock()5    rc.returncode = 06    mocker.patch("tox_ansible.utils.subprocess.run", return_value=rc)7    assert use_docker()8def test_docker_absent(mocker):9    use_docker.cache_clear()10    mocker.patch("tox_ansible.utils.subprocess.run", side_effect=FileNotFoundError)...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!!
