Example #1
0
def client():
    # Use our test integration config instead of the "real" version
    file_path = find_dotenv('.env.test')
    load_dotenv(file_path, override=True)

    # CosmosDB  secrets:
    cosmos_database_name = os.getenv('DATABASE_NAME')
    cosmos_url = os.getenv("COSMOS_URL")
    cosmos_port = os.getenv("COSMOS_PORT")
    cosmos_connection_string = os.getenv('COSMOS_CONNECTION_STRING')
    # Mongomock
    with mongomock.patch(servers=((f'{cosmos_database_name}.{cosmos_url}',
                                   int(cosmos_port)), )):
        # Create the new app.
        test_app = create_app()
        test_app.config['LOGIN_DISABLED'] = True

        # Connect to CosmosDB using mongo api:
        mclient = pymongo.MongoClient(cosmos_connection_string)

        # Add fake items to mongomock
        db = mclient.testboard

        insert_document('Test item 1', 'to do', db)
        insert_document('Test item 2', 'doing', db)
        insert_document('Test item 3', 'done', db)

        # Use the app to create a test_client that can be used in our tests.
        with test_app.test_client() as client:
            yield client
    def setUp(self) -> None:
        """Set up."""

        patcher = mongomock.patch(_FAKE_MONGO_URL)
        patcher.start()
        self.addCleanup(patcher.stop)
        self.mongo_db = pymongo.MongoClient(_FAKE_MONGO_URL).get_database()
Example #3
0
def client():
    load_dotenv('.env.test', override=True)
    os.environ["disable_login"] = '******'
    with mongomock.patch(servers=(("test.mongo.cosmos.azure.com", 10255), )):
        test_app = app.create_app()
        with test_app.test_client() as client:
            yield client
Example #4
0
    def setUp(self) -> None:
        super().setUp()

        patcher = mongomock.patch(['mydata.com', 'myprivatedata.com'])
        patcher.start()
        self.addCleanup(patcher.stop)
        patcher = mock.patch.dict(os.environ,
                                  values={
                                      'MONGO_URL':
                                      'mongodb://mydata.com/test',
                                      'USERS_MONGO_URL':
                                      'mongodb://myprivatedata.com/user_test',
                                  })
        patcher.start()
        self.addCleanup(patcher.stop)
        self._user_database = pymongo.MongoClient(
            'mongodb://myprivatedata.com/user_test').user_test
        self._user_database.cvs_and_cover_letters.insert_one({
            '_id':
            objectid.ObjectId('5b2173b9362bf80840db6c2a'),
            'name':
            'Nathalie',
            'anonymizedUrl':
            'https://dl.airtable.com/fakeurl.pdf',
            'kind':
            'DOCUMENT_COVER_LETTER',
            'ownerEmail':
            '*****@*****.**',
            'numDoneReviews':
            1,
        })
Example #5
0
def client():
    file_path = find_dotenv('.env.test')
    load_dotenv(file_path, override=True)
    with mongomock.patch(servers=(('fakemongo.com', 27017), )):
        test_app = app.create_app()
        with test_app.test_client() as client:
            setup_testdata()
            yield client
Example #6
0
def client():
    file_path = find_dotenv('.env.test')
    load_dotenv(file_path, override=True)
    test_login = '******'
    os.environ['LOGIN_DISABLED'] = test_login
    with mongomock.patch(servers=(('testmongo.com', 27017), )):
        test_app = todo_app.app.create_app()
        with test_app.test_client() as client:
            yield client
Example #7
0
def client():
    file_path = find_dotenv('.env.test')
    load_dotenv(file_path, override=True)

    with mongomock.patch(servers=(('fakemongo.com', 27017), )):
        test_app = todo_app.app.create_app()
        test_app.config['LOGIN_DISABLED'] = True
        with test_app.test_client() as client:
            yield client
def client():
    # Use our test integration config instead of the 'real' version
    file_path = find_dotenv('.env.test')
    load_dotenv(file_path, override=True)

    with mongomock.patch(servers=(('server.example.com', 27017),)):
        test_app = app.create_app()
        with test_app.test_client() as client:
            yield client
Example #9
0
    def setUp(self) -> None:
        super().setUp()
        self.output = io.StringIO()
        patcher = mongomock.patch()
        patcher.start()
        self.addCleanup(patcher.stop)

        self.db_client = pymongo.MongoClient('mongodb://localhost/test')
        for collection in self.db_client.test.list_collection_names():
            self.db_client.test.drop_collection(collection)
Example #10
0
    def setUp(self) -> None:
        super().setUp()

        cache.clear()
        patcher = mongomock.patch(['mydata.com', 'myprivatedata.com'])
        patcher.start()
        self.addCleanup(patcher.stop)
        env_patcher = mock.patch.dict(
            os.environ,
            values={
                'MONGO_URL': 'mongodb://mydata.com/test',
                'USERS_MONGO_URL': 'mongodb://myprivatedata.com/user_test',
            })
        env_patcher.start()
        self.addCleanup(env_patcher.stop)
        self.addCleanup(mongo.cache.clear)
        self.database = mongo.NoPiiMongoDatabase(
            pymongo.MongoClient('mongodb://mydata.com/test').test)
        self._user_database = pymongo.MongoClient(
            'mongodb://myprivatedata.com/user_test').user_test

        # TODO(cyrille): Use this to mock time whenever necessary.
        self.now: Optional[datetime.datetime] = None
        # Default values that shouldn't be expected, and should be overridden when necessary.
        user_name = 'Patrick'
        user_email = '*****@*****.**'
        user_user_id = f'{random.randrange(16**24):024x}'
        user_registration_date = datetime.datetime.now() - datetime.timedelta(
            days=90)
        # TODO(cyrille): Replace these values by personas.
        self.user = user_pb2.User(user_id=user_user_id)
        self.user.registered_at.FromDatetime(user_registration_date)
        self.user.profile.gender = user_profile_pb2.MASCULINE
        self.user.profile.name = user_name
        self.user.profile.email = user_email
        self.user.profile.year_of_birth = 1990
        self.project = self.user.projects.add()
        self.project.project_id = '0'
        self.project.target_job.masculine_name = 'Coiffeur'
        self.project.target_job.feminine_name = 'Coiffeuse'
        self.project.target_job.name = 'Coiffeur / Coiffeuse'
        self.project.target_job.code_ogr = '123456'
        self.project.target_job.job_group.rome_id = 'B1234'
        self.project.target_job.job_group.name = 'Coiffure'
        self.project.network_estimate = 1
        self.project.city.city_id = '69003'
        self.project.city.name = 'Lyon'
        self.project.city.departement_id = '69'
        self.project.city.departement_prefix = 'dans le '
        self.project.city.departement_name = 'Rhône'
        self.project.city.region_id = '84'
        self.project.city.region_name = 'Auvergne-Rhône-Alpes'

        self._variables: dict[str, Any] = {}
        self._from: dict[str, Any] = {}
def client():
    try:
        file_path = find_dotenv('.env.test')
        load_dotenv(file_path, override=True)
    except:
        pass

    with mongomock.patch(servers=(('fakemongo.com', 27017), )):
        test_app = create_app()
        with test_app.test_client() as client:
            yield client
Example #12
0
def client():
    with mongomock.patch(servers=('mongodb://example:27017/', )):
        # Use our test integration config instead of the 'real' version
        file_path = find_dotenv('../.env.test')
        load_dotenv(file_path, override=True)
        # Create the new app.
        test_app = app.create_app()
        test_app.config['LOGIN_DISABLED'] = True
        # Use the app to create a test_client that can be used in our tests.
        with test_app.test_client() as client:
            yield client
    def test_check_all_command_line(self, mock_logging_error: mock.MagicMock) -> None:
        """No problems with scoring models using the commandline."""

        with mongomock.patch(servers='bob-db'):
            data_db = pymongo.MongoClient('mongodb://bob-db/data').get_database()
            data_db.has_scoring_models.insert_one({'filters': ['for-women']})
            maintenance.main([
                '--check', 'scoring-models',
                '--deployment', 'test', 'mongodb://bob-db/data', 'mongodb://bob-db/users',
            ])
        self.assertFalse(mock_logging_error.called, msg=mock_logging_error.call_args)
Example #14
0
def client():
    # Use our test integration config instead of the 'real' version
    file_path = find_dotenv('.env.test')
    load_dotenv(file_path, override=True)

    with mongomock.patch(servers=(('fakemongo.com', 27017), )):
        prepare_test_data()
        test_app = app.create_app()
        test_app.config['LOGIN_DISABLED'] = True
        with test_app.test_client() as client:
            yield client
