def test_delete_supercar():
    supercars[1] = {'engine': '1'}
    app = TestApp(default_app())

    resp = app.delete('/supercars/1')
    assert_equal(resp.status, '200 OK')
    app.reset()
Example #2
0
def test_login_form_alerts():
    """Make sure login forms are validated"""
    app = HelperApp(server.observation_app)

    # Use bad field names
    response = app.post('/login/', {'usernam': 'carmon', 'passwor': 'frog'})
    assert response.status == "302 Found"
    assert urlsplit(response.location).path == "/login/"

    # Check for alerts
    alerts = unpack_alerts(app.cookies)
    assert len(alerts) == 2
    assert alerts == [
        {'kind': 'danger', 'message': 'Missing username field!'},
        {'kind': 'danger', 'message': 'Missing password field!'}
    ]

    # Clear EVERYTHING (including alerts)
    app.reset()

    # Use blank field names
    response = app.post('/login/', {'username': '', 'password': ''})
    assert response.status == "302 Found"
    assert urlsplit(response.location).path == "/login/"

    # Check for alerts
    alerts = unpack_alerts(app.cookies)
    assert len(alerts) == 2
    assert alerts == [
        {'kind': 'danger', 'message': 'username field cannot be blank!'},
        {'kind': 'danger', 'message': 'password field cannot be blank!'}
    ]
Example #3
0
def test_short_link_not_fount():
    test_app = Client(app)

    get_response = test_app.get('/fhwefwgeywg', expect_errors=True)
    assert get_response.status_int == 404

    test_app.reset()
Example #4
0
def test_webfinger():
    webapp = TestApp(app)

    username = "******"
    password = "******"
    domain = "oth.be"

    webapp.post("/auth/signup", {"username": username, "password": password})

    webfinger = webapp.get("/{0}/.well-known/webfinger".format(username))

    expected_webfinger = {
        "subject": "acct:{0}@{1}".format(username, domain),
        "links": [
            {
                "rel": "self",
                "type": "application/activity+json",
                "href": "https://{0}/u/{1}".format(domain, username),
            }
        ],
    }

    assert webfinger.status == "200 OK"
    assert webfinger.json == expected_webfinger

    webapp.reset()
Example #5
0
def injectionattack():
    app = TestApp(test.app)
    app.post('/login', {'username':'******','password':'******'})
    assert app.get('/admin').status == '200 OK'
    app.get('/logout')
    app.reset()
    assert app.get('/admin').status == '401 Unauthorized'
Example #6
0
class TestCase(unittest.TestCase):

    clean_collections = tuple()

    def setUp(self):
        settings = {
            'mongo_uri': MONGO_URI,
            'auth_tk_secret': '123456',
            'twitter_consumer_key': 'key',
            'twitter_consumer_secret': 'secret',
            'facebook_app_id': 'id',
            'facebook_app_secret': 'secret',
            'google_client_id': 'id',
            'google_client_secret': 'secret',
            'testing': 'True',
            'pyramid_mailer.prefix': 'mail_',
            'mail_default_sender': '*****@*****.**',
            'admin_emails': '[email protected] [email protected]',
            'public_url_root': 'http://localhost:6543/',
            }
        app = main({}, **settings)
        self.testapp = TestApp(app)
        self.db = app.registry.settings['db_conn']['test-yith-library']

    def tearDown(self):
        for col in self.clean_collections:
            self.db.drop_collection(col)

        self.testapp.reset()

    def set_user_cookie(self, user_id):
        request = TestRequest.blank('', {})
        request.registry = self.testapp.app.registry
        remember_headers = remember(request, user_id)
        cookie_value = remember_headers[0][1].split('"')[1]
        self.testapp.cookies['auth_tkt'] = cookie_value

    def add_to_session(self, data):
        queryUtility = self.testapp.app.registry.queryUtility
        session_factory = queryUtility(ISessionFactory)
        request = DummyRequest()
        session = session_factory(request)
        for key, value in data.items():
            session[key] = value
        session.persist()
        self.testapp.cookies['beaker.session.id'] = session._sess.id

    def get_session(self, response):
        queryUtility = self.testapp.app.registry.queryUtility
        session_factory = queryUtility(ISessionFactory)
        request = response.request

        if not hasattr(request, 'add_response_callback'):
            request.add_response_callback = lambda r: r

        if 'Set-Cookie' in response.headers:
            request.environ['HTTP_COOKIE'] = response.headers['Set-Cookie']

        return session_factory(request)
Example #7
0
def test_index():
    webapp = TestApp(app)
    response = webapp.get("/")

    assert response.status_code == 200
    assert response.json == {"message": "hello world"}

    webapp.reset()
Example #8
0
def test_functional_login_logout():
    app = TestApp(Bottle4)
    app.post('/login', {'user': '******', 'pass': '******'}) # log in and get a cookie
    assert app.get('/admin').status == '200 OK' # fetch a page successfully
    app.get('/logout') # log out
    app.reset() # drop the cookie
    # fetch the same page, unsuccessfully
    assert app.get('/admin').status == '401 Unauthorized'
Example #9
0
def test_root_redirect():
    webapp = TestApp(app)
    response = webapp.get("/")

    assert response.status_code == 302
    assert response.location == "https://dnscheck.now.sh"

    webapp.reset()
Example #10
0
def test_bad_request():
    test_app = Client(app)

    url = '//qwer%^%&%ty/123'
    save_response = test_app.post_json('/save/', {'url': url},
                                       expect_errors=True)
    assert save_response.status == '400 Bad Request'

    test_app.reset()
Example #11
0
def test_index():
    webapp = TestApp(app)
    response = webapp.post("/", dict(domain="jolvera.dev"))

    print("response", response)

    assert response.status_code == 200
    assert response.headers["Content-Type"] == "application/json"

    webapp.reset()
Example #12
0
def test_ok():
    webapp = TestApp(app)
    response = webapp.post("/", dict(domain="jolvera.dev",
                                     dns_server="1.1.1.1"))

    assert response.status_code == 200
    assert response.headers["Content-Type"] == "application/json"
    assert "data" in json.loads(response.body)

    webapp.reset()
Example #13
0
class TestCase(unittest.TestCase):

    db_uri = get_test_db_uri()

    def setUp(self):
        super(TestCase, self).setUp()

        self.db_context = sqlalchemy_setup(self.db_uri)

        settings = {
            'database_url': self.db_uri,
            'auth_tk_secret': '123456',
            'redis.sessions.secret': '123456',
            'redis.sessions.url': 'redis://127.0.0.1:6379/0',
            'twitter_consumer_key': 'key',
            'twitter_consumer_secret': 'secret',
            'facebook_app_id': 'id',
            'facebook_app_secret': 'secret',
            'google_client_id': 'id',
            'google_client_secret': 'secret',
            'liveconnect_client_id': 'id',
            'liveconnect_client_secret': 'secret',
            'paypal_user': '******',
            'paypal_password': '******',
            'paypal_signature':
            'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU',
            'testing': 'True',
            'pyramid_mailer.prefix': 'mail_',
            'mail_default_sender': '*****@*****.**',
            'admin_emails': '[email protected] [email protected]',
            'public_url_root': 'http://localhost:6543/',
            'webassets.debug': 'True',
        }
        app = main({}, **settings)
        self.testapp = TestApp(app)

        metadata.create_all()

    def tearDown(self):
        sqlalchemy_teardown(self.db_context)
        self.testapp.reset()
        super(TestCase, self).tearDown()

    def get_session(self, response):
        queryUtility = self.testapp.app.registry.queryUtility
        session_factory = queryUtility(ISessionFactory)
        request = response.request

        if not hasattr(request, 'add_response_callback'):
            request.add_response_callback = lambda r: r

        if 'Set-Cookie' in response.headers:
            request.environ['HTTP_COOKIE'] = response.headers['Set-Cookie']

        return session_factory(request)
Example #14
0
def test_functional_login_logout():
    app = TestApp(Bottle4)
    app.post('/login', {
        'user': '******',
        'pass': '******'
    })  # log in and get a cookie
    assert app.get('/admin').status == '200 OK'  # fetch a page successfully
    app.get('/logout')  # log out
    app.reset()  # drop the cookie
    # fetch the same page, unsuccessfully
    assert app.get('/admin').status == '401 Unauthorized'
Example #15
0
class TestCase(unittest.TestCase):

    db_uri = get_test_db_uri()

    def setUp(self):
        super(TestCase, self).setUp()

        self.db_context = sqlalchemy_setup(self.db_uri)

        settings = {
            'database_url': self.db_uri,
            'auth_tk_secret': '123456',
            'redis.sessions.secret': '123456',
            'redis.sessions.url': 'redis://127.0.0.1:6379/0',
            'twitter_consumer_key': 'key',
            'twitter_consumer_secret': 'secret',
            'facebook_app_id': 'id',
            'facebook_app_secret': 'secret',
            'google_client_id': 'id',
            'google_client_secret': 'secret',
            'liveconnect_client_id': 'id',
            'liveconnect_client_secret': 'secret',
            'paypal_user': '******',
            'paypal_password': '******',
            'paypal_signature': 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU',
            'testing': 'True',
            'pyramid_mailer.prefix': 'mail_',
            'mail_default_sender': '*****@*****.**',
            'admin_emails': '[email protected] [email protected]',
            'public_url_root': 'http://localhost:6543/',
            'webassets.debug': 'True',
        }
        app = main({}, **settings)
        self.testapp = TestApp(app)

        metadata.create_all()

    def tearDown(self):
        sqlalchemy_teardown(self.db_context)
        self.testapp.reset()
        super(TestCase, self).tearDown()

    def get_session(self, response):
        queryUtility = self.testapp.app.registry.queryUtility
        session_factory = queryUtility(ISessionFactory)
        request = response.request

        if not hasattr(request, 'add_response_callback'):
            request.add_response_callback = lambda r: r

        if 'Set-Cookie' in response.headers:
            request.environ['HTTP_COOKIE'] = response.headers['Set-Cookie']

        return session_factory(request)
Example #16
0
class TestCase(unittest.TestCase):

    db_uri = get_test_db_uri()

    def setUp(self):
        super(TestCase, self).setUp()

        self.db_context = sqlalchemy_setup(self.db_uri)

        settings = {
            "database_url": self.db_uri,
            "auth_tk_secret": "123456",
            "redis.sessions.secret": "123456",
            "redis.sessions.url": "redis://127.0.0.1:6379/0",
            "twitter_consumer_key": "key",
            "twitter_consumer_secret": "secret",
            "facebook_app_id": "id",
            "facebook_app_secret": "secret",
            "google_client_id": "id",
            "google_client_secret": "secret",
            "liveconnect_client_id": "id",
            "liveconnect_client_secret": "secret",
            "paypal_user": "******",
            "paypal_password": "******",
            "paypal_signature": "A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU",
            "testing": "True",
            "pyramid_mailer.prefix": "mail_",
            "mail_default_sender": "*****@*****.**",
            "admin_emails": "[email protected] [email protected]",
            "public_url_root": "http://localhost:6543/",
            "webassets.debug": "True",
        }
        app = main({}, **settings)
        self.testapp = TestApp(app)

        metadata.create_all()

    def tearDown(self):
        sqlalchemy_teardown(self.db_context)
        self.testapp.reset()
        super(TestCase, self).tearDown()

    def get_session(self, response):
        queryUtility = self.testapp.app.registry.queryUtility
        session_factory = queryUtility(ISessionFactory)
        request = response.request

        if not hasattr(request, "add_response_callback"):
            request.add_response_callback = lambda r: r

        if "Set-Cookie" in response.headers:
            request.environ["HTTP_COOKIE"] = response.headers["Set-Cookie"]

        return session_factory(request)
Example #17
0
class FunctionalTestCase(MongoTestCase):
    """TestCase with an embedded MongoDB temporary instance.

    Each test runs on a temporary instance of MongoDB. The instance will
    be listen in a random port between 40000 and 5000.

    A test can access the connection using the attribute `conn`.
    A test can access the port using the attribute `port`
    """

    def setUp(self):

        settings = copy.deepcopy(_SETTINGS)

        if getattr(self, 'settings', None) is None:
            self.settings = settings
        else:
            self.settings.update(settings)

        super(FunctionalTestCase, self).setUp(celery, get_attribute_manager)

        settings['mongo_uri'] = self.tmp_db.get_uri('eduid_actions_test')
        self.redis_instance = RedisTemporaryInstance.get_instance()
        self.settings['redis_host'] = 'localhost'
        self.settings['redis_port'] = self.redis_instance._port
        self.settings['redis_db'] = '0'

        app = main({}, **self.settings)

        self.actions_db = app.registry.settings['actions_db']
        self.actions_db._drop_whole_collection()

        self.testapp = TestApp(app)
        app = self.testapp.app
        app.registry.settings['action_plugins']['dummy'] = DummyActionPlugin1
        app.registry.settings['action_plugins']['dummy2'] = DummyActionPlugin1
        app.registry.settings['action_plugins']['dummy_2steps'] = DummyActionPlugin2

        def mock_verify_auth_token(*args, **kwargs):
            if args[1] == 'fail_verify':
                return False
            return True

        mock_config = {'new_callable': lambda: mock_verify_auth_token}
        self.patcher = patch.object(views, 'verify_auth_token', **mock_config)
        self.patcher.start()

    def tearDown(self):
        super(FunctionalTestCase, self).tearDown()
        self.actions_db._drop_whole_collection()
        self.testapp.reset()
        self.patcher.stop()
Example #18
0
def test_successful_redirect():
    test_app = Client(app)

    url = 'https://qwer.ty/123'
    save_response = test_app.post_json('/save/', {'url': url})
    assert save_response.status_int == 200
    code = save_response.json['code']

    get_response = test_app.get(f'/{code}')
    assert get_response.status_int == 301
    assert get_response.headers['Location'] == url

    test_app.reset()
Example #19
0
def test_signup():
    webapp = TestApp(app)

    username = "******"
    password = "******"

    response = webapp.post("/auth/signup", {"username": username, "password": password})

    assert response.status == "200 OK"
    assert response.json["username"] == username
    assert response.json["user_id"] == 1

    webapp.reset()
Example #20
0
def test_successful():
    test_app = Client(app)

    url = 'https://qwer.ty/123'
    save_response = test_app.post_json('/save/', {'url': url})
    assert save_response.status == '200 OK'
    code = save_response.json['code']

    get_response = test_app.post_json('/code/', {'code': code})
    assert get_response.status == '200 OK'
    assert get_response.json['url'] == url

    test_app.reset()
Example #21
0
class FunctionalTests(MongoTestCase):
    """Base TestCase for those tests that need a full environment setup"""

    def setUp(self):
        super(FunctionalTests, self).setUp(celery, get_attribute_manager, userdb_use_old_format=True)

        _settings = deepcopy(SETTINGS)
        _settings.update({
            'mongo_uri': self.tmp_db.get_uri('eduid_signup_test'),
            'mongo_uri_tou': self.tmp_db.get_uri('eduid_tou_test'),
            })
        self.settings.update(_settings)
        self.redis_instance = RedisTemporaryInstance.get_instance()
        self.settings['redis_host'] = 'localhost'
        self.settings['redis_port'] = self.redis_instance._port
        self.settings['redis_db'] = '0'

        try:
            app = main({}, **(self.settings))
            self.testapp = TestApp(app)
            self.signup_userdb = app.registry.settings['signup_db']
            self.toudb = app.registry.settings['mongodb_tou'].get_database()
        except MongoConnectionError:
            raise unittest.SkipTest("requires accessible MongoDB server")

    def tearDown(self):
        super(FunctionalTests, self).tearDown()
        self.signup_userdb._drop_whole_collection()
        self.amdb._drop_whole_collection()
        self.toudb.consent.drop()
        self.testapp.reset()

    def dummy_request(self, cookies={}):
        request = DummyRequest()
        request.context = DummyResource()
        request.signup_userdb = self.signup_userdb
        request.registry.settings = self.settings
        return request

    def add_to_session(self, data):
        queryUtility = self.testapp.app.registry.queryUtility
        session_factory = queryUtility(ISessionFactory)
        request = self.dummy_request()
        session = session_factory(request)
        for key, value in data.items():
            session[key] = value
        session.persist()
        session_key = self.settings['session.key']
        token = session._session.token
        self.testapp.cookies[session_key] = token
Example #22
0
class PezWebAppTestCase(FreshSchemaTestCase):

    def __init__(self, *args, **kwargs):
        super(PezWebAppTestCase, self).__init__(*args, **kwargs)
        self.app = TestApp(application)

    def tearDown(self):
        super(PezWebAppTestCase, self).tearDown()
        self.app.reset()

    @parameterized.expand(route_response_map)
    def test_smoke(self, uri, result):
        response = self.app.get(uri)
        self.assertEqual(response.status, HTTP_OK)
        self.assertEqual(response.json, result)

    def test_shall_fail_on_le_zero_v2(self):
        response = self.app.get(
            '/v2/forward?count=0',
            expect_errors=True
        )
        self.assertEqual(response.status, HTTP_BAD_REQUEST)

    def test_shall_fail_on_gt_max_count_v2(self):
        max_count = configuration.get('max_count')
        response = self.app.get(
            '/v2/forward?count={0}'.format(max_count + 1),
            expect_errors=True
        )
        self.assertEqual(response.status, HTTP_BAD_REQUEST)
    
    def test_shall_fail_with_404(self):
        response = self.app.get('/WRONG_BANANAS', expect_errors=True)
        self.assertEqual(response.status, HTTP_NOT_FOUND)

    def test_shall_return_help_on_options(self):
        response = self.app.options('/v2/forward')
        self.assertEqual(response.status, HTTP_OK)
        self.assertIn(u'description', response.json)
        self.assertIn(u'verbs', response.json)

    def test_shall_return_503_on_dead_db(self):
        with patch('sqlalchemy.orm.session.Session.execute') as mock_exec:
            mock_exec.side_effect = DBAPIError('Boom', 'mock', 'mock')
            response = self.app.get(
                '/v1/forward',
                expect_errors=True
            )
            self.assertEqual(response.status, HTTP_SERVICE_UNAVAILABLE)
Example #23
0
class TestCase(unittest.TestCase):

    def setUp(self):
        settings = {
            'mongo_uri': MONGO_URI,
            'auth_tk_secret': '123456',
            'twitter_consumer_key': 'key',
            'twitter_consumer_secret': 'secret',
            'facebook_app_id': 'id',
            'facebook_app_secret': 'secret',
            'google_client_id': 'id',
            'google_client_secret': 'secret',
            'liveconnect_client_id': 'id',
            'liveconnect_client_secret': 'secret',
            'paypal_user': '******',
            'paypal_password': '******',
            'paypal_signature': 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU',
            'testing': 'True',
            'pyramid_mailer.prefix': 'mail_',
            'mail_default_sender': '*****@*****.**',
            'admin_emails': '[email protected] [email protected]',
            'public_url_root': 'http://localhost:6543/',
            'webassets.debug': 'True',
        }
        app = main({}, **settings)
        self.testapp = TestApp(app)
        self.db = app.registry.settings['db_conn'][DB_NAME]

    def tearDown(self):
        clean_db(self.db)
        self.testapp.reset()

    def get_session(self, response):
        queryUtility = self.testapp.app.registry.queryUtility
        session_factory = queryUtility(ISessionFactory)
        request = response.request

        if not hasattr(request, 'add_response_callback'):
            request.add_response_callback = lambda r: r

        if 'Set-Cookie' in response.headers:
            request.environ['HTTP_COOKIE'] = response.headers['Set-Cookie']

        return session_factory(request)
Example #24
0
class BaseAppTest(unittest.TestCase):

    def setUp(self):
        unset_environment()
        settings = {
            'user_admin': '8c6976e5b5410415bde908bd4dee15dfb16'
                          '7a9c873fc4bb8a81f6f2ab448a918',
            'aws_bucket_name': 'bucket_example',
            'aws_access_key_id': '123123',
            'aws_secret_access_key': '123123123',
            'S3Wrapper': S3ConnectionMockup,
        }

        app = main({}, **settings)
        self.testapp = TestApp(app)

    def tearDown(self):
        unset_environment()
        self.testapp.reset()
Example #25
0
class FunctionalTests(unittest.TestCase):
    """
    this test is a functional test to check functionality of the whole app

    it also serves to get coverage for 'main'
    """
    def setUp(self):
        my_settings = {'sqlalchemy.url': 'sqlite://'}  # mock, not even used!?
        from sqlalchemy import engine_from_config
        engine = engine_from_config(my_settings)

        from c3sportal import main
        app = main({}, **my_settings)
        from webtest import TestApp
        self.testapp = TestApp(app)

    def tearDown(self):
        # maybe I need to check and remove globals here,
        # so the other tests are not compromised
        #del engine
        from c3sportal.models import DBSession
        DBSession.remove()

    def test_z_root(self):
        """load the front page, check string exists"""
        #print("this is test_z_root")
        res = self.testapp.get('/', status=200)
        self.failUnless('Creative Commons Collecting Society' in res.body)

    def test_lang_en(self):
        """load the front page, check english string exists"""
        res = self.testapp.get('/?_LOCALE_=en', status=200)
        self.failUnless('Artists' in res.body)

    def test_lang_de(self):
        """load the front page, check german string exists"""
        res = self.testapp.get('/?_LOCALE_=de', status=200)
        self.failUnless('Creative Commons Collecting Society' in res.body)
        self.failUnless('Verwertungsgesellschaft' in res.body)

    def test_no_cookies(self):
        """load the front page, check english string exists"""
        #print "will reset cookies"
        res = self.testapp.reset()
        res = self.testapp.get('/', status=200,
            headers={'Accept-Language': 'da, en-gb;q=0.8, en;q=0.7'})
        self.failUnless('Artists' in res.body)
Example #26
0
class EditMemberTests(unittest.TestCase):
    """
    these tests are functional tests to check functionality of the whole app
    (i.e. integration tests)
    they also serve to get coverage for 'main'
    """
    def setUp(self):
        """
        Setup test cases
        """
        self.config = testing.setUp()
        self.config.include('pyramid_mailer.testing')
        DBSession.close()
        DBSession.remove()
        my_settings = {
            'sqlalchemy.url': 'sqlite:///:memory:',
            'available_languages': 'da de en es fr',
            'c3smembership.dashboard_number': '30'
        }
        engine = engine_from_config(my_settings)
        DBSession.configure(bind=engine)
        Base.metadata.create_all(engine)

        # self._insert_members()

        with transaction.manager:
            # a group for accountants/staff
            accountants_group = Group(name=u"staff")
            DBSession.add(accountants_group)
            DBSession.flush()
            # staff personnel
            staffer1 = C3sStaff(
                login=u"rut",
                password=u"berries",
                email=u"*****@*****.**",
            )
            staffer1.groups = [accountants_group]
            DBSession.add(accountants_group)
            DBSession.add(staffer1)
            DBSession.flush()

        app = main({}, **my_settings)
        self.testapp = TestApp(app)

    def tearDown(self):
        """
        Tear down all test cases
        """
        DBSession.close()
        DBSession.remove()
        testing.tearDown()

    @staticmethod
    def __create_membership_applicant():
        """
        Create and return a membership applicant
        """
        member = None
        with transaction.manager:
            member = C3sMember(  # german
                firstname=u'SomeFirstnäme',
                lastname=u'Membership Applicant',
                email=u'*****@*****.**',
                address1=u"addr one",
                address2=u"addr two",
                postcode=u"12345",
                city=u"Footown Mäh",
                country=u"Foocountry",
                locale=u"DE",
                date_of_birth=date(1970, 1, 1),
                email_is_confirmed=False,
                email_confirm_code=u'ABCDEFGFOO',
                password=u'arandompassword',
                date_of_submission=date(2015, 1, 1),
                membership_type=u'normal',
                member_of_colsoc=True,
                name_of_colsoc=u"GEMA",
                num_shares=u'23',
            )
        return member

    @staticmethod
    def __create_accepted_member_full():
        """
        Creates and returns an accepted full member
        """
        member = None
        with transaction.manager:
            member = C3sMember(  # german
                firstname=u'SomeFirstnäme',
                lastname=u'Accepted Full Member',
                email=u'*****@*****.**',
                address1=u"addr one",
                address2=u"addr two",
                postcode=u"12345",
                city=u"Footown Mäh",
                country=u"Foocountry",
                locale=u"DE",
                date_of_birth=date(1970, 1, 1),
                email_is_confirmed=False,
                email_confirm_code=u'ABCDEFGFOO',
                password=u'arandompassword',
                date_of_submission=date(2014, 1, 1),
                membership_type=u'normal',
                member_of_colsoc=True,
                name_of_colsoc=u"GEMA",
                num_shares=u'23',
            )
            member.membership_accepted = True
            member.membership_date = date(2015, 1, 1)
        return member

    def test_edit_members(self):
        '''
        tests for the edit_member view
        '''
        # unauthorized access must be prevented
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/edit/1', status=403)
        self.failUnless('Access was denied to this resource' in res.body)

        self.__login()

        # no member in DB, so redirecting to dashboard
        res = self.testapp.get('/edit/1', status=302)
        self.__validate_dashboard_redirect(res)

        member = EditMemberTests.__create_membership_applicant()
        DBSession.add(member)
        DBSession.flush()
        # now there is a member in the DB

        # let's try invalid input
        res = self.testapp.get('/edit/foo', status=302)
        self.__validate_dashboard_redirect(res)

        # now try valid id
        res = self.__get_edit_member(member.id)

        # set the date correctly
        self.__validate_successful_edit(
            member.id, {
                'firstname': u'EinVörname',
                'lastname': u'EinNachname',
                'email': u'*****@*****.**',
                'address1': u'adressteil 1',
                'address2': u'adressteil 2',
                'postcode': u'12346',
                'city': u'die city',
                'country': u'FI',
                'membership_type': u'investing',
                'entity_type': u'legalentity',
                'other_colsoc': u'no',
                'name_of_colsoc': u'',
                'date_of_birth': '1999-12-30',
                'membership_date': '2013-09-24',
                'signature_received_date': '2013-09-24',
                'payment_received_date': '2013-09-24',
            }, [
                u'EinNachname',
                u'*****@*****.**',
                u'adressteil 1',
                u'adressteil 2',
                u'12346',
                u'die city',
                u'FI',
                u'investing',
            ])

        # edit again ... changing membership acceptance status
        self.__validate_successful_edit(member.id, {
            'membership_accepted': True,
        })

    def __validate_details_page(self, res):
        """
        Validate that the resource in res is the details page
        """
        self.assertTrue('<h1>Details for' in res.body)

    def __validate_successful_submit(self, res):
        """
        Submit the resource, validate that it was successful and return the
        resulting resource.
        """
        res = res.form.submit('submit', status=302)
        res = res.follow()
        self.__validate_details_page(res)
        return res

    def __validate_body_content(self, res, body_content_parts):
        """
        Validate that the body_content_parts occur within the resource's body.
        """
        if body_content_parts is not None:
            for body_content_part in body_content_parts:
                self.assertTrue(
                    body_content_part.decode('utf-8') in res.body.decode(
                        'utf-8'))

    @staticmethod
    def __validate_submit_error(res):
        """
        Submit the resource, validate that it was not successful and return
        the resulting resource
        """
        return res.form.submit('submit', status=200)

    @staticmethod
    def __set_form_properties(res, properties):
        """
        Set the properties of the form in the resource.
        """
        for key, value in properties.iteritems():
            res.form[key] = value

    def __validate_successful_edit(self,
                                   member_id,
                                   properties=None,
                                   body_content_parts=None):
        """
        Edit the member's properties, validate that it was successful,
        validate the body of the resulting resource and return it.
        """
        res = self.__get_edit_member(member_id)
        EditMemberTests.__set_form_properties(res, properties)
        res = self.__validate_successful_submit(res)
        self.__validate_body_content(res, body_content_parts)
        return res

    def __validate_abortive_edit(self,
                                 member_id,
                                 properties=None,
                                 body_content_parts=None):
        """
        Edit the member's properties, validate that it was not successful,
        validate the body of the resulting resource and return it.
        """
        res = self.__get_edit_member(member_id)
        EditMemberTests.__set_form_properties(res, properties)
        res = EditMemberTests.__validate_submit_error(res)
        self.__validate_body_content(res, body_content_parts)
        return res

    def __get_edit_member(self, member_id):
        """
        Get the edit page for the member and validate it's successful
        retrieval.
        """
        res = self.testapp.get('/edit/{0}'.format(member_id), status=200)
        self.failUnless('Mitglied bearbeiten' in res.body)
        return res

    def __login(self):
        """
        Log into the membership backend
        """
        res = self.testapp.get('/login', status=200)
        self.failUnless('login' in res.body)
        form = res.form
        form['login'] = '******'
        form['password'] = '******'
        res = form.submit('submit', status=302)
        res = res.follow()  # being redirected to dashboard_only
        self.__validate_dashboard(res)

    def __validate_dashboard_redirect(self, res):
        """
        Validate that res is redirecting to the dashboard
        """
        res = res.follow()  # being redirected to dashboard with parameters
        self.__validate_dashboard(res)

    def __validate_dashboard(self, res):
        """
        Validate that res is the dashboard
        """
        self.failUnless('Dashboard' in res.body)

    def test_membership_loss(self):
        '''
        Test the loss of membership.

        Test cases for:

        1 Editing non members

          1.1 Loss inputs must be hidden
          1.1 Hidden loss inputs should not make any problem and therefore
              submit without changes should work
          1.2 Try setting hidden values -> error

        2 Editing members

          2.1 Loss inputs must not be hidden

          2.2 Loss date and loss type must both be either set or unset

            2.2.1 Set only loss date -> error, set both
            2.2.2 Set only loss type -> error, set both
            2.2.3 Set neither loss date nor type -> success
            2.2.4 Set loss date and type to valid values -> success

          2.3 Loss date must be larger than acceptance date

            2.3.1 Set loss date prior to membership acceptance date -> error,
                  set date larger membership acceptance
            2.3.2 Set loss date after membership acceptance date -> success

          2.4 Loss date for resignation must be 31st of December

            2.4.1 Set loss type to resignation and loss date other than 31st
                  of December -> fail
            2.4.2 Set loss type to resignation and loss date to 31st but not
                  December -> fail
            2.4.3 Set loss type to resignation and loss date to December but
                  not 31st -> fail
            2.4.4 Set loss type to resignation and loss date to 31st of
                  December succeed

          2.5 Only natural persons can be set to loss type death

            2.5.1 Set loss type to death and entity type to legal entity ->
                  error
            2.5.2 Set loss type to death and entity type to natural person ->
                  success

          2.6 Only legal entites can be set to loss type winding-up

            2.6.1 Set loss type to winding-up and entity type to natural
                  person error
            2.6.2 Set loss type to winding-up and entity type to legal entity
                  -> success
        '''
        # setup
        res = self.testapp.reset()
        self.__login()
        member = EditMemberTests.__create_membership_applicant()
        DBSession.add(member)
        DBSession.flush()

        # 1 Editing non members
        res = self.__get_edit_member(member.id)
        self.assertFalse(res.form['membership_accepted'].checked)

        # 1.1 Loss inputs must be hidden
        res = self.__get_edit_member(member.id)
        self.assertTrue(
            type(res.form['membership_loss_date']) == webtest.forms.Hidden)
        self.assertTrue(res.form['membership_loss_date'].value == '')
        self.assertTrue(
            type(res.form['membership_loss_type']) == webtest.forms.Hidden)
        self.assertTrue(res.form['membership_loss_type'].value == '')

        # 1.2 Hidden loss inputs should not make any problem and therefore
        #     submit without changes should work
        res = self.__get_edit_member(member.id)
        self.__validate_successful_submit(res)

        # 1.3 Try setting hidden values -> error
        self.__validate_abortive_edit(
            member.id, {
                'membership_loss_date': date.today(),
                'membership_loss_type': u'resignation',
            },
            [u'Please note: There were errors, please check the form below.'])

        # 2 Editing members
        member = EditMemberTests.__create_accepted_member_full()
        DBSession.add(member)
        DBSession.flush()
        res = self.__get_edit_member(member.id)
        # make sure default values are valid
        self.__validate_successful_submit(res)

        # 2.1 Loss inputs must not be hidden
        res = self.__get_edit_member(member.id)
        self.assertTrue(res.form['membership_accepted'].checked)
        self.assertTrue(
            type(res.form['membership_loss_date']) == webtest.forms.Text)
        self.assertTrue(res.form['membership_loss_date'].value == '')
        self.assertTrue(
            type(res.form['membership_loss_type']) == webtest.forms.Select)
        self.assertTrue(res.form['membership_loss_type'].value == '')

        # 2.2.1 Set only loss date -> error, set both
        self.__validate_abortive_edit(
            member.id, {
                'membership_loss_date': date(2016, 12, 31),
            }, [
                'Please note: There were errors, please check the form '
                'below.',
                'Date and type of membership loss must be set both or none.',
            ])

        # 2.2.2 Set only loss type -> error, set both
        self.__validate_abortive_edit(member.id, {
            'membership_loss_type': 'resignation',
        }, [
            'Please note: There were errors, please check the form '
            'below.',
            'Date and type of membership loss must be set both or none.',
        ])

        # 2.2.3 Set neither loss date nor type -> success
        self.__validate_successful_edit(member.id, {
            'membership_loss_type': '',
            'membership_loss_date': '',
        })

        # 2.2.4 Set loss date and type to valid values -> success
        self.__validate_successful_edit(
            member.id, {
                'membership_loss_type': 'resignation',
                'membership_loss_date': date(2016, 12, 31),
            })

        # 2.3 Loss date must be larger than acceptance date

        # 2.3.1 Set loss date prior to membership acceptance date -> error,
        #       set date larger membership acceptance
        self.__validate_abortive_edit(
            member.id, {
                'membership_loss_date':
                (member.membership_date - timedelta(days=1)),
                'membership_loss_type':
                'resignation',
            }, [
                'Please note: There were errors, please check the form '
                'below.',
                'Date membership loss must be larger than membership '
                'acceptance date.',
            ])

        # 2.3.2 Set loss date after membership acceptance date -> success
        self.__validate_successful_edit(
            member.id, {
                'membership_loss_date': date(2016, 12, 31),
                'membership_loss_type': 'resignation',
            })

        # 2.4 Loss date for resignation must be 31st of December

        # 2.4.1 Set loss type to resignation and loss date other than 31st
        #       of December -> fail
        self.__validate_abortive_edit(
            member.id, {
                'membership_loss_date': date(2016, 5, 28),
                'membership_loss_type': 'resignation',
            }, [
                'Please note: There were errors, please check the form '
                'below.',
                'Resignations are only allowed to the 31st of December of a '
                'year.',
            ])

        # 2.4.2 Set loss type to resignation and loss date to 31st but not
        #       December -> fail
        self.__validate_abortive_edit(
            member.id, {
                'membership_loss_date': date(2016, 10, 31),
                'membership_loss_type': 'resignation',
            }, [
                'Please note: There were errors, please check the form '
                'below.',
                'Resignations are only allowed to the 31st of December of a '
                'year.',
            ])

        # 2.4.3 Set loss type to resignation and loss date to December but
        #       not 31st -> fail
        self.__validate_abortive_edit(
            member.id, {
                'membership_loss_date': date(2016, 12, 30),
                'membership_loss_type': 'resignation',
            }, [
                u'Resignations are only allowed to the 31st of December of a '
                'year.'
            ])

        # 2.4.4 Set loss type to resignation and loss date to 31st of
        #       December succeed
        self.__validate_successful_edit(
            member.id, {
                'membership_loss_date': date(2016, 12, 31),
                'membership_loss_type': 'resignation',
            })

        # 2.5 Only natural persons can be set to loss type death

        # 2.5.1 Set loss type to death and entity type to legal entity ->
        #       error
        self.__validate_abortive_edit(
            member.id, {
                'entity_type': 'legalentity',
                'membership_loss_date': date(2016, 3, 25),
                'membership_loss_type': 'death',
            }, [
                u'The membership loss type \'death\' is only allowed for natural '
                u'person members and not for legal entity members.'
            ])

        # 2.5.2 Set loss type to death and entity type to natural person ->
        #       success
        self.__validate_successful_edit(
            member.id, {
                'entity_type': 'person',
                'membership_loss_date': date(2016, 3, 25),
                'membership_loss_type': 'death',
            })

        # 2.6 Only legal entites can be set to loss type winding-up

        # 2.6.1 Set loss type to winding-up and entity type to natural
        #       person error
        self.__validate_abortive_edit(
            member.id, {
                'entity_type': 'person',
                'membership_loss_date': date(2016, 3, 25),
                'membership_loss_type': 'winding-up',
            }, [
                u'The membership loss type \'winding-up\' is only allowed for '
                u'legal entity members and not for natural person members.'
            ])

        # 2.6.2 Set loss type to winding-up and entity type to legal entity
        #       -> success
        self.__validate_successful_edit(
            member.id, {
                'entity_type': 'legalentity',
                'membership_loss_date': date(2016, 3, 25),
                'membership_loss_type': 'winding-up',
            })
