예제 #1
0
    def test_user_is_pro(self):
        """
        Test that the Pro user is correctly detected in various cases.

        Note : A pro user can be defined by his IP address too but it's not possible to test.
        So, only tests by email are provided
        """
        user_pro = User.create(email='*****@*****.**',
                               gender='male',
                               first_name='John',
                               last_name='Doe')
        user_public = User.create(email='*****@*****.**',
                                  gender='male',
                                  first_name='John',
                                  last_name='Doe')

        with self.test_request_context:
            # User which is not logged in should not be considered a pro user.
            self.assertFalse(pro.user_is_pro())

            # User with a pro email should be considered as a pro user.
            self.login(user_pro)
            self.assertTrue(pro.user_is_pro())
            self.logout()
            self.assertFalse(pro.user_is_pro())

            # User with a non pro email should not be considered a pro user.
            self.login(user_public)
            self.assertFalse(pro.user_is_pro())
            self.logout()
            self.assertFalse(pro.user_is_pro())
예제 #2
0
    def test_user_is_pro(self):
        """
        Test that the Pro Version is correctly detected in various cases.
        """

        user_pro = User.create(email=u'*****@*****.**',
                               gender=u'male',
                               first_name=u'John',
                               last_name=u'Doe')
        user_public = User.create(email=u'*****@*****.**',
                                  gender=u'male',
                                  first_name=u'John',
                                  last_name=u'Doe')
 def test_run_pipeline_with_user_email_change(self):
     user = User(email='*****@*****.**',
                 external_id='peconnect-userid')
     user.save()
     self.assertEqual(
         User.query.filter_by(external_id='peconnect-userid').first().email,
         '*****@*****.**',
     )
     result = self.run_pipeline(peam.PEAMOpenIdConnect)
     self.assertEqual(
         User.query.filter_by(external_id='peconnect-userid').first().email,
         '*****@*****.**',
     )
예제 #4
0
 def login_as_pro(self):
     user_pro = User.create(email='*****@*****.**',
                            gender='male',
                            first_name='John',
                            last_name='Doe')
     self.login(user_pro)
     self.assertTrue(pro.user_is_pro())
     self.assertFalse(pro.pro_version_enabled())
    def setUp(self):
        """
        Populate the DB with data required for these tests to work.
        """
        super(UserAccountTest, self).setUp()

        self.user = User(email='*****@*****.**',
                         gender='male',
                         first_name='John',
                         last_name='Doe')
        db_session.add(self.user)
        db_session.flush()

        self.office1 = Office(
            departement='57',
            siret='00000000000001',
            company_name='1',
            headcount='5',
            city_code='57070',
            zipcode='57070',
            naf='4646Z',
            score=90,
            x=6.166667,
            y=49.133333,
        )
        self.office2 = Office(
            departement='57',
            siret='00000000000002',
            company_name='1',
            headcount='5',
            city_code='57070',
            zipcode='57070',
            naf='4646Z',
            score=90,
            x=6.166667,
            y=49.133333,
        )
        db_session.add_all([self.office1, self.office2])
        db_session.flush()

        self.user_social_auth = UserSocialAuth(
            provider=PEAMOpenIdConnect.name,
            extra_data={'id_token': 'fake'},
            user_id=self.user.id,
        )
        self.fav1 = UserFavoriteOffice(user_id=self.user.id,
                                       office_siret=self.office1.siret)
        self.fav2 = UserFavoriteOffice(user_id=self.user.id,
                                       office_siret=self.office2.siret)
        db_session.add_all([self.user_social_auth, self.fav1, self.fav2])
        db_session.flush()

        db_session.commit()

        self.assertEqual(db_session.query(User).count(), 1)
        self.assertEqual(db_session.query(Office).count(), 2)
        self.assertEqual(db_session.query(UserFavoriteOffice).count(), 2)
        self.assertEqual(db_session.query(UserSocialAuth).count(), 1)
