Skip to content

Instantly share code, notes, and snippets.

@matteosuppo
Created March 5, 2013 07:28
Show Gist options
  • Save matteosuppo/5088621 to your computer and use it in GitHub Desktop.
Save matteosuppo/5088621 to your computer and use it in GitHub Desktop.
"""
Feature: Events API
"""
from datetime import datetime, timedelta
import json
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
import factory
from . import models
class EveryoneCanReadRetrieveEvents(TestCase):
"""
Scenario: Everyone can list and retrieve the events
Background: Three events in database, user on the events root api
"""
def setUp(self):
self.c = Client()
self.events = [EventFactory() for i in range(0,3)]
self.assertEqual(len(self.events), 3)
self.root = reverse("event-root")
def test_anonymous_list_events(self):
"""
Given I am Anonymous
When I visit the event-list API
Then I should see the three events
"""
res = self.c.get(self.root)
url = res.data['event-list'] # Get the url from the root api
res = self.c.get(url)
self.assertEqual(res.status_code, 200)
self.assertEqual(len(res.data['results']), 3)
return res
def test_anonymous_detail_event(self):
"""
Given I am Anonymous
And I saw the three events
When I visit the event-detail of one of those events
Then I should see the detail of the event
"""
res = self.test_anonymous_list_events() # On top of previous test
url = res.data['results'][0]['url']
res = self.c.get(url)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.data['title'], "Event 0")
return res
class OnlyLoggedUsersCreateEditEvents(TestCase):
"""
Scenario: Only logged users can create and edit events
Background: Three events in database, user on the events root api
"""
def setUp(self):
self.c = Client()
self.events = [EventFactory() for i in range(0,3)]
self.assertEqual(len(self.events), 3)
self.root = reverse("event-root")
def test_anonymous_cant_create(self):
"""
Given I am Anonymous
When I try to POST on the list-event API
Then I should not be able to
And I should see an error explaining I have to login
"""
res = self.c.get(self.root)
url = res.data['event-list'] # Get the url from the root api
res = self.c.post(url)
self.assertEqual(res.status_code, 401) # Unauthenticated
def test_authenticated_can_create(self):
"""
Given I am an Authenticated user
When I try to POST on the list-event-API
Then I should succeed
And I should see the resource created
"""
user = models.User.objects.create_user("janedoe", password="Missing")
self.c.login(username=user.username, password="Missing")
res = self.c.get(self.root)
url = res.data['event-list'] # Get the url from the root api
data = {
"title": "Jane's birthday",
"description": "A good party",
"date_start": datetime.now(),
"date_end": datetime.now()+timedelta(hours=2)
}
res = self.c.post(url, data=data)
self.assertEqual(res.status_code, 201) # Created
self.assertIn("A good party", res.content.decode())
self.assertIn("Jane's birthday", res.content.decode())
return res, user
def test_user2_can_create_event_belonging_to_them(self):
"""
Given I am an Authenticated user
When I POST and create an event
the event should be owned by me
"""
res, user = self.test_authenticated_can_create()
self.assertEqual(res.data['by'], user.username)
class UsersCanEditOnlyTheirEvents(TestCase):
"""
Scenario: Users can edit only the events that belongs to them.
Background: Two users registered, an event belonging to user 1,
user on the event detail api
"""
def setUp(self):
self.c = Client()
self.user1 = models.User.objects.create_user("janedoe",
password="Missing")
self.user2 = models.User.objects.create_user("johndoe",
password="Missing")
self.event = EventFactory(owner=self.user1)
self.assertEqual(self.event.owner, self.user1)
self.root = reverse("event-detail", args=(self.event.id,))
def test_user1_can_edit_their_event(self):
"""
Given I am an Authenticated user (User 1)
When I try to PUT an event owned by me
Then I should succeed
And I should see the resource modified
"""
data = {
"title": "Jane's birthday",
"description": "A good party",
"date_start": datetime.now(),
"date_end": datetime.now()+timedelta(hours=2)
}
res = self.c.get(self.root)
self.assertNotIn("A good party", res.content.decode())
self.c.login(username="janedoe", password="Missing")
# With PUT we have to encode data
data = DateTimeJSONEncoder().encode(data)
res = self.c.put(self.root, data=data, content_type="application/json")
self.assertEqual(res.status_code, 200) # OK
self.assertIn("A good party", res.content.decode())
def test_user2_cannot_edit_user1_event(self):
"""
Given I am an Authenticated user (User 2)
When I try to PUT an event owned by User 1
Then I should fail
"""
data = {
"title": "Jane's birthday",
"description": "A good party",
"date_start": datetime.now(),
"date_end": datetime.now()+timedelta(hours=2)
}
res = self.c.get(self.root)
self.assertNotIn("A good party", res.content.decode())
self.c.login(username="johndoe", password="Missing")
# With PUT we have to encode data
data = DateTimeJSONEncoder().encode(data)
res = self.c.put(self.root, data=data, content_type="application/json")
self.assertEqual(res.status_code, 403) # Forbidden
# Factories and Helpers
class DateTimeJSONEncoder(json.JSONEncoder):
"""
Serialize a datetime-like object
"""
def default(self, obj):
if hasattr(obj, 'isoformat') :
return obj.isoformat()
else:
return super(DateTimeJSONEncoder, self).default(obj)
class UserFactory(factory.Factory):
FACTORY_FOR = models.User
first_name = 'John'
last_name = 'Doe'
username = factory.Sequence(lambda n: 'johndoe{0}'.format(n))
class EventFactory(factory.Factory):
FACTORY_FOR = models.Event
title = factory.Sequence(lambda n: 'Event {0}'.format(n))
description = "Description"
date_start = datetime.now()-timedelta(hours=1) # 1 hour ago
date_end = datetime.now()+timedelta(hours=1) # in an hour
owner = factory.SubFactory(UserFactory)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment