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


Python Flask.test_client方法代码示例

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


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

示例1: EmailActivationTest

# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import test_client [as 别名]
class EmailActivationTest(TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        self.app.register_blueprint(emailactivation.views.app)
        self.app.config['SECRET_KEY'] = 'SECRET'
        self.mail = Mail(self.app)
        
        @self.app.route('/index')
        def index():
            return 'index'
        
    def testSendEmail(self):
        callback = my_callback
        
        data = {'mail':'[email protected]'}
        email = {'subject':'subject', 
                 'sender':'[email protected]'}
        with patch('test_activation.my_callback') as c:
            with self.app.test_request_context():
                c.return_value = url_for('index') 
                signature = signature_serialize(callback, data)
                with self.mail.record_messages() as outbox:
                    send_activation_email(self.mail,
                                          '[email protected]',
                                          callback=callback,
                                          data=data,
                                          email_context=email,
                                          template_context={},
                                          body_template='test.html')
                                      
                self.assertEquals(1, len(outbox), 'Email was sent')
                self.assertIn(url_for('emailactivation.activation', 
                                      signature=signature, _external=True),
                              outbox[0].body)
                
                with self.app.test_client() as client:
                    response = client.get(url_for('emailactivation.activation', 
                                                   signature=signature,))
                    self.assertEquals(302, response.status_code)
                    self.assertEquals(url_for('index', _external=True), 
                                      response.location)
开发者ID:tomasd,项目名称:flask-emailactivation,代码行数:43,代码来源:test_activation.py

示例2: BaseTestCase

# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import test_client [as 别名]
class BaseTestCase(TestCase):
    def setUp(self):
        self.app = Flask(__name__)

        self.test_client = self.app.test_client()
        self.init_logging()
        self.init_validator_context()
        self.config = TEST_CONFIG

        self.auth_cookie = None
        load_filters(self.app.jinja_env, self.config)
        self.app_context = self.app.app_context()
        self.app_context.__enter__()
        set_template_loader(self.app.jinja_env)
        init_configuration(self.app, self.config)
        init_blueprints(self.app)
        init_services(self.app)
        init_login_system(self.app)
        init_db(self.app)
        init_plugins()
        self.mailer = celery.conf['MAILER']
        self.mailer.mails = []
        self.sms_sender = celery.conf['SMS_SENDER']
        self.sms_sender.sms = []
        self.user = None
        self.user_profile = None
        UserManager.init(self.config, self.app.logger)
        sql_db.init_app(self.app)
        sql_db.create_all()
        for table in reversed(sql_db.metadata.sorted_tables):
            sql_db.engine.execute(table.delete())

        @self.app.errorhandler(413)
        def catcher(error):
            data_json = json.dumps({"error": {"code": errors.FileToLarge.ERROR_CODE, "message": errors.FileToLarge.ERROR_MESSAGE}})
            result = Response(data_json, mimetype='application/json', status=400)
            result.headers.add('Access-Control-Allow-Credentials', "true")
            result.headers.add('Access-Control-Allow-Origin', "http://%s" % self.config['site_domain'])
            return result

    def tearDown(self):
        sql_db.session.close()
        #sql_db.drop_all()
        for table in reversed(sql_db.metadata.sorted_tables):
            sql_db.engine.execute(table.delete())

        # noinspection PyUnresolvedReferences
        self.app.model_cache_context.clear()
        self.app_context.__exit__(None, None, None)

    def get_test_resource_name(self, name):
        return os.path.join(CURRENT_DIR, 'test_data', name)

    def init_logging(self):
        consoleHandler = logging.StreamHandler()
        consoleHandler.setFormatter(
            logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
        consoleHandler.setLevel(logging.DEBUG)
        self.app.logger.addHandler(consoleHandler)
        self.app.logger.setLevel(logging.DEBUG)

    def init_validator_context(self):
        self.app.validator_context = ValidatorContext()
        self.app.rendering_context = RenderingContext()
        self.app.model_cache_context = ModelCacheContext()
开发者ID:StanislavKraev,项目名称:jb_code,代码行数:67,代码来源:base_test_case.py

示例3: SimpleFlaskAppTest

# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import test_client [as 别名]
class SimpleFlaskAppTest(unittest.TestCase):

    def setUp(self):
        self.app = Flask(__name__)

        self.client = self.app.test_client()

        self.db = MongoEngine(self.app)

        with self.app.app_context():
            self.db.connection.drop_database("test")
        # self.db.connection

        class TestCol(db.Document):
            value = db.StringField()

            def __unicode__(self):
                return "TestCol(value={})".format(self.value)

        TestCol.objects.delete()

        TestCol.objects.create(value="1")
        TestCol.objects.create(value="2")

        self.TestCol = TestCol

    def _parse(self, resp):
        resp = resp.decode("utf-8")
        return json.loads(resp)

    def test_validation_mongoengine_will_work_with_model_serializer(self):

        class Doc(db.Document):
            value = db.StringField(validation=RegexpValidator(r"\d+", message="Bad value").for_mongoengine())

        Doc.drop_collection()

        class Serializer(ModelSerializer):
            class Meta:
                model = Doc

        Doc.objects.create(value="123")

        s = Serializer(data={"value": "asd"})
        self.assertEqual(s.validate(), False)
        self.assertEqual(s.errors, {"value": ["Bad value"]})

    def test_resource_decorator(self):

        class S(BaseSerializer):

            field = fields.StringField(required=True)

        @self.app.route("/test", methods=["POST"])
        @validate(S)
        def resource(cleaned_data):
            return "OK"

        resp = self.client.post("/test", data=json.dumps({}), headers={"Content-Type": "application/json"})
        self.assertEqual(resp.status_code, 400)
        self.assertEqual(
            json.loads(resp.data.decode("utf-8")), {'field': ['Field is required']}
        )

    def testSimpleResourceAndRouter(self):

        router = DefaultRouter(self.app)

        class Resource(BaseResource):

            def get(self, request):
                return "GET"

            def post(self, request):
                return "POST"

            def put(self, request):
                return "PUT"

            def patch(self, request):
                return "PATCH"

            def delete(self, request):
                return "DELETE"

            @list_route(methods=["GET", "POST"])
            def listroute(self, request):
                return "LIST"

            @detail_route(methods=["GET", "POST"])
            def detailroute(self, request, pk):
                return "detail"

        self.assertSetEqual(
            set(Resource.get_allowed_methods()), {"get", "post", "put", "patch", "delete"}
        )

        router.register("/test", Resource, "test")

        for method in ["get", "post", "put", "patch", "delete"]:
#.........这里部分代码省略.........
开发者ID:wnorales,项目名称:Python,代码行数:103,代码来源:test_flask_app.py


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