예제 #6
0
    def test_office_admin_add(self):
        form = {
            "siret": "78548035101646",
            "company_name": "SUPERMARCHES MATCH",
            "office_name": "SUPERMARCHES MATCH",
            "naf": "4711D",
            "street_number": "45",
            "street_name": "AVENUE ANDRE MALRAUX",
            "city_code": "57463",
            "zipcode": "57000",
            "email": "*****@*****.**",
            "tel": "0387787878",
            "website": "http://www.supermarchesmatch.fr",
            "flag_alternance": 0,
            "flag_junior": 0,
            "flag_senior": 0,
            "flag_handicap": 0,
            "departement": "57",
            "headcount": "12",
            "score": 90,
            "score_alternance": 75,
            "x": 6.17952,
            "y": 49.1044,
            "reason": "Demande de mise en avant",
        }

        with self.test_request_context():
            # Create an user admin
            self.user = User(email='*****@*****.**', gender='male',
                             first_name='John', last_name='Doe', active=True,
                             is_admin=True)
            db_session.add(self.user)
            db_session.flush()

            user_social_auth = UserSocialAuth(
                provider=PEAMOpenIdConnect.name,
                extra_data={'id_token': 'fake'},
                user_id=self.user.id,
            )
            db_session.add(user_social_auth)
            db_session.commit()

            # Login as user admin
            self.user = db_session.query(User).filter_by(id=self.user.id).first()
            self.assertEqual(db_session.query(User).count(), 1)
            self.login(self.user)

            # Create OfficeAdminRemove
            self.assertEqual(0, OfficeAdminAdd.query.filter_by(id=1).count())
            self.app.post(url_for('officeadminadd.create_view'), data=form)
            self.assertEqual(1, OfficeAdminAdd.query.filter_by(id=1).count())

            # Delete OfficeAdminAdd
            self.app.post(url_for('officeadminadd.delete_view'), data={'id': 1})
            self.assertEqual(0, OfficeAdminRemove.query.filter_by(id=1).count())
예제 #7
0
 def setUp(self):
     super().setUp()
     self.pro_user = User.create(
         email='*****@*****.**',
         gender='male',
         first_name='John',
         last_name='Doe',
     )
     self.public_user = User.create(
         email='*****@*****.**',
         gender='male',
         first_name='John',
         last_name='Doe',
     )
     user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0"
     allowed_ip = settings.VERSION_PRO_ALLOWED_IPS[
         1]  # IP address // should not be a range
     self.headers = {
         'X-Forwarded-For': allowed_ip,
         'User_Agent': user_agent,
     }
예제 #8
0
    def test_office_admin_remove(self):
        # Create officeAdminRemove
        form = {
            'siret': '01234567891234',
            'name': 'Test company',
            'reason': 'N/A',
            'initiative': 'office',
        }

        with self.test_request_context():
            # Create an user admin
            self.user = User(email='*****@*****.**',
                             gender='male',
                             first_name='John',
                             last_name='Doe',
                             active=True,
                             is_admin=True)
            db_session.add(self.user)
            db_session.flush()

            user_social_auth = UserSocialAuth(
                provider=PEAMOpenIdConnect.name,
                extra_data={'id_token': 'fake'},
                user_id=self.user.id,
            )
            db_session.add(user_social_auth)
            db_session.commit()

            # Login as user admin
            self.user = db_session.query(User).filter_by(
                id=self.user.id).first()
            self.assertEqual(db_session.query(User).count(), 1)
            self.login(self.user)

            # Create OfficeAdminRemove
            self.assertEqual(
                0,
                OfficeAdminRemove.query.filter_by(
                    siret='01234567891234').count())
            self.app.post(url_for('officeadminremove.create_view'), data=form)
            self.assertEqual(
                1,
                OfficeAdminRemove.query.filter_by(
                    siret='01234567891234').count())

            # Delete OfficeAdminRemove
            self.app.post(url_for('officeadminremove.delete_view'),
                          data={'id': 1})
            self.assertEqual(0,
                             OfficeAdminRemove.query.filter_by(id=1).count())
예제 #9
0
    def test_enable_disable_pro_version_view(self):
        """
        Test that the Pro Version is correctly enabled/disabled.
        """
        # Create a user.
        user_pro = User.create(email='*****@*****.**',
                               gender='male',
                               first_name='John',
                               last_name='Doe')

        next_url_without_domain = '/entreprises/metz-57000/boucherie?sort=score&d=10&h=1&p=0&f_a=0'
        next_url_with_domain = 'http://labonneboite.pole-emploi.fr' + next_url_without_domain
        url = self.url_for('user.pro_version',
                           **{'next': next_url_without_domain})

        with self.test_request_context:

            # Log the user in.
            self.login(user_pro)
            self.assertTrue(pro.user_is_pro())
            self.assertFalse(pro.pro_version_enabled())

            with self.app.session_transaction() as sess:
                self.assertNotIn(pro.PRO_VERSION_SESSION_KEY, sess)

            # Enable pro version.
            rv = self.app.get(url)
            self.assertEqual(rv.status_code, 302)
            self.assertEqual(rv.location, next_url_with_domain)
            # It is unclear what is the root cause of the following test
            # failure. The session object manipulated in the
            # pro_version_enabled function is different from the session
            # provided by the self.app.session_transaction context manager, but
            # I don't know why.
            # self.assertTrue(pro.pro_version_enabled())

            with self.app.session_transaction() as sess:
                self.assertIn(pro.PRO_VERSION_SESSION_KEY, sess)
                self.assertEqual(True, sess[pro.PRO_VERSION_SESSION_KEY])

            # Disable pro version.
            rv = self.app.get(url)
            self.assertEqual(rv.status_code, 302)
            self.assertEqual(rv.location, next_url_with_domain)
            self.assertFalse(pro.pro_version_enabled())

            with self.app.session_transaction() as sess:
                self.assertNotIn(pro.PRO_VERSION_SESSION_KEY, sess)
