def mock_create_labbooks(fixture_working_dir):
    # Create a labbook in the temporary directory
    config_file = fixture_working_dir[0]
    lb = LabBook(fixture_working_dir[0])
    lb.new(owner={"username": UT_USERNAME},
           name=UT_LBNAME,
           description="Cats labbook 1")

    # Create a file in the dir
    with open(os.path.join(fixture_working_dir[1], 'unittest-examplefile'),
              'w') as sf:
        sf.write("test data")
        sf.seek(0)
    FileOperations.insert_file(lb, 'code', sf.name)

    assert os.path.isfile(
        os.path.join(lb.root_dir, 'code', 'unittest-examplefile'))

    # Create test client
    schema = graphene.Schema(query=LabbookQuery, mutation=LabbookMutations)
    with patch.object(Configuration, 'find_default_config',
                      lambda self: config_file):
        app = Flask("lmsrvlabbook")
        app.config["LABMGR_CONFIG"] = Configuration()
        app.config["LABMGR_ID_MGR"] = get_identity_manager(Configuration())
        with app.app_context():
            flask.g.user_obj = app.config["LABMGR_ID_MGR"].get_user_profile()
            client = Client(
                schema,
                middleware=[LabBookLoaderMiddleware(), error_middleware],
                context_value=ContextMock())
            yield lb, client, schema
    shutil.rmtree(fixture_working_dir, ignore_errors=True)
Example #2
0
def fixture_working_dir_with_cached_user():
    """A pytest fixture that creates a temporary working directory, config file, schema, and local user identity
    """
    # Create temp dir
    config_file, temp_dir = _create_temp_work_dir()

    # Create user identity
    user_dir = os.path.join(temp_dir, '.labmanager', 'identity')
    os.makedirs(user_dir)
    with open(os.path.join(user_dir, 'user.json'), 'wt') as user_file:
        json.dump(
            {
                "username": "******",
                "email": "*****@*****.**",
                "given_name": "Jane",
                "family_name": "Doe"
            }, user_file)

    with patch.object(Configuration, 'find_default_config',
                      lambda self: config_file):
        app = Flask("lmsrvlabbook")

        # Load configuration class into the flask application
        app.config["LABMGR_CONFIG"] = Configuration()
        app.config["LABMGR_ID_MGR"] = get_identity_manager(Configuration())

        with app.app_context():
            # within this block, current_app points to app.
            yield config_file, temp_dir  # name of the config file, temporary working directory

    # Remove the temp_dir
    shutil.rmtree(temp_dir)
def fixture_working_dir_env_repo_scoped():
    """A pytest fixture that creates a temporary working directory, a config file to match, creates the schema,
    and populates the environment component repository.
    Class scope modifier attached
    """
    # Create temp dir
    config_file, temp_dir = _create_temp_work_dir()

    # Create user identity
    user_dir = os.path.join(temp_dir, '.labmanager', 'identity')
    os.makedirs(user_dir)
    with open(os.path.join(user_dir, 'user.json'), 'wt') as user_file:
        json.dump(
            {
                "username": "******",
                "email": "*****@*****.**",
                "given_name": "Jane",
                "family_name": "Doe"
            }, user_file)

    # Create test client
    schema = graphene.Schema(query=LabbookQuery, mutation=LabbookMutations)

    # get environment data and index
    erm = RepositoryManager(config_file)
    erm.update_repositories()
    erm.index_repositories()

    with patch.object(Configuration, 'find_default_config',
                      lambda self: config_file):
        # Load User identity into app context
        app = Flask("lmsrvlabbook")
        app.config["LABMGR_CONFIG"] = Configuration()
        app.config["LABMGR_ID_MGR"] = get_identity_manager(Configuration())

        with app.app_context():
            # within this block, current_app points to app. Set current user explicitly (this is done in the middleware)
            flask.g.user_obj = app.config["LABMGR_ID_MGR"].get_user_profile()

            # Create a test client
            client = Client(
                schema,
                middleware=[LabBookLoaderMiddleware(), error_middleware],
                context_value=ContextMock())

            yield config_file, temp_dir, client, schema  # name of the config file, temporary working directory, the schema

    # Remove the temp_dir
    shutil.rmtree(temp_dir)