class FunctionalTests(unittest.TestCase):
    """
    these tests are functional tests to check functionality of the whole app
    (i.e. integration tests)
    they also serve to get coverage for 'main'
    """
    def setUp(self):
        self.config = testing.setUp()
        self.config.include('pyramid_mailer.testing')
        try:
            DBSession.close()
            DBSession.remove()
            # print("removed old DBSession ==============================")
        except:
            # print("no DBSession to remove =============================")
            pass
        # try:
        #    os.remove('test_webtest_functional.db')
        #    #print "deleted old test database"
        # except:
        #    pass
        #    #print "never mind"

        my_settings = {
            # 'sqlalchemy.url': 'sqlite:///test_webtest_functional.db',
            'sqlalchemy.url': 'sqlite:///:memory:',
            'available_languages': 'da de en es fr',
            'c3smembership.mailaddr': '*****@*****.**',
            'testing.mail_to_console': 'false'}
        engine = engine_from_config(my_settings)
        DBSession.configure(bind=engine)
        self.session = DBSession  # ()

        Base.metadata.create_all(engine)
        # dummy database entries for testing
        with transaction.manager:
            member1 = C3sMember(  # german
                firstname=u'SomeFirstnäme',
                lastname=u'SomeLastnäme',
                email=u'*****@*****.**',
                address1=u"addr one",
                address2=u"addr two",
                postcode=u"12345",
                city=u"Footown Mäh",
                country=u"Foocountry",
                locale=u"DE",
                date_of_birth=date.today(),
                email_is_confirmed=False,
                email_confirm_code=u'ABCDEFGFOO',
                password=u'arandompassword',
                date_of_submission=date.today(),
                membership_type=u'normal',
                member_of_colsoc=True,
                name_of_colsoc=u"GEMA",
                num_shares=u'23',
            )
            DBSession.add(member1)
            DBSession.flush()

        from c3smembership import main
        app = main({}, **my_settings)

        from webtest import TestApp
        self.testapp = TestApp(app)

    def tearDown(self):
        self.session.close()
        self.session.remove()
        # os.remove('test_webtest_functional.db')

    def test_base_template(self):
        """load the front page, check string exists"""
        res = self.testapp.get('/', status=200)
        self.failUnless('Cultural Commons Collecting Society' in res.body)
        self.failUnless(
            'Copyright 2014, C3S SCE' in res.body)

    # def test_faq_template(self):
    #     """load the FAQ page, check string exists"""
    #     res = self.testapp.get('/faq', status=200)
    #     self.failUnless('FAQ' in res.body)
    #     self.failUnless(
    #         'Copyright 2013, OpenMusicContest.org e.V.' in res.body)

    def test_lang_en_LOCALE(self):
        """load the front page, forced to english (default pyramid way),
        check english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/?_LOCALE_=en', status=200)
        self.failUnless(
            'Application for Membership of ' in res.body)

    def test_lang_en(self):
        """load the front page, set to english (w/ pretty query string),
        check english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/?en', status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        self.failUnless(
            'Application for Membership of ' in res1.body)

# so let's test the app's obedience to the language requested by the browser
# i.e. will it respond to http header Accept-Language?

    # def test_accept_language_header_da(self):
    #     """check the http 'Accept-Language' header obedience: danish
    #     load the front page, check danish string exists"""
    #     res = self.testapp.reset()  # delete cookie
    #     res = self.testapp.get('/', status=200,
    #                            headers={
    #             'Accept-Language': 'da'})
    #     #print(res.body) #  if you want to see the pages source
    #     self.failUnless(
    #         '<input type="hidden" name="_LOCALE_" value="da"' in res.body)

    def test_accept_language_header_de_DE(self):
        """check the http 'Accept-Language' header obedience: german
        load the front page, check german string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get(
            '/', status=200,
            headers={
                'Accept-Language': 'de-DE'})
        # print(res.body) #  if you want to see the pages source
        self.failUnless(
            'Mitgliedschaftsantrag für die' in res.body)
        self.failUnless(
            '<input type="hidden" name="locale" value="de"' in res.body)

    def test_accept_language_header_en(self):
        """check the http 'Accept-Language' header obedience: english
        load the front page, check english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get(
            '/', status=200,
            headers={
                'Accept-Language': 'en'})
        # print(res.body) #  if you want to see the pages source
        self.failUnless(
            "I want to become"
            in res.body)

    # def test_accept_language_header_es(self):
    #     """check the http 'Accept-Language' header obedience: spanish
    #     load the front page, check spanish string exists"""
    #     res = self.testapp.reset()  # delete cookie
    #     res = self.testapp.get('/', status=200,
    #                            headers={
    #             'Accept-Language': 'es'})
    #     #print(res.body) #  if you want to see the pages source
    #     self.failUnless(
    #         'Luego de enviar el siguiente formulario,' in res.body)

    # def test_accept_language_header_fr(self):
    #     """check the http 'Accept-Language' header obedience: french
    #     load the front page, check french string exists"""
    #     res = self.testapp.reset()  # delete cookie
    #     res = self.testapp.get('/', status=200,
    #                            headers={
    #             'Accept-Language': 'fr'})
    #     #print(res.body) #  if you want to see the pages source
    #     self.failUnless(
    #         'En envoyant un courriel à [email protected] vous pouvez' in res.body)

    def test_no_cookies(self):
        """load the front page, check default english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get(
            '/', status=200,
            headers={
                'Accept-Language': 'af, cn'})  # ask for missing languages
        # print res.body
        self.failUnless('Application for Membership' in res.body)

#############################################################################
# check for validation stuff

    def test_form_lang_en_non_validating(self):
        """load the join form, check english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/?_LOCALE_=en', status=200)
        form = res.form
        # print(form.fields)
        # print(form.fields.values())
        form['firstname'] = 'John'
        # form['address2'] = 'some address part'
        res2 = form.submit('submit')
        self.failUnless(
            'There was a problem with your submission' in res2.body)

    def test_form_lang_de(self):
        """load the join form, check german string exists"""
        res = self.testapp.get('/?de', status=302)
        # print(res)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res2 = res.follow()
        # print(res2)
        # test for german translation of template text (lingua_xml)
        self.failUnless(
            'Mitgliedschaftsantrag für die' in res2.body)
        # test for german translation of form field label (lingua_python)
        self.failUnless('Vorname' in res2.body)

    def test_form_lang_LOCALE_de(self):
        """load the join form in german, check german string exists
        this time forcing german locale the pyramid way
        """
        res = self.testapp.get('/?_LOCALE_=de', status=200)
        # test for german translation of template text (lingua_xml)
        self.failUnless(
            'Mitgliedschaftsantrag für die' in res.body)
        # test for german translation of form field label (lingua_python)
        self.failUnless('Vorname' in res.body)

###########################################################################
# checking the success page that sends out email with verification link

    def test_check_email_en_wo_context(self):
        """try to access the 'check_email' page and be redirected
        check english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/check_email?en', status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        # print(res1)
        self.failUnless(
            'Application for Membership of ' in str(
                res1.body),
            'expected string was not found in web UI')

###########################################################################
# checking the view that gets code and mail, asks for a password
    def test_verify_email_en_w_bad_code(self):
        """load the page in english,
        be redirected to the form (data is missing)
        check english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/verify/[email protected]/ABCD-----', status=200)
        self.failUnless(
            'Password' in res.body)
        form = res.form
        form['password'] = '******'
        res2 = form.submit('submit')
        self.failUnless(
            'Password' in res2.body)

    def test_verify_email_en_w_good_code(self):
        """
        """
        res = self.testapp.reset()
        res = self.testapp.get('/verify/[email protected]/ABCDEFGFOO', status=200)
        self.failUnless(
            'Password' in res.body)
        form = res.form
        form['password'] = '******'
        res2 = form.submit('submit')
        # print res2.body
        self.failUnless(
            'C3S_SCE_AFM_SomeFirstn_meSomeLastn_me.pdf' in res2.body)
        # 'Your Email has been confirmed, Firstnäme Lastname!' in res.body)
        # res2 = self.testapp.get(
        #    '/C3S_SCE_AFM_Firstn_meLastname.pdf', status=200)
        # self.failUnless(len(res2.body) > 70000)

    def test_success_wo_data_en(self):
        """load the success page in english (via query_string),
        check for redirection and english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/success?en', status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        # print(res1)
        self.failUnless(  # check text on page redirected to
            'Please fill out the form' in str(
                res1.body),
            'expected string was not found in web UI')

    def test_success_pdf_wo_data_en(self):
        """
        try to load a pdf (which must fail because the form was not used)
        check for redirection to the form and test string exists
        """
        res = self.testapp.reset()
        res = self.testapp.get(
            '/C3S_SCE_AFM_ThefirstnameThelastname.pdf',
            status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        # print(res1)
        self.failUnless(  # check text on page redirected to
            'Please fill out the form' in str(
                res1.body),
            'expected string was not found in web UI')

    def test_email_confirmation(self):
        """
        test email confirmation form and PDF download
        with a known login/dataset
        """
        res = self.testapp.reset()
        res = self.testapp.get('/verify/[email protected]/ABCDEFGFOO', status=200)
        # print(res.body)
        form = res.form
        form['password'] = '******'
        res2 = form.submit('submit')
        # print res2.body
        self.failUnless("Load your PDF..." in res2.body)
        self.failUnless(
            "/C3S_SCE_AFM_SomeFirstn_meSomeLastn_me.pdf" in res2.body)
        # load the PDF, check size
        res3 = self.testapp.get(
            '/C3S_SCE_AFM_SomeFirstn_meSomeLastn_me.pdf',
            status=200
        )
        # print("length of result: %s") % len(res3.body)
        # print("body result: %s") % (res3.body)  # ouch, PDF content!
        self.failUnless(80000 < len(res3.body) < 220000)  # check pdf size

    def test_email_confirmation_wrong_mail(self):
        """
        test email confirmation with a wrong email
        """
        res = self.testapp.reset()
        res = self.testapp.get(
            '/verify/[email protected]/ABCDEFGHIJ', status=200)
        # print(res.body)
        self.failUnless("Please enter your password." in res.body)
        # XXX this test shows nothing interesting

    def test_email_confirmation_wrong_code(self):
        """
        test email confirmation with a wrong code
        """
        res = self.testapp.reset()
        res = self.testapp.get('/verify/[email protected]/WRONGCODE', status=200)
        # print(res.body)
        self.failUnless("Please enter your password." in res.body)

    def test_success_check_email(self):
        """
        test "check email" success page with wrong data:
        this should redirect to the form.
        """
        res = self.testapp.reset()
        res = self.testapp.get('/check_email', status=302)

        res2 = res.follow()
        self.failUnless("Please fill out the form" in res2.body)
Example #28
0
class GoogleViewTests(unittest.TestCase):

    def setUp(self):
        self.callback_counter = CallbackCounter()
        settings = {
            'google_client_id': '123',
            'google_client_secret': 's3cr3t',
            'google_callback': self.callback_counter,
            'google_scope': 'perm1 perm2',
        }
        app = main({}, **settings)
        self.testapp = TestApp(app)

    def tearDown(self):
        self.testapp.reset()

    def test_google_login(self):
        res = self.testapp.get('/google/login', {
            'next_url': 'https://localhost/foo/bar',
        })
        self.assertEqual(res.status, '302 Found')
        url = urlparse.urlparse(res.location)
        self.assertEqual(url.netloc, 'accounts.google.com')
        self.assertEqual(url.path, '/o/oauth2/auth')
        query = urlparse.parse_qs(url.query)
        self.assertEqual(sorted(query.keys()), [
            'client_id', 'redirect_uri', 'response_type', 'scope', 'state',
        ])
        self.assertEqual(query['scope'], ['perm1 perm2'])
        self.assertEqual(query['redirect_uri'],
                         ['http://localhost/google/callback'])
        self.assertEqual(query['client_id'], ['123'])

    def test_google_callback(self):
        # call the login to fill the session
        res = self.testapp.get('/google/login', {
            'next_url': 'https://localhost/foo/bar',
        })
        self.assertEqual(res.status, '302 Found')
        url = urlparse.urlparse(res.location)
        query = urlparse.parse_qs(url.query)
        state = query['state'][0]

        with patch('requests.post') as fake_post:
            fake_post.return_value.status_code = 200
            fake_post.return_value.json = lambda: {
                'access_token': '1234',
            }
            with patch('requests.get') as fake_get:
                fake_get.return_value.status_code = 200
                fake_get.return_value.json = lambda: {
                    'id': '789',
                    'name': 'John Doe',
                    'given_name': 'John',
                    'family_name': 'Doe',
                    'email': '*****@*****.**',
                }

                res = self.testapp.get('/google/callback', {
                    'code': '1234',
                    'state': state,
                })
                self.assertEqual(res.status, '200 OK')
                self.assertEqual(res.text, 'Register success!')

                self.assertEqual(self.callback_counter.counter, 1)
                call_args = self.callback_counter.calls[0]['args']
                self.assertTrue(isinstance(call_args[0], Request))
                self.assertEqual(call_args[1], '789')
                self.assertEqual(call_args[2], {
                    'email': '*****@*****.**',
                    'first_name': 'John',
                    'last_name': 'Doe',
                    'screen_name': 'John Doe',
                })
                call_kwargs = self.callback_counter.calls[0]['kwargs']
                self.assertEqual(call_kwargs, {})
Example #29
0
class FunctionalTests(unittest.TestCase):
    """
    these tests are functional tests to check functionality of the whole app
    (i.e. integration tests)
    they also serve to get coverage for 'main'
    """
    def setUp(self):
        my_settings = {'sqlalchemy.url': 'sqlite://',
                       'available_languages': 'da de en es fr',
                       'c3smembership.mailaddr': '*****@*****.**'}
        #my_other_settings = {'sqlalchemy.url': 'sqlite:///test.db',
        #                     'available_languages': 'da de en es fr'}
                        # mock, not even used!?
        #from sqlalchemy import engine_from_config
        #engine = engine_from_config(my_settings)
        from c3smembership.scripts.initialize_db import init
        init()

        from c3smembership import main
        #try:
        app = main({}, **my_settings)
        #except:
        #    app = main({}, **my_other_settings)
        #    pass
        from webtest import TestApp
        self.testapp = TestApp(app)

    def tearDown(self):
        # maybe I need to check and remove globals here,
        # so the other tests are not compromised
        #del engine
        from c3smembership.models import DBSession
        #DBSession.remove()
        DBSession.close()
        #TODO: delete database
        DBSession.remove()
        #import pdb; pdb.set_trace()

    def test_base_template(self):
        """load the front page, check string exists"""
        res = self.testapp.get('/', status=200)
        self.failUnless('Cultural Commons Collecting Society' in res.body)
        self.failUnless(
            'Copyright 2013, C3S SCE' in res.body)

    # def test_faq_template(self):
    #     """load the FAQ page, check string exists"""
    #     res = self.testapp.get('/faq', status=200)
    #     self.failUnless('FAQ' in res.body)
    #     self.failUnless(
    #         'Copyright 2013, OpenMusicContest.org e.V.' in res.body)

    def test_lang_en_LOCALE(self):
        """load the front page, forced to english (default pyramid way),
        check english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/?_LOCALE_=en', status=200)
        self.failUnless(
            'Application for Membership of ' in res.body)

    def test_lang_en(self):
        """load the front page, set to english (w/ pretty query string),
        check english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/?en', status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        self.failUnless(
            'Application for Membership of ' in res1.body)

# so let's test the app's obedience to the language requested by the browser
# i.e. will it respond to http header Accept-Language?

    # def test_accept_language_header_da(self):
    #     """check the http 'Accept-Language' header obedience: danish
    #     load the front page, check danish string exists"""
    #     res = self.testapp.reset()  # delete cookie
    #     res = self.testapp.get('/', status=200,
    #                            headers={
    #             'Accept-Language': 'da'})
    #     #print(res.body) #  if you want to see the pages source
    #     self.failUnless(
    #         '<input type="hidden" name="_LOCALE_" value="da"' in res.body)

    def test_accept_language_header_de_DE(self):
        """check the http 'Accept-Language' header obedience: german
        load the front page, check german string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get(
            '/', status=200,
            headers={
                'Accept-Language': 'de-DE'})
        #print(res.body) #  if you want to see the pages source
        self.failUnless(
            'Mitgliedschaftsantrag für die' in res.body)
        self.failUnless(
            '<input type="hidden" name="_LOCALE_" value="de"' in res.body)

    def test_accept_language_header_en(self):
        """check the http 'Accept-Language' header obedience: english
        load the front page, check english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get(
            '/', status=200,
            headers={
                'Accept-Language': 'en'})
        #print(res.body) #  if you want to see the pages source
        self.failUnless(
            "I want to become"
            in res.body)

    # def test_accept_language_header_es(self):
    #     """check the http 'Accept-Language' header obedience: spanish
    #     load the front page, check spanish string exists"""
    #     res = self.testapp.reset()  # delete cookie
    #     res = self.testapp.get('/', status=200,
    #                            headers={
    #             'Accept-Language': 'es'})
    #     #print(res.body) #  if you want to see the pages source
    #     self.failUnless(
    #         'Luego de enviar el siguiente formulario,' in res.body)

    # def test_accept_language_header_fr(self):
    #     """check the http 'Accept-Language' header obedience: french
    #     load the front page, check french string exists"""
    #     res = self.testapp.reset()  # delete cookie
    #     res = self.testapp.get('/', status=200,
    #                            headers={
    #             'Accept-Language': 'fr'})
    #     #print(res.body) #  if you want to see the pages source
    #     self.failUnless(
    #         'En envoyant un courriel à [email protected] vous pouvez' in res.body)

    def test_no_cookies(self):
        """load the front page, check default english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get(
            '/', status=200,
            headers={
                'Accept-Language': 'af, cn'})  # ask for missing languages
        #print res.body
        self.failUnless('Application for Membership' in res.body)

#############################################################################
# check for validation stuff

    def test_form_lang_en_non_validating(self):
        """load the join form, check english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/?_LOCALE_=en', status=200)
        form = res.form
        #print(form.fields)
        #print(form.fields.values())
        form['firstname'] = 'John'
        #form['address2'] = 'some address part'
        res2 = form.submit('submit')
        self.failUnless(
            'There was a problem with your submission' in res2.body)

    def test_form_lang_de(self):
        """load the join form, check german string exists"""
        res = self.testapp.get('/?de', status=302)
        #print(res)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res2 = res.follow()
        #print(res2)
        # test for german translation of template text (lingua_xml)
        self.failUnless(
            'Mitgliedschaftsantrag für die' in res2.body)
        # test for german translation of form field label (lingua_python)
        self.failUnless('Vorname' in res2.body)

    def test_form_lang_LOCALE_de(self):
        """load the join form in german, check german string exists
        this time forcing german locale the pyramid way
        """
        res = self.testapp.get('/?_LOCALE_=de', status=200)
        # test for german translation of template text (lingua_xml)
        self.failUnless(
            'Mitgliedschaftsantrag für die' in res.body)
        # test for german translation of form field label (lingua_python)
        self.failUnless('Vorname' in res.body)

###########################################################################
# checking the success page that sends out email with verification link

    def test_check_email_en_wo_context(self):
        """try to access the 'check_email' page and be redirected
        check english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/check_email?en', status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        #print(res1)
        self.failUnless(
            'Application for Membership of ' in str(
                res1.body),
            'expected string was not found in web UI')

###########################################################################
# checking the view that gets code and mail, asks for a password
    def test_verify_email_en_w_bad_code(self):
        """load the page in english,
        be redirected to the form (data is missing)
        check english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/verify/[email protected]/ABCD-----', status=200)
        self.failUnless(
            'Password' in res.body)
        form = res.form
        form['password'] = '******'
        res2 = form.submit('submit')
        self.failUnless(
            'Password' in res2.body)

    def test_verify_email_en_w_good_code(self):
        """
        check english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/verify/[email protected]/ABCDEFGHIJ', status=200)
        self.failUnless(
            'Password' in res.body)
        form = res.form
        form['password'] = '******'
        res2 = form.submit('submit')
        self.failUnless('C3S_SCE_AFM_Firstn_meLastname.pdf' in res2.body)
#        import pdb
#        pdb.set_trace()
            #'Your Email has been confirmed, Firstnäme Lastname!' in res.body)
        #res2 = self.testapp.get(
        #    '/C3S_SCE_AFM_Firstn_meLastname.pdf', status=200)
        #self.failUnless(len(res2.body) > 70000)

###########################################################################
# checking the disclaimer

    # def test_disclaimer_en(self):
    #     """load the disclaimer in english (via query_string),
    #     check english string exists"""
    #     res = self.testapp.reset()
    #     res = self.testapp.get('/disclaimer?en', status=302)
    #     self.failUnless('The resource was found at' in res.body)
    #     # we are being redirected...
    #     res1 = res.follow()
    #     self.failUnless(
    #         'you may order your data to be deleted at any time' in str(
    #             res1.body),
    #         'expected string was not found in web UI')

    # def test_disclaimer_de(self):
    #     """load the disclaimer in german (via query_string),
    #     check german string exists"""
    #     res = self.testapp.reset()
    #     res = self.testapp.get('/disclaimer?de', status=302)
    #     self.failUnless('The resource was found at' in res.body)
    #     # we are being redirected...
    #     res1 = res.follow()
    #     self.failUnless(
    #         'Datenschutzerkl' in str(
    #             res1.body),
    #         'expected string was not found in web UI')

    # def test_disclaimer_LOCALE_en(self):
    #     """load the disclaimer in english, check english string exists"""
    #     res = self.testapp.reset()
    #     res = self.testapp.get('/disclaimer?_LOCALE_=en', status=200)
    #     self.failUnless(
    #         'you may order your data to be deleted at any time' in str(
    #             res.body),
    #         'expected string was not found in web UI')

    # def test_disclaimer_LOCALE_de(self):
    #     """load the disclaimer in german, check german string exists"""
    #     res = self.testapp.reset()
    #     res = self.testapp.get('/disclaimer?_LOCALE_=de', status=200)
    #     self.failUnless(
    #         'Datenschutzerkl' in str(
    #             res.body),
    #         'expected string was not found in web UI')

    def test_success_wo_data_en(self):
        """load the success page in english (via query_string),
        check for redirection and english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/success?en', status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        #print(res1)
        self.failUnless(  # check text on page redirected to
            'Please fill out the form' in str(
                res1.body),
            'expected string was not found in web UI')

    def test_success_pdf_wo_data_en(self):
        """
        try to load a pdf (which must fail because the form was not used)
        check for redirection to the form and test string exists
        """
        res = self.testapp.reset()
        res = self.testapp.get(
            '/C3S_SCE_AFM_ThefirstnameThelastname.pdf',
            status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        #print(res1)
        self.failUnless(  # check text on page redirected to
            'Please fill out the form' in str(
                res1.body),
            'expected string was not found in web UI')

    # def test_success_w_data(self):
    #     """
    #     load the form, fill the form, (in one go via POST request)
    #     check for redirection, push button to send verification mail,
    #     check for 'mail was sent' message
    #     """
    #     res = self.testapp.reset()
    #     res = self.testapp.get('/', status=200)
    #     form = res.form
    #     print '*'*80
    #     print '*'*80
    #     print '*'*80
    #     print form.fields
    #     res = self.testapp.post(
    #         '/',  # where the form is served
    #         {
    #             'submit': True,
    #             'firstname': 'TheFirstName',
    #             'lastname': 'TheLastName',
    #             'date_of_birth': '1987-06-05',
    #             'address1': 'addr one',
    #             'address2': 'addr two',
    #             'postcode': '98765 xyz',
    #             'city': 'Devilstown',
    #             'country': 'AF',
    #             'email': '*****@*****.**',
    #             'password': '******',
    #             'num_shares': '42',
    #             '_LOCALE_': 'en',
    #             #'activity': set(
    #             #    [
    #             #        u'composer',
    #             #        #u'dj'
    #             #    ]
    #             #),
    #             'invest_member': 'yes',
    #             'member_of_colsoc': 'yes',
    #             'name_of_colsoc': 'schmoo',
    #             #'opt_band': 'yes band',
    #             #'opt_URL': 'http://yes.url',
    #             #'noticed_dataProtection': 'yes'
    #             'num_shares': '23',
    #         },
    #         #status=302,  # expect redirection to success page
    #         status=200,  # expect redirection to success page
    #     )

    #     print(res.body)
    #     self.failUnless('The resource was found at' in res.body)
    #     # we are being redirected...
    #     res2 = res.follow()
    #     self.failUnless('Success' in res2.body)
    #     #print("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv")
    #     #print res2.body
    #     #print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
    #     self.failUnless('TheFirstName' in res2.body)
    #     self.failUnless('TheLastName' in res2.body)
    #     self.failUnless('1987-06-05' in res2.body)
    #     self.failUnless('addr one' in res2.body)
    #     self.failUnless('addr two' in res2.body)
    #     self.failUnless('Devilstown' in res2.body)
    #     self.failUnless('*****@*****.**' in res2.body)
    #     self.failUnless('schmoo' in res2.body)

    #     # now check for the "mail was sent" confirmation
    #     res3 = self.testapp.post(
    #         '/check_email',
    #         {
    #             'submit': True,
    #             'value': "send mail"
    #         }
    #     )
    #     #print(res3)
    #     self.failUnless(
    #         'An email was sent, TheFirstName TheLastName!' in res3.body)