def client():
    # Use our test integration config instead of the 'real' version
    file_path = find_dotenv('.env.test')
    load_dotenv(file_path, override=True)

    with mongomock.patch(servers=(('test.mongodb.net', 27017), )):
        # Create the new app.
        test_app = create_app()

        # Use the app to create a test_client that can be used in our tests.
        with test_app.test_client() as client:
            yield client
    def test_unknown_model_command_line(self, mock_logging_error: mock.MagicMock) -> None:
        """A record has an unknown scoring model (using CLI)."""

        with mongomock.patch(servers='bob-db'):
            data_db = pymongo.MongoClient('mongodb://bob-db/data').get_database()
            data_db.has_scoring_models.insert_one(
                {'_id': 'culprit', 'filters': ['unknown-not-implemented']})
            maintenance.main([
                '--check', 'scoring-models',
                '--deployment', 'test', 'mongodb://bob-db/data', 'mongodb://bob-db/users',
            ])
        self.assertIn('has_scoring_models', mock_logging_error.call_args[0])
        self.assertIn('culprit', mock_logging_error.call_args[0])
Example #17
0
def api(mocker):

    with mongomock.patch():
        import repository.app as app

        mocker.patch("repository.resources.resources", new=RESOURCES)
        importlib.reload(app)

        with app.app.test_client() as client:
            yield client

        # Drop the MongoMock database
        uri: str = config["mongo_uri"]
        pymongo.MongoClient(host=uri).drop_database(uri[uri.rfind("/") + 1:])
Example #18
0
def client():
    # Use our test integration config instead of the 'real' version 
    try:
        file_path = find_dotenv('.env.test')
        load_dotenv(file_path, override=True)
    except OSError:
        print(".env file not found")

     # Create the new app. 
    with mongomock.patch(servers=(('fakemongo.com', 27017),)): 
        test_app = app.create_app()
        # Use the app to create a test_client that can be used in our tests.
        with test_app.test_client() as client:
            setup_test_data()
            yield client
Example #19
0
    def setUp(self) -> None:
        """Set up for each test: prepare the importer."""

        super().setUp()
        flag_values = argparse.Namespace()
        flag_values.mongo_collection = ''
        flag_values.chunk_size = 10000
        flag_values.always_accept_diff = False
        flag_values.report_to_slack = False
        self.output = io.StringIO()
        self.importer = mongo.Importer(flag_values, out=self.output)
        patcher = mongomock.patch(('my-db_client-url', ))
        patcher.start()
        self.addCleanup(patcher.stop)
        self.db_client = pymongo.MongoClient('mongodb://my-db_client-url/test')
Example #20
0
def test_app():
    with mongomock.patch(servers=('mongodb://example:27017/', )):
        file_path = find_dotenv('../.env.test')
        load_dotenv(file_path, override=True)
        # construct the new application
        application = app.create_app()
        application.config['LOGIN_DISABLED'] = True
        # start the app in its own thread.
        thread = Thread(target=lambda: application.run(use_reloader=False))
        thread.daemon = True
        thread.start()
        yield app
        # Tear Down
        thread.join(1)
        print('Completed tests')
Example #21
0
def client():
    # Use our test integration config instead of the'real' version
    file_path = find_dotenv('.env.test')
    load_dotenv(file_path, override=True)
    with mongomock.patch(servers=(('fakemongo.com', 27017), )):

        test_app = create_app()
        with test_app.test_client() as client:
            objects = {
                "name": "test",
                "idBoard": "test",
                "last_modified": "2021-03-15"
            }
            db_client = pymongo.MongoClient('fakemongo.com')
            db_client.db.collection.insert_one(objects)
            yield client
Example #22
0
    def setUp(self) -> None:
        super().setUp()
        self.addCleanup(cache.clear)
        env_patcher = mock.patch.dict(
            os.environ, {
                'MONGO_URL': 'mongodb://mydata.com/test',
                'USERS_MONGO_URL': 'mongodb://my-database/test',
            })
        env_patcher.start()
        self.addCleanup(env_patcher.stop)

        db_patcher = mongomock.patch(
            (('my-database', 27017), ('mydata.com', 27017)))
        db_patcher.start()
        self.addCleanup(db_patcher.stop)
        self._stats_db, self._user_db, self._eval_db = mongo.get_connections_from_env(
        )