def fixture_working_dir_lfs_disabled():
    """A pytest fixture that creates a temporary working directory, config file, schema, and local user identity
    """
    # Create temp dir
    config_file, temp_dir = _create_temp_work_dir(lfs_enabled=False)

    # Create user identity
    user_dir = os.path.join(temp_dir, '.labmanager', 'identity')
    os.makedirs(user_dir)
    with open(os.path.join(user_dir, 'user.json'), 'wt') as user_file:
        json.dump(
            {
                "username": "******",
                "email": "*****@*****.**",
                "given_name": "Jane",
                "family_name": "Doe"
            }, user_file)

    # Create test client
    schema = graphene.Schema(query=LabbookQuery, mutation=LabbookMutations)

    with patch.object(Configuration, 'find_default_config',
                      lambda self: config_file):
        # Load User identity into app context
        app = Flask("lmsrvlabbook")
        app.config["LABMGR_CONFIG"] = Configuration()
        app.config["LABMGR_ID_MGR"] = get_identity_manager(Configuration())

        with app.app_context():
            # within this block, current_app points to app. Set current usert explicitly(this is done in the middleware)
            flask.g.user_obj = app.config["LABMGR_ID_MGR"].get_user_profile()

            # Create a test client
            client = Client(schema,
                            middleware=[LabBookLoaderMiddleware()],
                            context_value=ContextMock())

            yield config_file, temp_dir, client, schema  # name of the config file, temporary working directory, the schema

    # Remove the temp_dir
    shutil.rmtree(temp_dir)
from lmcommon.environment import RepositoryManager
from lmcommon.auth.identity import AuthenticationError, get_identity_manager
from lmcommon.labbook.lock import reset_all_locks
from lmcommon.labbook import LabBook
from lmsrvcore.auth.user import get_logged_in_author

logger = LMLogger.get_logger()

# Create Flask app
app = Flask("lmsrvlabbook")

# Load configuration class into the flask application
random_bytes = os.urandom(32)
app.config["SECRET_KEY"] = base64.b64encode(random_bytes).decode('utf-8')
app.config["LABMGR_CONFIG"] = config = Configuration()
app.config["LABMGR_ID_MGR"] = get_identity_manager(Configuration())

if config.config["flask"]["allow_cors"]:
    # Allow CORS
    CORS(app, max_age=7200)

# Set Debug mode
app.config['DEBUG'] = config.config["flask"]["DEBUG"]

# Register LabBook service
app.register_blueprint(blueprint.complete_labbook_service)

# Configure CHP
try:
    api_prefix = app.config["LABMGR_CONFIG"].config['proxy'][
        "labmanager_api_prefix"]
def build_image_for_jupyterlab():
    # Create temp dir
    config_file, temp_dir = _create_temp_work_dir()

    # Create user identity
    user_dir = os.path.join(temp_dir, '.labmanager', 'identity')
    os.makedirs(user_dir)
    with open(os.path.join(user_dir, 'user.json'), 'wt') as user_file:
        json.dump(
            {
                "username": "******",
                "email": "*****@*****.**",
                "given_name": "unittester",
                "family_name": "tester"
            }, user_file)

    # Create test client
    schema = graphene.Schema(query=LabbookQuery, mutation=LabbookMutations)

    # get environment data and index
    erm = RepositoryManager(config_file)
    erm.update_repositories()
    erm.index_repositories()

    with patch.object(Configuration, 'find_default_config',
                      lambda self: config_file):
        # Load User identity into app context
        app = Flask("lmsrvlabbook")
        app.config["LABMGR_CONFIG"] = Configuration()
        app.config["LABMGR_ID_MGR"] = get_identity_manager(Configuration())

        with app.app_context():
            # within this block, current_app points to app. Set current user explicitly (this is done in the middleware)
            flask.g.user_obj = app.config["LABMGR_ID_MGR"].get_user_profile()

            # Create a test client
            client = Client(
                schema,
                middleware=[LabBookLoaderMiddleware(), error_middleware],
                context_value=ContextMock())

            # Create a labook
            lb = LabBook(config_file)
            lb.new(name="containerunittestbook",
                   description="Testing docker building.",
                   owner={"username": "******"})

            # Create Component Manager
            cm = ComponentManager(lb)
            # Add a component
            cm.add_component("base", ENV_UNIT_TEST_REPO, ENV_UNIT_TEST_BASE,
                             ENV_UNIT_TEST_REV)
            cm.add_packages("pip3", [{
                "manager": "pip3",
                "package": "requests",
                "version": "2.18.4"
            }])

            ib = ImageBuilder(lb)
            ib.assemble_dockerfile(write=True)
            docker_client = get_docker_client()

            try:
                lb, docker_image_id = ContainerOperations.build_image(
                    labbook=lb, username="******")

                yield lb, ib, docker_client, docker_image_id, client, "unittester"

            finally:
                shutil.rmtree(lb.root_dir)
                try:
                    docker_client.containers.get(docker_image_id).stop()
                    docker_client.containers.get(docker_image_id).remove()
                except:
                    pass

                try:
                    docker_client.images.remove(docker_image_id,
                                                force=True,
                                                noprune=False)
                except:
                    pass