예제 #10
0
    def test_get_user_social_auth(self):
        """
        Test the `get_user_social_auth()` function.
        """
        user = User(email='*****@*****.**', gender='male', first_name='John', last_name='Doe')
        db_session.add(user)
        db_session.flush()

        expected_user_social_auth = UserSocialAuth(provider=PEAMOpenIdConnect.name, extra_data=None, user_id=user.id)
        db_session.add(expected_user_social_auth)
        db_session.flush()

        db_session.commit()

        self.assertEqual(db_session.query(User).count(), 1)
        self.assertEqual(db_session.query(UserSocialAuth).count(), 1)

        user_social_auth = get_user_social_auth(user.id)
        self.assertEqual(user_social_auth.id, expected_user_social_auth.id)
예제 #11
0
    def test_logout(self):
        """
        Test that the session is cleaned after a logout.
        """

        user = User(email='*****@*****.**',
                    gender='male',
                    first_name='John',
                    last_name='Doe')
        db_session.add(user)
        db_session.flush()

        # This `UserSocialAuth` entry will be required later by the logout function.
        user_social_auth = UserSocialAuth(
            provider=PEAMOpenIdConnect.name,
            extra_data={'id_token': 'fake'},
            user_id=user.id,
        )
        db_session.add(user_social_auth)
        db_session.commit()

        with self.test_request_context:

            with self.app.session_transaction() as sess:
                sess[
                    'this_should_not_be_deleted'] = 'foo'  # This should not be deleted by a login or logout.

            self.login(user)

            with self.app.session_transaction() as sess:
                self.assertIn('this_should_not_be_deleted', sess)
                self.assertIn('user_id', sess)
                self.assertIn('social_auth_last_login_backend', sess)
                self.assertIn('peam-openidconnect_state', sess)

            self.logout()

            with self.app.session_transaction() as sess:
                self.assertIn('this_should_not_be_deleted', sess)
                self.assertNotIn('user_id', sess)
                self.assertNotIn('social_auth_last_login_backend', sess)
                self.assertNotIn('peam-openidconnect_state', sess)
예제 #12
0
    def setUp(self, *args, **kwargs):
        super(AdminTest, self).setUp(*args, **kwargs)

        self.user = User(email='*****@*****.**',
                         gender='male',
                         first_name='John',
                         last_name='Doe')
        db_session.add(self.user)
        db_session.flush()

        # Required for `self.logout` to work which looks for the `extra_data` attribute.
        user_social_auth = UserSocialAuth(
            provider=PEAMOpenIdConnect.name,
            extra_data={'id_token': 'fake'},
            user_id=self.user.id,
        )
        db_session.add(user_social_auth)
        db_session.commit()

        self.assertEqual(db_session.query(User).count(), 1)
예제 #13
0
def load_user(user_id):
    """
    Tell the login manager how to reload the user object from the user ID stored in the session:
    http://flask-login.readthedocs.io/en/0.4.0/#flask_login.LoginManager.user_loader
    """
    return User.get(user_id)