#     def test_success_and_reedit(self):
#         """
#         submit form, check success, re-edit: are the values pre-filled?
#         """
#         res = self.testapp.reset()
#         res = self.testapp.get('/', status=200)
#         form = res.form
#         form['firstname'] = 'TheFirstNäme'
#         form['lastname'] = 'TheLastNäme'
#         form['address1'] = 'addr one'
#         form['address2'] = 'addr two'
#         res2 = form.submit('submit')
#         print res2.body
# #                'submit': True,
# #                'date_of_birth': '1987-06-05',
# #                'address2': 'addr two',
# #                'postcode': '98765 xyz',
# #                'city': 'Devilstöwn',
# #                'email': '*****@*****.**',
# #                'num_shares': '23',
# #                '_LOCALE_': 'en',
# #                #'activity': set(
#                 #    [
#                 #        'composer',
#                 #        #u'dj'
#                 #    ]
#                 #),
# #                'country': 'AF',
# #                'membership_type': 'investing',
# #                'member_of_colsoc': 'yes',
# #                'name_of_colsoc': 'schmoö',
#                 #'opt_band': 'yes bänd',
#                 #'opt_URL': 'http://yes.url',
#                 #'noticed_dataProtection': 'yes'

# #            },
# #            status=302,  # expect redirection to success page
# #        )

    #    print(res.body)
    #     self.failUnless('The resource was found at' in res.body)
    #     # we are being redirected...
    #     res2 = res.follow()
    #     self.failUnless('Success' in res2.body)
    #     #print("success page: \n%s") % res2.body
    #     #self.failUnless(u'TheFirstNäme' in (res2.body))

    #     # go back to the form and check the pre-filled values
    #     res3 = self.testapp.get('/')
    #     #print(res3.body)
    #     #print("edit form: \n%s") % res3.body
    #     self.failUnless('TheFirstNäme' in res3.body)
    #     form = res3.form
    #     self.failUnless(form['firstname'].value == u'TheFirstNäme')

    def test_email_confirmation(self):
        """
        test email confirmation
        """
        res = self.testapp.reset()
        res = self.testapp.get('/verify/[email protected]/ABCDEFGHIJ', status=200)
        # print(res.body)
        form = res.form
        form['password'] = '******'
        res2 = form.submit('submit')
        #print res2.body
        self.failUnless("Load your PDF..." in res2.body)
        res3 = self.testapp.get(
            '/C3S_SCE_AFM_ThefirstnameThelastname.pdf',
            status=200
        )
        #print("length of result: %s") % len(res2.body)
        self.failUnless(80000 < len(res3.body) < 100000)  # check pdf size

    def test_email_confirmation_wrong_mail(self):
        """
        test email confirmation with a wrong email
        """
        res = self.testapp.reset()
        res = self.testapp.get(
            '/verify/[email protected]/ABCDEFGHIJ', status=200)
        #print(res.body)
        self.failUnless("Please enter your password." in res.body)

    def test_email_confirmation_wrong_code(self):
        """
        test email confirmation with a wrong code
        """
        res = self.testapp.reset()
        res = self.testapp.get('/verify/[email protected]/WRONGCODE', status=200)
        #print(res.body)
        self.failUnless("Please enter your password." in res.body)

    def test_success_check_email(self):
        """
        test "check email" success page with wrong data:
        this should redirect to the form.
        """
        res = self.testapp.reset()
        res = self.testapp.get('/check_email', status=302)

        res2 = res.follow()
        self.failUnless("Please fill out the form" in res2.body)
Example #30
0
class TestCookie(unittest.TestCase):
    """Tests API functions associated with VM actions.
       Note that all tests are in-process, we don't actually start a http server.
    """
    def setUp(self):
        """Launch pserve using webtest with test settings"""
        self.appconf = get_app(test_ini)
        self.app = TestApp(self.appconf)

        # Punch in new administrator account with direct server call

        server.choose_engine("SQLite")  # Sets global var "engine" - in the
        # case of SQLite this is a fresh RAM
        # DB each time.

        # Create new user. This will implicitly generate the tables.
        id1 = server.create_user(None, "testuser", "testuser", "testuser")
        server.touch_to_add_user_group("testuser", "users")
        server.touch_to_add_password(id1, "testpass")

        id2 = server.create_user(None, "administrator", "administrator",
                                 "administrator")
        server.touch_to_add_user_group("administrator", "administrators")
        server.touch_to_add_password(id2, "adminpass")

    """Confirm lack of any cookie without authentication."""

    def test_no_cookie_without_auth(self):
        """ No cookie should be set when calling an endpoint that
            does not require authorization.
        """
        self.app.authorization = None
        r = self.app.get("/", status=200)

        self.assertEqual(r.headers.get('Set-Cookie', 'empty'), 'empty')

        #Equivalently:
        self.assertEqual(self.app.cookies, {})

    def test_no_username(self):
        """ The DB API should return a 401 unauthorised if I submit a request
            with no username / password provided.
            Similar to test_unauthenticated_api but with an extra check that no
            cookie is set.
        """
        self.app.authorization = None
        r = self.app.get("/users/testuser", status=401)

        self.assertEqual(r.headers.get('Set-Cookie', 'empty'), 'empty')

    def test_invalid_username(self):
        """ The DB API should return a 401 unauthorised if I submit a bad
            username / password combination.  And again no cookie
        """
        self.app.authorization = ('Basic', ('invaliduser', 'invalidpassword'))

        r = self.app.get("/users/testuser", status=401)
        self.assertEqual(r.headers.get('Set-Cookie', 'empty'), 'empty')

    def test_valid_cookie(self):
        """Confirm cookie returned upon authentication.
        The DB API should return a cookie if I submit a correct username
        and password. The cookie should allow me to make a successful request
        using it alone. """

        self.app.authorization = ('Basic', ('testuser', 'testpass'))
        r = self.app.get("/users/testuser", status=200)
        cookie = self.app.cookies['auth_tkt']

        self.app.reset()  # clear cookie cache
        self.app.authorization = None  # remove auth credentials
        self.app.set_cookie("auth_tkt", cookie)  # set cookie to old value

        r = self.app.get("/users/testuser", status=200)

        #Furthermore, we should still get the same cookie on the second call
        self.assertEqual(self.app.cookies['auth_tkt'], cookie)

    def test_broken_cookie(self):
        """ The DB API should refuse to service a request with a broken cookie. """

        self.app.authorization = ('Basic', ('testuser', 'testpass'))
        r = self.app.get("/users/testuser", status=200)
        cookie = 'I am a fish'

        self.app.reset()  # clear cookie cache
        self.app.authorization = None  # remove auth credentials
        self.app.set_cookie("auth_tkt", cookie)  # set cookie to bad value
        r = self.app.get("/users/testuser", status=401, expect_errors=False)

    def test_invalid_cookie(self):
        """ The DB API should refuse to service a request with an invalid cookie. """

        self.app.authorization = ('Basic', ('testuser', 'testpass'))
        r = self.app.get("/users/testuser", status=200)
        cookie = '94514a32a7923939584470e8fc01f9b073bc3c8171542c8b7deb0' + \
                 'dd459400945553f9ed9dGVzdHVzZXI%3D!userid_type:b64unicode'

        self.app.reset()  # clear cookie cache
        self.app.authorization = None  # remove auth credentials
        self.app.set_cookie("auth_tkt", cookie)  # set cookie to bad value
        r = self.app.get("/users/testuser", status=401, expect_errors=False)

    def test_valid_authtkt(self):
        """Setting a cookie in the request is problematic for AJAX, so
           test that we can feed the token back in the auth_tkt header instead.
        """

        self.app.authorization = ('Basic', ('testuser', 'testpass'))
        r = self.app.get("/users/testuser", status=200)
        cookie = self.app.cookies['auth_tkt']

        self.app.reset()  # clear cookie cache
        self.app.authorization = None  # remove auth credentials

        r = self.app.get("/users/testuser",
                         headers={'auth_tkt': cookie},
                         status=200)

        #Furthermore, we should still get the same cookie on the second call
        self.assertEqual(self.app.cookies['auth_tkt'], cookie)

    def test_broken_cookie(self):
        """ The DB API should refuse to service a request with a broken auth_tkt.
            And should return a 408 error (I think - we don't want a 401 as it causes the
            browser to prompt for a username/password which will then be remembered for
            basic auth)
        """

        self.app.authorization = ('Basic', ('testuser', 'testpass'))
        r = self.app.get("/users/testuser", status=200)
        cookie = 'I am a fish'

        self.app.reset()  # clear cookie cache
        self.app.authorization = None  # remove auth credentials

        r = self.app.get("/users/testuser",
                         headers={'auth_tkt': cookie},
                         status=408,
                         expect_errors=False)
Example #31
0
class SharesTests(unittest.TestCase):
    """
    these tests are functional tests to check functionality of the whole app
    (i.e. integration tests)
    they also serve to get coverage for 'main'
    """
    def setUp(self):
        self.config = testing.setUp()
        self.config.include('pyramid_mailer.testing')
        try:
            DBSession.close()
            DBSession.remove()
            # print "closed and removed DBSession"
        except:
            pass
            # print "no session to close"
        my_settings = {
            'sqlalchemy.url': 'sqlite:///:memory:',
            'available_languages': 'da de en es fr',
            'c3smembership.dashboard_number': '30'}
        engine = engine_from_config(my_settings)
        DBSession.configure(bind=engine)
        Base.metadata.create_all(engine)

        with transaction.manager:
            # a group for accountants/staff
            accountants_group = Group(name=u"staff")
            try:
                DBSession.add(accountants_group)
                DBSession.flush()
                # print("adding group staff")
            except:
                # print("could not add group staff.")
                pass
            # staff personnel
            staffer1 = Staff(
                login=u"rut",
                password=u"berries",
                email=u"*****@*****.**",
            )
            staffer1.groups = [accountants_group]
            try:
                DBSession.add(accountants_group)
                DBSession.add(staffer1)
                DBSession.flush()
            except:
                # print("it borked! (rut)")
                pass

        from c3smembership import main
        app = main({}, **my_settings)
        from webtest import TestApp
        self.testapp = TestApp(app)

    def tearDown(self):
        DBSession.close()
        DBSession.remove()
        testing.tearDown()

    def make_member_with_shares(self):
        with transaction.manager:
            member1 = C3sMember(  # german
                firstname=u'SomeFirstnäme',
                lastname=u'SomeLastnäme',
                email=u'*****@*****.**',
                address1=u"addr one",
                address2=u"addr two",
                postcode=u"12345",
                city=u"Footown Mäh",
                country=u"Foocountry",
                locale=u"DE",
                date_of_birth=date.today(),
                email_is_confirmed=False,
                email_confirm_code=u'ABCDEFGFOO',
                password=u'arandompassword',
                date_of_submission=date.today(),
                membership_type=u'normal',
                member_of_colsoc=True,
                name_of_colsoc=u"GEMA",
                num_shares=u'23',
            )
            shares1 = Shares(
                number=2,
                date_of_acquisition=date.today(),
                reference_code=u'ABCDEFGH',
                signature_received=True,
                signature_received_date=date(2014, 6, 7),
                payment_received=True,
                payment_received_date=date(2014, 6, 8),
                signature_confirmed=True,
                signature_confirmed_date=date(2014, 6, 8),
                payment_confirmed=True,
                payment_confirmed_date=date(2014, 6, 9),
                accountant_comment=u'no comment',
            )
            member1.shares = [shares1]
            shares2 = Shares(
                number=23,
                date_of_acquisition=date.today(),
                reference_code=u'IJKLMNO',
                signature_received=True,
                signature_received_date=date(2014, 1, 7),
                payment_received=True,
                payment_received_date=date(2014, 1, 8),
                signature_confirmed=True,
                signature_confirmed_date=date(2014, 1, 8),
                payment_confirmed=True,
                payment_confirmed_date=date(2014, 1, 9),
                accountant_comment=u'not connected',
            )

        DBSession.add(member1)
        DBSession.add(shares1)
        DBSession.add(shares2)

    def make_member_with_shares2(self):
        with transaction.manager:
            member1 = C3sMember(  # german
                firstname=u'SomeFirstnäme',
                lastname=u'SomeLastnäme',
                email=u'*****@*****.**',
                address1=u"addr one",
                address2=u"addr two",
                postcode=u"12345",
                city=u"Footown Mäh",
                country=u"Foocountry",
                locale=u"DE",
                date_of_birth=date.today(),
                email_is_confirmed=False,
                email_confirm_code=u'ABCDEFGFOO',
                password=u'arandompassword',
                date_of_submission=date.today(),
                membership_type=u'normal',
                member_of_colsoc=True,
                name_of_colsoc=u"GEMA",
                num_shares=u'23',
            )
            shares1 = Shares(
                number=2,
                date_of_acquisition=date.today(),
                reference_code=u'ABCDEFGH',
                signature_received=True,
                signature_received_date=date(2014, 6, 7),
                payment_received=True,
                payment_received_date=date(2014, 6, 8),
                signature_confirmed=True,
                signature_confirmed_date=date(2014, 6, 8),
                payment_confirmed=True,
                payment_confirmed_date=date(2014, 6, 9),
                accountant_comment=u'no comment',
            )
            member1.shares = [shares1]
        DBSession.add(member1)
        DBSession.add(shares1)

    def make_unconnected_shares(self):
        with transaction.manager:
            shares2 = Shares(
                number=23,
                date_of_acquisition=date.today(),
                reference_code=u'IJKLMNO',
                signature_received=True,
                signature_received_date=date(2014, 1, 7),
                payment_received=True,
                payment_received_date=date(2014, 1, 8),
                signature_confirmed=True,
                signature_confirmed_date=date(2014, 1, 8),
                payment_confirmed=True,
                payment_confirmed_date=date(2014, 1, 9),
                accountant_comment=u'not connected',
            )
        DBSession.add(shares2)

    def test_shares_detail(self):
        '''
        tests for the shares_detail view
        '''
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/shares_edit/1', status=403)
        assert('Access was denied to this resource' in res.body)
        res = self.testapp.get('/login', status=200)
        self.failUnless('login' in res.body)
        # try valid user
        form = res.form
        form['login'] = '******'
        form['password'] = '******'
        res2 = form.submit('submit', status=302)
        # # being logged in ...
        # print('>'*20)
        # print(res3.body)
        # print('<'*20)
        res3 = res2.follow()  # being redirected to dashboard with parameters
        self.failUnless(
            'Acquisition of membership' in res3.body)
        # now look at a shares package
        res = self.testapp.get('/shares_detail/1', status=302)
        res2 = res.follow()
        # we were redirected to the menberships list
        # because the shares package did not exist
        self.assertTrue(
            'This shares id was not found in the database!' in res2.body)
        self.assertTrue('Membership tools' in res2.body)

        self.make_member_with_shares()

        # now look at a shares package
        res = self.testapp.get('/shares_detail/1', status=200)
        self.assertTrue('<h1>Details for Shares #1</h1>' in res.body)
        self.assertTrue('SomeFirstnäme SomeLastnäme' in res.body)
        self.assertTrue('ABCDEFGH' in res.body)

    def test_shares_edit(self):
        '''
        tests for the shares_edit view
        '''
        # unauthorized access must be prevented
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/shares_edit/1', status=403)
        assert('Access was denied to this resource' in res.body)
        res = self.testapp.get('/login', status=200)
        self.failUnless('login' in res.body)
        # try valid user
        form = res.form
        form['login'] = u'rut'
        form['password'] = u'berries'
        res2 = form.submit('submit', status=302)
        # # being logged in ...
        res3 = res2.follow()  # being redirected to dashboard with parameters
        self.failUnless('Acquisition of membership' in res3.body)

        # no member in DB, so redirecting to dashboard
        res = self.testapp.get('/shares_edit/1', status=302)
        res2 = res.follow()

        self.make_member_with_shares()

        # now there is a member with shares in the DB
        #
        # lets try invalid input
        res = self.testapp.get('/shares_edit/foo', status=302)
        res2 = res.follow()
        self.failUnless('Members' in res2.body)

        # now try valid id
        res = self.testapp.get('/shares_edit/1', status=200)
        self.failUnless('Edit Details for Shares' in res.body)

        # now we change details, really editing that member
        form = res.form

        if DEBUG:
            print "form.fields: {}".format(form.fields)

        self.assertTrue('2' in form['number'].value)
        self.assertTrue(datetime.today().strftime(
            '%Y-%m-%d') in form['date_of_acquisition'].value)
        # print(form['date_of_acquisition'].value)
        form['number'] = u'3'
        form['date_of_acquisition'] = u'2015-01-02'

        # try to submit now. this must fail,
        # because the date of birth is wrong
        # ... and other dates are missing
        res2 = form.submit('submit', status=200)

        # check data in DB
        _m1 = C3sMember.get_by_id(1)
        self.assertTrue(_m1.shares[0].number is 3)
        self.assertTrue(str(
            _m1.shares[0].date_of_acquisition) in str(datetime(2015, 1, 2)))

    def test_shares_delete(self):
        '''
        tests for the shares_delete view
        '''
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/shares_edit/1', status=403)
        assert('Access was denied to this resource' in res.body)
        res = self.testapp.get('/login', status=200)
        self.failUnless('login' in res.body)
        # try valid user
        form = res.form
        form['login'] = '******'
        form['password'] = '******'
        res2 = form.submit('submit', status=302)
        # # being logged in ...
        # print('>'*20)
        # print(res3.body)
        # print('<'*20)
        res3 = res2.follow()  # being redirected to dashboard with parameters
        self.failUnless(
            'Acquisition of membership' in res3.body)

        self.make_member_with_shares()

        # now look at a shares package
        res = self.testapp.get('/shares_detail/1', status=200)
        self.assertTrue('<h1>Details for Shares #1</h1>' in res.body)
        self.assertTrue('SomeFirstnäme SomeLastnäme' in res.body)
        self.assertTrue('ABCDEFGH' in res.body)

        # try to delete a non-existing package
        res = self.testapp.get('/shares_delete/123', status=302)
        res2 = res.follow()
        self.assertTrue(
            'This shares package 123 was not found in the DB.' in res2.body)

        # try to delete an existing package
        res = self.testapp.get('/shares_delete/1', status=302)
        res2 = res.follow()
        self.assertTrue(
            'This shares package 1 still has a member owning it.' in res2.body)
        res = self.testapp.get('/delete/1', status=302)
        res2 = res.follow()

        res = self.testapp.get('/shares_detail/1', status=200)
        self.assertTrue('<h1>Details for Shares #1</h1>' in res.body)
        # self.assertTrue('1: Not Found' in res.body)
        self.assertTrue('ABCDEFGH' in res.body)
Example #32
0
class ClientAgentTest(unittest.TestCase):
    """Test class for all Client Agent tests.

    This handles the creation of an in-process Client Agent server to run
    tests against.

    """

    def setUp(self):
        test_cfg = os.path.join(os.path.dirname(os.path.realpath(__file__)), "tests.conf")
        self.config = Config(cfgfile=test_cfg)
        # self.appdir = env.topdir
        self.app = TestApp(make_app(self.config))
        self.app.reset()

    def tearDown(self):
        pass

    def set_credentials(self, username=None, password=None):
        self.username = username
        if password is None:
            jws = JWS()
            password = jws.sign(
                header={"alg": "NONE", "typ": "IDAssertion"},
                payload={"exp": int(time.time() + 300), "moz-vep-id": username},
            )
        self.password = password

    def create_queue(self):
        res = self.app.post("/%s/new_queue" % VERSION, extra_environ={"test_session.uid": self.username})
        assert res.status_int == 200
        return json.loads(res.body)

    def create_subscription(self, token):
        res = self.app.post(
            "/%s/new_subscription" % VERSION,
            json.dumps({"token": token}),
            content_type="application/json",
            extra_environ={"test_session.uid": self.username},
        )
        assert res.status_int == 200

    def remove_subscription(self, token, success_response=200):
        res = self.app.post(
            "/%s/remove_subscription" % VERSION,
            json.dumps({"token": token}),
            status=success_response,
            content_type="application/json",
            extra_environ={"test_session.uid": self.username},
        )
        assert res.status_int == success_response

    def send_broadcast(self, message=None):
        if message is None:
            message = "'this is a broadcast message'"
        self.app.post(
            "/%s/broadcast" % (VERSION),
            message,
            content_type="application/json",
            extra_environ={"test_session.uid": self.username},
        )
        # TODO: Figure out a way to extract messages from queues in tests
        # For now we assume all is well if "200 OK" returned

    def test_create_queue(self):
        self.set_credentials(self.config.get("tests.user", "*****@*****.**"), self.config.get("tests.password", None))
        queue_info = self.create_queue()
        assert "queue_id" in queue_info
        assert "host" in queue_info
        assert "port" in queue_info
        assert len(queue_info["queue_id"]) > 0
        assert len(queue_info["host"]) > 0
        assert queue_info["port"]

    def test_subscriptions(self):
        self.set_credentials(self.config.get("tests.user", "*****@*****.**"), self.config.get("tests.password", None))
        token = "TEST123"

        # Can't delete subscription if it doesn't exist
        try:
            self.remove_subscription(token, success_response=400)
        except Exception, e:
            print str(e)
        # Normal create and delete
        self.create_subscription(token)
        self.remove_subscription(token)

        # Can't delete subscription if already deleted
        self.remove_subscription(token, success_response=400)
Example #33
0
class FunctionalTests(unittest.TestCase):
    """
    these tests are functional tests to check functionality of the whole app
    (i.e. integration tests)
    they also serve to get coverage for 'main'
    """
    def setUp(self):
        self.config = testing.setUp()
        self.config.include('pyramid_mailer.testing')
        #DBSession.remove()
        #DBSession = _initTestingDB()
        my_settings = {
            'sqlalchemy.url': 'sqlite:///test_webtest.db',  # the database
            'available_languages': 'de en',
            'speedfunding.dashboard_number': 20,
        }
        from speedfunding import main
        #try:
        app = main({}, **my_settings)

        from sqlalchemy import create_engine
        engine = create_engine('sqlite:///test_webtest.db')
        DBSession.configure(bind=engine)
        from speedfunding.models import Base
        Base.metadata.create_all(engine)
        _populate_testDB()
        #import pdb; pdb.set_trace()
        #except:
        #    app = main({}, **my_other_settings)
        #    pass
        from webtest import TestApp
        self.testapp = TestApp(app)

    def tearDown(self):
        # maybe I need to check and remove globals here,
        # so the other tests are not compromised
        #del engine
#        from c3smembership.models import DBSession
#        DBSession.close()
#        DBSession.remove()
        DBSession.remove()
        testing.tearDown()
        os.remove('test_webtest.db')

    def test_speedfunding(self):
        """
        load the landing page and form, do stuff
        """
        res = self.testapp.get('/', status=200)
        self.failUnless('FlashFund' in res.body)
        self.failUnless('Donate' in res.body)

    def test_donate_view(self):
        """
        load the donation page and form, do stuff
        """
        res = self.testapp.get('/donate', status=200)
        print res.body
        self.failUnless('FlashFund' in res.body)
        self.failUnless('The Donation' in res.body)
        self.failUnless('Please tell us your email address' in res.body)

    def test_login_and_dashboard(self):
        """
        load the login page and log in, test the dashboard
        """
        # login
        res2 = self.testapp.get('/login', status=200)
        # try valid user & invalid password
        form = res2.form
        form['login'] = '******'
        form['password'] = '******'
        res3 = form.submit('submit', status=200)
        # try valid user, valid password
        form = res2.form
        form['login'] = '******'
        form['password'] = '******'
        res3 = form.submit('submit', status=302)
        #
        # being logged in ...
        res4 = res3.follow()
        #print(res4.body)
        self.failUnless(
            'Dashboard' in res4.body)
        # now that we are logged in,
        # the login view should redirect us to the dashboard
        res5 = self.testapp.get('/login', status=302)
        # so yes: that was a redirect
        res6 = res5.follow()
        #print(res4.body)
        self.failUnless(
            'Dashboard' in res6.body)
        # choose number of applications shown
        res6a = self.testapp.get(
            '/dashboard/0',
            status=200,
            extra_environ={
                'num_display': '30',
            }
        )
#         #print('res6a:')
#         #print res6a
        self.failUnless('<h1>Dashboard</h1>' in res6a.body)
        res6a = self.testapp.get(
            '/dashboard/1', status=200,
        )
#         #print('res6a:')
#         #print res6a
#         self.failUnless('<h1>Dashboard</h1>' in res6a.body)
#         # try an invalid page number
#         res6b = self.testapp.get(
#             '/dashboard/foo',
#             status=200,
#         )
#         #print('res6b:')
#         #print res6b.body
#         self.failUnless(
#             '<p>Number of data sets:' in res6b.body)
#         #
#         # change the number oof items to show
#         form = res6b.form
#         form['num_to_show'] = "42"  # post a number: OK
#         resX = form.submit('submit', status=200)

#         form = resX.form
#         form['num_to_show'] = "mooo"  # post a string: no good
#         resY = form.submit('submit', status=200)

#         #import pdb; pdb.set_trace()
#         # member details
#         #
#         # now look at some members details with nonexistant id
#         res7 = self.testapp.get('/detail/5000', status=302)
#         res7a = res7.follow()
#         self.failUnless('Dashboard' in res7a.body)

#         # now look at some members details
#         res7 = self.testapp.get('/detail/1', status=200)
#         self.failUnless('Firstnäme' in res7.body)
#         self.failUnless(
#             "<td>signature received?</td><td>No</td>" in res7.body)
#         self.failUnless(
#             "<td>payment received?</td><td>No</td>" in res7.body)

#         form = res7.form
#         form['signature_received'] = True
#         form['payment_received'] = True
#         res8 = form.submit('submit')
#         #print(res8.body)
#         self.failUnless(
#             "<td>signature received?</td><td>True</td>" in res8.body)
#         self.failUnless(
#             "<td>payment received?</td><td>True</td>" in res8.body)
#         ################################################################
#         # now we change some of the details: switch signature status
#         # via http-request rather than the form
#         resD1 = self.testapp.get('/detail/1', status=200)  # look at details
#         self.assertTrue(
#             "<td>signature received?</td><td>True</td>" in resD1.body)
#         self.assertTrue(
#             "<td>payment received?</td><td>True</td>" in resD1.body)
#         #
#         # switch signature
#         resD2a = self.testapp.get('/switch_sig/1', status=302)  # # # # # OFF
#         resD2b = resD2a.follow()  # we are taken to the dashboard
#         resD2b = self.testapp.get('/detail/1', status=200)
#         self.assertTrue(
#             "<td>signature received?</td><td>No</td>" in resD2b.body)
#         resD2a = self.testapp.get('/switch_sig/1', status=302)  # # # # # ON
#         resD2b = resD2a.follow()  # we are taken to the dashboard
#         resD2b = self.testapp.get('/detail/1', status=200)
#         self.assertTrue(
#             "<td>signature received?</td><td>True</td>" in resD2b.body)
#         #
#         # switch payment
#         resD3a = self.testapp.get('/switch_pay/1', status=302)  # # # # OFF
#         resD3b = resD3a.follow()  # we are taken to the dashboard
#         resD3b = self.testapp.get('/detail/1', status=200)
#         self.assertTrue(
#             "<td>payment received?</td><td>No</td>" in resD3b.body)
#         resD3a = self.testapp.get('/switch_pay/1', status=302)  # # # # ON
#         resD3b = resD3a.follow()  # we are taken to the dashboard
#         resD3b = self.testapp.get('/detail/1', status=200)
#         self.assertTrue(
#             "<td>payment received?</td><td>True</td>" in resD3b.body)
#         #
#         ####################################################################
#         # delete an entry
#         resDel1 = self.testapp.get('/dashboard/0', status=200)
# #        self.failUnless(
# #            '      <p>Number of data sets: 1</p>' in resDel1.body.splitlines())
#         resDel2 = self.testapp.get('/delete/1', status=302)
#         resDel3 = resDel2.follow()
# #        self.failUnless(
# #            '      <p>Number of data sets: 0</p>' in resDel3.body.splitlines())

#         # finally log out ##################################################
#         res9 = self.testapp.get('/logout', status=302)  # redirects to login
#         res10 = res9.follow()
#         self.failUnless('login' in res10.body)
#         # def test_detail_wrong_id(self):
    def test_base_template(self):
        """load the front page, check string exists"""
        res = self.testapp.get('/', status=200)
        self.failUnless('C3S SCE' in res.body)
        self.failUnless(
            'Copyright 2013, C3S SCE' in res.body)

    # def test_faq_template(self):
    #     """load the FAQ page, check string exists"""
    #     res = self.testapp.get('/faq', status=200)
    #     self.failUnless('FAQ' in res.body)
    #     self.failUnless(
    #         'Copyright 2013, OpenMusicContest.org e.V.' in res.body)

    def test_lang_en_LOCALE(self):
        """load the front page, forced to english (default pyramid way),
        check english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/?_LOCALE_=en', status=200)
        self.failUnless(
            'FlashFunding!' in res.body)

    def test_lang_en(self):
        """load the front page, set to english (w/ pretty query string),
        check english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/?en', status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        self.failUnless(
            'FlashFunding!' in res1.body)

