我正在使用Flask-Testing进行Flask集成测试.我有一个表格,上面有一个徽标文件,我正在尝试编写测试但是我一直收到错误说:TypeError: 'str' does not support the buffer interface.
我正在使用Python 3.我找到的最接近的答案是这个,但它对我不起作用.
这是我的许多尝试之一:
def test_edit_logo(self):
"""Test can upload logo."""
data = {'name': 'this is a name', 'age': 12}
data['file'] = (io.BytesIO(b"abcdef"), 'test.jpg')
self.login()
response = self.client.post(
url_for('items.save'), data=data, follow_redirects=True)
})
self.assertIn(b'Your item has been saved.', response.data)
advert = Advert.query.get(1)
self.assertIsNotNone(item.logo)
Run Code Online (Sandbox Code Playgroud)
如何在Flask中测试文件上传?
我必须测试一个从request.args获取某些信息的视图.
我无法模仿这个,因为视图中的很多东西都使用了请求对象.我能想到的唯一选择是手动设置request.args.
我可以用test_request_context()做到这一点,例如:
with self.app.test_request_context() as req:
req.request.args = {'code': 'mocked access token'}
MyView()
Run Code Online (Sandbox Code Playgroud)
现在,此视图中的请求将包含我已设置的参数.但是我需要调用我的视图,而不仅仅是初始化它,所以我使用它:
with self.app.test_client() as c:
resp = c.get('/myview')
Run Code Online (Sandbox Code Playgroud)
但我不知道如何以这种方式操纵请求参数.
我试过这个:
with self.app.test_client() as c:
with self.app.test_request_context() as req:
req.request.args = {'code': 'mocked access token'}
resp = c.get('/myview')
Run Code Online (Sandbox Code Playgroud)
但是这没有设置request.args.
我开始用Flask-SQLAlchemy编写测试,我想为那些添加一些灯具.我在我的开发数据库和很多表中都有很多好的数据,因此手动编写数据会很烦人.我真的很想从dev数据库中将数据采样到灯具中然后使用它们.这样做的好方法是什么?
我使用Flask-Testing并使文件test_app.py进行测试但是我从app import create_app获得了此错误文件"test_app.py",第4行,db ImportError:没有名为app的模块.所以请帮助我如何解决它,问题是什么Thanx :)
这是我的结构:
myapplication
app
__ init __.py
model.py
form.py
autho
layout
static
templates
migrations
test
-test_app.py
config.py
manage.py
Run Code Online (Sandbox Code Playgroud)
test_app.py
#!flask/bin/python
import unittest
from flask.ext.testing import TestCase
from app import create_app, db
from app.model import Users
from flask import request, url_for
import flask
class BaseTestCase(TestCase):
def create_app(self):
self.app = create_app('testing')
return self.app
Run Code Online (Sandbox Code Playgroud)
config.py
class TestingConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'mytest.sqlite')
Run Code Online (Sandbox Code Playgroud)
__ init __.py
#!flask/bin/python
from flask import Flask
from flask.ext.sqlalchemy …Run Code Online (Sandbox Code Playgroud) 在做Miguel Grinberg的Flask Web开发时,我在测试gravatar代码时遇到困难,
def test_gravatar(self):
u = User(email='john@example.com', password='cat')
with self.app.test_request_context('/'):
gravatar = u.gravatar()
gravatar_256 = u.gravatar(size=256)
gravatar_pg = u.gravatar(rating='pg')
gravatar_retro = u.gravatar(default='retro')
with self.app.test_request_context('/', base_url='https://example.com'):
gravatar_ssl = u.gravatar()
self.assertTrue('http://www.gravatar.com/avatar/' +
'd4c74594d841139328695756648b6bd6'in gravatar)
self.assertTrue('s=256' in gravatar_256)
self.assertTrue('r=pg' in gravatar_pg)
self.assertTrue('d=retro' in gravatar_retro)
self.assertTrue('https://secure.gravatar.com/avatar/' +
'd4c74594d841139328695756648b6bd6' in gravatar_ssl)
Run Code Online (Sandbox Code Playgroud)
app.test_request_context()做什么以及它与app_context()的不同之处是什么?
为什么我们甚至需要使用self.app.test_request_context('/')进行调用?另外,我们可以做些什么更改来将调用转移到SetUp()中的app.test_request_context()?
失败unit_test.py::TestClass::test_login - AttributeError:'WrapperTestResponse'对象没有属性'text'
2.这是我的单元测试实现代码,我可以成功获取状态代码,但不能获取文本。我犯了一些错误吗?
import unittest
from app import app
import requests
from flask import request
import json
class TestClass(unittest.TestCase):
def setup_class(self):
app.config['TESTING'] = True
self.app = app.test_client()
def teardown_class(self):
"""Do the testing """
pass
def test_login(self):
response = self.app.get('/login')
print(response)
data = {'username': '123456@qq.com', 'password': '12345678'}
response = app.test_client().post('/login', data=json.dumps(data))
self.assertEqual(response.status_code, 200)
print('--------------')
self.assertEqual(response.text, "Invalid login credentials")
Run Code Online (Sandbox Code Playgroud) 运行我的测试时,我得到以下回溯.
in get_context_variable
raise RuntimeError("Signals not supported")
RuntimeError: Signals not supported
Run Code Online (Sandbox Code Playgroud)
__init__.py
from flask_testing import TestCase
from app import create_app, db
class BaseTest(TestCase):
BASE_URL = 'http://localhost:5000/'
def create_app(self):
return create_app('testing')
def setUp(self):
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
def test_setup(self):
response = self.client.get(self.BASE_URL)
self.assertEqual(response.status_code, 200)
Run Code Online (Sandbox Code Playgroud)
test_routes.py
from . import BaseTest
class TestMain(BaseTest):
def test_empty_index(self):
r = self.client.get('/')
self.assert200(r)
self.assertEqual(self.get_context_variable('partners'), None)
Run Code Online (Sandbox Code Playgroud)
似乎get_context_variable函数调用是错误来自的地方.如果我尝试使用,我也会收到此错误assert_template_used.找到任何解决方案都很困难.
我正在使用 Flask-testing 对 Postgres 应用程序进行一些单元测试。根据文档,我有以下代码。
from flask_testing import TestCase
from src.game.models import db
from src import create_app
class BaseTest(TestCase):
SQLALCHEMY_DATABASE_URI = 'postgresql://demo:demo@postgres:5432/test_db'
TESTING = True
def create_app(self):
# pass in test configuration
return create_app(self)
def setUp(self):
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
Run Code Online (Sandbox Code Playgroud)
当然我得到了这个错误
sqlalchemy.exc.OperationalError:(psycopg2.OperationalError)致命:数据库“test_db”不存在
我确实有一个数据库postgresql://demo:demo@postgres:5432/demo,它是我的生产数据库。
我如何test_db在这BaseTest堂课上进行创作?我正在使用Python 3.6和最新的flask和flask-sqlalchemy。非常感谢。
postgresql unit-testing flask flask-sqlalchemy flask-testing
我正在尝试使用Flask-Testing Flask-SQLAlchemy模型进行测试。更准确地说,该模型使用静态方法first_or_404(),但我无法找到使我的测试工作的方法。
这是一个突出问题的独立示例:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask.ext.testing import TestCase
db = SQLAlchemy()
class ModelToTest(db.Model):
__tablename__ = 'model_to_test'
identifier = db.Column(db.String(80), unique=True, nullable=False, primary_key=True)
@staticmethod
def get_by_identifier(identifier):
return ModelToTest.query.filter_by(identifier=identifier).first_or_404()
class Config:
DEBUG = True
TESTING = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///'
SQLALCHEMY_TRACK_MODIFICATIONS = False
class TestGetByIdentifier(TestCase):
def create_app(self):
app = Flask('test')
app.config.from_object(Config())
db.init_app(app)
return app
def setUp(self):
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
def test_get_by_identifier(self):
self.assert404(ModelToTest.get_by_identifier('identifier'))
Run Code Online (Sandbox Code Playgroud)
我收到错误:
(my_env) PS C:\Dev\Test\Python\test_flask> nosetests-3.4.exe
E
====================================================================== …Run Code Online (Sandbox Code Playgroud) I'm trying to do unit testing of my Flask web app. I'm use a pattern I saw in a Udemy class on Flask and a pattern similar to the Flask Mega-Tutorial online (http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-vii-unit-testing). The problem I'm having is that the test does not actual create it's own database -- rather it uses the production database and messes it up.
Here's what tests.py script looks like:
import os,sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
basedir = os.path.abspath(os.path.dirname(__file__))
import unittest
from myapp import app, …Run Code Online (Sandbox Code Playgroud) 我试图使用烧瓶测试客户端在我的Flask应用程序中测试PUT请求.一切看起来都不错,但我一直得到400 BAD请求.
我使用POSTMAN尝试了相同的请求,然后我得到了回复.
这是代码
from flask import Flask
app = Flask(__name__)
data = {"filename": "/Users/resources/rovi_source_mock.csv"}
headers = {'content-type': 'application/json'}
api = "http://localhost:5000/ingest"
with app.test_client() as client:
api_response = client.put(api, data=data, headers=headers)
print(api_response)
Run Code Online (Sandbox Code Playgroud)
产量
Response streamed [400 BAD REQUEST]
Run Code Online (Sandbox Code Playgroud) 当我尝试使用 Flask_testing 中的 LiveServerTestCase 在 Flask 应用程序上运行单元测试时,我收到了标题中提到的错误。
这是我的测试文件:
from app import create_app
from flask_testing import LiveServerTestCase
class TestBase(LiveServerTestCase):
def create_app(self):
app = create_app()
app.config.update(LIVESERVER_PORT=8847, TESTING=True)
return app
def test_app(self):
self.assertEqual('test', 'test')
Run Code Online (Sandbox Code Playgroud)
这是我使用nose2运行测试时遇到的错误:
AttributeError: Can't pickle local object 'LiveServerTestCase._spawn_live_server.<locals>.worker'
During handling of the above exception, another exception occurred:
AttributeError: 'NoneType' object has no attribute 'terminate'
Internal Error: runTests aborted: 'NoneType' object has no attribute 'terminate'
Run Code Online (Sandbox Code Playgroud)
我真的在网上找不到任何关于这个问题的有用信息,
flask-testing ×12
flask ×11
python ×9
unit-testing ×3
http ×1
postgresql ×1
pytest ×1
python-2.7 ×1
python-3.x ×1
selenium ×1
sqlalchemy ×1
sqlite ×1
testing ×1
web ×1