예제 #14
0
    def setUp(self, *args, **kwargs):
        super(FavoriteBaseTest, self).setUp(*args, **kwargs)

        # Create a user.
        self.user = User.create(email=u'*****@*****.**', gender=u'male', first_name=u'John', last_name=u'Doe')

        # Delete index.
        self.es.indices.delete(index=self.ES_TEST_INDEX)

        # Create new index.
        request_body = {
            "mappings": {
                "office": {
                    "properties": {
                        "naf": {
                            "type": "string",
                            "index": "not_analyzed"
                        },
                        "siret": {
                            "type": "string",
                            "index": "not_analyzed"
                        },
                        "name": {
                            "type": "string",
                            "index": "not_analyzed"
                        },
                        "score": {
                            "type": "integer",
                            "index": "not_analyzed"
                        },
                        "headcount": {
                            "type": "integer",
                            "index": "not_analyzed"
                        },
                        "location": {
                            "type": "geo_point",
                        }
                    }
                }
            }
        }
        self.es.indices.create(index=self.ES_TEST_INDEX, body=request_body)

        # Insert test data into Elasticsearch.
        docs = [
            {
                'naf': u'4711F',
                'siret': u'00000000000001',
                'score': 98,
                'headcount': 32,
                'location': self.positions['metz']['location'],
                'name': u'Centre Distributeur E.Leclerc',
            },
            {
                'naf': u'4722Z',
                'siret': u'00000000000002',
                'score': 98,
                'headcount': 12,
                'location': self.positions['metz']['location'],
                'name': u'Maison Nicolas',
            },
            {
                'naf': u'4711F',
                'siret': u'00000000000003',
                'score': 98,
                'headcount': 32,
                'location': self.positions['paris']['location'],
                'name': u'Carrefour Paris',
            },
            {
                'naf': u'4722Z',
                'siret': u'00000000000004',
                'score': 98,
                'headcount': 84,
                'location': self.positions['paris']['location'],
                'name': u'Maistre Mathieu',
            },
        ]
        for i, doc in enumerate(docs, start=1):
            self.es.index(index=self.ES_TEST_INDEX, doc_type=self.ES_OFFICE_TYPE, id=i, body=doc)

        # Sleep required by ES to register new documents, flaky test here otherwise.
        time.sleep(1)

        # Create related Office instances into MariaDB/MySQL.
        for doc in docs:

            # Set the right `commune_id` and `zipcode` depending on the location.
            commune_id = None
            zip_code = None
            commune_id = None
            for position in self.positions:
                if doc['location'] == self.positions[position]['location']:
                    commune_id = self.positions[position]['commune_id']
                    zip_code = self.positions[position]['zip_code']
                    break

            if not commune_id:
                raise ValueError("Cannot create an entry in Office with a city absent from self.positions.")

            office = Office(
                company_name=doc['name'],
                siret=doc['siret'],
                score=doc['score'],
                naf=doc['naf'],
                city_code=commune_id,
                zipcode=zip_code,
                email=u'*****@*****.**',
                departement=zip_code[:2],
                x=doc['location']['lon'],
                y=doc['location']['lat'],
            )
            office.save()

        # We should have as much entries in MariaDB/MySQL than in Elasticsearch.
        self.assertEquals(Office.query.count(), len(docs))
예제 #15
0
    def setUp(self):
        super(FavoriteBaseTest, self).setUp()

        # Create a user.
        self.user = User.create(email='*****@*****.**',
                                gender='male',
                                first_name='John',
                                last_name='Doe')

        # Insert test data into Elasticsearch.
        docs = [
            {
                'naf': '4711F',
                'siret': '00000000000001',
                'score': 98,
                'headcount': 32,
                'locations': self.positions['metz']['coords'],
                'name': 'Centre Distributeur E.Leclerc',
            },
            {
                'naf': '4722Z',
                'siret': '00000000000002',
                'score': 98,
                'headcount': 12,
                'locations': self.positions['metz']['coords'],
                'name': 'Maison Nicolas',
            },
            {
                'naf': '4711F',
                'siret': '00000000000003',
                'score': 98,
                'headcount': 32,
                'locations': self.positions['paris']['coords'],
                'name': 'Carrefour Paris',
            },
            {
                'naf': '4722Z',
                'siret': '00000000000004',
                'score': 98,
                'headcount': 84,
                'locations': self.positions['paris']['coords'],
                'name': 'Maistre Mathieu',
            },
        ]
        for i, doc in enumerate(docs, start=1):
            self.es.index(index=settings.ES_INDEX,
                          doc_type=es.OFFICE_TYPE,
                          id=i,
                          body=doc)

        # Required by ES to register new documents, flaky test here otherwise.
        self.es.indices.flush(index=settings.ES_INDEX)

        # Create related Office instances into MariaDB/MySQL.
        for doc in docs:

            # Set the right `commune_id` and `zipcode` depending on the location.
            commune_id = None
            zip_code = None
            commune_id = None
            for position in self.positions:
                if doc['locations'] == self.positions[position]['coords']:
                    commune_id = self.positions[position]['commune_id']
                    zip_code = self.positions[position]['zip_code']
                    break

            if not commune_id:
                raise ValueError(
                    "Cannot create an entry in Office with a city absent from self.positions."
                )

            office = Office(
                company_name=doc['name'],
                siret=doc['siret'],
                score=doc['score'],
                naf=doc['naf'],
                city_code=commune_id,
                zipcode=zip_code,
                email='*****@*****.**',
                departement=zip_code[:2],
                x=doc['locations'][0]['lon'],
                y=doc['locations'][0]['lat'],
            )
            office.save()

        # We should have as much entries in MariaDB/MySQL than in Elasticsearch.
        self.assertEqual(Office.query.count(), len(docs))