# so let's test the app's obedience to the language requested by the browser
# i.e. will it respond to http header Accept-Language?

    # def test_accept_language_header_da(self):
    #     """check the http 'Accept-Language' header obedience: danish
    #     load the front page, check danish string exists"""
    #     res = self.testapp.reset()  # delete cookie
    #     res = self.testapp.get('/', status=200,
    #                            headers={
    #             'Accept-Language': 'da'})
    #     #print(res.body) #  if you want to see the pages source
    #     self.failUnless(
    #         '<input type="hidden" name="_LOCALE_" value="da"' in res.body)

    def test_accept_language_header_de_DE(self):
        """check the http 'Accept-Language' header obedience: german
        load the front page, check german string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get(
            '/', status=200,
            headers={
                'Accept-Language': 'de-DE'})
        #print(res.body) #  if you want to see the pages source
        self.failUnless(
            'FlashFunding' in res.body)

    def test_accept_language_header_en(self):
        """check the http 'Accept-Language' header obedience: english
        load the front page, check english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get(
            '/', status=200,
            headers={
                'Accept-Language': 'en'})
        #print(res.body) #  if you want to see the pages source
        self.failUnless(
            "I want to become"
            in res.body)

    # def test_accept_language_header_es(self):
    #     """check the http 'Accept-Language' header obedience: spanish
    #     load the front page, check spanish string exists"""
    #     res = self.testapp.reset()  # delete cookie
    #     res = self.testapp.get('/', status=200,
    #                            headers={
    #             'Accept-Language': 'es'})
    #     #print(res.body) #  if you want to see the pages source
    #     self.failUnless(
    #         'Luego de enviar el siguiente formulario,' in res.body)

    # def test_accept_language_header_fr(self):
    #     """check the http 'Accept-Language' header obedience: french
    #     load the front page, check french string exists"""
    #     res = self.testapp.reset()  # delete cookie
    #     res = self.testapp.get('/', status=200,
    #                            headers={
    #             'Accept-Language': 'fr'})
    #     #print(res.body) #  if you want to see the pages source
    #     self.failUnless(
    #         'En envoyant un courriel à [email protected] vous pouvez' in res.body)

    def test_no_cookies(self):
        """load the front page, check default english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get(
            '/', status=200,
            headers={
                'Accept-Language': 'af, cn'})  # ask for missing languages
        #print res.body
        self.failUnless('FlashFunding!' in res.body)

#############################################################################
# check for validation stuff

#    def test_form_lang_en_non_validating(self):
#        """load the join form, check english string exists"""
#        res = self.testapp.reset()
#        res = self.testapp.get('/?_LOCALE_=en', status=200)
#        form = res.form
#        #print(form.fields)
#        #print(form.fields.values())
#        #form['deformField1'] = 'paypal'
#        #form['address2'] = 'some address part'
#        res2 = form.submit('donate')
#        self.failUnless(
#            'There was a problem with your submission' in res2.body)

    def test_form_lang_de(self):
        """load the form, check german string exists"""
        res = self.testapp.get('/?de', status=302)
        #print(res)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res2 = res.follow()
        #print(res2)
        # test for german translation of template text (lingua_xml)
        self.failUnless(
            'FlashFunding!' in res2.body)
        # test for german translation of form field label (lingua_python)
        self.failUnless('PayPal' in res2.body)

    def test_form_lang_LOCALE_de(self):
        """load the form in german, check german string exists
        this time forcing german locale the pyramid way
        """
        res = self.testapp.get('/?_LOCALE_=de', status=200)
        # test for german translation of template text (lingua_xml)
        self.failUnless(
            'FlashFunding!' in res.body)
        # test for german translation of form field label (lingua_python)
        self.failUnless('PayPal' in res.body)
Example #34
0
class FacebookViewTests(unittest.TestCase):
    def setUp(self):
        self.callback_counter = CallbackCounter()
        settings = {
            'facebook_app_id': '123',
            'facebook_app_secret': 's3cr3t',
            'facebook_callback': self.callback_counter,
            'facebook_scope': 'perm1 perm2',
        }
        app = main({}, **settings)
        self.testapp = TestApp(app)

    def tearDown(self):
        self.testapp.reset()

    def test_facebook_login(self):
        res = self.testapp.get('/facebook/login', {
            'next_url': 'https://localhost/foo/bar',
        })
        self.assertEqual(res.status, '302 Found')
        url = urlparse.urlparse(res.location)
        self.assertEqual(url.netloc, 'www.facebook.com')
        self.assertEqual(url.path, '/dialog/oauth/')
        query = urlparse.parse_qs(url.query)
        self.assertEqual(sorted(query.keys()), [
            'client_id',
            'redirect_uri',
            'response_type',
            'scope',
            'state',
        ])
        self.assertEqual(query['scope'], ['perm1 perm2'])
        self.assertEqual(query['redirect_uri'],
                         ['http://localhost/facebook/callback'])
        self.assertEqual(query['client_id'], ['123'])

    def test_facebook_callback(self):
        # call the login to fill the session
        res = self.testapp.get('/facebook/login', {
            'next_url': 'https://localhost/foo/bar',
        })
        self.assertEqual(res.status, '302 Found')
        url = urlparse.urlparse(res.location)
        query = urlparse.parse_qs(url.query)
        state = query['state'][0]

        with patch('requests.post') as fake_post:
            fake_post.return_value.status_code = 200
            fake_post.return_value.json = lambda: {
                'access_token': '1234',
            }
            with patch('requests.get') as fake_get:
                fake_get.return_value.status_code = 200
                fake_get.return_value.json = lambda: {
                    'id': '789',
                    'username': '******',
                    'first_name': 'John',
                    'last_name': 'Doe',
                    'name': 'John Doe',
                    'email': '*****@*****.**',
                }

                res = self.testapp.get('/facebook/callback', {
                    'code': '1234',
                    'state': state,
                })
                self.assertEqual(res.status, '200 OK')
                self.assertEqual(res.text, 'Register success!')

                self.assertEqual(self.callback_counter.counter, 1)
                call_args = self.callback_counter.calls[0]['args']
                self.assertTrue(isinstance(call_args[0], Request))
                self.assertEqual(call_args[1], '789')
                self.assertEqual(
                    call_args[2], {
                        'id': '789',
                        'username': '******',
                        'first_name': 'John',
                        'last_name': 'Doe',
                        'name': 'John Doe',
                        'screen_name': 'John Doe',
                        'email': '*****@*****.**',
                    })
                call_kwargs = self.callback_counter.calls[0]['kwargs']
                self.assertEqual(call_kwargs, {})
Example #35
0
class FunctionalTests(unittest.TestCase):
    """
    these tests are functional tests to check functionality of the whole app
    (i.e. integration tests)
    they also serve to get coverage for 'main'
    """
    def setUp(self):
        my_settings = {
            'sqlalchemy.url': 'sqlite://',
            'available_languages': 'da de en es fr',
            'c3smembership.mailaddr': '*****@*****.**'
        }
        #my_other_settings = {'sqlalchemy.url': 'sqlite:///test.db',
        #                     'available_languages': 'da de en es fr'}
        # mock, not even used!?
        #from sqlalchemy import engine_from_config
        #engine = engine_from_config(my_settings)
        from c3smembership.scripts.initialize_db import init
        init()

        from c3smembership import main
        #try:
        app = main({}, **my_settings)
        #except:
        #    app = main({}, **my_other_settings)
        #    pass
        from webtest import TestApp
        self.testapp = TestApp(app)

    def tearDown(self):
        # maybe I need to check and remove globals here,
        # so the other tests are not compromised
        #del engine
        from c3smembership.models import DBSession
        #DBSession.remove()
        DBSession.close()
        #TODO: delete database
        DBSession.remove()
        #import pdb; pdb.set_trace()

    def test_base_template(self):
        """load the front page, check string exists"""
        res = self.testapp.get('/', status=200)
        self.failUnless('Cultural Commons Collecting Society' in res.body)
        self.failUnless('Copyright 2013, C3S SCE' in res.body)

    # def test_faq_template(self):
    #     """load the FAQ page, check string exists"""
    #     res = self.testapp.get('/faq', status=200)
    #     self.failUnless('FAQ' in res.body)
    #     self.failUnless(
    #         'Copyright 2013, OpenMusicContest.org e.V.' in res.body)

    def test_lang_en_LOCALE(self):
        """load the front page, forced to english (default pyramid way),
        check english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/?_LOCALE_=en', status=200)
        self.failUnless('Application for Membership of ' in res.body)

    def test_lang_en(self):
        """load the front page, set to english (w/ pretty query string),
        check english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/?en', status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        self.failUnless('Application for Membership of ' in res1.body)

# so let's test the app's obedience to the language requested by the browser
# i.e. will it respond to http header Accept-Language?

# def test_accept_language_header_da(self):
#     """check the http 'Accept-Language' header obedience: danish
#     load the front page, check danish string exists"""
#     res = self.testapp.reset()  # delete cookie
#     res = self.testapp.get('/', status=200,
#                            headers={
#             'Accept-Language': 'da'})
#     #print(res.body) #  if you want to see the pages source
#     self.failUnless(
#         '<input type="hidden" name="_LOCALE_" value="da"' in res.body)

    def test_accept_language_header_de_DE(self):
        """check the http 'Accept-Language' header obedience: german
        load the front page, check german string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/',
                               status=200,
                               headers={'Accept-Language': 'de-DE'})
        #print(res.body) #  if you want to see the pages source
        self.failUnless('Mitgliedschaftsantrag für die' in res.body)
        self.failUnless(
            '<input type="hidden" name="_LOCALE_" value="de"' in res.body)

    def test_accept_language_header_en(self):
        """check the http 'Accept-Language' header obedience: english
        load the front page, check english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/',
                               status=200,
                               headers={'Accept-Language': 'en'})
        #print(res.body) #  if you want to see the pages source
        self.failUnless("I want to become" in res.body)

    # def test_accept_language_header_es(self):
    #     """check the http 'Accept-Language' header obedience: spanish
    #     load the front page, check spanish string exists"""
    #     res = self.testapp.reset()  # delete cookie
    #     res = self.testapp.get('/', status=200,
    #                            headers={
    #             'Accept-Language': 'es'})
    #     #print(res.body) #  if you want to see the pages source
    #     self.failUnless(
    #         'Luego de enviar el siguiente formulario,' in res.body)

    # def test_accept_language_header_fr(self):
    #     """check the http 'Accept-Language' header obedience: french
    #     load the front page, check french string exists"""
    #     res = self.testapp.reset()  # delete cookie
    #     res = self.testapp.get('/', status=200,
    #                            headers={
    #             'Accept-Language': 'fr'})
    #     #print(res.body) #  if you want to see the pages source
    #     self.failUnless(
    #         'En envoyant un courriel à [email protected] vous pouvez' in res.body)

    def test_no_cookies(self):
        """load the front page, check default english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/',
                               status=200,
                               headers={'Accept-Language':
                                        'af, cn'})  # ask for missing languages
        #print res.body
        self.failUnless('Application for Membership' in res.body)

#############################################################################
# check for validation stuff

    def test_form_lang_en_non_validating(self):
        """load the join form, check english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/?_LOCALE_=en', status=200)
        form = res.form
        #print(form.fields)
        #print(form.fields.values())
        form['firstname'] = 'John'
        #form['address2'] = 'some address part'
        res2 = form.submit('submit')
        self.failUnless(
            'There was a problem with your submission' in res2.body)

    def test_form_lang_de(self):
        """load the join form, check german string exists"""
        res = self.testapp.get('/?de', status=302)
        #print(res)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res2 = res.follow()
        #print(res2)
        # test for german translation of template text (lingua_xml)
        self.failUnless('Mitgliedschaftsantrag für die' in res2.body)
        # test for german translation of form field label (lingua_python)
        self.failUnless('Vorname' in res2.body)

    def test_form_lang_LOCALE_de(self):
        """load the join form in german, check german string exists
        this time forcing german locale the pyramid way
        """
        res = self.testapp.get('/?_LOCALE_=de', status=200)
        # test for german translation of template text (lingua_xml)
        self.failUnless('Mitgliedschaftsantrag für die' in res.body)
        # test for german translation of form field label (lingua_python)
        self.failUnless('Vorname' in res.body)

###########################################################################
# checking the success page that sends out email with verification link

    def test_check_email_en_wo_context(self):
        """try to access the 'check_email' page and be redirected
        check english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/check_email?en', status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        #print(res1)
        self.failUnless('Application for Membership of ' in str(res1.body),
                        'expected string was not found in web UI')

###########################################################################
# checking the view that gets code and mail, asks for a password

    def test_verify_email_en_w_bad_code(self):
        """load the page in english,
        be redirected to the form (data is missing)
        check english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/verify/[email protected]/ABCD-----', status=200)
        self.failUnless('Password' in res.body)
        form = res.form
        form['password'] = '******'
        res2 = form.submit('submit')
        self.failUnless('Password' in res2.body)

    def test_verify_email_en_w_good_code(self):
        """
        check english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/verify/[email protected]/ABCDEFGHIJ', status=200)
        self.failUnless('Password' in res.body)
        form = res.form
        form['password'] = '******'
        res2 = form.submit('submit')
        self.failUnless('C3S_SCE_AFM_Firstn_meLastname.pdf' in res2.body)
#        import pdb
#        pdb.set_trace()
#'Your Email has been confirmed, Firstnäme Lastname!' in res.body)
#res2 = self.testapp.get(
#    '/C3S_SCE_AFM_Firstn_meLastname.pdf', status=200)
#self.failUnless(len(res2.body) > 70000)

###########################################################################
# checking the disclaimer

# def test_disclaimer_en(self):
#     """load the disclaimer in english (via query_string),
#     check english string exists"""
#     res = self.testapp.reset()
#     res = self.testapp.get('/disclaimer?en', status=302)
#     self.failUnless('The resource was found at' in res.body)
#     # we are being redirected...
#     res1 = res.follow()
#     self.failUnless(
#         'you may order your data to be deleted at any time' in str(
#             res1.body),
#         'expected string was not found in web UI')

# def test_disclaimer_de(self):
#     """load the disclaimer in german (via query_string),
#     check german string exists"""
#     res = self.testapp.reset()
#     res = self.testapp.get('/disclaimer?de', status=302)
#     self.failUnless('The resource was found at' in res.body)
#     # we are being redirected...
#     res1 = res.follow()
#     self.failUnless(
#         'Datenschutzerkl' in str(
#             res1.body),
#         'expected string was not found in web UI')

# def test_disclaimer_LOCALE_en(self):
#     """load the disclaimer in english, check english string exists"""
#     res = self.testapp.reset()
#     res = self.testapp.get('/disclaimer?_LOCALE_=en', status=200)
#     self.failUnless(
#         'you may order your data to be deleted at any time' in str(
#             res.body),
#         'expected string was not found in web UI')

# def test_disclaimer_LOCALE_de(self):
#     """load the disclaimer in german, check german string exists"""
#     res = self.testapp.reset()
#     res = self.testapp.get('/disclaimer?_LOCALE_=de', status=200)
#     self.failUnless(
#         'Datenschutzerkl' in str(
#             res.body),
#         'expected string was not found in web UI')

    def test_success_wo_data_en(self):
        """load the success page in english (via query_string),
        check for redirection and english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/success?en', status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        #print(res1)
        self.failUnless(  # check text on page redirected to
            'Please fill out the form' in str(res1.body),
            'expected string was not found in web UI')

    def test_success_pdf_wo_data_en(self):
        """
        try to load a pdf (which must fail because the form was not used)
        check for redirection to the form and test string exists
        """
        res = self.testapp.reset()
        res = self.testapp.get('/C3S_SCE_AFM_ThefirstnameThelastname.pdf',
                               status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        #print(res1)
        self.failUnless(  # check text on page redirected to
            'Please fill out the form' in str(res1.body),
            'expected string was not found in web UI')

    # def test_success_w_data(self):
    #     """
    #     load the form, fill the form, (in one go via POST request)
    #     check for redirection, push button to send verification mail,
    #     check for 'mail was sent' message
    #     """
    #     res = self.testapp.reset()
    #     res = self.testapp.get('/', status=200)
    #     form = res.form
    #     print '*'*80
    #     print '*'*80
    #     print '*'*80
    #     print form.fields
    #     res = self.testapp.post(
    #         '/',  # where the form is served
    #         {
    #             'submit': True,
    #             'firstname': 'TheFirstName',
    #             'lastname': 'TheLastName',
    #             'date_of_birth': '1987-06-05',
    #             'address1': 'addr one',
    #             'address2': 'addr two',
    #             'postcode': '98765 xyz',
    #             'city': 'Devilstown',
    #             'country': 'AF',
    #             'email': '*****@*****.**',
    #             'password': '******',
    #             'num_shares': '42',
    #             '_LOCALE_': 'en',
    #             #'activity': set(
    #             #    [
    #             #        u'composer',
    #             #        #u'dj'
    #             #    ]
    #             #),
    #             'invest_member': 'yes',
    #             'member_of_colsoc': 'yes',
    #             'name_of_colsoc': 'schmoo',
    #             #'opt_band': 'yes band',
    #             #'opt_URL': 'http://yes.url',
    #             #'noticed_dataProtection': 'yes'
    #             'num_shares': '23',
    #         },
    #         #status=302,  # expect redirection to success page
    #         status=200,  # expect redirection to success page
    #     )

    #     print(res.body)
    #     self.failUnless('The resource was found at' in res.body)
    #     # we are being redirected...
    #     res2 = res.follow()
    #     self.failUnless('Success' in res2.body)
    #     #print("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv")
    #     #print res2.body
    #     #print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
    #     self.failUnless('TheFirstName' in res2.body)
    #     self.failUnless('TheLastName' in res2.body)
    #     self.failUnless('1987-06-05' in res2.body)
    #     self.failUnless('addr one' in res2.body)
    #     self.failUnless('addr two' in res2.body)
    #     self.failUnless('Devilstown' in res2.body)
    #     self.failUnless('*****@*****.**' in res2.body)
    #     self.failUnless('schmoo' in res2.body)

    #     # now check for the "mail was sent" confirmation
    #     res3 = self.testapp.post(
    #         '/check_email',
    #         {
    #             'submit': True,
    #             'value': "send mail"
    #         }
    #     )
    #     #print(res3)
    #     self.failUnless(
    #         'An email was sent, TheFirstName TheLastName!' in res3.body)

#     def test_success_and_reedit(self):
#         """
#         submit form, check success, re-edit: are the values pre-filled?
#         """
#         res = self.testapp.reset()
#         res = self.testapp.get('/', status=200)
#         form = res.form
#         form['firstname'] = 'TheFirstNäme'
#         form['lastname'] = 'TheLastNäme'
#         form['address1'] = 'addr one'
#         form['address2'] = 'addr two'
#         res2 = form.submit('submit')
#         print res2.body
# #                'submit': True,
# #                'date_of_birth': '1987-06-05',
# #                'address2': 'addr two',
# #                'postcode': '98765 xyz',
# #                'city': 'Devilstöwn',
# #                'email': '*****@*****.**',
# #                'num_shares': '23',
# #                '_LOCALE_': 'en',
# #                #'activity': set(
#                 #    [
#                 #        'composer',
#                 #        #u'dj'
#                 #    ]
#                 #),
# #                'country': 'AF',
# #                'membership_type': 'investing',
# #                'member_of_colsoc': 'yes',
# #                'name_of_colsoc': 'schmoö',
#                 #'opt_band': 'yes bänd',
#                 #'opt_URL': 'http://yes.url',
#                 #'noticed_dataProtection': 'yes'

# #            },
# #            status=302,  # expect redirection to success page
# #        )

#    print(res.body)
#     self.failUnless('The resource was found at' in res.body)
#     # we are being redirected...
#     res2 = res.follow()
#     self.failUnless('Success' in res2.body)
#     #print("success page: \n%s") % res2.body
#     #self.failUnless(u'TheFirstNäme' in (res2.body))

#     # go back to the form and check the pre-filled values
#     res3 = self.testapp.get('/')
#     #print(res3.body)
#     #print("edit form: \n%s") % res3.body
#     self.failUnless('TheFirstNäme' in res3.body)
#     form = res3.form
#     self.failUnless(form['firstname'].value == u'TheFirstNäme')

    def test_email_confirmation(self):
        """
        test email confirmation
        """
        res = self.testapp.reset()
        res = self.testapp.get('/verify/[email protected]/ABCDEFGHIJ', status=200)
        # print(res.body)
        form = res.form
        form['password'] = '******'
        res2 = form.submit('submit')
        #print res2.body
        self.failUnless("Load your PDF..." in res2.body)
        res3 = self.testapp.get('/C3S_SCE_AFM_ThefirstnameThelastname.pdf',
                                status=200)
        #print("length of result: %s") % len(res2.body)
        self.failUnless(80000 < len(res3.body) < 100000)  # check pdf size

    def test_email_confirmation_wrong_mail(self):
        """
        test email confirmation with a wrong email
        """
        res = self.testapp.reset()
        res = self.testapp.get('/verify/[email protected]/ABCDEFGHIJ',
                               status=200)
        #print(res.body)
        self.failUnless("Please enter your password." in res.body)

    def test_email_confirmation_wrong_code(self):
        """
        test email confirmation with a wrong code
        """
        res = self.testapp.reset()
        res = self.testapp.get('/verify/[email protected]/WRONGCODE', status=200)
        #print(res.body)
        self.failUnless("Please enter your password." in res.body)

    def test_success_check_email(self):
        """
        test "check email" success page with wrong data:
        this should redirect to the form.
        """
        res = self.testapp.reset()
        res = self.testapp.get('/check_email', status=302)

        res2 = res.follow()
        self.failUnless("Please fill out the form" in res2.body)
class NewMemberTests(unittest.TestCase):
    """
    test creation of a new member by staff

    these tests are functional tests to check functionality of the whole app
    (i.e. integration tests)
    they also serve to get coverage for 'main'
    """
    def setUp(self):
        self.config = testing.setUp()
        self.config.include('pyramid_mailer.testing')
        try:
            DBSession.close()
            DBSession.remove()
            # print "closed and removed DBSession"
        except:
            pass
            # print "no session to close"
        # self.session = DBSession()
        my_settings = {
            'sqlalchemy.url': 'sqlite:///:memory:',
            'available_languages': 'da de en es fr',
            'c3smembership.dashboard_number': '30'
        }
        engine = engine_from_config(my_settings)
        DBSession.configure(bind=engine)
        Base.metadata.create_all(engine)

        with transaction.manager:
            # a group for accountants/staff
            accountants_group = Group(name=u"staff")
            try:
                DBSession.add(accountants_group)
                DBSession.flush()
            except:
                pass
            # staff personnel
            staffer1 = C3sStaff(
                login=u"rut",
                password=u"berries",
                email=u"*****@*****.**",
            )
            staffer1.groups = [accountants_group]
            try:
                DBSession.add(accountants_group)
                DBSession.add(staffer1)
                DBSession.flush()
            except:
                # print("it borked! (rut)")
                pass

        from c3smembership import main
        app = main({}, **my_settings)
        from webtest import TestApp
        self.testapp = TestApp(app)

    def tearDown(self):
        DBSession.close()
        DBSession.remove()
        testing.tearDown()

    def _login(self):
        res = self.testapp.get('/login', status=200)
        self.failUnless('login' in res.body)
        res.form['login'] = '******'
        res.form['password'] = '******'
        res.form.submit('submit', status=302)

    def _fill_form_valid_natural(self, form):
        # print form.fields
        form['firstname'] = u'SomeFirstname'
        form['lastname'] = u'SomeLastname'
        form['email'] = u'*****@*****.**'
        form['address1'] = u"addr one"
        form['address2'] = u"addr two"
        form['postcode'] = u"12345"
        form['city'] = u"Footown Meeh"
        form['country'].value__set(u"DE")
        form['locale'] = u"DE"
        form['date_of_birth'] = unicode(date(date.today().year - 40, 1, 1))
        form['entity_type'].value__set(u'person')
        form['membership_type'].value__set(u'normal')
        form['other_colsoc'].value__set(u'no')
        form['name_of_colsoc'] = u"GEMA"
        form['num_shares'] = u'23'
        return form

    def _fill_form_valid_legal(self, form):
        form['firstname'] = u'SomeLegalentity'
        form['lastname'] = u'SomeLegalName'
        form['email'] = u'*****@*****.**'
        form['address1'] = u"addr one"
        form['address2'] = u"addr two"
        form['postcode'] = u"12345"
        form['city'] = u"Footown Meeh"
        form['country'].value__set(u"DE")
        form['locale'] = u"DE"
        form['date_of_birth'] = unicode(date(date.today().year - 40, 1, 1))
        form['entity_type'] = u'legalentity'
        form['membership_type'] = u'investing'
        form['other_colsoc'].value__set(u'no')
        form['name_of_colsoc'] = u""
        form['num_shares'] = u'42'
        return form

    def test_add_member(self):
        '''
        tests for the new_member view
        '''
        # unauthorized access must be prevented
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/new_member', status=403)
        assert ('Access was denied to this resource' in res.body)

        # so login first
        self._login()

        # no member with id=1 in DB
        res = self.testapp.get('/new_member?id=1', status=200)
        # enter valid data
        form = self._fill_form_valid_natural(res.form)
        res = form.submit(u'submit', status=302)
        res4 = res.follow()

        self.assertTrue('Details for Member Application #1' in res4.body)
        self.assertTrue('SomeFirstname' in res4.body)
        self.assertTrue('SomeLastname' in res4.body)
        self.assertTrue('*****@*****.**' in res4.body)
        self.assertTrue('addr one' in res4.body)
        self.assertTrue('addr two' in res4.body)
        self.assertTrue('12345' in res4.body)
        self.assertTrue('DE' in res4.body)
        self.assertTrue('normal' in res4.body)
        self.assertTrue('23' in res4.body)

        # now, there is a member with id=1 in DB
        res = self.testapp.get('/new_member?id=1', status=200)

        # check the number of entries in the DB
        self.assertEqual(C3sMember.get_number(), 1)

        res = self.testapp.get('/new_member', status=200)
        form = self._fill_form_valid_legal(res.form)
        res = form.submit(u'submit', status=302)
        res4 = res.follow()

        self.assertTrue('Details for Member Application #2' in res4.body)
        self.assertTrue('SomeLegalentity' in res4.body)
        self.assertTrue('SomeLegalName' in res4.body)
        self.assertTrue('*****@*****.**' in res4.body)
        self.assertTrue('addr one' in res4.body)
        self.assertTrue('addr two' in res4.body)
        self.assertTrue('12345' in res4.body)
        self.assertTrue('' in res4.body)
        self.assertTrue('DE' in res4.body)
        self.assertTrue('investing' in res4.body)
        self.assertTrue('42' in res4.body)
Example #37
0
class Test(object):
    def __init__(self):
        self._tmpdir = None
        self._tmproot = None
        self._app = None
        self._starting_dir = os.getcwd()

    #def setUp(self):
    #    assert False
    def populate_conf_directory(self):
        """Populate a directory with valid configuration files, to be run just once
        The files are not modified by each test
        """
        self._tmpdir = os.path.join(self, _tmproot,
                                    "cork_functional_test_source")

        # only do this once, as advertised
        if os.path.exists(self._tmpdir): return

        os.mkdir(self._tmpdir)
        os.mkdir(self._tmpdir + "/example_conf")

        cork = Cork(os.path.join(self._tmpdir, "example_conf"),
                    initialize=True)

        cork._store.roles['admin'] = 100
        cork._store.roles['editor'] = 60
        cork._store.roles['user'] = 50
        cork._store._savejson('roles', cork._store.roles)

        tstamp = str(datetime.utcnow())
        username = password = '******'
        cork._store.users[username] = {
            'role': 'admin',
            'hash': cork._hash(username, password),
            'email_addr': username + '@localhost.local',
            'desc': username + ' test user',
            'creation_date': tstamp
        }
        username = password = ''
        cork._store.users[username] = {
            'role': 'user',
            'hash': cork._hash(username, password),
            'email_addr': username + '@localhost.local',
            'desc': username + ' test user',
            'creation_date': tstamp
        }
        cork._store._save_users()

    def remove_temp_dir(self):
        p = os.path.join(self._tmproot, 'cork_functional_test_wd')
        for f in glob.glob('%s*' % p):
            #shutil.rmtree(f)
            pass

    @classmethod
    def setUpClass(cls):
        print("Setup class")

    def setup(self):
        # create test dir and populate it using the example files

        # save the directory where the unit testing has been run
        if self._starting_dir is None:
            self._starting_dir = os.getcwd()

        # create json files to be used by Cork
        self._tmproot = testutils.pick_temp_directory()
        assert self._tmproot is not None

        # purge the temporary test directory
        self.remove_temp_dir()

        self.populate_temp_dir()
        self.create_app_instance()
        self._app.reset()
        print("Reset done")
        print("Setup completed")

    def populate_temp_dir(self):
        """populate the temporary test dir"""
        assert self._tmproot is not None
        assert self._tmpdir is None

        tstamp = str(time())[5:]
        self._tmpdir = os.path.join(self._tmproot,
                                    "cork_functional_test_wd_%s" % tstamp)

        try:
            os.mkdir(self._tmpdir)
        except OSError:
            # The directory is already there, purge it
            print("Deleting %s" % self._tmpdir)
            shutil.rmtree(self._tmpdir)
            os.mkdir(self._tmpdir)

            #p = os.path.join(self._tmproot, 'cork_functional_test_wd')
            #for f in glob.glob('%s*' % p):
            #    shutil.rmtree(f)

        # copy the needed files
        shutil.copytree(os.path.join(self._starting_dir, 'test/example_conf'),
                        os.path.join(self._tmpdir, 'example_conf'))
        shutil.copytree(os.path.join(self._starting_dir, 'test/views'),
                        os.path.join(self._tmpdir, 'views'))

        # change to the temporary test directory
        # cork relies on this being the current directory
        os.chdir(self._tmpdir)

        print("Test directory set up")

    def create_app_instance(self):
        """create TestApp instance"""
        assert self._app is None
        import simple_webapp
        self._bottle_app = simple_webapp.app
        self._app = TestApp(self._bottle_app)
        print("Test App created")

    def assert_redirect(self, page, redir_page):
        """Assert that a page redirects to another one"""
        p = self._app.get(page, status=302)
        dest = p.location.split(':80/')[-1]
        dest = "/%s" % dest
        assert dest == redir_page, "%s redirects to %s instead of %s" % \
            (page, dest, redir_page)

    def login_as_admin(self):
        """perform log in"""
        assert self._app is not None
        assert 'beaker.session.id' not in self._app.cookies, "Unexpected cookie found"
        self.assert_redirect('/admin', '/sorry_page')

        p = self._app.post('/login', {
            'username': '******',
            'password': '******'
        })
        assert p.status == REDIR, "Redirect expected"
        assert p.location == 'http://localhost:80/', \
            "Incorrect redirect to %s" % p.location
        print repr(p)

        assert 'beaker.session.id' in self._app.cookies, "Cookie not found"

        print "TO", repr(self._bottle_app.session)
        print "TO", dir(self._bottle_app)

        a = self._app.app
        for n in 'app', 'environ_key', 'options', 'session', 'wrap_app':
            print
            print n
            print "REP", repr(getattr(a, n))
            print "DIR", dir(getattr(a, n))

        import bottle
        session = bottle.request.environ.get('beaker.session')
        print "Session from func. test", repr(session)

        print 'running GET myrole'
        p = self._app.get('/my_role')
        print 'myrole', repr(p)

        p = self._app.get('/admin')
        print 'admin', repr(p)
        assert 'Welcome' in p.body, repr(p)

        p = self._app.get('/my_role', status=200)
        assert p.status == '200 OK'
        assert p.body == 'admin', "Sta"

        print("Login performed")

    def teardown(self):
        print("Doing logout")
        try:
            self._app.post('/logout')
        except:
            pass

        assert self._app.get('/admin').status != '200 OK'
        os.chdir(self._starting_dir)
        #if self._tmproot is not None:
        #    testutils.purge_temp_directory(self._tmproot)

        self._app = None
        self._tmproot = None
        self._tmpdir = None
        print("Teardown done")

    @SkipTest
    def test_functional_login(self):
        assert self._app
        self._app.get('/admin', status=302)
        self._app.get('/my_role', status=302)

        self.login_as_admin()

        # fetch a page successfully
        r = self._app.get('/admin')
        assert r.status == '200 OK', repr(r)

    def test_login_existing_user_none_password(self):
        p = self._app.post('/login', {'username': '******', 'password': None})
        assert p.status == REDIR, "Redirect expected"
        assert p.location == 'http://localhost:80/login', \
            "Incorrect redirect to %s" % p.location

    def test_login_nonexistent_user_none_password(self):
        p = self._app.post('/login', {
            'username': '******',
            'password': None
        })
        assert p.status == REDIR, "Redirect expected"
        assert p.location == 'http://localhost:80/login', \
            "Incorrect redirect to %s" % p.location

    def test_login_existing_user_empty_password(self):
        p = self._app.post('/login', {'username': '******', 'password': ''})
        assert p.status == REDIR, "Redirect expected"
        assert p.location == 'http://localhost:80/login', \
            "Incorrect redirect to %s" % p.location

    def test_login_nonexistent_user_empty_password(self):
        p = self._app.post('/login', {
            'username': '******',
            'password': ''
        })
        assert p.status == REDIR, "Redirect expected"
        assert p.location == 'http://localhost:80/login', \
            "Incorrect redirect to %s" % p.location

    def test_login_existing_user_wrong_password(self):
        p = self._app.post('/login', {
            'username': '******',
            'password': '******'
        })
        assert p.status == REDIR, "Redirect expected"
        assert p.location == 'http://localhost:80/login', \
            "Incorrect redirect to %s" % p.location

    @SkipTest
    def test_functional_login_logout(self):
        # Incorrect login
        p = self._app.post('/login', {
            'username': '******',
            'password': '******'
        })
        assert p.status == REDIR
        assert p.location == 'http://localhost:80/login', \
            "Incorrect redirect to %s" % p.location

        # log in and get a cookie
        p = self._app.post('/login', {
            'username': '******',
            'password': '******'
        })
        assert p.status == REDIR
        assert p.location == 'http://localhost:80/', \
            "Incorrect redirect to %s" % p.location

        # fetch a page successfully
        assert self._app.get(
            '/admin').status == '200 OK', "Admin page should be served"

        # log out
        assert self._app.get('/logout').status == REDIR

        # drop the cookie
        self._app.reset()
        assert self._app.cookies == {}, "The cookie should be gone"

        # fetch the same page, unsuccessfully
        assert self._app.get('/admin').status == REDIR

    @SkipTest
    def test_functional_user_creation_login_deletion(self):
        assert self._app.cookies == {}, "The cookie should be not set"

        # Log in as Admin
        p = self._app.post('/login', {
            'username': '******',
            'password': '******'
        })
        assert p.status == REDIR
        assert p.location == 'http://*****:*****@localhost.local'
    #    })

    #
    def test_functionalxxx(self):
        assert self._app is not None

    def test_functional_expiration(self):
        self.login_as_admin()
        r = self._app.get('/admin')
        assert r.status == '200 OK', repr(r)
        # change the cookie expiration in order to expire it
        self._app.app.options['timeout'] = 0
        assert self._app.get(
            '/admin').status == REDIR, "The cookie should have expired"
