Я застрял, работая с TDD мои тесты проходят, когда они не должны, не знаю почему. Должен произойти сбой, модель заказа не обновляется, поэтому я думаю, что она должна выдать ошибку. Другое дело, я не мог записывать данные, когда тест пройден.
Django>=3.0.2,<3.1.0
djangorestframework>=3.11.0,<3.12.0
psycopg2>=2.8.4,<2.9.0
flake8>=3.7.9,<3.8.0
djangorestframework-simplejwt>=4.4.0,<4.5.0
channels>=2.4.0,<2.5.0
channels-redis>=2.4.2,<2.5.0
pytest-django>=3.8.0,<3.9.0
pytest-asyncio>=0.10.0,<1.0.0
test_websocket.py
@database_sync_to_async
async def test_user_can_create_orders(self, settings):
settings.CHANNEL_LAYERS = TEST_CHANNEL_LAYERS
user = await create_user(
email='employee@example.com',
group='user'
)
client = Client()
client.force_login(user=user)
communicator = WebsocketCommunicator(
application=channel_routing,
path='/notification/',
headers=[(
b'cookie',
f'sessionid={client.cookies["sessionid"].value}'.encode('ascii')
)]
)
# send JSON msg to a server.
await communicator.send_json_to({
'type': 'create.order',
'data': {
'user' : user.id,
}
})
response = await communicator.receive_json_from()
data = response.get('data')
assert data['id'] is not None
assert Order.REQUESTED == data['status']
assert data['employee'] is None
assert user.email == data['user'].get('email')
await communicator.disconnect()
models.py
class Order(models.Model):
REQUESTED = 'REQUESTED'
ACCEPTED = 'ACCEPTED'
DECLINED = 'DECLINED'
STARTED = 'STARTED'
IN_PROGRESS = "IN_PROGRESS"
READY = "READY"
COMPLETED = "COMPLETED"
STATUSES = (
(REQUESTED, REQUESTED),
(ACCEPTED, ACCEPTED),
(DECLINED, DECLINED),
(STARTED, STARTED),
(IN_PROGRESS, IN_PROGRESS),
(READY, READY),
(COMPLETED, COMPLETED),
)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
null=True
)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(
max_length=20, choices=STATUSES, default=REQUESTED)
def __str__(self):
return f'{self.id}'
def get_absolute_url(self):
return reverse('order:order_detail', kwargs={'order_id': self.id})
consumer.py
from channels.generic.websocket import AsyncJsonWebsocketConsumer
class NotificationConsumer(AsyncJsonWebsocketConsumer):
async def connect(self):
user = self.scope['user']
if user.is_anonymous:
await self.close()
else:
await self.accept()
routing.py
from channels.routing import ProtocolTypeRouter, URLRouter
from orders.consumers import NotificationConsumer
from django.urls import path
from .middleware.channelsmiddleware import TokenAuthMiddleware
channel_routing = ProtocolTypeRouter({
'websocket': TokenAuthMiddleware(
URLRouter([
path('notification/', NotificationConsumer),
])
)
}
)
Команда $ sudo docker - составить приложение run sh - c "pytest"