Example #23
0
    def setUp(self) -> None:
        """Set up mock environment."""

        super().setUp()
        # Simulate a clean load of the modules.

        self.app = server.app.test_client()
        self.app_context = typing.cast(
            Callable[[], typing.ContextManager[None]], server.app.app_context)
        cache.clear()
        patcher = mongomock.patch(on_new='create')
        patcher.start()
        self.addCleanup(patcher.stop)
        self._db, self._user_db, self._eval_db = server.mongo.get_connections_from_env(
        )
        server.jobs._JOB_GROUPS_INFO.reset_cache()  # pylint: disable=protected-access
        self._db.action_templates.insert_many([{
            '_id': f'a{i:d}',
            'actionTemplateId': f'a{i:d}',
        } for i in range(30)])
        self._db.local_diagnosis.insert_one({
            '_id': '38:M1403',
            'bmo': {
                'percentDifficult': 5,
                'percentSeasonal': 10,
            },
            'salary': {
                'shortText': '17 400 - 17 400',
                'medianSalary': 17400.0,
                'unit': 'ANNUAL_GROSS_SALARY',
                'maxSalary': 17400.0,
                'minSalary': 17400.0
            }
        })
        logging_patch = mock.patch(server.__name__ + '.logging', spec=True)
        logging_patch.start()
        self.addCleanup(logging_patch.stop)
        self._translations: list[dict[str, str]] = []
    def setUp(self) -> None:
        airtablemock.clear()
        patcher = mock.patch('airtable.airtable.Airtable', airtablemock.Airtable)
        patcher.start()
        self.addCleanup(patcher.stop)

        job_group_info.AIRTABLE_API_KEY = 'key01234567'

        advice_airtable = airtablemock.Airtable('app01234567', 'key01234567')
        advice_airtable.create('advice', {
            'code_rome': 'D1501',
            'SKILLS': '* Être créatif',
            'BONUS SKILLS': "* Avoir le sens de l'humour",
            'TRAINING': '* Maîtriser des logiciels',
            'other': 'foo',
        })

        rome_airtable = airtablemock.Airtable('app4242', 'key01234567')
        rome_airtable.create('domains', {
            'name': 'Commerce de gros',
            'domain_name': 'Commerce, négoce et distribution',
        })
        rome_airtable.create('domains', {
            'name': 'Commerce/grande distribution',
            'domain_name': 'Commerce, négoce et distribution',
        })
        rome_airtable.create('Rigid Diplomas', {
            'code_rome': 'D1501',
            'is_diploma_strictly_required': True,
        })
        rome_airtable.create('info_by_prefix', {
            'domain': 'Commerce, vente et grande distribution',
            'rome_prefix': 'D',
            'inDomain': 'dans le commerce ',
        })
        rome_airtable.create('info_by_prefix', {
            'rome_prefix': 'D15',
            'inDomain': 'dans la grande distribution',
            'preferredApplicationMedium': 'APPLY_BY_EMAIL',
            'hasFreelancers': True,
            'inAWorkplace': 'dans un supermarché',
            'likeYourWorkplace': 'comme le vôtre',
            'placePlural': 'des supermarchés',
            'whatILoveAbout': "j'adore vos allées",
            'toTheWorkplace': 'A la manufacture',
            'whySpecificCompany': 'vous aimez être au service des autres',
            'atVariousCompanies': 'à la MAIF, à la MATMUT',
            'whatILoveAboutFeminine': "j'adore vos allées",
            'covidRisk': 'COVID_RISKY',
        })

        job_group_info.USERS_MONGO_URL = 'mongodb://fake-mongo-url/test'

        db_patcher = mongomock.patch(('fake-mongo-url',))
        db_patcher.start()
        self.addCleanup(db_patcher.stop)
        self.user_db = pymongo.MongoClient('mongodb://fake-mongo-url/test').get_database()
        self.user_db.user.insert_many([
            {'projects': [{
                'isIncomplete': True,
            }]},
            {
                'profile': {'highestDegree': 'CAP_BEP'},
                'projects': [{'targetJob': {'jobGroup': {'romeId': 'D1501'}}}],
            },
            {
                'profile': {'highestDegree': 'CAP_BEP'},
                'projects': [{'targetJob': {'jobGroup': {'romeId': 'D1501'}}}],
            },
            {
                'profile': {'highestDegree': 'BAC_BACPRO'},
                'projects': [{'targetJob': {'jobGroup': {'romeId': 'D1501'}}}],
            },
        ])
Example #25
0
def mock_db():
    with mongomock.patch(servers=["localhost", "mongodb"]):
        yield