Example #38
0
class TestApiViews(unittest.TestCase):
    def setUp(self):
        my_settings = {"sqlalchemy.url": "sqlite:///:memory:", "api_auth_token": u"SECRETAUTHTOKEN"}
        self.config = testing.setUp()
        app = main({}, **my_settings)
        # set up the database
        engine = engine_from_config(my_settings)
        DBSession.configure(bind=engine)
        Base.metadata.create_all(engine)
        with transaction.manager:
            member1 = C3sMember(  # german
                firstname=u"SomeFirstnäme",
                lastname=u"SomeLastnäme",
                email=u"*****@*****.**",
                address1=u"addr one",
                address2=u"addr two",
                postcode=u"12345",
                city=u"Footown Mäh",
                country=u"Foocountry",
                locale=u"de",
                date_of_birth=date.today(),
                email_is_confirmed=False,
                email_confirm_code=u"ABCDEFGFOO",
                password=u"arandompassword",
                date_of_submission=date.today(),
                membership_type=u"normal",
                member_of_colsoc=True,
                name_of_colsoc=u"GEMA",
                num_shares=u"23",
            )
        DBSession.add(member1)
        member1.email_invite_token_bcgv16 = u"MEMBERS_TOKEN"
        DBSession.flush()

        self.testapp = TestApp(app)

    def tearDown(self):
        testing.tearDown()
        DBSession.close()
        DBSession.remove()

    def test_api_userinfo(self):
        """
        Test the api_userinfo service.

        * must be a PUT, not a GET request
        * the auth header must be present
        * returns None if members refcode does not match
        * returns firstname, lastname, email, membership type
        """
        # try a GET -- must fail
        res = self.testapp.get("/lm", status=405)
        self.assertTrue("405 Method Not Allowed" in res.body)
        self.assertTrue("The method GET is not allowed for this resource." in res.body)

        # try a PUT -- fails under certain conditions
        with self.assertRaises(ValueError):
            res = self.testapp.put("/lm", status=200)
            # ValueError: No JSON object could be decoded

        # try a PUT -- fails under certain conditions
        with self.assertRaises(KeyError):
            res = self.testapp.put_json("/lm", dict(id=1))  # status=200)
            # KeyError: 'token'
        # missing auth token -- must fail
        with self.assertRaises(KeyError):
            res = self.testapp.put_json("/lm", dict(token=1))  # status=200)
            # KeyError: 'HTTP_X_MESSAGING_TOKEN'

        # try false auth token -- must fail: 401 unauthorized
        _headers = {"X-messaging-token": "bar"}
        res = self.testapp.put_json("/lm", dict(token=1), headers=_headers, status=401)

        # now use the correct auth token
        _auth_info = {"X-messaging-token": "SECRETAUTHTOKEN"}

        # ..but a non-existing refcode (email_invite_token_bcgv16)
        # returns no user (None)
        res = self.testapp.put_json("/lm", dict(token="foo"), headers=_auth_info, status=200)
        # body: {"lastname": "None", "firstname": "None"}
        self.assertTrue(json.loads(res.body)["firstname"], "None")
        self.assertTrue(json.loads(res.body)["lastname"], "None")

        self.testapp.reset()

        m1 = C3sMember.get_by_id(1)  # load member from DB for crosscheck

        # now try a valid refcode (email_invite_token_bcgv16)
        res2 = self.testapp.put_json("/lm", dict(token=m1.email_invite_token_bcgv16), headers=_auth_info, status=200)
        self.assertTrue(json.loads(res2.body)["firstname"], m1.firstname)
        self.assertTrue(json.loads(res2.body)["lastname"], m1.lastname)
        self.assertTrue(json.loads(res2.body)["email"], m1.email)
        self.assertTrue(json.loads(res2.body)["mtype"], m1.membership_type)
Example #39
0
class TestApiViews(unittest.TestCase):
    """
    Tests the ApiViews class.
    """

    def setUp(self):
        my_settings = {
            'sqlalchemy.url': 'sqlite:///:memory:',
            'api_auth_token': u"SECRETAUTHTOKEN",
        }
        self.config = testing.setUp()
        app = main({}, **my_settings)
        # set up the database
        engine = engine_from_config(my_settings)
        DBSession.configure(bind=engine)
        Base.metadata.create_all(engine)
        with transaction.manager:
            member1 = C3sMember(  # german
                firstname=u'SomeFirstnäme',
                lastname=u'SomeLastnäme',
                email=u'*****@*****.**',
                address1=u"addr one",
                address2=u"addr two",
                postcode=u"12345",
                city=u"Footown Mäh",
                country=u"Foocountry",
                locale=u"de",
                date_of_birth=date.today(),
                email_is_confirmed=False,
                email_confirm_code=u'ABCDEFGFOO',
                password=u'arandompassword',
                date_of_submission=date.today(),
                membership_type=u'normal',
                member_of_colsoc=True,
                name_of_colsoc=u"GEMA",
                num_shares=u'23',
            )
        member1.membership_number = 'M1'
        # pylint: disable=no-member
        DBSession.add(member1)
        GeneralAssemblyRepository.invite_member(
            member1.membership_number, GENERAL_ASSEMBLY, u'MEMBERS_TOKEN')
        # pylint: disable=no-member
        DBSession.flush()

        self.testapp = TestApp(app)

    def tearDown(self):
        testing.tearDown()
        # pylint: disable=no-member
        DBSession.close()
        DBSession.remove()

    def test_api_userinfo(self):
        """
        Test the api_userinfo service.

        * must be a PUT, not a GET request
        * the auth header must be present
        * returns None if members refcode does not match
        * returns firstname, lastname, email, membership type
        """
        # try a GET -- must fail
        res = self.testapp.get('/lm', status=405)
        self.assertTrue('405 Method Not Allowed' in res.body)
        self.assertTrue('The method GET is not allowed for this resource.'
                        in res.body)

        # try a PUT -- fails under certain conditions
        with self.assertRaises(ValueError):
            res = self.testapp.put('/lm', status=200)
            # ValueError: No JSON object could be decoded

        # try a PUT -- fails under certain conditions
        with self.assertRaises(KeyError):
            res = self.testapp.put_json(
                '/lm', dict(id=1))  # status=200)
            # KeyError: 'token'
        # missing auth token -- must fail
        with self.assertRaises(KeyError):
            res = self.testapp.put_json(
                '/lm', dict(token=1))  # status=200)
            # KeyError: 'HTTP_X_MESSAGING_TOKEN'

        # try false auth token -- must fail: 401 unauthorized
        _headers = {'X-messaging-token': 'bar'}
        res = self.testapp.put_json(
            '/lm', dict(token=1), headers=_headers, status=401)

        # now use the correct auth token
        _auth_info = {'X-messaging-token': 'SECRETAUTHTOKEN'}

        # ..but a non-existing refcode
        # returns no user (None)
        res = self.testapp.put_json(
            '/lm', dict(token='foo'), headers=_auth_info, status=200)
        # body: {"lastname": "None", "firstname": "None"}
        self.assertTrue(json.loads(res.body)['firstname'], "None")
        self.assertTrue(json.loads(res.body)['lastname'], "None")

        self.testapp.reset()

        member1 = C3sMember.get_by_id(1)  # load member from DB for crosscheck

        # now try a valid refcode
        res2 = self.testapp.put_json(
            '/lm', dict(token='MEMBERS_TOKEN'),
            headers=_auth_info, status=200)
        self.assertTrue(json.loads(res2.body)['firstname'], member1.firstname)
        self.assertTrue(json.loads(res2.body)['lastname'], member1.lastname)
        self.assertTrue(json.loads(res2.body)['email'], member1.email)
        self.assertTrue(
            json.loads(res2.body)['mtype'], member1.membership_type)
class FunctionalTests(unittest.TestCase):
    def _get_default_headers(self):
        return {'Accept': 'application/json'}

    @classmethod
    def setUpClass(cls):
        cls.settings = appconfig('config:' + os.path.join(here, 'test.ini'))

    def setUp(self):
        self.app = main({}, **self.settings)
        self.testapp = TestApp(self.app)
        responses.add(responses.POST, "https://test-geo.onroerenderfgoed.be/zoekdiensten/administratievegrenzen")

    def tearDown(self):
        self.testapp.reset()

    def test_get_nearest_address(self):
        res = self.testapp.post('/nearest_address', test_geom)
        self.assertEqual('200 OK', res.status)

    def test_get_nearest_address_outside_Flanders(self):
        res = self.testapp.post('/nearest_address', json.dumps(test_json_outside_flanders), expect_errors=True)
        self.assertEqual('400 Bad Request', res.status)

    def test_get_nearest_address_not_found(self):
        res = self.testapp.post('/nearest_address', json.dumps(test_json_intersects_flanders), expect_errors=True)
        self.assertEqual('200 OK', res.status)

    def test_check_in_flanders(self):
        res = self.testapp.post('/check_in_flanders', test_geom)
        self.assertEqual('200 OK', res.status)

    def test_check_within_flanders(self):
        res = self.testapp.post('/check_within_flanders', test_geom)
        self.assertEqual('200 OK', res.status)

    def test_check_in_flanders_no_json_body(self):
        res = self.testapp.post('/check_in_flanders', expect_errors=True)
        self.assertEqual('400 Bad Request', res.status)

    def test_check_in_flanders_validation_failure(self):
        res = self.testapp.post('/check_in_flanders', '{}', expect_errors=True)
        self.assertEqual('400 Bad Request', res.status)

    def test_check_in_flanders_invalid_url(self):
        res = self.testapp.post('/test', '{}', expect_errors=True)
        self.assertEqual('404 Not Found', res.status)

    def test_internal_server_error(self):
        a = Exception()
        internal_server_error(a, testing.DummyRequest())

    @responses.activate
    def test_gemeente(self):
        res = self.testapp.post('/gemeente', test_geom)
        self.assertEqual('200 OK', res.status)
        print res.text

    @responses.activate
    def test_gemeente(self):
        responses.add(responses.POST, 'http://geozoekdienst.en', body=json.dumps(get_gemeente_results))
        res = self.testapp.post('/gemeente', test_geom)
        self.assertEqual('200 OK', res.status)
        print res.text

    @responses.activate
    def test_provincie(self):
        responses.add(responses.POST, 'http://geozoekdienst.en', body=json.dumps(get_provincie_results))
        res = self.testapp.post('/provincie', test_geom)
        self.assertEqual('200 OK', res.status)
        print res.text

    @responses.activate
    def test_check_erfgoedgemeente(self):
        contour = {
            "coordinates": [[[[172933.6922879719, 174851.1496091811], [172930.21180502675, 174832.7836931711],
                              [172920.64762709616, 174848.13247794658], [172933.6922879719, 174851.1496091811]]]],
            "type": "MultiPolygon", "crs": {"type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::31370"}}
        }
        responses.add(
            responses.POST,
            'http://geozoekdienst.en',
            body='[{"naam": "Leuven", "type": "gemeente", "id": "24062"}]', status=200)
        res = self.testapp.post('/check_in_erfgoedgemeente', params=json.dumps(contour),
                                headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertIn('ok', res.json["status"])

    @responses.activate
    def test_check_erfgoedgemeente_full_overlap(self):
        responses.add(
            responses.POST,
            'http://geozoekdienst.en',
            body='[{"naam": "Koksijde", "type": "gemeente", "id": "38014"}]', status=200)
        contour = {
            "coordinates": [[[[172933.6922879719, 174851.1496091811], [172930.21180502675, 174832.7836931711],
                              [172920.64762709616, 174848.13247794658], [172933.6922879719, 174851.1496091811]]]],
            "type": "MultiPolygon", "crs": {"type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::31370"}}
        }
        res = self.testapp.post('/check_in_erfgoedgemeente', params=json.dumps(contour),
                                headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertIn('error', res.json["status"])
        self.assertIn('Gelieve de melding in te dienen bij deze gemeente', res.json["message"])

    @responses.activate
    def test_check_erfgoedgemeente_partial_overlap(self):
        responses.add(
            responses.POST,
            'http://geozoekdienst.en',
            body='[{"naam": "Koksijde", "type": "gemeente", "id": "38014"}, '
                 '{"naam": "Nieuwpoort", "type": "gemeente", "id": "38016"}]', status=200)
        contour = {
            "coordinates": [[[[172933.6922879719, 174851.1496091811], [172930.21180502675, 174832.7836931711],
                              [172920.64762709616, 174848.13247794658], [172933.6922879719, 174851.1496091811]]]],
            "type": "MultiPolygon", "crs": {"type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::31370"}}
        }
        res = self.testapp.post('/check_in_erfgoedgemeente', params=json.dumps(contour),
                                headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertIn('warn', res.json["status"])
        self.assertIn('Gelieve de melding vooronderzoek eveneens in te dienen bij deze gemeente', res.json['message'])
Example #41
0
class LoggedInRequestTests(MongoTestCase):
    """Base TestCase for those tests that need a logged in environment setup"""

    def setUp(self, settings={}, skip_on_fail=False, std_user='******'):

        self.settings = deepcopy(SETTINGS)
        self.settings.update(settings)
        super(LoggedInRequestTests, self).setUp(celery, get_attribute_manager, userdb_use_old_format=True)

        self.redis_instance = RedisTemporaryInstance.get_instance()
        self.settings['redis_host'] = 'localhost'
        self.settings['redis_port'] = self.redis_instance._port
        self.settings['redis_db'] = '0'

        self.settings['mongo_uri'] = self.mongodb_uri('')
        try:
            app = eduiddashboard_main({}, **self.settings)
        except pymongo.errors.ConnectionFailure:
            if skip_on_fail:
                raise unittest.SkipTest("requires accessible MongoDB server on {!r}".format(
                    self.settings['mongo_uri']))
            raise

        self.testapp = TestApp(app)

        self.config = testing.setUp()
        self.config.registry.settings = self.settings
        self.config.registry.registerUtility(self, IDebugLogger)

        self.userdb = app.registry.settings['userdb']
        _userdoc = self.userdb.get_user_by_mail(std_user)
        self.assertIsNotNone(_userdoc, "Could not load the standard test user {!r} from the database {!s}".format(
            std_user, self.userdb))
        self.user = OldUser(data=_userdoc)
        self.logged_in_user = None

        #self.db = get_db(self.settings)
        self.db = app.registry.settings['mongodb'].get_database('eduid_dashboard')    # central userdb, raw mongodb
        self.userdb_new = UserDB(self.mongodb_uri(''), 'eduid_am')   # central userdb in new format (User)
        self.dashboard_db = DashboardUserDB(self.mongodb_uri('eduid_dashboard'))
        # Clean up the dashboards private database collections
        logger.debug("Dropping profiles, verifications and reset_passwords from {!s}".format(self.db))
        self.db.profiles.drop()
        self.db.verifications.drop()
        self.db.reset_passwords.drop()

        # Copy all the users from the eduid userdb into the dashboard applications userdb
        # since otherwise the out-of-sync check will trigger on every save to the dashboard
        # applications database because there is no document there with the right modified_ts
        for userdoc in self.userdb._get_all_docs():
            logger.debug("Copying user {!r}\nfrom {!r}\nto {!r}:\n{!s}".format(userdoc.get('eduPersonPrincipalName'),
                                                                               self.userdb, self.db.profiles,
                                                                               pprint.pformat(userdoc)))
            self.db.profiles.insert(userdoc)

        self.initial_verifications = (getattr(self, 'initial_verifications', None)
                                      or INITIAL_VERIFICATIONS)

        for verification_data in self.initial_verifications:
            self.db.verifications.insert(verification_data)

        logger.debug("setUp finished\n\n" + ('-=-' * 30) + "\n\n")

    def tearDown(self):
        super(LoggedInRequestTests, self).tearDown()
        logger.debug("tearDown: Dropping profiles, verifications and reset_passwords from {!s}".format(self.db))
        for userdoc in self.db.profiles.find({}):
            assert OldUser(userdoc)
        self.db.profiles.drop()
        self.db.verifications.drop()
        self.db.reset_passwords.drop()
        self.testapp.reset()

    def dummy_get_user(self, userid=''):
        return self.user

    def set_mocked_get_user(self):
        patcher = patch('eduid_userdb.dashboard.UserDBWrapper.get_user_by_eppn',
                        self.dummy_get_user)
        patcher.start()

    def dummy_request(self, cookies={}):
        request = DummyRequest()
        request.context = DummyResource()
        request.userdb = self.userdb
        request.userdb_new = self.userdb_new
        request.db = self.db
        request.registry.settings = self.settings

        def propagate_user_changes(user):
            """
            Make sure there is a request.context.propagate_user_changes in testing too.
            """
            logger.debug('FREDRIK: Testing dummy_request.context propagate_user_changes')
            return self.request.amrelay.request_sync(user)

        request.context.propagate_user_changes = propagate_user_changes

        return request

    def set_logged(self, email='*****@*****.**', extra_session_data={}):
        request = self.set_user_cookie(email)
        user_obj = self.userdb.get_user_by_mail(email, raise_on_missing=True)
        if not user_obj:
            logging.error("User {!s} not found in database {!r}. Users:".format(email, self.userdb))
            for this in self.userdb._get_all_userdocs():
                this_user = OldUser(this)
                logging.debug("  User: {!s}".format(this_user))
        # user only exists in eduid-userdb, so need to clear modified-ts to be able
        # to save it to eduid-dashboard.profiles
        user_obj.set_modified_ts(None)
        dummy = DummyRequest()
        dummy.session = {
            'eduPersonAssurance': loa(3),
            'eduPersonIdentityProofing': loa(3),
        }
        store_session_user(dummy, user_obj)
        # XXX ought to set self.user = user_obj
        self.logged_in_user = self.userdb_new.get_user_by_id(user_obj.get_id())
        dummy.session.update(extra_session_data)
        request = self.add_to_session(dummy.session)
        return request

    def set_user_cookie(self, user_id):
        request = TestRequest.blank('', {})
        request.registry = self.testapp.app.registry
        remember_headers = remember(request, user_id)
        cookie_value = remember_headers[0][1].split('"')[1]
        self.testapp.set_cookie('auth_tkt', cookie_value)
        return request

    def add_to_session(self, data):
        # Log warning since we're moving away from direct request.session access
        logger.warning('Add to session called with data: {!r}'.format(data))
        queryUtility = self.testapp.app.registry.queryUtility
        session_factory = queryUtility(ISessionFactory)
        request = self.dummy_request()
        session = session_factory(request)
        for key, value in data.items():
            session[key] = value
        session.persist()
        self.testapp.set_cookie(self.settings['session.key'], session._session.token)
        return request

    def check_values(self, fields, values, ignore_not_found=[]):
        for field in fields:
            if field.attrs['type'] == 'checkbox':
                # A webtest.app.Checkbox only has a value if it is checked (!)
                old_status = field.checked
                field.checked = True
                if field.value in values:
                    logger.debug("Checked checkbox {!r} (value {!r})".format(field.id, field.value))
                    values.remove(field.value)
                else:
                    # restore the checkbox whose value was not found in values
                    field.checked = False
        values = [x for x in values if x not in ignore_not_found]
        self.assertEqual(values, [], "Failed checking one or more checkboxes: {!r}".format(values))

    def values_are_checked(self, fields, values):
        checked = [f.value for f in fields if f.value is not None]

        self.assertEqual(values, checked)

    def sync_user_from_dashboard_to_userdb(self, user_id, old_format = True):
        """
        When there is no eduid-dashboard-amp Attribute Manager plugin loaded to
        sync users from dashboard to userdb, this crude function can do it.

        :param user_id: User id
        :param old_format: Write in old format to userdb

        :type user_id: ObjectId
        :type old_format: bool
        :return:
        """
        user = self.dashboard_db.get_user_by_id(user_id)
        logger.debug('Syncing user {!s} from dashboard to userdb'.format(user))
        test_doc = {'_id': user_id}
        user_doc = user.to_dict(old_userdb_format=old_format)
        # Fixups to turn the DashboardUser into a User
        del user_doc['terminated']
        self.userdb_new._coll.update(test_doc, user_doc, upsert=False)
Example #42
0
class FunctionalTests(unittest.TestCase):
    """
    these tests are functional tests to check functionality of the whole app

    they also serve to get coverage for 'main'
    """
    def setUp(self):
        my_settings = {
            'sqlalchemy.url': 'sqlite://',
            'available_languages': 'da de en es fr'
        }
        # mock, not even used!?
        #from sqlalchemy import engine_from_config
        #engine = engine_from_config(my_settings)

        from c3sintent import main
        app = main({}, **my_settings)
        from webtest import TestApp
        self.testapp = TestApp(app)

    def tearDown(self):
        # maybe I need to check and remove globals here,
        # so the other tests are not compromised
        #del engine
        from c3sintent.models import DBSession
        DBSession.remove()

    def test_base_template(self):
        """load the front page, check string exists"""
        res = self.testapp.get('/', status=200)
        self.failUnless('Cultural Commons Collecting Society' in res.body)
        self.failUnless(
            'Copyright 2012, OpenMusicContest.org e.V.' in res.body)

    def test_lang_en_LOCALE(self):
        """load the front page, forced to english (default pyramid way),
        check english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/?_LOCALE_=en', status=200)
        self.failUnless('When we' in res.body)

    def test_lang_en(self):
        """load the front page, set to english (w/ pretty query string),
        check english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/?en', status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        self.failUnless('When we' in res1.body)

# so let's test the app's obedience to the language requested by the browser
# i.e. will it respond to http header Accept-Language?

    def test_accept_language_header_da(self):
        """check the http 'Accept-Language' header obedience: danish
        load the front page, check danish string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/',
                               status=200,
                               headers={'Accept-Language': 'da'})
        #print(res.body) #  if you want to see the pages source
        self.failUnless(
            '<input type="hidden" name="_LOCALE_" value="da"' in res.body)

    def test_accept_language_header_de_DE(self):
        """check the http 'Accept-Language' header obedience: german
        load the front page, check german string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/',
                               status=200,
                               headers={'Accept-Language': 'de-DE'})
        #print(res.body) #  if you want to see the pages source
        self.failUnless('zum geplanten Beitritt' in res.body)
        self.failUnless(
            '<input type="hidden" name="_LOCALE_" value="de"' in res.body)

    def test_accept_language_header_en(self):
        """check the http 'Accept-Language' header obedience: english
        load the front page, check english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/',
                               status=200,
                               headers={'Accept-Language': 'en'})
        #print(res.body) #  if you want to see the pages source
        self.failUnless(
            'You have to be a composer, lyricist, musician, music producer, ' +
            'remixer or DJ' in res.body)

    def test_accept_language_header_es(self):
        """check the http 'Accept-Language' header obedience: spanish
        load the front page, check spanish string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/',
                               status=200,
                               headers={'Accept-Language': 'es'})
        #print(res.body) #  if you want to see the pages source
        self.failUnless('Luego de enviar el siguiente formulario,' in res.body)

    def test_accept_language_header_fr(self):
        """check the http 'Accept-Language' header obedience: french
        load the front page, check french string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/',
                               status=200,
                               headers={'Accept-Language': 'fr'})
        #print(res.body) #  if you want to see the pages source
        self.failUnless(
            'En envoyant un courriel à [email protected] vous pouvez' in res.body)

    def test_no_cookies(self):
        """load the front page, check default english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/',
                               status=200,
                               headers={'Accept-Language':
                                        'af, cn'})  # ask for missing languages
        #print res.body
        self.failUnless('Declaration' in res.body)

