""" Tests for :py:mod:`contact_form.forms`. """ from __future__ import absolute_import, unicode_literals import mock from mock import MagicMock, Mock from django.core.urlresolvers import reverse from django.test import TestCase from django.contrib.sites.models import Site from contact_form.forms import ContactForm TEST_DATA = { 'name': 'Test User', 'email': 'test@example.org', 'body': 'Test message' } class ContactFormTest(TestCase): def test_constructor_needs_request(self): with self.assertRaises(KeyError): ContactForm() def test_constructor(self): request = MagicMock() form = ContactForm(request=request) self.assertTrue(hasattr(form, 'request')) self.assertEqual(form.request, request) self.assertTrue(hasattr(form, 'helper')) self.assertEqual(form.helper.form_action, reverse('contact_form')) self.assertEqual(len(form.helper.inputs), 1) self.assertEqual(form.helper.inputs[0].name, 'submit') def test_constructor_fields(self): request = MagicMock() form = ContactForm(request=request) self.assertEqual(len(form.fields), 3) self.assertIn('email', form.fields) self.assertIn('name', form.fields) self.assertIn('body', form.fields) self.assertEqual(len(form.data), 0) def test_get_context_invalid(self): request = MagicMock() form = ContactForm(request=request) with self.assertRaisesMessage( ValueError, 'Cannot generate context from invalid contact form'): form.get_context() def test_get_context_valid_site_installed(self): request = MagicMock() form = ContactForm(request=request, data=TEST_DATA) context = form.get_context() self.assertIn('site', context) self.assertIn('name', context) self.assertIn('email', context) self.assertIn('body', context) def test_get_context_valid_site_not_installed(self): request = MagicMock() form = ContactForm(request=request, data=TEST_DATA) with mock.patch('contact_form.forms.Site') as sitemock: sitemock._meta.installed = False context = form.get_context() self.assertIn('site', context) self.assertIn('name', context) self.assertIn('email', context) self.assertIn('body', context) def test_message(self): request = Mock() request.META = {'REMOTE_ADDR': '127.0.0.1'} form = ContactForm(request=request, data=TEST_DATA) message = form.message() self.assertIn(TEST_DATA['name'], message) self.assertIn(TEST_DATA['email'], message) self.assertIn(TEST_DATA['body'], message) self.assertIn('127.0.0.1', message) def test_subject(self): request = Mock() form = ContactForm(request=request, data=TEST_DATA) subject = form.subject() self.assertIn(Site.objects.get_current().name, subject) self.assertIn(TEST_DATA['name'], subject)