def fixture_working_dir_populated_scoped():
    """A pytest fixture that creates a temporary working directory, a config file to match, creates the schema,
    and populates the environment component repository.
    Class scope modifier attached
    """
    # Create temp dir
    config_file, temp_dir = _create_temp_work_dir()

    # Create user identity
    user_dir = os.path.join(temp_dir, '.labmanager', 'identity')
    os.makedirs(user_dir)
    with open(os.path.join(user_dir, 'user.json'), 'wt') as user_file:
        json.dump(
            {
                "username": "******",
                "email": "*****@*****.**",
                "given_name": "Jane",
                "family_name": "Doe"
            }, user_file)

    # Create test client
    schema = graphene.Schema(query=LabbookQuery, mutation=LabbookMutations)

    # Create a bunch of lab books
    lb = LabBook(config_file)

    lb.new(owner={"username": "******"},
           name="labbook1",
           description="Cats labbook 1")
    time.sleep(1.1)
    lb.new(owner={"username": "******"},
           name="labbook2",
           description="Dogs labbook 2")
    time.sleep(1.1)
    lb.new(owner={"username": "******"},
           name="labbook3",
           description="Mice labbook 3")
    time.sleep(1.1)
    lb.new(owner={"username": "******"},
           name="labbook4",
           description="Horses labbook 4")
    time.sleep(1.1)
    lb.new(owner={"username": "******"},
           name="labbook5",
           description="Cheese labbook 5")
    time.sleep(1.1)
    lb.new(owner={"username": "******"},
           name="labbook6",
           description="Goat labbook 6")
    time.sleep(1.1)
    lb.new(owner={"username": "******"},
           name="labbook7",
           description="Turtle labbook 7")
    time.sleep(1.1)
    lb.new(owner={"username": "******"},
           name="labbook8",
           description="Lamb labbook 8")
    time.sleep(1.1)
    lb.new(owner={"username": "******"},
           name="labbook9",
           description="Taco labbook 9")
    time.sleep(1.1)
    lb.new(owner={"username": "******"},
           name="labbook-0",
           description="This should not show up.")

    with patch.object(Configuration, 'find_default_config',
                      lambda self: config_file):
        # Load User identity into app context
        app = Flask("lmsrvlabbook")
        app.config["LABMGR_CONFIG"] = Configuration()
        app.config["LABMGR_ID_MGR"] = get_identity_manager(Configuration())

        with app.app_context():
            # within this block, current_app points to app. Set current user explicitly (this is done in the middleware)
            flask.g.user_obj = app.config["LABMGR_ID_MGR"].get_user_profile()

            # Create a test client
            client = Client(schema,
                            middleware=[LabBookLoaderMiddleware()],
                            context_value=ContextMock())

            yield config_file, temp_dir, client, schema

    # Remove the temp_dir
    shutil.rmtree(temp_dir)