#############################################################################
# check for validation stuff

    def test_form_lang_en_non_validating(self):
        """load the join form, check english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/?_LOCALE_=en', status=200)
        form = res.form
        #print(form.fields)
        #print(form.fields.values())
        form['firstname'] = 'John'
        form['address2'] = 'some address part'
        res2 = form.submit('submit')
        self.failUnless(
            'There was a problem with your submission' in res2.body)

    def test_form_lang_de(self):
        """load the join form, check german string exists"""
        res = self.testapp.get('/?de', status=302)
        #print(res)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res2 = res.follow()
        # test for german translation of template text (lingua_xml)
        self.failUnless('Bei Antragstellung zur Zulassung als' in res2.body)
        # test for german translation of form field label (lingua_python)
        self.failUnless('Texter' in res2.body)

    def test_form_lang_LOCALE_de(self):
        """load the join form in german, check german string exists
        this time forcing german locale the pyramid way
        """
        res = self.testapp.get('/?_LOCALE_=de', status=200)
        # test for german translation of template text (lingua_xml)
        self.failUnless('Bei Antragstellung zur Zulassung als' in res.body)
        # test for german translation of form field label (lingua_python)
        self.failUnless('Texter' in res.body)

###########################################################################
# checking the disclaimer

    def test_disclaimer_en(self):
        """load the disclaimer in english (via query_string),
        check english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/disclaimer?en', status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        self.failUnless(
            'you may order your data to be deleted at any time'
            in str(res1.body), 'expected string was not found in web UI')

    def test_disclaimer_de(self):
        """load the disclaimer in german (via query_string),
        check german string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/disclaimer?de', status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        self.failUnless(
            'Die mit der Absichtserklärung zum geplanten Beitritt der'
            in str(res1.body), 'expected string was not found in web UI')

    def test_disclaimer_LOCALE_en(self):
        """load the disclaimer in english, check english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/disclaimer?_LOCALE_=en', status=200)
        self.failUnless(
            'you may order your data to be deleted at any time'
            in str(res.body), 'expected string was not found in web UI')

    def test_disclaimer_LOCALE_de(self):
        """load the disclaimer in german, check german string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/disclaimer?_LOCALE_=de', status=200)
        self.failUnless(
            'Die mit der Absichtserklärung zum geplanten Beitritt der'
            in str(res.body), 'expected string was not found in web UI')
Example #43
0
class TestApiViews(unittest.TestCase):
    """
    Tests the ApiViews class.
    """

    def setUp(self):
        my_settings = {
            'sqlalchemy.url': 'sqlite:///:memory:',
            'api_auth_token': u"SECRETAUTHTOKEN",
        }
        self.config = testing.setUp()
        app = main({}, **my_settings)
        # set up the database
        engine = engine_from_config(my_settings)
        DBSession.configure(bind=engine)
        Base.metadata.create_all(engine)
        with transaction.manager:
            member1 = C3sMember(  # german
                firstname=u'SomeFirstnäme',
                lastname=u'SomeLastnäme',
                email=u'*****@*****.**',
                address1=u"addr one",
                address2=u"addr two",
                postcode=u"12345",
                city=u"Footown Mäh",
                country=u"Foocountry",
                locale=u"de",
                date_of_birth=date.today(),
                email_is_confirmed=False,
                email_confirm_code=u'ABCDEFGFOO',
                password=u'arandompassword',
                date_of_submission=date.today(),
                membership_type=u'normal',
                member_of_colsoc=True,
                name_of_colsoc=u"GEMA",
                num_shares=u'23',
            )
        # pylint: disable=no-member
        DBSession.add(member1)
        member1.email_invite_token_bcgv18 = u'MEMBERS_TOKEN'
        # pylint: disable=no-member
        DBSession.flush()

        self.testapp = TestApp(app)

    def tearDown(self):
        testing.tearDown()
        # pylint: disable=no-member
        DBSession.close()
        DBSession.remove()

    def test_api_userinfo(self):
        """
        Test the api_userinfo service.

        * must be a PUT, not a GET request
        * the auth header must be present
        * returns None if members refcode does not match
        * returns firstname, lastname, email, membership type
        """
        # try a GET -- must fail
        res = self.testapp.get('/lm', status=405)
        self.assertTrue('405 Method Not Allowed' in res.body)
        self.assertTrue('The method GET is not allowed for this resource.'
                        in res.body)

        # try a PUT -- fails under certain conditions
        with self.assertRaises(ValueError):
            res = self.testapp.put('/lm', status=200)
            # ValueError: No JSON object could be decoded

        # try a PUT -- fails under certain conditions
        with self.assertRaises(KeyError):
            res = self.testapp.put_json(
                '/lm', dict(id=1))  # status=200)
            # KeyError: 'token'
        # missing auth token -- must fail
        with self.assertRaises(KeyError):
            res = self.testapp.put_json(
                '/lm', dict(token=1))  # status=200)
            # KeyError: 'HTTP_X_MESSAGING_TOKEN'

        # try false auth token -- must fail: 401 unauthorized
        _headers = {'X-messaging-token': 'bar'}
        res = self.testapp.put_json(
            '/lm', dict(token=1), headers=_headers, status=401)

        # now use the correct auth token
        _auth_info = {'X-messaging-token': 'SECRETAUTHTOKEN'}

        # ..but a non-existing refcode (email_invite_token_bcgv18)
        # returns no user (None)
        res = self.testapp.put_json(
            '/lm', dict(token='foo'), headers=_auth_info, status=200)
        # body: {"lastname": "None", "firstname": "None"}
        self.assertTrue(json.loads(res.body)['firstname'], "None")
        self.assertTrue(json.loads(res.body)['lastname'], "None")

        self.testapp.reset()

        member1 = C3sMember.get_by_id(1)  # load member from DB for crosscheck

        # now try a valid refcode (email_invite_token_bcgv18)
        res2 = self.testapp.put_json(
            '/lm', dict(token=member1.email_invite_token_bcgv18),
            headers=_auth_info, status=200)
        self.assertTrue(json.loads(res2.body)['firstname'], member1.firstname)
        self.assertTrue(json.loads(res2.body)['lastname'], member1.lastname)
        self.assertTrue(json.loads(res2.body)['email'], member1.email)
        self.assertTrue(json.loads(res2.body)['mtype'], member1.membership_type)
Example #44
0
class NewMemberTests(unittest.TestCase):
    """
    test creation of a new member by staff

    these tests are functional tests to check functionality of the whole app
    (i.e. integration tests)
    they also serve to get coverage for 'main'
    """
    def setUp(self):
        self.config = testing.setUp()
        self.config.include('pyramid_mailer.testing')
        try:
            DBSession.close()
            DBSession.remove()
            # print "closed and removed DBSession"
        except:
            pass
            # print "no session to close"
        # self.session = DBSession()
        my_settings = {
            'sqlalchemy.url': 'sqlite:///:memory:',
            'available_languages': 'da de en es fr',
            'c3smembership.dashboard_number': '30'}
        engine = engine_from_config(my_settings)
        DBSession.configure(bind=engine)
        Base.metadata.create_all(engine)

        with transaction.manager:
            # a group for accountants/staff
            accountants_group = Group(name=u"staff")
            try:
                DBSession.add(accountants_group)
                DBSession.flush()
            except:
                pass
            # staff personnel
            staffer1 = C3sStaff(
                login=u"rut",
                password=u"berries",
                email=u"*****@*****.**",
            )
            staffer1.groups = [accountants_group]
            try:
                DBSession.add(accountants_group)
                DBSession.add(staffer1)
                DBSession.flush()
            except:
                # print("it borked! (rut)")
                pass

        from c3smembership import main
        app = main({}, **my_settings)
        from webtest import TestApp
        self.testapp = TestApp(app)

    def tearDown(self):
        DBSession.close()
        DBSession.remove()
        testing.tearDown()

    def test_add_member(self):
        '''
        tests for the new_member view
        '''
        # unauthorized access must be prevented
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/new_member', status=403)
        assert('Access was denied to this resource' in res.body)
        # so login first
        res = self.testapp.get('/login', status=200)
        self.failUnless('login' in res.body)
        # try valid user
        form = res.form
        form['login'] = '******'
        form['password'] = '******'
        res2 = form.submit('submit', status=302)
        # # being logged in ...
        res3 = res2.follow()  # being redirected to dashboard_only
        self.failUnless(
            'Dashboard' in res3.body)
        # # now that we are logged in,
        # # the login view should redirect us to the dashboard
        # res5 = self.testapp.get('/login', status=302)
        # # so yes: that was a redirect
        # res6 = res5.follow()
        # res6 = res6.follow()
        # # print(res4.body)
        # self.failUnless(
        #     'Dashboard' in res6.body)
        # # choose number of applications shown
        # res6a = self.testapp.get(
        #     '/dashboard',
        #     status=302,
        #     extra_environ={
        #         'num_display': '30',
        #     }
        # )
        # res6a = res6a.follow()

        # no member with id=1 in DB
        res = self.testapp.get('/new_member?id=1', status=200)

        form = res.form
        # print form.fields
        form['firstname'] = u'SomeFirstname'
        form['lastname'] = u'SomeLastname'
        form['email'] = u'*****@*****.**'
        form['address1'] = u"addr one"
        form['address2'] = u"addr two"
        form['postcode'] = u"12345"
        form['city'] = u"Footown Meeh"
        form['country'].value__set(u"DE")
        form['_LOCALE_'] = u"DE"
        form['date_of_birth'] = '1014-01-01'  # date.today(),
        # form['email_is_confirmed=False,
        # email_confirm_code=u'ABCDEFGFOO',
        # password=u'arandompassword',
        # date_of_submission=date.today(),
        # form['membership_type'] = u'normal',
        form['entity_type'].value__set(u'person')
        form['membership_type'].value__set(u'normal')
        # form['other_colsoc'] = (u'no',),
        form['other_colsoc'].value__set(u'no')

        form['name_of_colsoc'] = u"GEMA"
        form['num_shares'] = u'23'

        # try to submit the form (knowing that the date is missing)
        res2 = form.submit(u'submit', status=200)
        form2 = res2.form
        # set the date to a usefull/allowed value
        form2['date_of_birth'] = u'1999-09-19'
        res3 = form2.submit(u'submit', status=302)
        res4 = res3.follow()
        # print res4
        self.assertTrue('Details for Member Application #1' in res4.body)

        # more asserts
        self.assertTrue('SomeFirstname' in res4.body)
        self.assertTrue('SomeLastname' in res4.body)
        self.assertTrue('*****@*****.**' in res4.body)
        self.assertTrue('addr one' in res4.body)
        self.assertTrue('addr two' in res4.body)
        self.assertTrue('12345' in res4.body)
        self.assertTrue('' in res4.body)
        self.assertTrue('DE' in res4.body)
        self.assertTrue('normal' in res4.body)
        self.assertTrue('23' in res4.body)
        #        self.assertTrue('' in res3.body)
        #        self.assertTrue('' in res3.body)
        #        self.assertTrue('' in res3.body)
        #        self.assertTrue('' in res3.body)

        # now, there is a member with id=1 in DB
        res = self.testapp.get('/new_member?id=1', status=200)

        form = res.form
        # print form.fields
        form['firstname'] = u'SomeFirstname'
        form['lastname'] = u'SomeLastname'
        form['email'] = u'*****@*****.**'
        form['address1'] = u"addr one"
        form['address2'] = u"addr two"
        form['postcode'] = u"12345"
        form['city'] = u"Footown Meeh"
        form['country'].value__set(u"DE")
        form['_LOCALE_'] = u"DE"
        form['date_of_birth'] = date.today()
        # form['email_is_confirmed=False,
        # email_confirm_code=u'ABCDEFGFOO',
        # password=u'arandompassword',
        # date_of_submission=date.today(),
        form['entity_type'] = u'person'
        form['membership_type'] = u'normal'
        # form['membership_type'].value__set(u'normal')
        # form['other_colsoc'] = (u'no',),
        form['other_colsoc'].value__set(u'no')

        form['name_of_colsoc'] = u"GEMA"
        form['num_shares'] = u'23'

        # try to submit the form (knowing that the date is missing)
        res2 = form.submit(u'submit', status=200)
        form2 = res2.form
        form2['date_of_birth'] = u'1999-09-19'
        res3 = form2.submit(u'submit', status=302)
        res4 = res3.follow()
        # print res4
        self.assertTrue('Details for Member Application #2' in res4.body)

        # more asserts
        self.assertTrue('SomeFirstname' in res4.body)
        self.assertTrue('SomeLastname' in res4.body)
        self.assertTrue('*****@*****.**' in res4.body)
        self.assertTrue('addr one' in res4.body)
        self.assertTrue('addr two' in res4.body)
        self.assertTrue('12345' in res4.body)
        self.assertTrue('' in res4.body)
        self.assertTrue('DE' in res4.body)
        self.assertTrue('normal' in res4.body)
        self.assertTrue('23' in res4.body)

        # no member with id=1 in DB
        res = self.testapp.get('/new_member', status=200)

        form = res.form
        # print form.fields
        form['firstname'] = u'SomeFirstname'
        form['lastname'] = u'SomeLastname'
        form['email'] = u'*****@*****.**'
        form['address1'] = u"addr one"
        form['address2'] = u"addr two"
        form['postcode'] = u"12345"
        form['city'] = u"Footown Meeh"
        form['country'].value__set(u"DE")
        form['_LOCALE_'] = u"DE"
        form['date_of_birth'] = date.today()
        # form['email_is_confirmed=False,
        # email_confirm_code=u'ABCDEFGFOO',
        # password=u'arandompassword',
        # date_of_submission=date.today(),
        form['entity_type'] = u'person'
        form['membership_type'] = u'normal'
        # form['deformField14'].value__set(u'normal')
        # form['other_colsoc'] = (u'no',),
        form['other_colsoc'].value__set(u'no')

        form['name_of_colsoc'] = u"GEMA"
        form['num_shares'] = u'23'

        # try to submit the form (knowing that the date is missing)
        res2 = form.submit(u'submit', status=200)
        form2 = res2.form
        form2['date_of_birth'] = u'1999-09-19'

        res3 = form2.submit(u'submit', status=302)
        res4 = res3.follow()
        # print res4
        self.assertTrue('Details for Member Application #3' in res4.body)

        # more asserts
        self.assertTrue('SomeFirstname' in res4.body)
        self.assertTrue('SomeLastname' in res4.body)
        self.assertTrue('*****@*****.**' in res4.body)
        self.assertTrue('addr one' in res4.body)
        self.assertTrue('addr two' in res4.body)
        self.assertTrue('12345' in res4.body)
        self.assertTrue('' in res4.body)
        self.assertTrue('DE' in res4.body)
        self.assertTrue('normal' in res4.body)
        self.assertTrue('23' in res4.body)

        # check the number of entries in the DB
        num = C3sMember.get_number()
        # print num
        self.assertTrue(num == 3)

        '''
        now add a legal entity / aka Körperschaft
        '''
        res = self.testapp.get('/new_member', status=200)

        form = res.form
        # print form.fields
        form['firstname'] = u'SomeLegalentity'
        form['lastname'] = u'SomeLegalName'
        form['email'] = u'*****@*****.**'
        form['address1'] = u"addr one"
        form['address2'] = u"addr two"
        form['postcode'] = u"12345"
        form['city'] = u"Footown Meeh"
        form['country'].value__set(u"DE")
        form['_LOCALE_'] = u"DE"
        form['date_of_birth'] = date.today()
        # form['email_is_confirmed=False,
        # email_confirm_code=u'ABCDEFGFOO',
        # password=u'arandompassword',
        # date_of_submission=date.today(),
        form['entity_type'] = u'legalentity'
        form['membership_type'] = u'investing'
        # form['deformField14'].value__set(u'normal')
        # form['other_colsoc'] = (u'no',),
        form['other_colsoc'].value__set(u'no')

        form['name_of_colsoc'] = u""
        form['num_shares'] = u'42'

        # try to submit the form (knowing that the date is missing)
        res2 = form.submit(u'submit', status=200)
        form2 = res2.form
        form2['date_of_birth'] = u'1999-09-19'

        res3 = form2.submit(u'submit', status=302)
        res4 = res3.follow()
        # print res4
        self.assertTrue('Details for Member Application #4' in res4.body)

        # more asserts
        self.assertTrue('SomeLegalentity' in res4.body)
        self.assertTrue('SomeLegalName' in res4.body)
        self.assertTrue('*****@*****.**' in res4.body)
        self.assertTrue('addr one' in res4.body)
        self.assertTrue('addr two' in res4.body)
        self.assertTrue('12345' in res4.body)
        self.assertTrue('' in res4.body)
        self.assertTrue('DE' in res4.body)
        self.assertTrue('investing' in res4.body)
        self.assertTrue('23' in res4.body)

        # check the number of entries in the DB
        num = C3sMember.get_number()
        # print num
        self.assertTrue(num == 4)
Example #45
0
class TestApi(unittest.TestCase):

    bad_credentials = {'email': '*****@*****.**',
                       'password': '******'}

    # Please use valid credentials and targets
    good_credentials = {'email': '*****@*****.**',
                        'password': '******',
                        'pubKey': cjson.encode({'algorithm': 'HS256',
                                              'keydata': 'J RANDOM KEY'})}

    default_params = {'sid': '123abc',
                       'output': 'json',
                       'audience': 'test.example.com'}

    user_info = {'uid': 'test_api_1',
                 'pemail': '*****@*****.**',
                 'emails': {'*****@*****.**': {'state': 'verified'},
                            '*****@*****.**': {'state': 'pending'}}
                }

    ## API Entry points:
    #  get_certificate x
    #  refresh_certificate x
    #  validate/....
    #
    ## Admin entry points
    #  verify_address
    #

    ## beaker is being stupid and overwriting session information
    beaker_is_being_stupid = True

    extra_environ = {'beaker.session': {'uid': 'test_api_1'}}
    session = {}

    def setUp(self, **kw):
        # use a default 'dummy' config file.
        config = {
            'oidstorage.backend': 'oidserver.storage.memory.MemoryStorage',
            'oid.host': 'http://*****:*****@example.org',
             'oid.reply_to': '*****@*****.**',
             'oid.admin_page': True,
             'oid.login_host': 'http://*****:*****@example.org', 'act': 'add'}
        params.update(test_info)
        path = '/%s/manage_email' % VERSION
        response = self.app.post(path,
                      params = params,
                      extra_environ = self.extra_environ,
                      status = 200
                      )
        user = storage.get_user_info(self.user_info.get('uid'))
        ## pull the confirmation code
        conf_code = \
            user.get('emails').get(test_info['email']).get('conf_code')
        params = self.default_params.copy()
        path = ('/%s/validate/' % VERSION) + conf_code
        response = self.app.get(path,
                                 params = params,
                                 extra_environ = self.extra_environ,
                                 status = 200)
        self.failIf('<meta name="page" content="conf_email" />' not in
            response.body)
        user = storage.get_user_info(self.user_info.get('uid'))
        self.failIf(test_info['email'] not in user.get('emails'))
        self.failIf(user['emails'][test_info['email']].get('state') \
                    != 'verified')

    def test_debug(self):
        resp = self.app.get('/__debug__',
                     status = 200)
        self.failIf('Debug information' not in resp.body)

    def test_get_certificate(self):
        """ First part of the sync dance. """
        self.setUp()
        # get the list of valid emails
        storage = self.app.app.wrap_app.app.storage
        uid = self.user_info.get('uid')
        validEmails = storage.get_addresses(uid, 'verified')
        self.failUnless(self.good_credentials.get('email') in validEmails)
        # verify that the good email address is present.
        path = '/%s/get_certificate' % VERSION
        params = self.default_params.copy()
        params.update({'id': validEmails[0],
                       'pubkey': self.good_credentials.get('pubKey'),
                       'output': 'html'})
        response = self.app.post(path,
                                 params = params,
                                 status = 200)
        self.failUnless("navigator.id.registerVerifiedEmailCertificate" in
                        response.body)
        self.failUnless('"success": true' in response.body)
        self.purge_db()

    def test_heartbeat(self):
        self.app.get('/__heartbeat__',
                     status = 200)

    def test_login(self):
        #page should return 302 (not 307)
        self.setUp()
        self.purge_db()
        params = self.default_params.copy()

        params.update({'id': self.good_credentials.get('email'),
                       'password': self.good_credentials.get('password')})
        params.update({'output': 'html'})
        path = '/%s/login' % VERSION
        self.app.post(path,
                            params
                            )
#        self.failIf(self.user_info.get('pemail') not in response.body)

    def skip_login_bad(self):
        self.setUp()
        params = self.default_params.copy()
        params.update(self.bad_credentials)
        path = '/%s/login' % VERSION
        response = self.app.post(path, params = params)
        resp_obj = cjson.decode(response.body)
        self.check_default(resp_obj, path)
        self.failIf(resp_obj['error']['code'] != 401)

    def test_logout(self):
        self.setUp()
        path = "/%s/logout" % VERSION
        request = FakeRequest()
        request.remote_addr = "127.0.0.1"
        signature = self.app.app.wrap_app.app.\
                    controllers['auth'].gen_signature(
                        self.user_info.get('uid'),
                        request)
        params = self.default_params.copy()
        params.update({'sig': signature})

        self.app.get(path,
                    params = params,
                    extra_environ = self.extra_environ)

    def test_random(self):
        path = "/%s/random" % VERSION
        params = self.default_params.copy()
        response = self.app.get(path,
                                 params = params)
        resp_obj = cjson.decode(response.body)
        self.failUnless('random' in resp_obj)
        self.failUnless(type(resp_obj['random']).__name__ == 'list' )

    def test_refresh_certificate(self):
        """ attempt to refresh a given certificate """
        self.setUp()
        path = '/%s/refresh_certificate/%s' % (VERSION,
                                        quote(self.user_info.get('pemail')))
        response = self.app.get(path)
        self.failUnless('success' in response.body)
        self.failUnless('registerVerifiedEmails' in response.body)
        path = '/%s/refresh_certificate' % (VERSION)
        response = self.app.get(path)
        self.failUnless('success' in response.body)
        self.failUnless('registerVerifiedEmails' in response.body)
        self.purge_db()

    def test_registered_emails(self):
        """ Return a list of emails associated with the user. """
        self.setUp()
        request = FakeRequest()
        request.remote_addr = '127.0.0.1'
        path = '/%s/register' % VERSION
        response = self.app.get(path,
                                status = 200)
        self.failUnless('navigator.id.registerVerifiedEmail'
                        in response.body)
        self.failUnless(self.good_credentials.get('email') in response.body)
        # get_certificate tested elsewhere.
        self.purge_db()
Example #46
0
class SharesTests(unittest.TestCase):
    """
    these tests are functional tests to check functionality of the whole app
    (i.e. integration tests)
    they also serve to get coverage for 'main'
    """
    def setUp(self):
        self.config = testing.setUp()
        self.config.include('pyramid_mailer.testing')
        try:
            DBSession.close()
            DBSession.remove()
            # print "closed and removed DBSession"
        except:
            pass
            # print "no session to close"
        my_settings = {
            'sqlalchemy.url': 'sqlite:///:memory:',
            'available_languages': 'da de en es fr',
            'c3smembership.dashboard_number': '30'
        }
        engine = engine_from_config(my_settings)
        DBSession.configure(bind=engine)
        Base.metadata.create_all(engine)

        with transaction.manager:
            # a group for accountants/staff
            accountants_group = Group(name=u"staff")
            try:
                DBSession.add(accountants_group)
                DBSession.flush()
                # print("adding group staff")
            except:
                # print("could not add group staff.")
                pass
            # staff personnel
            staffer1 = C3sStaff(
                login=u"rut",
                password=u"berries",
                email=u"*****@*****.**",
            )
            staffer1.groups = [accountants_group]
            try:
                DBSession.add(accountants_group)
                DBSession.add(staffer1)
                DBSession.flush()
            except:
                # print("it borked! (rut)")
                pass

        from c3smembership import main
        app = main({}, **my_settings)
        from webtest import TestApp
        self.testapp = TestApp(app)

    def tearDown(self):
        DBSession.close()
        DBSession.remove()
        testing.tearDown()

    def make_member_with_shares(self):
        with transaction.manager:
            member1 = C3sMember(  # german
                firstname=u'SomeFirstnäme',
                lastname=u'SomeLastnäme',
                email=u'*****@*****.**',
                address1=u"addr one",
                address2=u"addr two",
                postcode=u"12345",
                city=u"Footown Mäh",
                country=u"Foocountry",
                locale=u"DE",
                date_of_birth=date.today(),
                email_is_confirmed=False,
                email_confirm_code=u'ABCDEFGFOO',
                password=u'arandompassword',
                date_of_submission=date.today(),
                membership_type=u'normal',
                member_of_colsoc=True,
                name_of_colsoc=u"GEMA",
                num_shares=u'23',
            )
            shares1 = Shares(
                number=2,
                date_of_acquisition=date.today(),
                reference_code=u'ABCDEFGH',
                signature_received=True,
                signature_received_date=date(2014, 6, 7),
                payment_received=True,
                payment_received_date=date(2014, 6, 8),
                signature_confirmed=True,
                signature_confirmed_date=date(2014, 6, 8),
                payment_confirmed=True,
                payment_confirmed_date=date(2014, 6, 9),
                accountant_comment=u'no comment',
            )
            member1.shares = [shares1]
            shares2 = Shares(
                number=23,
                date_of_acquisition=date.today(),
                reference_code=u'IJKLMNO',
                signature_received=True,
                signature_received_date=date(2014, 1, 7),
                payment_received=True,
                payment_received_date=date(2014, 1, 8),
                signature_confirmed=True,
                signature_confirmed_date=date(2014, 1, 8),
                payment_confirmed=True,
                payment_confirmed_date=date(2014, 1, 9),
                accountant_comment=u'not connected',
            )

        DBSession.add(member1)
        DBSession.add(shares1)
        DBSession.add(shares2)

    def make_member_with_shares2(self):
        with transaction.manager:
            member1 = C3sMember(  # german
                firstname=u'SomeFirstnäme',
                lastname=u'SomeLastnäme',
                email=u'*****@*****.**',
                address1=u"addr one",
                address2=u"addr two",
                postcode=u"12345",
                city=u"Footown Mäh",
                country=u"Foocountry",
                locale=u"DE",
                date_of_birth=date.today(),
                email_is_confirmed=False,
                email_confirm_code=u'ABCDEFGFOO',
                password=u'arandompassword',
                date_of_submission=date.today(),
                membership_type=u'normal',
                member_of_colsoc=True,
                name_of_colsoc=u"GEMA",
                num_shares=u'23',
            )
            shares1 = Shares(
                number=2,
                date_of_acquisition=date.today(),
                reference_code=u'ABCDEFGH',
                signature_received=True,
                signature_received_date=date(2014, 6, 7),
                payment_received=True,
                payment_received_date=date(2014, 6, 8),
                signature_confirmed=True,
                signature_confirmed_date=date(2014, 6, 8),
                payment_confirmed=True,
                payment_confirmed_date=date(2014, 6, 9),
                accountant_comment=u'no comment',
            )
            member1.shares = [shares1]
        DBSession.add(member1)
        DBSession.add(shares1)

    def make_unconnected_shares(self):
        with transaction.manager:
            shares2 = Shares(
                number=23,
                date_of_acquisition=date.today(),
                reference_code=u'IJKLMNO',
                signature_received=True,
                signature_received_date=date(2014, 1, 7),
                payment_received=True,
                payment_received_date=date(2014, 1, 8),
                signature_confirmed=True,
                signature_confirmed_date=date(2014, 1, 8),
                payment_confirmed=True,
                payment_confirmed_date=date(2014, 1, 9),
                accountant_comment=u'not connected',
            )
        DBSession.add(shares2)

    def test_shares_detail(self):
        '''
        tests for the shares_detail view
        '''
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/shares_edit/1', status=403)
        assert ('Access was denied to this resource' in res.body)
        res = self.testapp.get('/login', status=200)
        self.failUnless('login' in res.body)
        # try valid user
        form = res.form
        form['login'] = '******'
        form['password'] = '******'
        res2 = form.submit('submit', status=302)
        # # being logged in ...
        # print('>'*20)
        # print(res3.body)
        # print('<'*20)
        res3 = res2.follow()  # being redirected to dashboard with parameters
        self.failUnless('Dashboard' in res3.body)
        # now look at a shares package
        res = self.testapp.get('/shares_detail/1', status=302)
        res2 = res.follow()
        # we were redirected to the menberships list
        # because the shares package did not exist
        self.assertTrue(
            'This shares id was not found in the database!' in res2.body)
        self.assertTrue('Toolbox' in res2.body)

        self.make_member_with_shares()

        # now look at a shares package
        res = self.testapp.get('/shares_detail/1', status=200)
        self.assertTrue('<h1>Details for Shares #1</h1>' in res.body)
        self.assertTrue('1: SomeFirstnäme SomeLastnäme' in res.body)
        self.assertTrue('ABCDEFGH' in res.body)

    def test_shares_edit(self):
        '''
        tests for the shares_edit view
        '''
        # unauthorized access must be prevented
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/shares_edit/1', status=403)
        assert ('Access was denied to this resource' in res.body)
        res = self.testapp.get('/login', status=200)
        self.failUnless('login' in res.body)
        # try valid user
        form = res.form
        form['login'] = u'rut'
        form['password'] = u'berries'
        res2 = form.submit('submit', status=302)
        # # being logged in ...
        res3 = res2.follow()  # being redirected to dashboard with parameters
        self.failUnless('Dashboard' in res3.body)

        # no member in DB, so redirecting to dashboard
        res = self.testapp.get('/shares_edit/1', status=302)
        res2 = res.follow()

        self.make_member_with_shares()

        # now there is a member with shares in the DB
        #
        # lets try invalid input
        res = self.testapp.get('/shares_edit/foo', status=302)
        res2 = res.follow()
        self.failUnless('Dashboard' in res2.body)

        # now try valid id
        res = self.testapp.get('/shares_edit/1', status=200)
        self.failUnless('Edit Details for Shares' in res.body)

        # now we change details, really editing that member
        form = res.form

        if DEBUG:
            print "form.fields: {}".format(form.fields)

        self.assertTrue('2' in form['number'].value)
        self.assertTrue(datetime.today().strftime('%Y-%m-%d') in
                        form['date_of_acquisition'].value)
        # print(form['date_of_acquisition'].value)
        form['number'] = u'3'
        form['date_of_acquisition'] = u'2015-01-02'

        # try to submit now. this must fail,
        # because the date of birth is wrong
        # ... and other dates are missing
        res2 = form.submit('submit', status=200)

        # check data in DB
        _m1 = C3sMember.get_by_id(1)
        self.assertTrue(_m1.shares[0].number is 3)
        self.assertTrue(
            str(_m1.shares[0].date_of_acquisition) in str(datetime(2015, 1,
                                                                   2)))

    def test_shares_delete(self):
        '''
        tests for the shares_delete view
        '''
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/shares_edit/1', status=403)
        assert ('Access was denied to this resource' in res.body)
        res = self.testapp.get('/login', status=200)
        self.failUnless('login' in res.body)
        # try valid user
        form = res.form
        form['login'] = '******'
        form['password'] = '******'
        res2 = form.submit('submit', status=302)
        # # being logged in ...
        # print('>'*20)
        # print(res3.body)
        # print('<'*20)
        res3 = res2.follow()  # being redirected to dashboard with parameters
        self.failUnless('Dashboard' in res3.body)

        self.make_member_with_shares()

        # now look at a shares package
        res = self.testapp.get('/shares_detail/1', status=200)
        self.assertTrue('<h1>Details for Shares #1</h1>' in res.body)
        self.assertTrue('1: SomeFirstnäme SomeLastnäme' in res.body)
        self.assertTrue('ABCDEFGH' in res.body)

        # try to delete a non-existing package
        res = self.testapp.get('/shares_delete/123', status=302)
        res2 = res.follow()
        self.assertTrue(
            'This shares package 123 was not found in the DB.' in res2.body)

        # try to delete an existing package
        res = self.testapp.get('/shares_delete/1', status=302)
        res2 = res.follow()
        self.assertTrue(
            'This shares package 1 still has a member owning it.' in res2.body)
        res = self.testapp.get('/delete/1', status=302)
        res2 = res.follow()

        res = self.testapp.get('/shares_detail/1', status=200)
        self.assertTrue('<h1>Details for Shares #1</h1>' in res.body)
        # self.assertTrue('1: Not Found' in res.body)
        self.assertTrue('ABCDEFGH' in res.body)
Example #47
0
class Test(object):
    def __init__(self):
        self._tmpdir = None
        self._tmproot = None
        self._app = None
        self._starting_dir = os.getcwd()

    # def setUp(self):
    #    assert False
    def populate_conf_directory(self):
        """Populate a directory with valid configuration files, to be run just once
        The files are not modified by each test
        """
        self._tmpdir = os.path.join(self, _tmproot, "cork_functional_test_source")

        # only do this once, as advertised
        if os.path.exists(self._tmpdir):
            return

        os.mkdir(self._tmpdir)
        os.mkdir(self._tmpdir + "/example_conf")

        cork = Cork(os.path.join(self._tmpdir, "example_conf"), initialize=True)

        cork._store.roles["admin"] = 100
        cork._store.roles["editor"] = 60
        cork._store.roles["user"] = 50
        cork._store._savejson("roles", cork._store.roles)

        tstamp = str(datetime.utcnow())
        username = password = "******"
        cork._store.users[username] = {
            "role": "admin",
            "hash": cork._hash(username, password),
            "email_addr": username + "@localhost.local",
            "desc": username + " test user",
            "creation_date": tstamp,
        }
        username = password = ""
        cork._store.users[username] = {
            "role": "user",
            "hash": cork._hash(username, password),
            "email_addr": username + "@localhost.local",
            "desc": username + " test user",
            "creation_date": tstamp,
        }
        cork._store._save_users()

    def remove_temp_dir(self):
        p = os.path.join(self._tmproot, "cork_functional_test_wd")
        for f in glob.glob("%s*" % p):
            # shutil.rmtree(f)
            pass

    @classmethod
    def setUpClass(cls):
        print ("Setup class")

    def setup(self):
        # create test dir and populate it using the example files

        # save the directory where the unit testing has been run
        if self._starting_dir is None:
            self._starting_dir = os.getcwd()

        # create json files to be used by Cork
        self._tmproot = testutils.pick_temp_directory()
        assert self._tmproot is not None

        # purge the temporary test directory
        self.remove_temp_dir()

        self.populate_temp_dir()
        self.create_app_instance()
        self._app.reset()
        print ("Reset done")
        print ("Setup completed")

    def populate_temp_dir(self):
        """populate the temporary test dir"""
        assert self._tmproot is not None
        assert self._tmpdir is None

        tstamp = str(time())[5:]
        self._tmpdir = os.path.join(self._tmproot, "cork_functional_test_wd_%s" % tstamp)

        try:
            os.mkdir(self._tmpdir)
        except OSError:
            # The directory is already there, purge it
            print ("Deleting %s" % self._tmpdir)
            shutil.rmtree(self._tmpdir)
            os.mkdir(self._tmpdir)

            # p = os.path.join(self._tmproot, 'cork_functional_test_wd')
            # for f in glob.glob('%s*' % p):
            #    shutil.rmtree(f)

        # copy the needed files
        shutil.copytree(
            os.path.join(self._starting_dir, "test/example_conf"), os.path.join(self._tmpdir, "example_conf")
        )
        shutil.copytree(os.path.join(self._starting_dir, "test/views"), os.path.join(self._tmpdir, "views"))

        # change to the temporary test directory
        # cork relies on this being the current directory
        os.chdir(self._tmpdir)

        print ("Test directory set up")

    def create_app_instance(self):
        """create TestApp instance"""
        assert self._app is None
        import simple_webapp

        self._bottle_app = simple_webapp.app
        self._app = TestApp(self._bottle_app)
        print ("Test App created")

    def assert_redirect(self, page, redir_page):
        """Assert that a page redirects to another one"""
        p = self._app.get(page, status=302)
        dest = p.location.split(":80/")[-1]
        dest = "/%s" % dest
        assert dest == redir_page, "%s redirects to %s instead of %s" % (page, dest, redir_page)

    def login_as_admin(self):
        """perform log in"""
        assert self._app is not None
        assert "beaker.session.id" not in self._app.cookies, "Unexpected cookie found"
        self.assert_redirect("/admin", "/sorry_page")

        p = self._app.post("/login", {"username": "******", "password": "******"})
        assert p.status == REDIR, "Redirect expected"
        assert p.location == "http://localhost:80/", "Incorrect redirect to %s" % p.location
        print repr(p)

        assert "beaker.session.id" in self._app.cookies, "Cookie not found"

        print "TO", repr(self._bottle_app.session)
        print "TO", dir(self._bottle_app)

        a = self._app.app
        for n in "app", "environ_key", "options", "session", "wrap_app":
            print
            print n
            print "REP", repr(getattr(a, n))
            print "DIR", dir(getattr(a, n))

        import bottle

        session = bottle.request.environ.get("beaker.session")
        print "Session from func. test", repr(session)

        print "running GET myrole"
        p = self._app.get("/my_role")
        print "myrole", repr(p)

        p = self._app.get("/admin")
        print "admin", repr(p)
        assert "Welcome" in p.body, repr(p)

        p = self._app.get("/my_role", status=200)
        assert p.status == "200 OK"
        assert p.body == "admin", "Sta"

        print ("Login performed")

    def teardown(self):
        print ("Doing logout")
        try:
            self._app.post("/logout")
        except:
            pass

        assert self._app.get("/admin").status != "200 OK"
        os.chdir(self._starting_dir)
        # if self._tmproot is not None:
        #    testutils.purge_temp_directory(self._tmproot)

        self._app = None
        self._tmproot = None
        self._tmpdir = None
        print ("Teardown done")

    @SkipTest
    def test_functional_login(self):
        assert self._app
        self._app.get("/admin", status=302)
        self._app.get("/my_role", status=302)

        self.login_as_admin()

        # fetch a page successfully
        r = self._app.get("/admin")
        assert r.status == "200 OK", repr(r)

    def test_login_existing_user_none_password(self):
        p = self._app.post("/login", {"username": "******", "password": None})
        assert p.status == REDIR, "Redirect expected"
        assert p.location == "http://localhost:80/login", "Incorrect redirect to %s" % p.location

    def test_login_nonexistent_user_none_password(self):
        p = self._app.post("/login", {"username": "******", "password": None})
        assert p.status == REDIR, "Redirect expected"
        assert p.location == "http://localhost:80/login", "Incorrect redirect to %s" % p.location

    def test_login_existing_user_empty_password(self):
        p = self._app.post("/login", {"username": "******", "password": ""})
        assert p.status == REDIR, "Redirect expected"
        assert p.location == "http://localhost:80/login", "Incorrect redirect to %s" % p.location

    def test_login_nonexistent_user_empty_password(self):
        p = self._app.post("/login", {"username": "******", "password": ""})
        assert p.status == REDIR, "Redirect expected"
        assert p.location == "http://localhost:80/login", "Incorrect redirect to %s" % p.location

    def test_login_existing_user_wrong_password(self):
        p = self._app.post("/login", {"username": "******", "password": "******"})
        assert p.status == REDIR, "Redirect expected"
        assert p.location == "http://localhost:80/login", "Incorrect redirect to %s" % p.location

    @SkipTest
    def test_functional_login_logout(self):
        # Incorrect login
        p = self._app.post("/login", {"username": "******", "password": "******"})
        assert p.status == REDIR
        assert p.location == "http://localhost:80/login", "Incorrect redirect to %s" % p.location

        # log in and get a cookie
        p = self._app.post("/login", {"username": "******", "password": "******"})
        assert p.status == REDIR
        assert p.location == "http://localhost:80/", "Incorrect redirect to %s" % p.location

        # fetch a page successfully
        assert self._app.get("/admin").status == "200 OK", "Admin page should be served"

        # log out
        assert self._app.get("/logout").status == REDIR

        # drop the cookie
        self._app.reset()
        assert self._app.cookies == {}, "The cookie should be gone"

        # fetch the same page, unsuccessfully
        assert self._app.get("/admin").status == REDIR

    @SkipTest
    def test_functional_user_creation_login_deletion(self):
        assert self._app.cookies == {}, "The cookie should be not set"

        # Log in as Admin
        p = self._app.post("/login", {"username": "******", "password": "******"})
        assert p.status == REDIR
        assert p.location == "http://*****:*****@localhost.local'
    #    })

    #
    def test_functionalxxx(self):
        assert self._app is not None

    def test_functional_expiration(self):
        self.login_as_admin()
        r = self._app.get("/admin")
        assert r.status == "200 OK", repr(r)
        # change the cookie expiration in order to expire it
        self._app.app.options["timeout"] = 0
        assert self._app.get("/admin").status == REDIR, "The cookie should have expired"
Example #48
0
class FunctionalTests(unittest.TestCase):
    """
    these tests are functional tests to check functionality of the whole app
    (i.e. integration tests)
    they also serve to get coverage for 'main'
    """
    def setUp(self):
        self.config = testing.setUp()
        self.config.include('pyramid_mailer.testing')
        try:
            DBSession.close()
            DBSession.remove()
            # print("removed old DBSession ==============================")
        except:
            # print("no DBSession to remove =============================")
            pass
        # try:
        #    os.remove('test_webtest_functional.db')
        #    #print "deleted old test database"
        # except:
        #    pass
        #    #print "never mind"

        my_settings = {
            # 'sqlalchemy.url': 'sqlite:///test_webtest_functional.db',
            'sqlalchemy.url': 'sqlite:///:memory:',
            'available_languages': 'da de en es fr',
            'c3smembership.mailaddr': '*****@*****.**',
            'testing.mail_to_console': 'false'}
        engine = engine_from_config(my_settings)
        DBSession.configure(bind=engine)
        self.session = DBSession  # ()

        Base.metadata.create_all(engine)
        # dummy database entries for testing
        with transaction.manager:
            member1 = C3sMember(  # german
                firstname=u'SomeFirstnäme',
                lastname=u'SomeLastnäme',
                email=u'*****@*****.**',
                address1=u"addr one",
                address2=u"addr two",
                postcode=u"12345",
                city=u"Footown Mäh",
                country=u"Foocountry",
                locale=u"DE",
                date_of_birth=date.today(),
                email_is_confirmed=False,
                email_confirm_code=u'ABCDEFGFOO',
                password=u'arandompassword',
                date_of_submission=date.today(),
                membership_type=u'normal',
                member_of_colsoc=True,
                name_of_colsoc=u"GEMA",
                num_shares=u'23',
            )
            DBSession.add(member1)
            DBSession.flush()

        from c3smembership import main
        app = main({}, **my_settings)

        from webtest import TestApp
        self.testapp = TestApp(app)

    def tearDown(self):
        self.session.close()
        self.session.remove()
        # os.remove('test_webtest_functional.db')

    def test_base_template(self):
        """load the front page, check string exists"""
        res = self.testapp.get('/', status=200)
        self.failUnless('Cultural Commons Collecting Society' in res.body)
        self.failUnless(
            'Copyright 2014, C3S SCE' in res.body)

    # def test_faq_template(self):
    #     """load the FAQ page, check string exists"""
    #     res = self.testapp.get('/faq', status=200)
    #     self.failUnless('FAQ' in res.body)
    #     self.failUnless(
    #         'Copyright 2013, OpenMusicContest.org e.V.' in res.body)

    def test_lang_en_LOCALE(self):
        """load the front page, forced to english (default pyramid way),
        check english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/?_LOCALE_=en', status=200)
        self.failUnless(
            'Application for Membership of ' in res.body)

    def test_lang_en(self):
        """load the front page, set to english (w/ pretty query string),
        check english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/?en', status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        self.failUnless(
            'Application for Membership of ' in res1.body)

# so let's test the app's obedience to the language requested by the browser
# i.e. will it respond to http header Accept-Language?

    # def test_accept_language_header_da(self):
    #     """check the http 'Accept-Language' header obedience: danish
    #     load the front page, check danish string exists"""
    #     res = self.testapp.reset()  # delete cookie
    #     res = self.testapp.get('/', status=200,
    #                            headers={
    #             'Accept-Language': 'da'})
    #     #print(res.body) #  if you want to see the pages source
    #     self.failUnless(
    #         '<input type="hidden" name="_LOCALE_" value="da"' in res.body)

    def test_accept_language_header_de_DE(self):
        """check the http 'Accept-Language' header obedience: german
        load the front page, check german string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get(
            '/', status=200,
            headers={
                'Accept-Language': 'de-DE'})
        # print(res.body) #  if you want to see the pages source
        self.failUnless(
            'Mitgliedschaftsantrag für die' in res.body)
        self.failUnless(
            '<input type="hidden" name="_LOCALE_" value="de"' in res.body)

    def test_accept_language_header_en(self):
        """check the http 'Accept-Language' header obedience: english
        load the front page, check english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get(
            '/', status=200,
            headers={
                'Accept-Language': 'en'})
        # print(res.body) #  if you want to see the pages source
        self.failUnless(
            "I want to become"
            in res.body)

    # def test_accept_language_header_es(self):
    #     """check the http 'Accept-Language' header obedience: spanish
    #     load the front page, check spanish string exists"""
    #     res = self.testapp.reset()  # delete cookie
    #     res = self.testapp.get('/', status=200,
    #                            headers={
    #             'Accept-Language': 'es'})
    #     #print(res.body) #  if you want to see the pages source
    #     self.failUnless(
    #         'Luego de enviar el siguiente formulario,' in res.body)

    # def test_accept_language_header_fr(self):
    #     """check the http 'Accept-Language' header obedience: french
    #     load the front page, check french string exists"""
    #     res = self.testapp.reset()  # delete cookie
    #     res = self.testapp.get('/', status=200,
    #                            headers={
    #             'Accept-Language': 'fr'})
    #     #print(res.body) #  if you want to see the pages source
    #     self.failUnless(
    #         'En envoyant un courriel à [email protected] vous pouvez' in res.body)

    def test_no_cookies(self):
        """load the front page, check default english string exists"""
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get(
            '/', status=200,
            headers={
                'Accept-Language': 'af, cn'})  # ask for missing languages
        # print res.body
        self.failUnless('Application for Membership' in res.body)

