# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime import re import socket import unittest import mock from django.test import SimpleTestCase from ..views import RootView class RootUnitTestCase(unittest.TestCase): def test_get_context_data(self): default_color_hex = '47825b' test_data_sets = [ {}, {'hostname': 'localhost'}, {'hostname': 'abcde'}, {'hostname': 'frodo.abcdef.example.com'}, {'hostname': 'aBc-dEf', 'expected_color_hex': 'abcdef'}, {'hostname': 'ab34EF12cd56ZZ', 'expected_color_hex': 'ab34ef'}, {'hostname': 'abcde.example.com', 'expected_color_hex': 'abcdee'}, {'hostname': 'abcdef', 'kwargs': {'color_hex': '123456'}, 'expected_color_hex': '123456'}, ] real_hostname = socket.gethostname() for test_data in test_data_sets: if 'hostname' in test_data: hostname = test_data['hostname'] else: hostname = real_hostname if 'expected_color_hex' in test_data: expected_color_hex = test_data['expected_color_hex'] else: expected_color_hex = default_color_hex with mock.patch('socket.gethostname', return_value=hostname): view = RootView() if 'kwargs' in test_data: ctx = view.get_context_data(**test_data['kwargs']) else: ctx = view.get_context_data() self.assertIsInstance(ctx, dict) self.assertIn('hostname', ctx) self.assertEqual(ctx['hostname'], hostname) self.assertIn('color_hex', ctx) self.assertTrue(re.match('[0-9a-f]{6}', ctx['color_hex'])) self.assertEqual(ctx['color_hex'], expected_color_hex) self.assertIn('time', ctx) self.assertIsInstance(ctx['time'], datetime.datetime) class DjangoAdminDjangoTestCase(SimpleTestCase): def test_djangoadmin(self): response = self.client.get('/djangoadmin', follow=True) self.assertContains(response, 'Django administration') class RootDjangoTestCase(SimpleTestCase): def test_root_template(self): response = self.client.get('/') self.assertTemplateUsed(response, 'base/root.html') def test_root_context(self): response = self.client.get('/') self.assertIn('hostname', response.context) hostname = socket.gethostname() self.assertEqual(response.context['hostname'], hostname) self.assertIn('color_hex', response.context) self.assertTrue(re.match('[0-9a-f]{6}', response.context['color_hex'])) self.assertIn('time', response.context) self.assertIsInstance(response.context['time'], datetime.datetime) def test_root_content(self): response = self.client.get('/') hostname = socket.gethostname().capitalize() self.assertContains(response, hostname)