当前位置: 首页>>代码示例>>Python>>正文


Python TestApp.reset方法代码示例

本文整理汇总了Python中webtest.TestApp.reset方法的典型用法代码示例。如果您正苦于以下问题:Python TestApp.reset方法的具体用法?Python TestApp.reset怎么用?Python TestApp.reset使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在webtest.TestApp的用法示例。


在下文中一共展示了TestApp.reset方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: injectionattack

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import reset [as 别名]
def injectionattack():
    app = TestApp(test.app)
    app.post('/login', {'username':'user','password':'pass'})
    assert app.get('/admin').status == '200 OK'
    app.get('/logout')
    app.reset()
    assert app.get('/admin').status == '401 Unauthorized'
开发者ID:AshleyRegan,项目名称:CSC485,代码行数:9,代码来源:attack.py

示例2: test_delete_supercar

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import reset [as 别名]
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()
开发者ID:finklabs,项目名称:supercars-service,代码行数:9,代码来源:test_routes.py

示例3: TestCase

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import reset [as 别名]
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': '[email protected]',
            '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)
开发者ID:danigm,项目名称:yith-library-server,代码行数:61,代码来源:testing.py

示例4: test_functional_login_logout

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import reset [as 别名]
def test_functional_login_logout():
    app = TestApp(Bottle4)
    app.post('/login', {'user': 'foo', 'pass': 'bar'}) # 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'
开发者ID:vikramuk,项目名称:Test,代码行数:10,代码来源:Bottle4FuncTest.py

示例5: TestCase

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import reset [as 别名]
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': 'sdk-three_api1.sdk.com',
            'paypal_password': 'QFZCWN5HZM8VBG7Q',
            'paypal_signature': 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU',
            'testing': 'True',
            'pyramid_mailer.prefix': 'mail_',
            'mail_default_sender': '[email protected]',
            '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)
开发者ID:lorenzogil,项目名称:yith-library-server,代码行数:56,代码来源:testing.py

示例6: FunctionalTestCase

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import reset [as 别名]
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()
开发者ID:SUNET,项目名称:eduid-actions,代码行数:54,代码来源:testing.py

示例7: FunctionalTests

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import reset [as 别名]
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
开发者ID:SUNET,项目名称:eduid-signup,代码行数:52,代码来源:testing.py

示例8: TestCase

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import reset [as 别名]
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': 'sdk-three_api1.sdk.com',
            'paypal_password': 'QFZCWN5HZM8VBG7Q',
            'paypal_signature': 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU',
            'testing': 'True',
            'pyramid_mailer.prefix': 'mail_',
            'mail_default_sender': '[email protected]',
            '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)
开发者ID:srus,项目名称:yith-library-server,代码行数:46,代码来源:testing.py

示例9: BaseAppTest

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import reset [as 别名]
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()
开发者ID:amtrack,项目名称:s3authbasic,代码行数:21,代码来源:testing.py

示例10: FunctionalTests

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import reset [as 别名]
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)
开发者ID:AnneGilles,项目名称:c3sPortal,代码行数:49,代码来源:test_main_webtest.py

示例11: FunctionalTests

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import reset [as 别名]
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'})
#.........这里部分代码省略.........
开发者ID:OnroerendErfgoed,项目名称:oe_geoutils,代码行数:103,代码来源:test_functional.py

示例12: Test

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import reset [as 别名]
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 = "admin"
        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(
#.........这里部分代码省略.........
开发者ID:TheJF,项目名称:bottle-cork,代码行数:103,代码来源:test_functional.py

示例13: FunctionalTests

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import reset [as 别名]

#.........这里部分代码省略.........
#         #
#         ####################################################################
#         # 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"""
开发者ID:C3S,项目名称:speedfunding,代码行数:70,代码来源:test_webtest.py

示例14: ClientAgentTest

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import reset [as 别名]
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", "[email protected]"), 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", "[email protected]"), 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)
开发者ID:jrconlin,项目名称:moz_push,代码行数:91,代码来源:test_client_api.py

示例15: FunctionalTests

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import reset [as 别名]
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': '[email protected]'}
        #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):
#.........这里部分代码省略.........
开发者ID:AnneGilles,项目名称:c3sMembership,代码行数:103,代码来源:test_webtest.py


注:本文中的webtest.TestApp.reset方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。