#############################################################################
# check for validation stuff

    def test_form_lang_en_non_validating(self):
        """load the join form, check english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/?_LOCALE_=en', status=200)
        form = res.form
        # print(form.fields)
        # print(form.fields.values())
        form['firstname'] = 'John'
        # form['address2'] = 'some address part'
        res2 = form.submit('submit')
        self.failUnless(
            'There was a problem with your submission' in res2.body)

    def test_form_lang_de(self):
        """load the join form, check german string exists"""
        res = self.testapp.get('/?de', status=302)
        # print(res)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res2 = res.follow()
        # print(res2)
        # test for german translation of template text (lingua_xml)
        self.failUnless(
            'Mitgliedschaftsantrag für die' in res2.body)
        # test for german translation of form field label (lingua_python)
        self.failUnless('Vorname' in res2.body)

    def test_form_lang_LOCALE_de(self):
        """load the join form in german, check german string exists
        this time forcing german locale the pyramid way
        """
        res = self.testapp.get('/?_LOCALE_=de', status=200)
        # test for german translation of template text (lingua_xml)
        self.failUnless(
            'Mitgliedschaftsantrag für die' in res.body)
        # test for german translation of form field label (lingua_python)
        self.failUnless('Vorname' in res.body)

###########################################################################
# checking the success page that sends out email with verification link

    def test_check_email_en_wo_context(self):
        """try to access the 'check_email' page and be redirected
        check english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/check_email?en', status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        # print(res1)
        self.failUnless(
            'Application for Membership of ' in str(
                res1.body),
            'expected string was not found in web UI')

###########################################################################
# checking the view that gets code and mail, asks for a password
    def test_verify_email_en_w_bad_code(self):
        """load the page in english,
        be redirected to the form (data is missing)
        check english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/verify/[email protected]/ABCD-----', status=200)
        self.failUnless(
            'Password' in res.body)
        form = res.form
        form['password'] = '******'
        res2 = form.submit('submit')
        self.failUnless(
            'Password' in res2.body)

    def test_verify_email_en_w_good_code(self):
        """
        """
        res = self.testapp.reset()
        res = self.testapp.get('/verify/[email protected]/ABCDEFGFOO', status=200)
        self.failUnless(
            'Password' in res.body)
        form = res.form
        form['password'] = '******'
        res2 = form.submit('submit')
        # print res2.body
        self.failUnless(
            'C3S_SCE_AFM_SomeFirstn_meSomeLastn_me.pdf' in res2.body)
        # 'Your Email has been confirmed, Firstnäme Lastname!' in res.body)
        # res2 = self.testapp.get(
        #    '/C3S_SCE_AFM_Firstn_meLastname.pdf', status=200)
        # self.failUnless(len(res2.body) > 70000)

    def test_success_wo_data_en(self):
        """load the success page in english (via query_string),
        check for redirection and english string exists"""
        res = self.testapp.reset()
        res = self.testapp.get('/success?en', status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        # print(res1)
        self.failUnless(  # check text on page redirected to
            'Please fill out the form' in str(
                res1.body),
            'expected string was not found in web UI')

    def test_success_pdf_wo_data_en(self):
        """
        try to load a pdf (which must fail because the form was not used)
        check for redirection to the form and test string exists
        """
        res = self.testapp.reset()
        res = self.testapp.get(
            '/C3S_SCE_AFM_ThefirstnameThelastname.pdf',
            status=302)
        self.failUnless('The resource was found at' in res.body)
        # we are being redirected...
        res1 = res.follow()
        # print(res1)
        self.failUnless(  # check text on page redirected to
            'Please fill out the form' in str(
                res1.body),
            'expected string was not found in web UI')

    def test_email_confirmation(self):
        """
        test email confirmation form and PDF download
        with a known login/dataset
        """
        res = self.testapp.reset()
        res = self.testapp.get('/verify/[email protected]/ABCDEFGFOO', status=200)
        # print(res.body)
        form = res.form
        form['password'] = '******'
        res2 = form.submit('submit')
        # print res2.body
        self.failUnless("Load your PDF..." in res2.body)
        self.failUnless(
            "/C3S_SCE_AFM_SomeFirstn_meSomeLastn_me.pdf" in res2.body)
        # load the PDF, check size
        res3 = self.testapp.get(
            '/C3S_SCE_AFM_SomeFirstn_meSomeLastn_me.pdf',
            status=200
        )
        # print("length of result: %s") % len(res3.body)
        # print("body result: %s") % (res3.body)  # ouch, PDF content!
        self.failUnless(80000 < len(res3.body) < 220000)  # check pdf size

    def test_email_confirmation_wrong_mail(self):
        """
        test email confirmation with a wrong email
        """
        res = self.testapp.reset()
        res = self.testapp.get(
            '/verify/[email protected]/ABCDEFGHIJ', status=200)
        # print(res.body)
        self.failUnless("Please enter your password." in res.body)
        # XXX this test shows nothing interesting

    def test_email_confirmation_wrong_code(self):
        """
        test email confirmation with a wrong code
        """
        res = self.testapp.reset()
        res = self.testapp.get('/verify/[email protected]/WRONGCODE', status=200)
        # print(res.body)
        self.failUnless("Please enter your password." in res.body)

    def test_success_check_email(self):
        """
        test "check email" success page with wrong data:
        this should redirect to the form.
        """
        res = self.testapp.reset()
        res = self.testapp.get('/check_email', status=302)

        res2 = res.follow()
        self.failUnless("Please fill out the form" in res2.body)
Example #49
0
class AwaitingApprovalTests(unittest.TestCase):
    """
    test the "awaiting approval" view
    """
    def setUp(self):
        self.config = testing.setUp()
        self.config.include('pyramid_mailer.testing')
        try:
            DBSession.close()
            DBSession.remove()
            # print "closed and removed DBSession"
        except:
            pass
            # print "no session to close"
        my_settings = {
            'sqlalchemy.url': 'sqlite:///:memory:',
            'available_languages': 'da de en es fr',
            'c3smembership.dashboard_number': '30'}
        engine = engine_from_config(my_settings)
        DBSession.configure(bind=engine)
        Base.metadata.create_all(engine)

        with transaction.manager:
            # a group for accountants/staff
            accountants_group = Group(name=u"staff")
            try:
                DBSession.add(accountants_group)
                DBSession.flush()
                # print("adding group staff")
            except:
                # print("could not add group staff.")
                pass
            # staff personnel
            staffer1 = C3sStaff(
                login=u"rut",
                password=u"berries",
                email=u"*****@*****.**",
            )
            staffer1.groups = [accountants_group]
            try:
                DBSession.add(accountants_group)
                DBSession.add(staffer1)
                DBSession.flush()
            except:
                # print("it borked! (rut)")
                pass

        from c3smembership import main
        app = main({}, **my_settings)
        from webtest import TestApp
        self.testapp = TestApp(app)

    def tearDown(self):
        DBSession.close()
        DBSession.remove()
        testing.tearDown()

    def make_member_ready_for_approval(self):
        with transaction.manager:
            member1 = C3sMember(  # german
                firstname=u'SomeFirstnäme',
                lastname=u'SomeLastnäme',
                email=u'*****@*****.**',
                address1=u"addr one",
                address2=u"addr two",
                postcode=u"12345",
                city=u"Footown Mäh",
                country=u"Foocountry",
                locale=u"DE",
                date_of_birth=date.today(),
                email_is_confirmed=False,
                email_confirm_code=u'ABCDEFGFOO',
                password=u'arandompassword',
                date_of_submission=date.today(),
                membership_type=u'normal',
                member_of_colsoc=True,
                name_of_colsoc=u"GEMA",
                num_shares=u'23',
            )
            member1.signature_received = True
            member1.payment_received = True
        DBSession.add(member1)

    def test_awaiting_approval(self):
        '''
        tests for the awaiting approval view
        '''
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/afms_awaiting_approval', status=403)
        assert('Access was denied to this resource' in res.body)
        res = self.testapp.get('/login', status=200)
        self.failUnless('login' in res.body)
        # try valid user
        form = res.form
        form['login'] = '******'
        form['password'] = '******'
        res2 = form.submit('submit', status=302)
        # # being logged in ...
        res3 = res2.follow()  # being redirected to dashboard with parameters
        self.failUnless(
            'Dashboard' in res3.body)
        # now look at the view to test
        res = self.testapp.get('/afms_awaiting_approval', status=200)
        self.assertTrue('Neue Genossenschaftsmitglieder' not in res.body)

        # create a member
        self.make_member_ready_for_approval()

        res = self.testapp.get('/afms_awaiting_approval', status=200)
        self.assertTrue('Neue Genossenschaftsmitglieder' in res.body)
        self.assertTrue('SomeFirstnäme' in res.body)
Example #50
0
class LoggedInRequestTests(MongoTestCase):
    """Base TestCase for those tests that need a logged in environment setup"""
    def setUp(self,
              settings={},
              skip_on_fail=False,
              std_user='******'):

        self.settings = deepcopy(SETTINGS)
        self.settings.update(settings)
        super(LoggedInRequestTests, self).setUp(celery,
                                                get_attribute_manager,
                                                userdb_use_old_format=True)

        self.redis_instance = RedisTemporaryInstance.get_instance()
        self.settings['redis_host'] = 'localhost'
        self.settings['redis_port'] = self.redis_instance._port
        self.settings['redis_db'] = '0'

        self.settings['mongo_uri'] = self.mongodb_uri('')
        try:
            app = eduiddashboard_main({}, **self.settings)
        except pymongo.errors.ConnectionFailure:
            if skip_on_fail:
                raise unittest.SkipTest(
                    "requires accessible MongoDB server on {!r}".format(
                        self.settings['mongo_uri']))
            raise

        self.testapp = TestApp(app)

        self.config = testing.setUp()
        self.config.registry.settings = self.settings
        self.config.registry.registerUtility(self, IDebugLogger)

        #self.db = get_db(self.settings)
        self.db = app.registry.settings['mongodb'].get_database(
            'eduid_dashboard')  # central userdb, raw mongodb
        self.userdb_new = UserDB(
            self.mongodb_uri(''),
            'eduid_am')  # central userdb in new format (User)
        self.dashboard_db = DashboardUserDB(
            self.mongodb_uri('eduid_dashboard'))
        # Clean up the dashboards private database collections
        logger.debug(
            "Dropping profiles, verifications and reset_passwords from {!s}".
            format(self.db))
        self.db.profiles.drop()
        self.db.verifications.drop()
        self.db.reset_passwords.drop()

        self.user = self.userdb_new.get_user_by_mail(std_user)
        self.assertIsNotNone(
            self.user,
            "Could not load the standard test user {!r} from the database {!s}"
            .format(std_user, self.userdb_new))
        self.logged_in_user = None

        # Copy all the users from the eduid userdb into the dashboard applications userdb
        # since otherwise the out-of-sync check will trigger on every save to the dashboard
        # applications database because there is no document there with the right modified_ts
        for userdoc in self.userdb_new._get_all_docs():
            logger.debug("COPYING USER INTO PROFILES:\n{!s}".format(userdoc))
            self.db.profiles.insert(userdoc)

        self.initial_verifications = (getattr(self, 'initial_verifications',
                                              None) or INITIAL_VERIFICATIONS)

        for verification_data in self.initial_verifications:
            self.db.verifications.insert(verification_data)

        logger.debug("setUp finished\n\n" + ('-=-' * 30) + "\n\n")

    def tearDown(self):
        super(LoggedInRequestTests, self).tearDown()
        logger.debug(
            "tearDown: Dropping profiles, verifications and reset_passwords from {!s}"
            .format(self.db))
        for userdoc in self.db.profiles.find({}):
            assert DashboardUser(data=userdoc)
        self.db.profiles.drop()
        self.db.verifications.drop()
        self.db.reset_passwords.drop()
        self.testapp.reset()

    def dummy_get_user(self, userid=''):
        return self.user

    def set_mocked_get_user(self):
        patcher = patch(
            'eduid_userdb.dashboard.UserDBWrapper.get_user_by_eppn',
            self.dummy_get_user)
        patcher.start()

    def dummy_request(self, cookies={}):
        request = DummyRequest()
        request.context = DummyResource()
        request.context.request = request
        request.userdb_new = self.userdb_new
        request.db = self.db
        request.dashboard_userdb = self.dashboard_db
        request.registry.settings = self.settings

        def propagate_user_changes(user):
            """
            Make sure there is a request.context.propagate_user_changes in testing too.
            """
            logger.debug(
                'FREDRIK: Testing dummy_request.context propagate_user_changes'
            )
            return self.request.amrelay.request_sync(user)

        request.context.propagate_user_changes = propagate_user_changes

        return request

    def set_logged(self, email='*****@*****.**', extra_session_data={}):
        request = self.set_user_cookie(email)
        user_obj = self.userdb_new.get_user_by_mail(email,
                                                    raise_on_missing=True)
        if not user_obj:
            logging.error(
                "User {!s} not found in database {!r}. Users:".format(
                    email, self.userdb))
            for this in self.userdb_new._get_all_userdocs():
                this_user = DashboardUser(this)
                logging.debug("  User: {!s}".format(this_user))
        # user only exists in eduid-userdb, so need to clear modified-ts to be able
        # to save it to eduid-dashboard.profiles
        user_obj.modified_ts = None
        dummy = DummyRequest()
        dummy.session = {
            'eduPersonAssurance': loa(3),
            'eduPersonIdentityProofing': loa(3),
            'eduPersonPrincipalName': 'hubba-bubba',
            'user_eppn': 'hubba-bubba',
        }
        store_session_user(dummy, user_obj)
        # XXX ought to set self.user = user_obj
        self.logged_in_user = self.userdb_new.get_user_by_id(user_obj.user_id)
        dummy.session.update(extra_session_data)
        request = self.add_to_session(dummy.session)
        return request

    def set_user_cookie(self, user_id):
        request = TestRequest.blank('', {})
        request.registry = self.testapp.app.registry
        remember_headers = remember(request, user_id)
        cookie_value = remember_headers[0][1].split('"')[1]
        self.testapp.set_cookie('auth_tkt', cookie_value)
        return request

    def add_to_session(self, data):
        # Log warning since we're moving away from direct request.session access
        logger.warning('Add to session called with data: {!r}'.format(data))
        queryUtility = self.testapp.app.registry.queryUtility
        session_factory = queryUtility(ISessionFactory)
        request = self.dummy_request()
        session = session_factory(request)
        for key, value in data.items():
            session[key] = value
        session.persist()
        self.testapp.set_cookie(self.settings['session.key'],
                                session._session.token)
        return request

    def check_values(self, fields, values, ignore_not_found=[]):
        for field in fields:
            if field.attrs['type'] == 'checkbox':
                # A webtest.app.Checkbox only has a value if it is checked (!)
                field.checked = True
                if field.value in values:
                    logger.debug("Checked checkbox {!r} (value {!r})".format(
                        field.id, field.value))
                    values.remove(field.value)
                else:
                    # restore the checkbox whose value was not found in values
                    field.checked = False
        values = [x for x in values if x not in ignore_not_found]
        self.assertEqual(
            values, [],
            "Failed checking one or more checkboxes: {!r}".format(values))

    def values_are_checked(self, fields, values):
        checked = [f.value for f in fields if f.value is not None]

        self.assertEqual(values, checked)

    def sync_user_from_dashboard_to_userdb(self, user_id, old_format=False):
        """
        When there is no eduid-dashboard-amp Attribute Manager plugin loaded to
        sync users from dashboard to userdb, this crude function can do it.

        :param user_id: User id
        :param old_format: Write in old format to userdb

        :type user_id: ObjectId
        :type old_format: bool
        :return:
        """
        user = self.dashboard_db.get_user_by_id(user_id)
        logger.debug('Syncing user {!s} from dashboard to userdb'.format(user))
        test_doc = {'_id': user_id}
        user_doc = user.to_dict(old_userdb_format=old_format)
        # Fixups to turn the DashboardUser into a User
        user_doc['terminated'] = True
        self.userdb_new._coll.update(test_doc, user_doc, upsert=False)
Example #51
0
class Saml2RequestTests(MongoTestCase):
    """Base TestCase for those tests usign saml2 that need a full environment
       setup
    """

    def setUp(self, settings={}):
        super(Saml2RequestTests, self).setUp(celery, get_attribute_manager, userdb_use_old_format=True)

        self.settings = {
            'saml2.settings_module': path.join(path.dirname(__file__),
                                               'tests/data/saml2_settings.py'),
            'saml2.login_redirect_url': '/',
            'saml2.logout_redirect_url': '/',
            'saml2.strip_saml_user_suffix': '@test',
            'auth_tk_secret': '123456',
            'testing': True,
            'jinja2.directories': 'eduiddashboard:saml2/templates',
            'jinja2.undefined': 'strict',
            'jinja2.filters': """
                route_url = pyramid_jinja2.filters:route_url_filter
                static_url = pyramid_jinja2.filters:static_url_filter
            """,
            'session.key': 'sessid',
            'session.secret': '123341234',
            'session.cookie_domain': 'localhost',
            'session.cookie_path': '/',
            'session.cookie_max_age': '3600',
            'session.cookie_httponly': True,
            'session.cookie_secure': False,
        }
        self.settings.update(settings)

        if not self.settings.get('groups_callback', None):
            self.settings['groups_callback'] = dummy_groups_callback

        self.settings['mongo_uri'] = self.mongodb_uri('')

        self.redis_instance = RedisTemporaryInstance.get_instance()
        self.settings['REDIS_HOST'] = 'localhost'
        self.settings['REDIS_PORT'] = self.redis_instance._port
        self.settings['REDIS_DB'] = '0'
        self.redis_conn = redis.Redis(host='localhost',
                port=self.redis_instance._port, db=0)

        app = saml2_main({}, **self.settings)
        self.testapp = TestApp(app)

        self.config = testing.setUp()
        self.config.registry.settings = self.settings
        self.config.registry.registerUtility(self, IDebugLogger)
        self.userdb = app.registry.settings['userdb']
        self.db = app.registry.settings['db']

    def tearDown(self):
        super(Saml2RequestTests, self).tearDown()
        for k in self.redis_conn.keys():
            self.redis_conn.delete(k)
        self.testapp.reset()

    def set_user_cookie(self, user_id):
        request = TestRequest.blank('', {})
        request.registry = self.testapp.app.registry
        remember_headers = remember(request, user_id)
        cookie_value = remember_headers[0][1].split('"')[1]
        self.testapp.set_cookie('auth_tkt', cookie_value)
        return request

    def dummy_request(self):
        request = DummyRequest()
        request.context = DummyResource()
        request.userdb = self.userdb
        request.db = self.db
        request.registry.settings = self.settings
        return request

    def get_request_with_session(self):
        queryUtility = self.testapp.app.registry.queryUtility
        session_factory = queryUtility(ISessionFactory)

        request = self.dummy_request()
        session = session_factory(request)
        session.persist()
        self.testapp.set_cookie(self.settings['session.key'], session._session.token)
        self.pol = self.config.testing_securitypolicy(
            'user', ('editors', ),
            permissive=False, remember_result=True)
        return request

    def get_fake_session_info(self, eppn=None):
        session_info = {
            'authn_info': [
                ('urn:oasis:names:tc:SAML:2.0:ac:classes:Password', [])
            ],
            'name_id': None,
            'not_on_or_after': 1371671386,
            'came_from': u'/',
            'ava': {
                'cn': ['John'],
                'objectclass': ['top', 'inetOrgPerson', 'person', 'eduPerson'],
                'userpassword': ['1234'],
                'edupersonaffiliation': ['student'],
                'sn': ['Smith'],
                'mail': ['*****@*****.**'],
                'eduPersonPrincipalName': ['hubba-bubba@test']
            },
            'issuer': 'https://idp.example.com/saml/saml2/idp/metadata.php'
        }

        if eppn is not None:
            session_info['ava']['eduPersonPrincipalName'] = eppn

        return session_info
Example #52
0
class Test(testutils.WebFunctional):

    def create_app_instance(self):
        """create TestApp instance"""
        assert self._app is None
        import simple_webapp_flask
        self._bottle_app = simple_webapp_flask.app
        self._app = TestApp(self._bottle_app)
        #simple_webapp_flask.flask.session.secret_key = 'bogus'
        simple_webapp_flask.SECRET_KEY = 'bogus'
        print("Test App created")

    def teardown(self):
        print("Doing teardown")
        try:
            self._app.post('/logout')
        except:
            pass

        # drop the cookie
        self._app.reset()
        assert 'beaker.session.id' not in self._app.cookies, "Unexpected cookie found"
        # drop the cookie
        self._app.reset()

        #assert self._app.get('/admin').status != '200 OK'
        os.chdir(self._starting_dir)

        self._app.app.options['timeout'] = self._default_timeout
        self._app = None
        shutil.rmtree(self._tmpdir)
        self._tmpdir = None
        print("Teardown done")

    def setup(self):
        # create test dir and populate it using the example files

        # save the directory where the unit testing has been run
        if self._starting_dir is None:
            self._starting_dir = os.getcwd()

        # create json files to be used by Cork
        self._tmpdir = testutils.pick_temp_directory()
        assert self._tmpdir is not None
        self.populate_temp_dir()

        # change to the temporary test directory
        # cork relies on this being the current directory
        os.chdir(self._tmpdir)
        self.create_app_instance()
        self._app.reset()
        print("Reset done")
        #self._default_timeout = self._app.app.options['timeout']
        self._default_timeout = 30
        #FIXME: reset
        print("Setup completed")


    def login_as_admin(self):
        """perform log in"""
        assert self._app is not None
        assert 'session' not in self._app.cookies, "Unexpected cookie found"

        self.assert_200('/login', 'Please insert your credentials')
        assert 'session' not in self._app.cookies, "Unexpected cookie found"

        self.assert_redirect('/admin', '/sorry_page')

        self.assert_200('/user_is_anonymous', 'True')
        assert 'session' not in self._app.cookies, "Unexpected cookie found"

        post = {'username': '******', 'password': '******'}
        self.assert_redirect('/login', '/', post=post)
        assert 'session' in self._app.cookies, "Cookie not found"

        import bottle
        session = bottle.request.environ.get('beaker.session')
        print("Session from func. test", repr(session))

        self.assert_200('/login', 'Please insert your credentials')


        p = self._app.get('/admin')
        assert 'Welcome' in p.body, repr(p)

        p = self._app.get('/my_role', status=200)
        assert p.status_int == 200
        assert p.body == 'admin', "Sta"

        print("Login performed")


    def test_functional_expiration(self):
        self.login_as_admin()
        r = self._app.get('/admin')
        assert r.status_int == 200, repr(r)

        # change the cookie expiration in order to expire it
        saved = self._bottle_app.permanent_session_lifetime
        try:
            self._bottle_app.permanent_session_lifetime = timedelta(seconds=-1)

            # change the cookie expiration in order to expire it
            self._app.app.options['timeout'] = 0

            assert self._app.get('/admin').status_int == REDIR, "The cookie should have expired"


        finally:
            self._bottle_app.permanent_session_lifetime = saved
class Test(object):
    def __init__(self):
        self._tmpdir = None
        self._tmproot = None
        self._app = None
        self._starting_dir = os.getcwd()

    def remove_temp_dir(self):
        p = os.path.join(self._tmproot, 'cork_functional_test_wd')
        for f in glob.glob('%s*' % p):
            #shutil.rmtree(f)
            pass

    @classmethod
    def setUpClass(cls):
        print("Setup class")

    def populate_temp_dir(self):
        """populate the temporary test dir"""
        assert self._tmproot is not None
        assert self._tmpdir is None

        tstamp = str(time())[5:]
        self._tmpdir = os.path.join(self._tmproot, "cork_functional_test_wd_%s" % tstamp)

        try:
            os.mkdir(self._tmpdir)
        except OSError:
            # The directory is already there, purge it
            print("Deleting %s" % self._tmpdir)
            shutil.rmtree(self._tmpdir)
            os.mkdir(self._tmpdir)

            #p = os.path.join(self._tmproot, 'cork_functional_test_wd')
            #for f in glob.glob('%s*' % p):
            #    shutil.rmtree(f)

        # copy the needed files
        shutil.copytree(
            os.path.join(self._starting_dir, 'tests/example_conf'),
            os.path.join(self._tmpdir, 'example_conf')
        )
        shutil.copytree(
            os.path.join(self._starting_dir, 'tests/views'),
            os.path.join(self._tmpdir, 'views')
        )

        # change to the temporary test directory
        # cork relies on this being the current directory
        os.chdir(self._tmpdir)

        print("Test directory set up")

    def create_app_instance(self):
        """create TestApp instance"""
        assert self._app is None
        import simple_webapp_decorated
        self._bottle_app = simple_webapp_decorated.app
        env = {'REMOTE_ADDR': '127.0.0.1'}
        self._app = TestApp(self._bottle_app, extra_environ=env)
        print("Test App created")

    def teardown(self):
        print("Doing teardown")
        try:
            self._app.post('/logout')
        except:
            pass

        # drop the cookie
        self._app.reset()
        assert 'beaker.session.id' not in self._app.cookies, "Unexpected cookie found"
        # drop the cookie
        self._app.reset()

        #assert self._app.get('/admin').status != '200 OK'
        os.chdir(self._starting_dir)
        #if self._tmproot is not None:
        #    testutils.purge_temp_directory(self._tmproot)

        self._app.app.options['timeout'] = self._default_timeout
        self._app = None
        self._tmproot = None
        self._tmpdir = None
        print("Teardown done")

    def setup(self):
        # create test dir and populate it using the example files

        # save the directory where the unit testing has been run
        if self._starting_dir is None:
            self._starting_dir = os.getcwd()

        # create json files to be used by Cork
        self._tmproot = testutils.pick_temp_directory()
        assert self._tmproot is not None

        # purge the temporary test directory
        self.remove_temp_dir()

        self.populate_temp_dir()
        self.create_app_instance()
        self._app.reset()
        print("Reset done")
        self._default_timeout = self._app.app.options['timeout']
        print("Setup completed")

    def assert_200(self, path, match):
        """Assert that a page returns 200"""
        p = self._app.get(path)
        assert p.status_int == 200, "Status: %d, Location: %s" % \
            (p.status_int, p.location)

        if match is not None:
            assert match in p.body, "'%s' not found in body: '%s'" % (match, p.body)

        return p

    def assert_redirect(self, page, redir_page, post=None):
        """Assert that a page redirects to another one"""

        # perform GET or POST
        if post is None:
            p = self._app.get(page, status=302)
        else:
            assert isinstance(post, dict)
            p = self._app.post(page, post, status=302)

        dest = p.location.split(':80/')[-1]
        dest = "/%s" % dest
        assert dest == redir_page, "%s redirects to %s instead of %s" % \
            (page, dest, redir_page)

        return p

    def login_as_admin(self):
        """perform log in"""
        assert self._app is not None
        assert 'beaker.session.id' not in self._app.cookies, "Unexpected cookie found"

        self.assert_200('/login', 'Please insert your credentials')
        assert 'beaker.session.id' not in self._app.cookies, "Unexpected cookie found"

        self.assert_redirect('/admin', '/sorry_page')

        self.assert_200('/user_is_anonymous', 'True')
        assert 'beaker.session.id' not in self._app.cookies, "Unexpected cookie found"

        post = {'username': '******', 'password': '******'}
        self.assert_redirect('/login', '/', post=post)
        assert 'beaker.session.id' in self._app.cookies, "Cookie not found"

        self.assert_200('/my_role', 'admin')
        assert 'beaker.session.id' in self._app.cookies, "Cookie not found"

        import bottle
        session = bottle.request.environ.get('beaker.session')
        print("Session from func. test", repr(session))

        self.assert_200('/login', 'Please insert your credentials')


        p = self._app.get('/admin')
        assert 'Welcome' in p.body, repr(p)

        p = self._app.get('/my_role', status=200)
        assert p.status == '200 OK'
        assert p.body == 'admin', "Sta"

        print("Login performed")



    def test_functional_login(self):
        assert self._app
        self._app.get('/admin', status=302)
        self._app.get('/my_role', status=302)

        self.login_as_admin()

        # fetch a page successfully
        r = self._app.get('/admin')
        assert r.status == '200 OK', repr(r)

    def test_login_existing_user_none_password(self):
        p = self._app.post('/login', {'username': '******', 'password': None})
        assert p.status == REDIR, "Redirect expected"
        assert p.location == 'http://*****:*****@localhost.local'
    #    })

    def test_functionalxxx(self):
        assert self._app is not None

    def test_functional_expiration(self):
        self.login_as_admin()
        r = self._app.get('/admin')
        assert r.status == '200 OK', repr(r)
        # change the cookie expiration in order to expire it
        self._app.app.options['timeout'] = 0
        assert self._app.get('/admin').status == REDIR, "The cookie should have expired"
class Test(object):
    def __init__(self):
        self._tmpdir = None
        self._tmproot = None
        self._app = None
        self._starting_dir = os.getcwd()

    def remove_temp_dir(self):
        p = os.path.join(self._tmproot, 'cork_functional_test_wd')
        for f in glob.glob('%s*' % p):
            #shutil.rmtree(f)
            pass

    @classmethod
    def setUpClass(cls):
        print("Setup class")

    def populate_temp_dir(self):
        """populate the temporary test dir"""
        assert self._tmproot is not None
        assert self._tmpdir is None

        tstamp = str(time())[5:]
        self._tmpdir = os.path.join(self._tmproot,
                                    "cork_functional_test_wd_%s" % tstamp)

        try:
            os.mkdir(self._tmpdir)
        except OSError:
            # The directory is already there, purge it
            print("Deleting %s" % self._tmpdir)
            shutil.rmtree(self._tmpdir)
            os.mkdir(self._tmpdir)

            #p = os.path.join(self._tmproot, 'cork_functional_test_wd')
            #for f in glob.glob('%s*' % p):
            #    shutil.rmtree(f)

        # copy the needed files
        shutil.copytree(os.path.join(self._starting_dir, 'tests/example_conf'),
                        os.path.join(self._tmpdir, 'example_conf'))
        shutil.copytree(os.path.join(self._starting_dir, 'tests/views'),
                        os.path.join(self._tmpdir, 'views'))

        # change to the temporary test directory
        # cork relies on this being the current directory
        os.chdir(self._tmpdir)

        print("Test directory set up")

    def create_app_instance(self):
        """create TestApp instance"""
        assert self._app is None
        import simple_webapp_decorated
        self._bottle_app = simple_webapp_decorated.app
        env = {'REMOTE_ADDR': '127.0.0.1'}
        self._app = TestApp(self._bottle_app, extra_environ=env)
        print("Test App created")

    def teardown(self):
        print("Doing teardown")
        try:
            self._app.post('/logout')
        except:
            pass

        # drop the cookie
        self._app.reset()
        assert 'beaker.session.id' not in self._app.cookies, "Unexpected cookie found"
        # drop the cookie
        self._app.reset()

        #assert self._app.get('/admin').status != '200 OK'
        os.chdir(self._starting_dir)
        #if self._tmproot is not None:
        #    testutils.purge_temp_directory(self._tmproot)

        self._app.app.options['timeout'] = self._default_timeout
        self._app = None
        self._tmproot = None
        self._tmpdir = None
        print("Teardown done")

    def setup(self):
        # create test dir and populate it using the example files

        # save the directory where the unit testing has been run
        if self._starting_dir is None:
            self._starting_dir = os.getcwd()

        # create json files to be used by Cork
        self._tmproot = testutils.pick_temp_directory()
        assert self._tmproot is not None

        # purge the temporary test directory
        self.remove_temp_dir()

        self.populate_temp_dir()
        self.create_app_instance()
        self._app.reset()
        print("Reset done")
        self._default_timeout = self._app.app.options['timeout']
        print("Setup completed")

    def assert_200(self, path, match):
        """Assert that a page returns 200"""
        p = self._app.get(path)
        assert p.status_int == 200, "Status: %d, Location: %s" % \
            (p.status_int, p.location)

        if match is not None:
            assert match in p.body, "'%s' not found in body: '%s'" % (match,
                                                                      p.body)

        return p

    def assert_redirect(self, page, redir_page, post=None):
        """Assert that a page redirects to another one"""

        # perform GET or POST
        if post is None:
            p = self._app.get(page, status=302)
        else:
            assert isinstance(post, dict)
            p = self._app.post(page, post, status=302)

        dest = p.location.split(':80/')[-1]
        dest = "/%s" % dest
        assert dest == redir_page, "%s redirects to %s instead of %s" % \
            (page, dest, redir_page)

        return p

    def login_as_admin(self):
        """perform log in"""
        assert self._app is not None
        assert 'beaker.session.id' not in self._app.cookies, "Unexpected cookie found"

        self.assert_200('/login', 'Please insert your credentials')
        assert 'beaker.session.id' not in self._app.cookies, "Unexpected cookie found"

        self.assert_redirect('/admin', '/sorry_page')

        self.assert_200('/user_is_anonymous', 'True')
        assert 'beaker.session.id' not in self._app.cookies, "Unexpected cookie found"

        post = {'username': '******', 'password': '******'}
        self.assert_redirect('/login', '/', post=post)
        assert 'beaker.session.id' in self._app.cookies, "Cookie not found"

        self.assert_200('/my_role', 'admin')
        assert 'beaker.session.id' in self._app.cookies, "Cookie not found"

        import bottle
        session = bottle.request.environ.get('beaker.session')
        print("Session from func. test", repr(session))

        self.assert_200('/login', 'Please insert your credentials')

        p = self._app.get('/admin')
        assert 'Welcome' in p.body, repr(p)

        p = self._app.get('/my_role', status=200)
        assert p.status == '200 OK'
        assert p.body == 'admin', "Sta"

        print("Login performed")

    def test_functional_login(self):
        assert self._app
        self._app.get('/admin', status=302)
        self._app.get('/my_role', status=302)

        self.login_as_admin()

        # fetch a page successfully
        r = self._app.get('/admin')
        assert r.status == '200 OK', repr(r)

    def test_login_existing_user_none_password(self):
        p = self._app.post('/login', {'username': '******', 'password': None})
        assert p.status == REDIR, "Redirect expected"
        assert p.location == 'http://*****:*****@localhost.local'
    #    })

    def test_functionalxxx(self):
        assert self._app is not None

    def test_functional_expiration(self):
        self.login_as_admin()
        r = self._app.get('/admin')
        assert r.status == '200 OK', repr(r)
        # change the cookie expiration in order to expire it
        self._app.app.options['timeout'] = 0
        assert self._app.get(
            '/admin').status == REDIR, "The cookie should have expired"
Example #55
0
class LoggedInReguestTests(am.MongoTestCase):
    """Base TestCase for those tests that need a logged in environment setup"""

    MockedUserDB = am.MockedUserDB

    user = User(am.MOCKED_USER_STANDARD)
    user.set_modified_ts(datetime.datetime.utcnow())
    users = []

    def setUp(self, settings={}):
        # Don't call DBTests.setUp because we are getting the
        # db in a different way

        self.settings = {
            'auth_tk_secret': '123456',
            'auth_shared_secret': '123_456',
            'site.name': 'eduiID Testing',
            'saml2.settings_module': path.join(path.dirname(__file__),
                                               'saml2/tests/data/saml2_settings.py'),
            'saml2.login_redirect_url': '/',
            'saml2.logout_redirect_url': '/',
            'saml2.user_main_attribute': 'mail',
            # Required only if not dont want mongodb
            # 'groups_callback': dummy_groups_callback,
            #'session.type': 'memory',
            #'session.lock_dir': '/tmp',
            #'session.webtest_varname': 'session',
            # 'session.secret': '1234',
            'mongo_uri': am.MONGO_URI_TEST,
            'mongo_uri_am': am.MONGO_URI_AM_TEST,
            'mongo_uri_authninfo': MONGO_URI_AUTHNINFO_TEST,
            'testing': True,
            'jinja2.directories': [
                'eduiddashboard:saml2/templates',
                'eduiddashboard:/templates'
            ],
            'jinja2.undefined': 'strict',
            'jinja2.filters': """
                route_url = pyramid_jinja2.filters:route_url_filter
                static_url = pyramid_jinja2.filters:static_url_filter
                get_flash_message_text = eduiddashboard.filters:get_flash_message_text
                get_flash_message_type = eduiddashboard.filters:get_flash_message_type
                address_type_text = eduiddashboard.filters:address_type_text
                country_name = eduiddashboard.filters:country_name
                context_route_url = eduiddashboard.filters:context_route_url
                safe_context_route_url = eduiddashboard.filters:safe_context_route_url
            """,
            'personal_dashboard_base_url': 'http://localhost/',
            'nin_service_name': 'Mina meddelanden',
            'nin_service_url': 'http://minameddelanden.se/',
            'available_languages': '''
                en = English
                sv = Svenska
            ''',
            'default_country_code': '+46',
            'vccs_url': 'http://localhost:8550/',
            'password_reset_timeout': '120',
        }
        
        super(LoggedInReguestTests, self).setUp()

        self.settings.update(settings)

        try:
            app = eduiddashboard_main({}, **self.settings)
        except pymongo.errors.ConnectionFailure:
            raise unittest.SkipTest("requires accessible MongoDB server on {!r}".format(
                self.settings['mongo_uri']))

        self.testapp = TestApp(app)

        self.config = testing.setUp()
        self.config.registry.settings = self.settings
        self.config.registry.registerUtility(self, IDebugLogger)

        self.db = get_db(self.settings)
        self.db.profiles.drop()
        self.db.verifications.drop()
        for verification_data in self.initial_verifications:
            self.db.verifications.insert(verification_data)

        userdocs = []
        #ts = datetime.datetime.utcnow()
        for userdoc in self.userdb.all_userdocs():
            newdoc = deepcopy(userdoc)
        #    newdoc['modified_ts'] = ts
            userdocs.append(newdoc)
        self.db.profiles.insert(userdocs)


    def tearDown(self):
        super(LoggedInReguestTests, self).tearDown()
        self.db.profiles.drop()
        self.db.verifications.drop()
        self.db.reset_passwords.drop()
        self.testapp.reset()

    def dummy_get_user(self, userid=''):
        return self.user

    def set_mocked_get_user(self):
        patcher = patch('eduid_am.userdb.UserDB.get_user',
                        self.dummy_get_user)
        patcher.start()

    def dummy_request(self, cookies={}):
        request = DummyRequest()
        request.context = DummyResource()
        request.userdb = self.userdb
        request.db = self.db
        request.registry.settings = self.settings
        return request

    def set_logged(self, user='******', extra_session_data={}):
        request = self.set_user_cookie(user)
        user_obj = self.userdb.get_user(user)
        session_data = {
            'user': user_obj,
            'eduPersonAssurance': loa(3),
            'eduPersonIdentityProofing': loa(3),
        }
        session_data.update(extra_session_data)
        request = self.add_to_session(session_data)
        return request

    def set_user_cookie(self, user_id):
        request = TestRequest.blank('', {})
        request.registry = self.testapp.app.registry
        remember_headers = remember(request, user_id)
        cookie_value = remember_headers[0][1].split('"')[1]
        self.testapp.cookies['auth_tkt'] = cookie_value
        return request

    def add_to_session(self, data):
        queryUtility = self.testapp.app.registry.queryUtility
        session_factory = queryUtility(ISessionFactory)
        request = self.dummy_request()
        session = session_factory(request)
        for key, value in data.items():
            session[key] = value
        session.persist()
        self.testapp.cookies[session_factory._options.get('key')] = session._sess.id
        return request

    def check_values(self, fields, values):
        for field in fields:
            if field.attrs['type'] == 'checkbox':
                old_status = field.checked
                field.checked = True
                if field.value not in values:
                    field.checked = old_status

    def values_are_checked(self, fields, values):
        checked = [f.value for f in fields if f.value is not None]

        self.assertEqual(values, checked)
Example #56
0
class TestCookie(unittest.TestCase):
    """Tests API functions associated with VM actions.
       Note that all tests are in-process, we don't actually start a http server.
    """
    def setUp(self):
        """Launch pserve using webtest with test settings"""
        self.appconf = get_app(test_ini)
        self.app = TestApp(self.appconf)

        # Punch in new administrator account with direct server call

        server.choose_engine("SQLite")  # Sets global var "engine" - in the
                                        # case of SQLite this is a fresh RAM
                                        # DB each time.

        # Create new user. This will implicitly generate the tables.
        id1 = server.create_user(None, "testuser", "testuser", "testuser")
        server.touch_to_add_user_group("testuser", "users")
        server.touch_to_add_password(id1, "testpass")

        id2 = server.create_user(None, "administrator", "administrator", "administrator")
        server.touch_to_add_user_group("administrator", "administrators")
        server.touch_to_add_password(id2, "adminpass")

    """Confirm lack of any cookie without authentication."""
    def test_no_cookie_without_auth(self):
        """ No cookie should be set when calling an endpoint that
            does not require authorization.
        """
        self.app.authorization = None
        r = self.app.get("/", status=200)

        self.assertEqual(r.headers.get('Set-Cookie', 'empty'), 'empty')

        #Equivalently:
        self.assertEqual(self.app.cookies, {})

    def test_no_username(self):
        """ The DB API should return a 401 unauthorised if I submit a request
            with no username / password provided.
            Similar to test_unauthenticated_api but with an extra check that no
            cookie is set.
        """
        self.app.authorization = None
        r = self.app.get("/users/testuser", status=401)

        self.assertEqual(r.headers.get('Set-Cookie', 'empty'), 'empty')


    def test_invalid_username(self):
        """ The DB API should return a 401 unauthorised if I submit a bad
            username / password combination.  And again no cookie
        """
        self.app.authorization = ('Basic', ('invaliduser', 'invalidpassword'))

        r = self.app.get("/users/testuser", status=401)
        self.assertEqual(r.headers.get('Set-Cookie', 'empty'), 'empty')

    def test_valid_cookie(self):
        """Confirm cookie returned upon authentication.
        The DB API should return a cookie if I submit a correct username
        and password. The cookie should allow me to make a successful request
        using it alone. """

        self.app.authorization = ('Basic', ('testuser', 'testpass'))
        r = self.app.get("/users/testuser", status=200)
        cookie = self.app.cookies['auth_tkt']

        self.app.reset()                         # clear cookie cache
        self.app.authorization = None            # remove auth credentials
        self.app.set_cookie("auth_tkt", cookie)  # set cookie to old value

        r = self.app.get("/users/testuser", status=200)

        #Furthermore, we should still get the same cookie on the second call
        self.assertEqual(self.app.cookies['auth_tkt'], cookie)

    def test_broken_cookie(self):
        """ The DB API should refuse to service a request with a broken cookie. """

        self.app.authorization = ('Basic', ('testuser', 'testpass'))
        r = self.app.get("/users/testuser", status=200)
        cookie = 'I am a fish'

        self.app.reset()                         # clear cookie cache
        self.app.authorization = None            # remove auth credentials
        self.app.set_cookie("auth_tkt", cookie)  # set cookie to bad value
        r = self.app.get("/users/testuser", status=401, expect_errors=False)

    def test_invalid_cookie(self):
        """ The DB API should refuse to service a request with an invalid cookie. """

        self.app.authorization = ('Basic', ('testuser', 'testpass'))
        r = self.app.get("/users/testuser", status=200)
        cookie = '94514a32a7923939584470e8fc01f9b073bc3c8171542c8b7deb0' + \
                 'dd459400945553f9ed9dGVzdHVzZXI%3D!userid_type:b64unicode'

        self.app.reset()                         # clear cookie cache
        self.app.authorization = None            # remove auth credentials
        self.app.set_cookie("auth_tkt", cookie)  # set cookie to bad value
        r = self.app.get("/users/testuser", status=401, expect_errors=False)

    def test_valid_authtkt(self):
        """Setting a cookie in the request is problematic for AJAX, so
           test that we can feed the token back in the auth_tkt header instead.
        """

        self.app.authorization = ('Basic', ('testuser', 'testpass'))
        r = self.app.get("/users/testuser", status=200)
        cookie = self.app.cookies['auth_tkt']

        self.app.reset()                         # clear cookie cache
        self.app.authorization = None            # remove auth credentials

        r = self.app.get("/users/testuser",
                         headers={'auth_tkt': cookie},
                         status=200)

        #Furthermore, we should still get the same cookie on the second call
        self.assertEqual(self.app.cookies['auth_tkt'], cookie)

    def test_broken_cookie(self):
        """ The DB API should refuse to service a request with a broken auth_tkt.
            And should return a 408 error (I think - we don't want a 401 as it causes the
            browser to prompt for a username/password which will then be remembered for
            basic auth)
        """

        self.app.authorization = ('Basic', ('testuser', 'testpass'))
        r = self.app.get("/users/testuser", status=200)
        cookie = 'I am a fish'

        self.app.reset()                         # clear cookie cache
        self.app.authorization = None            # remove auth credentials

        r = self.app.get("/users/testuser",
                         headers={'auth_tkt': cookie},
                         status=408,
                         expect_errors=False)
Example #57
0
class Saml2RequestTests(unittest.TestCase):
    """Base TestCase for those tests usign saml2 that need a full environment
       setup
    """

    def setUp(self, settings={}):
        # Don't call DBTests.setUp because we are getting the
        # db in a different way

        self.settings = {
            'saml2.settings_module': path.join(path.dirname(__file__),
                                               'tests/data/saml2_settings.py'),
            'saml2.login_redirect_url': '/',
            'saml2.logout_redirect_url': '/',
            'saml2.user_main_attribute': 'mail',
            'auth_tk_secret': '123456',
            'mongo_uri': am.MONGO_URI_TEST,
            'testing': True,
            'jinja2.directories': 'eduiddashboard:saml2/templates',
            'jinja2.undefined': 'strict',
            'jinja2.filters': """
                route_url = pyramid_jinja2.filters:route_url_filter
                static_url = pyramid_jinja2.filters:static_url_filter
            """,
        }
        self.settings.update(settings)

        if not self.settings.get('groups_callback', None):
            self.settings['groups_callback'] = dummy_groups_callback

        app = saml2_main({}, **self.settings)
        self.testapp = TestApp(app)
        self.userdb = MockedUserDB()
        try:
            self.db = get_db(self.settings)
        except pymongo.errors.ConnectionFailure:
            raise unittest.SkipTest("requires accessible MongoDB server on {!r}".format(
                self.settings['mongo_uri']))
        self.db.profiles.drop()
        userdocs = []
        for userdoc in self.userdb.all_userdocs():
            newdoc = deepcopy(userdoc)
            userdocs.append(newdoc)
        self.db.profiles.insert(userdocs)

        self.config = testing.setUp()
        self.config.registry.settings = self.settings
        self.config.registry.registerUtility(self, IDebugLogger)

    def tearDown(self):
        super(Saml2RequestTests, self).tearDown()
        self.testapp.reset()
        self.db.profiles.drop()

    def set_user_cookie(self, user_id):
        request = TestRequest.blank('', {})
        request.userdb = self.userdb
        request.db = self.db
        request.registry = self.testapp.app.registry
        remember_headers = remember(request, user_id)
        cookie_value = remember_headers[0][1].split('"')[1]
        self.testapp.cookies['auth_tkt'] = cookie_value
        return request

    def dummy_request(self):
        request = DummyRequest()
        request.context = DummyResource()
        request.userdb = self.userdb
        request.db = self.db
        request.registry.settings = self.settings
        return request

    def get_request_with_session(self):
        queryUtility = self.testapp.app.registry.queryUtility
        session_factory = queryUtility(ISessionFactory)

        request = self.dummy_request()
        session = session_factory(request)
        session.persist()
        self.testapp.cookies['beaker.session.id'] = session._sess.id
        self.pol = self.config.testing_securitypolicy(
            'user', ('editors', ),
            permissive=False, remember_result=True)
        return request

    def get_fake_session_info(self, user=None):
        session_info = {
            'authn_info': [
                ('urn:oasis:names:tc:SAML:2.0:ac:classes:Password', [])
            ],
            'name_id': None,
            'not_on_or_after': 1371671386,
            'came_from': u'/',
            'ava': {
                'cn': ['Usuario1'],
                'objectclass': ['top', 'inetOrgPerson', 'person', 'eduPerson'],
                'userpassword': ['1234'],
                'edupersonaffiliation': ['student'],
                'sn': ['last name'],
                'mail': ['*****@*****.**']
            },
            'issuer': 'https://idp.example.com/saml/saml2/idp/metadata.php'
        }

        if user is not None:
            session_info['ava']['mail'] = user

        return session_info
Example #58
0
        """ INICIO TESTE PASTA ALUNO"""

    """Pagina aluno.tpl"""

    def test_aluno_inicio(self):
        res = test_app.get('/jogar_conecturma')
        self.assertEqual(res.status_int, 200)
        self.assertIn('''<form action="/jogos" method="get">''', res.text, res.text)
        self.assertIn('''<a href="/loja"><button>Loja</button></a>''', res.text, res.text)
        self.assertIn('''<a href="/aluno/ver_itens_comprados"><button>Ver Itens</button></a>''', res.text, res.text)
        self.assertIn('''<a href="/sair"><button>Sair</button></a>''', res.text, res.text)

    def test_acesso_loja(self):
        self._fixaluno()
        res= test_app.get('/loja')
        self.assertEqual(res.status_int,200)
        self.assertIn('<form action="/compras_loja">', res.text, res.text)
        self.assertIn('''<button type="submit" name="id" value=''', res.text, res.text)
        self.assertIn('''Comprar</button>''',res.text,res.text)

    def test_ver_itens(self):
        res= test_app.get('/aluno/ver_itens_comprados')
        self.assertEqual(res.status_int, 200)
        # self.assertIn('<form action="/equipar_item" method="post">', res.text, res.text)
        self.assertIn('<a href="/aluno"><button>Voltar</button></a>', res.text, res.text)


test_app.reset()
if __name__ == '__main__':
    unittest.main()