Fix tests for Python 3

- drop Python 2 __future__ imports
- fix tests to handle new Django and Python 3 module names
- reformat changed files with black
This commit is contained in:
Jan Dittberner 2019-01-30 21:27:25 +01:00
parent ddec6b4184
commit 3d18392b67
32 changed files with 2707 additions and 2675 deletions

View file

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

View file

@ -2,126 +2,122 @@
Tests for :py:mod:`contact_form.views`. Tests for :py:mod:`contact_form.views`.
""" """
from __future__ import absolute_import, unicode_literals
from django.core import mail
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.core import mail
from django.test import TestCase
from django.urls import reverse
User = get_user_model() User = get_user_model()
TEST_USER = 'test' TEST_USER = "test"
TEST_PASSWORD = 'secret' TEST_PASSWORD = "secret"
TEST_EMAIL = 'test@example.org' TEST_EMAIL = "test@example.org"
TEST_NAME = 'Example Tester'.split() TEST_NAME = "Example Tester".split()
TEST_MESSAGE = ''' TEST_MESSAGE = """
This is a really unimportant test message. This is a really unimportant test message.
''' """
class ContactFormViewTest(TestCase): class ContactFormViewTest(TestCase):
def _setup_user(self, **kwargs): def _setup_user(self, **kwargs):
return User.objects.create_user( return User.objects.create_user(
TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD, TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD, **kwargs
**kwargs) )
def test_get_contact_form_template(self): def test_get_contact_form_template(self):
response = self.client.get(reverse('contact_form')) response = self.client.get(reverse("contact_form"))
self.assertTemplateUsed(response, 'contact_form/contact_form.html') self.assertTemplateUsed(response, "contact_form/contact_form.html")
def test_get_contact_form_anonymous_status(self): def test_get_contact_form_anonymous_status(self):
response = self.client.get(reverse('contact_form')) response = self.client.get(reverse("contact_form"))
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_get_contact_form_anonymous_has_empty_form(self): def test_get_contact_form_anonymous_has_empty_form(self):
response = self.client.get(reverse('contact_form')) response = self.client.get(reverse("contact_form"))
self.assertIn('form', response.context) self.assertIn("form", response.context)
form = response.context['form'] form = response.context["form"]
self.assertEqual(len(form.initial), 0) self.assertEqual(len(form.initial), 0)
def test_get_contact_form_fields_anonymous(self): def test_get_contact_form_fields_anonymous(self):
response = self.client.get(reverse('contact_form')) response = self.client.get(reverse("contact_form"))
for name in ('name', 'email', 'body'): for name in ("name", "email", "body"):
self.assertIn(name, response.context['form'].fields) self.assertIn(name, response.context["form"].fields)
def test_post_empty_form_template(self): def test_post_empty_form_template(self):
response = self.client.post(reverse('contact_form'), {}) response = self.client.post(reverse("contact_form"), {})
self.assertTemplateUsed(response, 'contact_form/contact_form.html') self.assertTemplateUsed(response, "contact_form/contact_form.html")
def test_post_empty_form_status(self): def test_post_empty_form_status(self):
response = self.client.post(reverse('contact_form'), {}) response = self.client.post(reverse("contact_form"), {})
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_post_empty_form_validation_errors(self): def test_post_empty_form_validation_errors(self):
response = self.client.post(reverse('contact_form'), {}) response = self.client.post(reverse("contact_form"), {})
self.assertIn('form', response.context) self.assertIn("form", response.context)
form = response.context['form'] form = response.context["form"]
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertEqual(len(form.errors), 3) self.assertEqual(len(form.errors), 3)
def test_post_empty_form_no_mail(self): def test_post_empty_form_no_mail(self):
self.client.post(reverse('contact_form'), {}) self.client.post(reverse("contact_form"), {})
self.assertEqual(len(mail.outbox), 0) self.assertEqual(len(mail.outbox), 0)
def test_get_contact_form_logged_in_no_fullname_initial(self): def test_get_contact_form_logged_in_no_fullname_initial(self):
self._setup_user() self._setup_user()
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get(reverse('contact_form')) response = self.client.get(reverse("contact_form"))
self.assertIn('form', response.context) self.assertIn("form", response.context)
form = response.context['form'] form = response.context["form"]
self.assertEqual( self.assertEqual(form.initial, {"name": TEST_USER, "email": TEST_EMAIL})
form.initial, {'name': TEST_USER, 'email': TEST_EMAIL})
def test_get_contact_form_logged_in_fullname_initial(self): def test_get_contact_form_logged_in_fullname_initial(self):
self._setup_user( self._setup_user(first_name=TEST_NAME[0], last_name=TEST_NAME[1])
first_name=TEST_NAME[0], last_name=TEST_NAME[1])
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get(reverse('contact_form')) response = self.client.get(reverse("contact_form"))
self.assertIn('form', response.context) self.assertIn("form", response.context)
form = response.context['form'] form = response.context["form"]
self.assertEqual( self.assertEqual(
form.initial, form.initial, {"name": " ".join(TEST_NAME), "email": TEST_EMAIL}
{'name': " ".join(TEST_NAME), 'email': TEST_EMAIL}) )
def test_post_filled_form_anonymous_redirects(self): def test_post_filled_form_anonymous_redirects(self):
response = self.client.post(reverse('contact_form'), { response = self.client.post(
'name': TEST_USER, 'email': TEST_EMAIL, 'body': TEST_MESSAGE}) reverse("contact_form"),
self.assertRedirects(response, reverse('contact_success')) {"name": TEST_USER, "email": TEST_EMAIL, "body": TEST_MESSAGE},
)
self.assertRedirects(response, reverse("contact_success"))
def test_post_filled_form_anonymous_mail(self): def test_post_filled_form_anonymous_mail(self):
self.client.post(reverse('contact_form'), { self.client.post(
'name': TEST_USER, 'email': TEST_EMAIL, 'body': TEST_MESSAGE}) reverse("contact_form"),
{"name": TEST_USER, "email": TEST_EMAIL, "body": TEST_MESSAGE},
)
self.assertEqual(len(mail.outbox), 1) self.assertEqual(len(mail.outbox), 1)
def test_post_filled_form_logged_in_redirects(self): def test_post_filled_form_logged_in_redirects(self):
self._setup_user( self._setup_user(first_name=TEST_NAME[0], last_name=TEST_NAME[1])
first_name=TEST_NAME[0], last_name=TEST_NAME[1])
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.post(reverse('contact_form'), { response = self.client.post(
'name': " ".join(TEST_NAME), 'email': TEST_EMAIL, reverse("contact_form"),
'body': TEST_MESSAGE}) {"name": " ".join(TEST_NAME), "email": TEST_EMAIL, "body": TEST_MESSAGE},
self.assertRedirects(response, reverse('contact_success')) )
self.assertRedirects(response, reverse("contact_success"))
def test_post_filled_form_logged_in_mail(self): def test_post_filled_form_logged_in_mail(self):
self._setup_user( self._setup_user(first_name=TEST_NAME[0], last_name=TEST_NAME[1])
first_name=TEST_NAME[0], last_name=TEST_NAME[1])
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
self.client.post(reverse('contact_form'), { self.client.post(
'name': " ".join(TEST_NAME), 'email': TEST_EMAIL, reverse("contact_form"),
'body': TEST_MESSAGE}) {"name": " ".join(TEST_NAME), "email": TEST_EMAIL, "body": TEST_MESSAGE},
)
self.assertEqual(len(mail.outbox), 1) self.assertEqual(len(mail.outbox), 1)
class ContactSuccessViewTest(TestCase): class ContactSuccessViewTest(TestCase):
def test_get_template(self): def test_get_template(self):
response = self.client.get(reverse('contact_success')) response = self.client.get(reverse("contact_success"))
self.assertTemplateUsed(response, 'contact_form/contact_success.html') self.assertTemplateUsed(response, "contact_form/contact_success.html")
def test_get_status(self): def test_get_status(self):
response = self.client.get(reverse('contact_success')) response = self.client.get(reverse("contact_success"))
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)

View file

@ -3,66 +3,65 @@ Tests for :py:mod:`dashboard.views`.
""" """
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
User = get_user_model() User = get_user_model()
TEST_USER = 'test' TEST_USER = "test"
TEST_PASSWORD = 'secret' TEST_PASSWORD = "secret"
class IndexViewTest(TestCase): class IndexViewTest(TestCase):
def test_index_view(self): def test_index_view(self):
response = self.client.get(reverse('dashboard')) response = self.client.get(reverse("dashboard"))
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'dashboard/index.html') self.assertTemplateUsed(response, "dashboard/index.html")
class UserDashboardViewTest(TestCase): class UserDashboardViewTest(TestCase):
def _create_test_user(self): def _create_test_user(self):
self.user = User.objects.create(username=TEST_USER) self.user = User.objects.create(username=TEST_USER)
self.user.set_password(TEST_PASSWORD) self.user.set_password(TEST_PASSWORD)
self.user.save() self.user.save()
def test_user_dashboard_view_no_user(self): def test_user_dashboard_view_no_user(self):
response = self.client.get(reverse( response = self.client.get(
'customer_dashboard', kwargs={'slug': TEST_USER})) reverse("customer_dashboard", kwargs={"slug": TEST_USER})
)
self.assertEqual(response.status_code, 404) self.assertEqual(response.status_code, 404)
def test_user_dashboard_view_anonymous(self): def test_user_dashboard_view_anonymous(self):
User.objects.create(username=TEST_USER) User.objects.create(username=TEST_USER)
response = self.client.get(reverse( response = self.client.get(
'customer_dashboard', kwargs={'slug': TEST_USER})) reverse("customer_dashboard", kwargs={"slug": TEST_USER})
)
self.assertEqual(response.status_code, 403) self.assertEqual(response.status_code, 403)
def test_user_dashboard_view_logged_in_ok(self): def test_user_dashboard_view_logged_in_ok(self):
self._create_test_user() self._create_test_user()
self.assertTrue( self.assertTrue(self.client.login(username=TEST_USER, password=TEST_PASSWORD))
self.client.login(username=TEST_USER, password=TEST_PASSWORD)) response = self.client.get(
response = self.client.get(reverse( reverse("customer_dashboard", kwargs={"slug": TEST_USER})
'customer_dashboard', kwargs={'slug': TEST_USER})) )
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_user_dashboard_view_logged_in_template(self): def test_user_dashboard_view_logged_in_template(self):
self._create_test_user() self._create_test_user()
self.assertTrue( self.assertTrue(self.client.login(username=TEST_USER, password=TEST_PASSWORD))
self.client.login(username=TEST_USER, password=TEST_PASSWORD)) response = self.client.get(
response = self.client.get(reverse( reverse("customer_dashboard", kwargs={"slug": TEST_USER})
'customer_dashboard', kwargs={'slug': TEST_USER})) )
self.assertTemplateUsed(response, 'dashboard/user_dashboard.html') self.assertTemplateUsed(response, "dashboard/user_dashboard.html")
def test_user_dashboard_view_logged_in_context_fresh(self): def test_user_dashboard_view_logged_in_context_fresh(self):
self._create_test_user() self._create_test_user()
self.assertTrue( self.assertTrue(self.client.login(username=TEST_USER, password=TEST_PASSWORD))
self.client.login(username=TEST_USER, password=TEST_PASSWORD)) response = self.client.get(
response = self.client.get(reverse( reverse("customer_dashboard", kwargs={"slug": TEST_USER})
'customer_dashboard', kwargs={'slug': TEST_USER})) )
self.assertIn('dashboard_user', response.context) self.assertIn("dashboard_user", response.context)
self.assertEqual(self.user, response.context['dashboard_user']) self.assertEqual(self.user, response.context["dashboard_user"])
self.assertIn('hosting_packages', response.context) self.assertIn("hosting_packages", response.context)
self.assertEqual(len(response.context['hosting_packages']), 0) self.assertEqual(len(response.context["hosting_packages"]), 0)

View file

@ -1,8 +1,8 @@
from django.test import TestCase from django.test import TestCase
from django.core.urlresolvers import reverse from django.urls import reverse
class TestMailDomainAdmin(TestCase): class TestMailDomainAdmin(TestCase):
def test_admin_for_maildomain(self): def test_admin_for_maildomain(self):
admin_url = reverse('admin:domains_maildomain_changelist') admin_url = reverse("admin:domains_maildomain_changelist")
self.assertIsNotNone(admin_url) self.assertIsNotNone(admin_url)

View file

@ -2,51 +2,42 @@
Tests for :py:mod:`domains.forms`. Tests for :py:mod:`domains.forms`.
""" """
from __future__ import absolute_import, unicode_literals from unittest.mock import MagicMock, Mock, patch
from mock import MagicMock, Mock, patch
from django.core.urlresolvers import reverse
from django.forms import ValidationError from django.forms import ValidationError
from django.test import TestCase from django.test import TestCase
from django.urls import reverse
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from domains.forms import relative_domain_validator, CreateHostingDomainForm from domains.forms import relative_domain_validator, CreateHostingDomainForm
class RelativeDomainValidatorTest(TestCase): class RelativeDomainValidatorTest(TestCase):
def test_valid_domainname(self): def test_valid_domainname(self):
relative_domain_validator('example.org') relative_domain_validator("example.org")
def test_domain_name_too_long(self): def test_domain_name_too_long(self):
with self.assertRaisesMessage( with self.assertRaisesMessage(ValidationError, _("host name too long")):
ValidationError, _('host name too long')): relative_domain_validator("e" * 255)
relative_domain_validator('e' * 255)
def test_domain_name_part_too_long(self): def test_domain_name_part_too_long(self):
with self.assertRaisesMessage( with self.assertRaisesMessage(ValidationError, _("invalid domain name")):
ValidationError, _('invalid domain name')): relative_domain_validator("a" * 64 + ".org")
relative_domain_validator('a' * 64 + '.org')
def test_domain_name_illegal_characters(self): def test_domain_name_illegal_characters(self):
with self.assertRaisesMessage( with self.assertRaisesMessage(ValidationError, _("invalid domain name")):
ValidationError, _('invalid domain name')): relative_domain_validator("eXampl3.org")
relative_domain_validator('eXampl3.org')
def test_domain_name_starts_with_dash(self): def test_domain_name_starts_with_dash(self):
with self.assertRaisesMessage( with self.assertRaisesMessage(ValidationError, _("invalid domain name")):
ValidationError, _('invalid domain name')): relative_domain_validator("-example.org")
relative_domain_validator('-example.org')
def test_domain_name_ends_with_dash(self): def test_domain_name_ends_with_dash(self):
with self.assertRaisesMessage( with self.assertRaisesMessage(ValidationError, _("invalid domain name")):
ValidationError, _('invalid domain name')): relative_domain_validator("example-.org")
relative_domain_validator('example-.org')
class CreateHostingDomainFormTest(TestCase): class CreateHostingDomainFormTest(TestCase):
def test_constructor_needs_hostingpackage(self): def test_constructor_needs_hostingpackage(self):
instance = MagicMock() instance = MagicMock()
with self.assertRaises(KeyError): with self.assertRaises(KeyError):
@ -56,50 +47,53 @@ class CreateHostingDomainFormTest(TestCase):
hostingpackage = Mock(id=42) hostingpackage = Mock(id=42)
instance = MagicMock() instance = MagicMock()
form = CreateHostingDomainForm(instance, hostingpackage=hostingpackage) form = CreateHostingDomainForm(instance, hostingpackage=hostingpackage)
self.assertTrue(hasattr(form, 'hosting_package')) self.assertTrue(hasattr(form, "hosting_package"))
self.assertEqual(form.hosting_package, hostingpackage) self.assertEqual(form.hosting_package, hostingpackage)
self.assertTrue(hasattr(form, 'helper')) self.assertTrue(hasattr(form, "helper"))
self.assertEqual(form.helper.form_action, reverse( self.assertEqual(
'create_hosting_domain', kwargs={'package': 42})) form.helper.form_action,
reverse("create_hosting_domain", kwargs={"package": 42}),
)
self.assertEqual(len(form.helper.layout.fields), 2) self.assertEqual(len(form.helper.layout.fields), 2)
self.assertEqual(form.helper.layout.fields[1].name, 'submit') self.assertEqual(form.helper.layout.fields[1].name, "submit")
def test_domain_field_has_relative_domain_validator(self): def test_domain_field_has_relative_domain_validator(self):
hostingpackage = Mock(id=42) hostingpackage = Mock(id=42)
instance = MagicMock() instance = MagicMock()
form = CreateHostingDomainForm(instance, hostingpackage=hostingpackage) form = CreateHostingDomainForm(instance, hostingpackage=hostingpackage)
self.assertIn( self.assertIn(relative_domain_validator, form.fields["domain"].validators)
relative_domain_validator, form.fields['domain'].validators)
def test_clean(self): def test_clean(self):
hostingpackage = Mock(id=42) hostingpackage = Mock(id=42)
instance = MagicMock() instance = MagicMock()
form = CreateHostingDomainForm( form = CreateHostingDomainForm(
instance, hostingpackage=hostingpackage, instance, hostingpackage=hostingpackage, data={"domain": "example.org"}
data={'domain': 'example.org'}) )
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
self.assertIn('hosting_package', form.cleaned_data) self.assertIn("hosting_package", form.cleaned_data)
self.assertEqual(hostingpackage, form.cleaned_data['hosting_package']) self.assertEqual(hostingpackage, form.cleaned_data["hosting_package"])
def test_save(self): def test_save(self):
hostingpackage = Mock(id=42) hostingpackage = Mock(id=42)
instance = MagicMock() instance = MagicMock()
form = CreateHostingDomainForm( form = CreateHostingDomainForm(
instance, hostingpackage=hostingpackage, instance, hostingpackage=hostingpackage, data={"domain": "example.org"}
data={'domain': 'example.org'}) )
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
with patch('domains.forms.HostingDomain') as domain: with patch("domains.forms.HostingDomain") as domain:
form.save() form.save()
domain.objects.create_for_hosting_package.assert_called_with( domain.objects.create_for_hosting_package.assert_called_with(
commit=True, **form.cleaned_data) commit=True, **form.cleaned_data
)
form.save(commit=False) form.save(commit=False)
domain.objects.create_for_hosting_package.assert_called_with( domain.objects.create_for_hosting_package.assert_called_with(
commit=False, **form.cleaned_data) commit=False, **form.cleaned_data
)
def test_save_m2m(self): def test_save_m2m(self):
hostingpackage = Mock(id=42) hostingpackage = Mock(id=42)
instance = MagicMock() instance = MagicMock()
form = CreateHostingDomainForm( form = CreateHostingDomainForm(
instance, hostingpackage=hostingpackage, instance, hostingpackage=hostingpackage, data={"domain": "example.org"}
data={'domain': 'example.org'}) )
form.save_m2m() form.save_m2m()

View file

@ -2,9 +2,7 @@
Tests for :py:mod:`domains.models`. Tests for :py:mod:`domains.models`.
""" """
from __future__ import absolute_import, unicode_literals from unittest.mock import patch
from mock import patch
from django.test import TestCase from django.test import TestCase
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
@ -20,41 +18,38 @@ from domains.models import (
HostingDomain, HostingDomain,
MailDomain, MailDomain,
) )
from hostingpackages.models import ( from hostingpackages.models import CustomerHostingPackage, HostingPackageTemplate
CustomerHostingPackage,
HostingPackageTemplate,
)
User = get_user_model() User = get_user_model()
TEST_USER = 'test' TEST_USER = "test"
class MailDomainTest(TestCase): class MailDomainTest(TestCase):
def test___str__(self): def test___str__(self):
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
self.assertEqual(str(md), 'example.org') self.assertEqual(str(md), "example.org")
def test_get_mailaddresses(self): def test_get_mailaddresses(self):
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
from managemails.models import MailAddress from managemails.models import MailAddress
addrmock = MailAddress.objects.create(localpart='info', domain=md)
addrmock = MailAddress.objects.create(localpart="info", domain=md)
self.assertIn(addrmock, md.get_mailaddresses()) self.assertIn(addrmock, md.get_mailaddresses())
self.assertIn(addrmock, md.mailaddresses) self.assertIn(addrmock, md.mailaddresses)
class HostingDomainManagerTest(TestCase): class HostingDomainManagerTest(TestCase):
def _setup_hosting_package(self): def _setup_hosting_package(self):
template = HostingPackageTemplate.objects.create( template = HostingPackageTemplate.objects.create(
name='testpackagetemplate', mailboxcount=0, diskspace=1, name="testpackagetemplate", mailboxcount=0, diskspace=1, diskspace_unit=0
diskspace_unit=0) )
customer = User.objects.create_user(username=TEST_USER) customer = User.objects.create_user(username=TEST_USER)
package = CustomerHostingPackage.objects.create_from_template( package = CustomerHostingPackage.objects.create_from_template(
customer, template, 'testpackage') customer, template, "testpackage"
with patch('hostingpackages.models.settings') as hmsettings: )
with patch("hostingpackages.models.settings") as hmsettings:
hmsettings.OSUSER_DEFAULT_GROUPS = [] hmsettings.OSUSER_DEFAULT_GROUPS = []
package.save() package.save()
return package return package
@ -62,7 +57,8 @@ class HostingDomainManagerTest(TestCase):
def test_create_for_hosting_package_with_commit(self): def test_create_for_hosting_package_with_commit(self):
package = self._setup_hosting_package() package = self._setup_hosting_package()
hostingdomain = HostingDomain.objects.create_for_hosting_package( hostingdomain = HostingDomain.objects.create_for_hosting_package(
package, 'example.org', True) package, "example.org", True
)
self.assertIsNotNone(hostingdomain) self.assertIsNotNone(hostingdomain)
self.assertTrue(hostingdomain.customer, package.customer) self.assertTrue(hostingdomain.customer, package.customer)
@ -70,70 +66,60 @@ class HostingDomainManagerTest(TestCase):
def test_create_for_hosting_package_no_commit(self): def test_create_for_hosting_package_no_commit(self):
package = self._setup_hosting_package() package = self._setup_hosting_package()
hostingdomain = HostingDomain.objects.create_for_hosting_package( hostingdomain = HostingDomain.objects.create_for_hosting_package(
package, 'example.org', False) package, "example.org", False
)
self.assertIsNotNone(hostingdomain) self.assertIsNotNone(hostingdomain)
self.assertTrue(hostingdomain.customer, package.customer) self.assertTrue(hostingdomain.customer, package.customer)
class HostingDomainTest(TestCase): class HostingDomainTest(TestCase):
def test___str__(self): def test___str__(self):
hostingdomain = HostingDomain(domain='test') hostingdomain = HostingDomain(domain="test")
self.assertEqual(str(hostingdomain), 'test') self.assertEqual(str(hostingdomain), "test")
class DNSDomainTest(TestCase): class DNSDomainTest(TestCase):
def test___str__(self): def test___str__(self):
dnsdomain = DNSDomain(domain='test') dnsdomain = DNSDomain(domain="test")
self.assertEqual(str(dnsdomain), 'test') self.assertEqual(str(dnsdomain), "test")
class DNSRecordTest(TestCase): class DNSRecordTest(TestCase):
def test___str__(self): def test___str__(self):
dnsrecord = DNSRecord( dnsrecord = DNSRecord(name="localhost", recordtype="A", content="127.0.0.1")
name='localhost', recordtype='A', content='127.0.0.1') self.assertEqual(str(dnsrecord), "localhost IN A 127.0.0.1")
self.assertEqual(str(dnsrecord), 'localhost IN A 127.0.0.1')
class DNSSupermasterTest(TestCase): class DNSSupermasterTest(TestCase):
def test___str__(self): def test___str__(self):
dnssupermaster = DNSSupermaster( dnssupermaster = DNSSupermaster(ip="127.0.0.1", nameserver="dns.example.org")
ip='127.0.0.1', nameserver='dns.example.org') self.assertEqual(str(dnssupermaster), "127.0.0.1 dns.example.org")
self.assertEqual(str(dnssupermaster), '127.0.0.1 dns.example.org')
class DNSCommentTest(TestCase): class DNSCommentTest(TestCase):
def test___str__(self): def test___str__(self):
dnscomment = DNSComment( dnscomment = DNSComment(name="localhost", commenttype="A", comment="good stuff")
name='localhost', commenttype='A', comment='good stuff') self.assertEqual(str(dnscomment), "localhost IN A: good stuff")
self.assertEqual(str(dnscomment), 'localhost IN A: good stuff')
class DNSDomainMetadataTest(TestCase): class DNSDomainMetadataTest(TestCase):
def test___str__(self): def test___str__(self):
dnsdomain = DNSDomain(domain='test') dnsdomain = DNSDomain(domain="test")
dnsdomainmetadata = DNSDomainMetadata( dnsdomainmetadata = DNSDomainMetadata(
domain=dnsdomain, kind='SOA-EDIT', content='INCEPTION') domain=dnsdomain, kind="SOA-EDIT", content="INCEPTION"
self.assertEqual(str(dnsdomainmetadata), 'test SOA-EDIT INCEPTION') )
self.assertEqual(str(dnsdomainmetadata), "test SOA-EDIT INCEPTION")
class DNSCryptoKeyTest(TestCase): class DNSCryptoKeyTest(TestCase):
def test___str__(self): def test___str__(self):
dnsdomain = DNSDomain(domain='test') dnsdomain = DNSDomain(domain="test")
dnscryptokey = DNSCryptoKey(domain=dnsdomain, content='testvalue') dnscryptokey = DNSCryptoKey(domain=dnsdomain, content="testvalue")
self.assertEqual(str(dnscryptokey), 'test testvalue') self.assertEqual(str(dnscryptokey), "test testvalue")
class DNSTSIGKeyTest(TestCase): class DNSTSIGKeyTest(TestCase):
def test___str__(self): def test___str__(self):
dnstsigkey = DNSTSIGKey( dnstsigkey = DNSTSIGKey(name="testkey", algorithm="hmac-md5", secret="dummykey")
name='testkey', algorithm='hmac-md5', secret='dummykey') self.assertEqual(str(dnstsigkey), "testkey hmac-md5 XXXX")
self.assertEqual(str(dnstsigkey), 'testkey hmac-md5 XXXX')

View file

@ -2,149 +2,152 @@
Tests for :py:mod:`domains.views`. Tests for :py:mod:`domains.views`.
""" """
from __future__ import absolute_import, unicode_literals from unittest.mock import MagicMock, patch
from mock import patch, MagicMock
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.test import TestCase
from hostingpackages.models import ( from django.urls import reverse
CustomerHostingPackage,
HostingPackageTemplate,
)
from domains.views import CreateHostingDomain from domains.views import CreateHostingDomain
from hostingpackages.models import CustomerHostingPackage, HostingPackageTemplate
User = get_user_model() User = get_user_model()
TEST_USER = 'test' TEST_USER = "test"
TEST_PASSWORD = 'secret' TEST_PASSWORD = "secret"
TEST_EMAIL = 'test@example.org' TEST_EMAIL = "test@example.org"
TEST_NAME = 'Example Tester'.split() TEST_NAME = "Example Tester".split()
class CreateHostingDomainTest(TestCase): class CreateHostingDomainTest(TestCase):
def _setup_hosting_package(self, customer): def _setup_hosting_package(self, customer):
template = HostingPackageTemplate.objects.create( template = HostingPackageTemplate.objects.create(
name='testpackagetemplate', mailboxcount=0, diskspace=1, name="testpackagetemplate", mailboxcount=0, diskspace=1, diskspace_unit=0
diskspace_unit=0) )
package = CustomerHostingPackage.objects.create_from_template( package = CustomerHostingPackage.objects.create_from_template(
customer, template, 'testpackage') customer, template, "testpackage"
with patch('hostingpackages.models.settings') as hmsettings: )
with patch("hostingpackages.models.settings") as hmsettings:
hmsettings.OSUSER_DEFAULT_GROUPS = [] hmsettings.OSUSER_DEFAULT_GROUPS = []
package.save() package.save()
return package return package
def test_get_anonymous(self): def test_get_anonymous(self):
response = self.client.get( response = self.client.get(
reverse('create_hosting_domain', kwargs={'package': 1})) reverse("create_hosting_domain", kwargs={"package": 1})
)
self.assertEqual(response.status_code, 403) self.assertEqual(response.status_code, 403)
def test_get_regular_user(self): def test_get_regular_user(self):
customer = User.objects.create_user( customer = User.objects.create_user(
TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD) TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD
)
package = self._setup_hosting_package(customer) package = self._setup_hosting_package(customer)
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get( response = self.client.get(
reverse('create_hosting_domain', reverse("create_hosting_domain", kwargs={"package": package.id})
kwargs={'package': package.id})) )
self.assertEqual(response.status_code, 403) self.assertEqual(response.status_code, 403)
def test_get_staff_user(self): def test_get_staff_user(self):
customer = User.objects.create_user('customer') customer = User.objects.create_user("customer")
package = self._setup_hosting_package(customer) package = self._setup_hosting_package(customer)
User.objects.create_superuser( User.objects.create_superuser(
TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD) TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD
)
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get( response = self.client.get(
reverse('create_hosting_domain', reverse("create_hosting_domain", kwargs={"package": package.id})
kwargs={'package': package.id})) )
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_get_template(self): def test_get_template(self):
customer = User.objects.create_user('customer') customer = User.objects.create_user("customer")
package = self._setup_hosting_package(customer) package = self._setup_hosting_package(customer)
User.objects.create_superuser( User.objects.create_superuser(
TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD) TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD
)
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get( response = self.client.get(
reverse('create_hosting_domain', reverse("create_hosting_domain", kwargs={"package": package.id})
kwargs={'package': package.id})) )
self.assertTemplateUsed(response, 'domains/hostingdomain_create.html') self.assertTemplateUsed(response, "domains/hostingdomain_create.html")
def test_get_no_package_found(self): def test_get_no_package_found(self):
User.objects.create_superuser( User.objects.create_superuser(
TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD) TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD
)
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get( response = self.client.get(
reverse('create_hosting_domain', reverse("create_hosting_domain", kwargs={"package": 1})
kwargs={'package': 1})) )
self.assertEqual(response.status_code, 404) self.assertEqual(response.status_code, 404)
def test_get_get_form_kwargs(self): def test_get_get_form_kwargs(self):
customer = User.objects.create_user('customer') customer = User.objects.create_user("customer")
package = self._setup_hosting_package(customer) package = self._setup_hosting_package(customer)
User.objects.create_superuser( User.objects.create_superuser(
TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD) TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD
)
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
view = CreateHostingDomain( view = CreateHostingDomain(
request=MagicMock(), kwargs={'package': str(package.id)}) request=MagicMock(), kwargs={"package": str(package.id)}
)
the_kwargs = view.get_form_kwargs() the_kwargs = view.get_form_kwargs()
self.assertIn('hostingpackage', the_kwargs) self.assertIn("hostingpackage", the_kwargs)
self.assertEqual(the_kwargs['hostingpackage'], package) self.assertEqual(the_kwargs["hostingpackage"], package)
def test_get_context_data_has_hosting_package(self): def test_get_context_data_has_hosting_package(self):
customer = User.objects.create_user('customer') customer = User.objects.create_user("customer")
package = self._setup_hosting_package(customer) package = self._setup_hosting_package(customer)
User.objects.create_superuser( User.objects.create_superuser(
TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD) TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD
)
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get( response = self.client.get(
reverse('create_hosting_domain', reverse("create_hosting_domain", kwargs={"package": package.id})
kwargs={'package': package.id})) )
self.assertIn('hostingpackage', response.context) self.assertIn("hostingpackage", response.context)
self.assertEqual(response.context['hostingpackage'], package) self.assertEqual(response.context["hostingpackage"], package)
def test_get_context_data_has_customer(self): def test_get_context_data_has_customer(self):
customer = User.objects.create_user('customer') customer = User.objects.create_user("customer")
package = self._setup_hosting_package(customer) package = self._setup_hosting_package(customer)
User.objects.create_superuser( User.objects.create_superuser(
TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD) TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD
)
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get( response = self.client.get(
reverse('create_hosting_domain', reverse("create_hosting_domain", kwargs={"package": package.id})
kwargs={'package': package.id})) )
self.assertIn('customer', response.context) self.assertIn("customer", response.context)
self.assertEqual(response.context['customer'], customer) self.assertEqual(response.context["customer"], customer)
def test_form_valid_redirect(self): def test_form_valid_redirect(self):
customer = User.objects.create_user('customer') customer = User.objects.create_user("customer")
package = self._setup_hosting_package(customer) package = self._setup_hosting_package(customer)
User.objects.create_superuser( User.objects.create_superuser(
TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD) TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD
)
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.post( response = self.client.post(
reverse('create_hosting_domain', reverse("create_hosting_domain", kwargs={"package": package.id}),
kwargs={'package': package.id}), data={"domain": "example.org"},
data={'domain': 'example.org'}) )
self.assertRedirects(response, package.get_absolute_url()) self.assertRedirects(response, package.get_absolute_url())
def test_form_valid_message(self): def test_form_valid_message(self):
customer = User.objects.create_user('customer') customer = User.objects.create_user("customer")
package = self._setup_hosting_package(customer) package = self._setup_hosting_package(customer)
User.objects.create_superuser( User.objects.create_superuser(
TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD) TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD
)
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.post( response = self.client.post(
reverse('create_hosting_domain', reverse("create_hosting_domain", kwargs={"package": package.id}),
kwargs={'package': package.id}), follow=True, follow=True,
data={'domain': 'example.org'}) data={"domain": "example.org"},
messages = list(response.context['messages']) )
messages = list(response.context["messages"])
self.assertEqual(len(messages), 1) self.assertEqual(len(messages), 1)
self.assertEqual( self.assertEqual("Successfully created domain example.org", str(messages[0]))
'Successfully created domain example.org', str(messages[0]))

View file

@ -5,54 +5,49 @@ This module defines views related to domains.
from __future__ import absolute_import, unicode_literals from __future__ import absolute_import, unicode_literals
from braces.views import StaffuserRequiredMixin from braces.views import StaffuserRequiredMixin
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect, get_object_or_404
from django.views.generic.edit import CreateView
from django.utils.translation import ugettext as _
from django.contrib import messages from django.contrib import messages
from django.shortcuts import get_object_or_404, redirect
from django.utils.translation import ugettext as _
from django.views.generic.edit import CreateView
from hostingpackages.models import CustomerHostingPackage from hostingpackages.models import CustomerHostingPackage
from .forms import CreateHostingDomainForm from .forms import CreateHostingDomainForm
from .models import HostingDomain from .models import HostingDomain
class CreateHostingDomain( class CreateHostingDomain(StaffuserRequiredMixin, CreateView):
LoginRequiredMixin, StaffuserRequiredMixin, CreateView
):
""" """
This view is used for creating a new HostingDomain instance for an existing This view is used for creating a new HostingDomain instance for an existing
hosting package. hosting package.
""" """
model = HostingDomain model = HostingDomain
raise_exception = True raise_exception = True
template_name_suffix = '_create' template_name_suffix = "_create"
form_class = CreateHostingDomainForm form_class = CreateHostingDomainForm
def _get_hosting_package(self): def _get_hosting_package(self):
return get_object_or_404( return get_object_or_404(CustomerHostingPackage, pk=int(self.kwargs["package"]))
CustomerHostingPackage, pk=int(self.kwargs['package']))
def get_form_kwargs(self): def get_form_kwargs(self):
kwargs = super(CreateHostingDomain, self).get_form_kwargs() kwargs = super(CreateHostingDomain, self).get_form_kwargs()
kwargs['hostingpackage'] = self._get_hosting_package() kwargs["hostingpackage"] = self._get_hosting_package()
return kwargs return kwargs
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(CreateHostingDomain, self).get_context_data(**kwargs) context = super(CreateHostingDomain, self).get_context_data(**kwargs)
hosting_package = self._get_hosting_package() hosting_package = self._get_hosting_package()
context.update({ context.update(
'hostingpackage': hosting_package, {"hostingpackage": hosting_package, "customer": hosting_package.customer}
'customer': hosting_package.customer, )
})
return context return context
def form_valid(self, form): def form_valid(self, form):
hostingdomain = form.save() hostingdomain = form.save()
messages.success( messages.success(
self.request, self.request,
_('Successfully created domain {domainname}').format( _("Successfully created domain {domainname}").format(
domainname=hostingdomain.domain) domainname=hostingdomain.domain
),
) )
return redirect(self._get_hosting_package()) return redirect(self._get_hosting_package())

View file

@ -38,8 +38,10 @@ DEBUG = False
# ######### MANAGER CONFIGURATION # ######### MANAGER CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#admins # See: https://docs.djangoproject.com/en/dev/ref/settings/#admins
ADMINS = ( ADMINS = (
(get_env_variable('GVA_ADMIN_NAME', default='Admin'), (
get_env_variable('GVA_ADMIN_EMAIL', default='admin@example.org')), get_env_variable("GVA_ADMIN_NAME", default="Admin"),
get_env_variable("GVA_ADMIN_EMAIL", default="admin@example.org"),
),
) )
# See: https://docs.djangoproject.com/en/dev/ref/settings/#managers # See: https://docs.djangoproject.com/en/dev/ref/settings/#managers
@ -50,13 +52,13 @@ MANAGERS = ADMINS
# ######### DATABASE CONFIGURATION # ######### DATABASE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases # See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = { DATABASES = {
'default': { "default": {
'ENGINE': 'django.db.backends.postgresql', "ENGINE": "django.db.backends.postgresql",
'NAME': get_env_variable('GVA_PGSQL_DATABASE', default='gnuviechadmin'), "NAME": get_env_variable("GVA_PGSQL_DATABASE", default="gnuviechadmin"),
'USER': get_env_variable('GVA_PGSQL_USER', default='gnuviechadmin'), "USER": get_env_variable("GVA_PGSQL_USER", default="gnuviechadmin"),
'PASSWORD': get_env_variable('GVA_PGSQL_PASSWORD'), "PASSWORD": get_env_variable("GVA_PGSQL_PASSWORD"),
'HOST': get_env_variable('GVA_PGSQL_HOSTNAME', default='db'), "HOST": get_env_variable("GVA_PGSQL_HOSTNAME", default="db"),
'PORT': get_env_variable('GVA_PGSQL_PORT', int, default=5432), "PORT": get_env_variable("GVA_PGSQL_PORT", int, default=5432),
} }
} }
# ######### END DATABASE CONFIGURATION # ######### END DATABASE CONFIGURATION
@ -64,15 +66,15 @@ DATABASES = {
# ######### GENERAL CONFIGURATION # ######### GENERAL CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#time-zone # See: https://docs.djangoproject.com/en/dev/ref/settings/#time-zone
TIME_ZONE = 'Europe/Berlin' TIME_ZONE = "Europe/Berlin"
# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code # See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code
LANGUAGE_CODE = 'en-us' LANGUAGE_CODE = "en-us"
# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id # See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id
SITE_ID = 1 SITE_ID = 1
SITES_DOMAIN_NAME = get_env_variable('GVA_DOMAIN_NAME') SITES_DOMAIN_NAME = get_env_variable("GVA_DOMAIN_NAME")
SITES_SITE_NAME = get_env_variable('GVA_SITE_NAME') SITES_SITE_NAME = get_env_variable("GVA_SITE_NAME")
# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
USE_I18N = True USE_I18N = True
@ -85,33 +87,28 @@ USE_TZ = True
# ######### END GENERAL CONFIGURATION # ######### END GENERAL CONFIGURATION
LOCALE_PATHS = ( LOCALE_PATHS = (normpath(join(SITE_ROOT, "gnuviechadmin", "locale")),)
normpath(join(SITE_ROOT, 'gnuviechadmin', 'locale')),
)
# ######### MEDIA CONFIGURATION # ######### MEDIA CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root
MEDIA_ROOT = normpath(join(SITE_ROOT, 'media')) MEDIA_ROOT = normpath(join(SITE_ROOT, "media"))
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = '/media/' MEDIA_URL = "/media/"
# ######### END MEDIA CONFIGURATION # ######### END MEDIA CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = '/static/' STATIC_URL = "/static/"
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS # noqa # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS # noqa
STATICFILES_DIRS = ( STATICFILES_DIRS = (normpath(join(SITE_ROOT, "gnuviechadmin", "assets")),)
normpath(join(SITE_ROOT, 'gnuviechadmin', 'assets')),
)
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders # noqa # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders # noqa
STATICFILES_FINDERS = ( STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder', "django.contrib.staticfiles.finders.FileSystemFinder",
'django.contrib.staticfiles.finders.AppDirectoriesFinder', "django.contrib.staticfiles.finders.AppDirectoriesFinder",
) )
# ######### END STATIC FILE CONFIGURATION # ######### END STATIC FILE CONFIGURATION
@ -119,7 +116,7 @@ STATICFILES_FINDERS = (
# ######### SECRET CONFIGURATION # ######### SECRET CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
# Note: This key should only be used for development and testing. # Note: This key should only be used for development and testing.
SECRET_KEY = get_env_variable('GVA_SITE_SECRET') SECRET_KEY = get_env_variable("GVA_SITE_SECRET")
# ######### END SECRET CONFIGURATION # ######### END SECRET CONFIGURATION
@ -132,9 +129,7 @@ ALLOWED_HOSTS = []
# ######### FIXTURE CONFIGURATION # ######### FIXTURE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS # noqa # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS # noqa
FIXTURE_DIRS = ( FIXTURE_DIRS = (normpath(join(SITE_ROOT, "fixtures")),)
normpath(join(SITE_ROOT, 'fixtures')),
)
# ######### END FIXTURE CONFIGURATION # ######### END FIXTURE CONFIGURATION
@ -142,27 +137,25 @@ FIXTURE_DIRS = (
# See: https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-TEMPLATES # noqa # See: https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-TEMPLATES # noqa
TEMPLATES = [ TEMPLATES = [
{ {
'BACKEND': 'django.template.backends.django.DjangoTemplates', "BACKEND": "django.template.backends.django.DjangoTemplates",
'DIRS': [ "DIRS": [normpath(join(DJANGO_ROOT, "templates"))],
normpath(join(DJANGO_ROOT, 'templates')), "APP_DIRS": True,
], "OPTIONS": {
'APP_DIRS': True, "context_processors": [
'OPTIONS': { "django.contrib.auth.context_processors.auth",
'context_processors': [ "django.template.context_processors.debug",
'django.contrib.auth.context_processors.auth', "django.template.context_processors.i18n",
'django.template.context_processors.debug', "django.template.context_processors.media",
'django.template.context_processors.i18n', "django.template.context_processors.static",
'django.template.context_processors.media', "django.template.context_processors.tz",
'django.template.context_processors.static', "django.contrib.messages.context_processors.messages",
'django.template.context_processors.tz', "django.template.context_processors.request",
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.request',
# custom context processors # custom context processors
'gnuviechadmin.context_processors.navigation', "gnuviechadmin.context_processors.navigation",
'gnuviechadmin.context_processors.version_info', "gnuviechadmin.context_processors.version_info",
], ]
},
}, },
}
] ]
# ######### END TEMPLATE CONFIGURATION # ######### END TEMPLATE CONFIGURATION
@ -171,14 +164,14 @@ TEMPLATES = [
# See: https://docs.djangoproject.com/en/dev/ref/settings/#middleware-classes # See: https://docs.djangoproject.com/en/dev/ref/settings/#middleware-classes
MIDDLEWARE = [ MIDDLEWARE = [
# Default Django middleware. # Default Django middleware.
'django.middleware.common.CommonMiddleware', "django.middleware.common.CommonMiddleware",
'django.contrib.sessions.middleware.SessionMiddleware', "django.contrib.sessions.middleware.SessionMiddleware",
'django.middleware.csrf.CsrfViewMiddleware', "django.middleware.csrf.CsrfViewMiddleware",
'django.contrib.auth.middleware.AuthenticationMiddleware', "django.contrib.auth.middleware.AuthenticationMiddleware",
'django.middleware.locale.LocaleMiddleware', "django.middleware.locale.LocaleMiddleware",
'django.contrib.messages.middleware.MessageMiddleware', "django.contrib.messages.middleware.MessageMiddleware",
# uncomment next line to enable translation to browser locale # uncomment next line to enable translation to browser locale
'django.middleware.clickjacking.XFrameOptionsMiddleware', "django.middleware.clickjacking.XFrameOptionsMiddleware",
] ]
# ######### END MIDDLEWARE CONFIGURATION # ######### END MIDDLEWARE CONFIGURATION
@ -186,7 +179,6 @@ MIDDLEWARE = [
AUTHENTICATION_BACKENDS = ( AUTHENTICATION_BACKENDS = (
# Needed to login by username in Django admin, regardless of `allauth` # Needed to login by username in Django admin, regardless of `allauth`
"django.contrib.auth.backends.ModelBackend", "django.contrib.auth.backends.ModelBackend",
# `allauth` specific authentication methods, such as login by e-mail # `allauth` specific authentication methods, such as login by e-mail
"allauth.account.auth_backends.AuthenticationBackend", "allauth.account.auth_backends.AuthenticationBackend",
) )
@ -194,87 +186,83 @@ AUTHENTICATION_BACKENDS = (
# ######### URL CONFIGURATION # ######### URL CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf # See: https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf
ROOT_URLCONF = '%s.urls' % SITE_NAME ROOT_URLCONF = "%s.urls" % SITE_NAME
# ######### END URL CONFIGURATION # ######### END URL CONFIGURATION
# ######### TEST RUNNER CONFIGURATION # ######### TEST RUNNER CONFIGURATION
TEST_RUNNER = 'django.test.runner.DiscoverRunner' TEST_RUNNER = "django.test.runner.DiscoverRunner"
# ######### END TEST RUNNER CONFIGURATION # ######### END TEST RUNNER CONFIGURATION
# ######### APP CONFIGURATION # ######### APP CONFIGURATION
DJANGO_APPS = ( DJANGO_APPS = (
# Default Django apps: # Default Django apps:
'django.contrib.auth', "django.contrib.auth",
'django.contrib.contenttypes', "django.contrib.contenttypes",
'django.contrib.sessions', "django.contrib.sessions",
'django.contrib.sites', "django.contrib.sites",
'django.contrib.messages', "django.contrib.messages",
'django.contrib.staticfiles', "django.contrib.staticfiles",
# Useful template tags: # Useful template tags:
'django.contrib.humanize', "django.contrib.humanize",
# Admin panel and documentation: # Admin panel and documentation:
'django.contrib.admin', "django.contrib.admin",
# Flatpages for about page # Flatpages for about page
'django.contrib.flatpages', "django.contrib.flatpages",
"crispy_forms",
'crispy_forms',
) )
ALLAUTH_APPS = ( ALLAUTH_APPS = (
'allauth', "allauth",
'allauth.account', "allauth.account",
'allauth.socialaccount', "allauth.socialaccount",
'allauth.socialaccount.providers.google', "allauth.socialaccount.providers.google",
'allauth.socialaccount.providers.linkedin_oauth2', "allauth.socialaccount.providers.linkedin_oauth2",
'allauth.socialaccount.providers.twitter', "allauth.socialaccount.providers.twitter",
) )
# Apps specific for this project go here. # Apps specific for this project go here.
LOCAL_APPS = ( LOCAL_APPS = (
'dashboard', "dashboard",
'taskresults', "taskresults",
'ldaptasks', "ldaptasks",
'mysqltasks', "mysqltasks",
'pgsqltasks', "pgsqltasks",
'fileservertasks', "fileservertasks",
'webtasks', "webtasks",
'domains', "domains",
'osusers', "osusers",
'managemails', "managemails",
'userdbs', "userdbs",
'hostingpackages', "hostingpackages",
'websites', "websites",
'contact_form', "contact_form",
) )
# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps # See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + ALLAUTH_APPS + LOCAL_APPS INSTALLED_APPS = DJANGO_APPS + ALLAUTH_APPS + LOCAL_APPS
MESSAGE_TAGS = { MESSAGE_TAGS = {
messages.DEBUG: '', messages.DEBUG: "",
messages.ERROR: 'alert-danger', messages.ERROR: "alert-danger",
messages.INFO: 'alert-info', messages.INFO: "alert-info",
messages.SUCCESS: 'alert-success', messages.SUCCESS: "alert-success",
messages.WARNING: 'alert-warning', messages.WARNING: "alert-warning",
} }
# ######### END APP CONFIGURATION # ######### END APP CONFIGURATION
# ######### ALLAUTH CONFIGURATION # ######### ALLAUTH CONFIGURATION
ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_EMAIL_VERIFICATION = "mandatory"
LOGIN_REDIRECT_URL = '/' LOGIN_REDIRECT_URL = "/"
SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_QUERY_EMAIL = True
# ######### END ALLAUTH CONFIGURATION # ######### END ALLAUTH CONFIGURATION
# ######### CRISPY FORMS CONFIGURATION # ######### CRISPY FORMS CONFIGURATION
CRISPY_TEMPLATE_PACK = 'bootstrap3' CRISPY_TEMPLATE_PACK = "bootstrap3"
# ######### END CRISPY_FORMS CONFIGURATION # ######### END CRISPY_FORMS CONFIGURATION
@ -286,170 +274,197 @@ CRISPY_TEMPLATE_PACK = 'bootstrap3'
# See http://docs.djangoproject.com/en/dev/topics/logging for # See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration. # more details on how to customize your logging configuration.
LOGGING = { LOGGING = {
'version': 1, "version": 1,
'disable_existing_loggers': False, "disable_existing_loggers": False,
'formatters': { "formatters": {
'verbose': { "verbose": {
'format': '%(levelname)s %(asctime)s %(name)s ' "format": "%(levelname)s %(asctime)s %(name)s "
'%(module)s:%(lineno)d %(process)d %(thread)d %(message)s', "%(module)s:%(lineno)d %(process)d %(thread)d %(message)s"
}, },
'simple': { "simple": {"format": "%(levelname)s %(name)s:%(lineno)d %(message)s"},
'format': '%(levelname)s %(name)s:%(lineno)d %(message)s',
}, },
}, "filters": {"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}},
'filters': { "handlers": {
'require_debug_false': { "mail_admins": {
'()': 'django.utils.log.RequireDebugFalse' "level": "ERROR",
"filters": ["require_debug_false"],
"class": "django.utils.log.AdminEmailHandler",
} }
}, },
'handlers': { "loggers": {
'mail_admins': { "django.request": {
'level': 'ERROR', "handlers": ["mail_admins"],
'filters': ['require_debug_false'], "level": "ERROR",
'class': 'django.utils.log.AdminEmailHandler' "propagate": True,
} }
}, },
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
} }
# ######### END LOGGING CONFIGURATION # ######### END LOGGING CONFIGURATION
# ######### WSGI CONFIGURATION # ######### WSGI CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application # See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = '%s.wsgi.application' % SITE_NAME WSGI_APPLICATION = "%s.wsgi.application" % SITE_NAME
# ######### END WSGI CONFIGURATION # ######### END WSGI CONFIGURATION
# ######### CELERY CONFIGURATION # ######### CELERY CONFIGURATION
BROKER_URL = get_env_variable( BROKER_URL = get_env_variable(
'GVA_BROKER_URL', "GVA_BROKER_URL", default="amqp://gnuviechadmin:gnuviechadmin@mq/gnuviechadmin"
default='amqp://gnuviechadmin:gnuviechadmin@mq/gnuviechadmin')
CELERY_RESULT_BACKEND = get_env_variable(
'GVA_RESULTS_REDIS_URL',
default='redis://:gnuviechadmin@redis:6379/0')
CELERY_TASK_RESULT_EXPIRES = None
CELERY_ROUTES = (
'gvacommon.celeryrouters.GvaRouter',
) )
CELERY_TIMEZONE = 'Europe/Berlin' BROKER_TRANSPORT_OPTIONS = {
"max_retries": 3,
"interval_start": 0,
"interval_step": 0.2,
"interval_max": 0.2,
}
CELERY_RESULT_BACKEND = get_env_variable(
"GVA_RESULTS_REDIS_URL", default="redis://:gnuviechadmin@redis:6379/0"
)
CELERY_TASK_RESULT_EXPIRES = None
CELERY_ROUTES = ("gvacommon.celeryrouters.GvaRouter",)
CELERY_TIMEZONE = "Europe/Berlin"
CELERY_ENABLE_UTC = True CELERY_ENABLE_UTC = True
CELERY_ACCEPT_CONTENT = ['json'] CELERY_ACCEPT_CONTENT = ["json"]
CELERY_TASK_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = "json"
CELERY_RESULT_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = "json"
# ######### END CELERY CONFIGURATION # ######### END CELERY CONFIGURATION
# ######### CUSTOM APP CONFIGURATION # ######### CUSTOM APP CONFIGURATION
OSUSER_MINUID = get_env_variable('GVA_MIN_OS_UID', int, default=10000) OSUSER_MINUID = get_env_variable("GVA_MIN_OS_UID", int, default=10000)
OSUSER_MINGID = get_env_variable('GVA_MIN_OS_GID', int, default=10000) OSUSER_MINGID = get_env_variable("GVA_MIN_OS_GID", int, default=10000)
OSUSER_USERNAME_PREFIX = get_env_variable('GVA_OSUSER_PREFIX', default='usr') OSUSER_USERNAME_PREFIX = get_env_variable("GVA_OSUSER_PREFIX", default="usr")
OSUSER_HOME_BASEPATH = get_env_variable( OSUSER_HOME_BASEPATH = get_env_variable("GVA_OSUSER_HOME_BASEPATH", default="/home")
'GVA_OSUSER_HOME_BASEPATH', default='/home')
OSUSER_DEFAULT_SHELL = get_env_variable( OSUSER_DEFAULT_SHELL = get_env_variable(
'GVA_OSUSER_DEFAULT_SHELL', default='/usr/bin/rssh') "GVA_OSUSER_DEFAULT_SHELL", default="/usr/bin/rssh"
OSUSER_SFTP_GROUP = 'sftponly' )
OSUSER_SSH_GROUP = 'sshusers' OSUSER_SFTP_GROUP = "sftponly"
OSUSER_SSH_GROUP = "sshusers"
OSUSER_DEFAULT_GROUPS = [OSUSER_SFTP_GROUP] OSUSER_DEFAULT_GROUPS = [OSUSER_SFTP_GROUP]
OSUSER_UPLOAD_SERVER = get_env_variable( OSUSER_UPLOAD_SERVER = get_env_variable("GVA_OSUSER_UPLOADSERVER", default="file")
'GVA_OSUSER_UPLOADSERVER', default='file')
GVA_LINK_WEBMAIL = get_env_variable( GVA_LINK_WEBMAIL = get_env_variable(
'GVA_WEBMAIL_URL', default='https://webmail.example.org/') "GVA_WEBMAIL_URL", default="https://webmail.example.org/"
)
GVA_LINK_PHPMYADMIN = get_env_variable( GVA_LINK_PHPMYADMIN = get_env_variable(
'GVA_PHPMYADMIN_URL', default='https://phpmyadmin.example.org/') "GVA_PHPMYADMIN_URL", default="https://phpmyadmin.example.org/"
)
GVA_LINK_PHPPGADMIN = get_env_variable( GVA_LINK_PHPPGADMIN = get_env_variable(
'GVA_PHPPGADMIN_URL', default='https://phppgadmin.example.org/') "GVA_PHPPGADMIN_URL", default="https://phppgadmin.example.org/"
)
# ######### END CUSTOM APP CONFIGURATION # ######### END CUSTOM APP CONFIGURATION
GVA_ENVIRONMENT = get_env_variable('GVA_ENVIRONMENT', default='prod') GVA_ENVIRONMENT = get_env_variable("GVA_ENVIRONMENT", default="prod")
# ######### STATIC FILE CONFIGURATION # ######### STATIC FILE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = '/srv/gnuviechadmin/static/' STATIC_ROOT = "/srv/gnuviechadmin/static/"
def show_debug_toolbar(request): def show_debug_toolbar(request):
return DEBUG == True and GVA_ENVIRONMENT == 'local' return DEBUG == True and GVA_ENVIRONMENT == "local"
if GVA_ENVIRONMENT == 'local': if GVA_ENVIRONMENT == "local":
# ######### DEBUG CONFIGURATION # ######### DEBUG CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug # See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = True DEBUG = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
TEMPLATES[0]['OPTIONS']['debug'] = DEBUG TEMPLATES[0]["OPTIONS"]["debug"] = DEBUG
# ######### END DEBUG CONFIGURATION # ######### END DEBUG CONFIGURATION
# ######### EMAIL CONFIGURATION # ######### EMAIL CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
# ######### END EMAIL CONFIGURATION # ######### END EMAIL CONFIGURATION
# ######### CACHE CONFIGURATION # ######### CACHE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#caches # See: https://docs.djangoproject.com/en/dev/ref/settings/#caches
CACHES = { CACHES = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
# ######### END CACHE CONFIGURATION # ######### END CACHE CONFIGURATION
# ######### TOOLBAR CONFIGURATION # ######### TOOLBAR CONFIGURATION
# See: http://django-debug-toolbar.readthedocs.org/en/latest/installation.html#explicit-setup # noqa # See: http://django-debug-toolbar.readthedocs.org/en/latest/installation.html#explicit-setup # noqa
INSTALLED_APPS += ( INSTALLED_APPS += ("debug_toolbar",)
'debug_toolbar',
)
MIDDLEWARE += [ MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"]
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
LOGGING['handlers'].update({ LOGGING["handlers"].update(
'console': { {
'level': 'DEBUG', "console": {
'class': 'logging.StreamHandler', "level": "DEBUG",
'formatter': 'simple', "class": "logging.StreamHandler",
"formatter": "simple",
} }
}) }
LOGGING['loggers'].update(dict( )
[(key, {'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }) LOGGING["loggers"].update(
dict(
[
(key, {"handlers": ["console"], "level": "DEBUG", "propagate": True})
for key in [ for key in [
'dashboard', 'domains', 'fileservertasks', 'gvacommon', "dashboard",
'gvawebcore', 'hostingpackages', 'ldaptasks', 'managemails', "domains",
'mysqltasks', 'osusers', 'pgsqltasks', 'taskresults', "fileservertasks",
'userdbs', 'websites']])) "gvacommon",
"gvawebcore",
"hostingpackages",
"ldaptasks",
"managemails",
"mysqltasks",
"osusers",
"pgsqltasks",
"taskresults",
"userdbs",
"websites",
]
]
)
)
DEBUG_TOOLBAR_PATCH_SETTINGS = False DEBUG_TOOLBAR_PATCH_SETTINGS = False
DEBUG_TOOLBAR_CONFIG = { DEBUG_TOOLBAR_CONFIG = {
'SHOW_TOOLBAR_CALLBACK': 'gnuviechadmin.settings.show_debug_toolbar', "SHOW_TOOLBAR_CALLBACK": "gnuviechadmin.settings.show_debug_toolbar"
} }
# ######### END TOOLBAR CONFIGURATION # ######### END TOOLBAR CONFIGURATION
elif GVA_ENVIRONMENT == 'test': elif GVA_ENVIRONMENT == "test":
PASSWORD_HASHERS = ( PASSWORD_HASHERS = ("django.contrib.auth.hashers.MD5PasswordHasher",)
'django.contrib.auth.hashers.MD5PasswordHasher', LOGGING["handlers"].update(
) {
LOGGING['handlers'].update({ "console": {
'console': { "level": "ERROR",
'level': 'ERROR', "class": "logging.StreamHandler",
'class': 'logging.StreamHandler', "formatter": "simple",
'formatter': 'simple',
} }
}) }
LOGGING['loggers'].update(dict( )
[(key, {'handlers': ['console'], 'level': 'ERROR', 'propagate': True, }) LOGGING["loggers"].update(
dict(
[
(key, {"handlers": ["console"], "level": "ERROR", "propagate": True})
for key in [ for key in [
'dashboard', 'domains', 'fileservertasks', 'gvacommon', "dashboard",
'gvawebcore', 'hostingpackages', 'ldaptasks', 'managemails', "domains",
'mysqltasks', 'osusers', 'pgsqltasks', 'taskresults', "fileservertasks",
'userdbs', 'websites']])) "gvacommon",
BROKER_URL = BROKER_URL + '_test' "gvawebcore",
"hostingpackages",
"ldaptasks",
"managemails",
"mysqltasks",
"osusers",
"pgsqltasks",
"taskresults",
"userdbs",
"websites",
]
]
)
)
BROKER_URL = BROKER_URL + "_test"
CELERY_RESULT_PERSISTENT = False CELERY_RESULT_PERSISTENT = False
else: else:
# ######### HOST CONFIGURATION # ######### HOST CONFIGURATION
@ -459,18 +474,18 @@ else:
# ######### EMAIL CONFIGURATION # ######### EMAIL CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-subject-prefix # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-subject-prefix
EMAIL_SUBJECT_PREFIX = '[%s] ' % SITE_NAME EMAIL_SUBJECT_PREFIX = "[%s] " % SITE_NAME
# See: https://docs.djangoproject.com/en/dev/ref/settings/#default-from-email # See: https://docs.djangoproject.com/en/dev/ref/settings/#default-from-email
DEFAULT_FROM_EMAIL = get_env_variable( DEFAULT_FROM_EMAIL = get_env_variable(
'GVA_SITE_ADMINMAIL', default='admin@example.org') "GVA_SITE_ADMINMAIL", default="admin@example.org"
)
# See: https://docs.djangoproject.com/en/dev/ref/settings/#server-email # See: https://docs.djangoproject.com/en/dev/ref/settings/#server-email
SERVER_EMAIL = get_env_variable( SERVER_EMAIL = get_env_variable("GVA_SITE_ADMINMAIL", default="admin@example.org")
'GVA_SITE_ADMINMAIL', default='admin@example.org')
# ######### END EMAIL CONFIGURATION # ######### END EMAIL CONFIGURATION
# ######### CACHE CONFIGURATION # ######### CACHE CONFIGURATION
@ -479,6 +494,6 @@ else:
# ######### END CACHE CONFIGURATION # ######### END CACHE CONFIGURATION
# ######### ALLAUTH PRODUCTION CONFIGURATION # ######### ALLAUTH PRODUCTION CONFIGURATION
ACCOUNT_EMAIL_SUBJECT_PREFIX = '[Jan Dittberner IT-Consulting & -Solutions] ' ACCOUNT_EMAIL_SUBJECT_PREFIX = "[Jan Dittberner IT-Consulting & -Solutions] "
ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https' ACCOUNT_DEFAULT_HTTP_PROTOCOL = "https"
# ######### END ALLAUTH PRODUCTION CONFIGURATION # ######### END ALLAUTH PRODUCTION CONFIGURATION

View file

@ -5,14 +5,13 @@ This module contains tests for :py:mod:`gnuviechadmin.context_processors`.
""" """
from mock import MagicMock from unittest.mock import MagicMock
from django.conf import settings from django.conf import settings
from django.core.urlresolvers import reverse from django.contrib.auth import get_user_model
from django.http import HttpRequest from django.http import HttpRequest
from django.test import TestCase from django.test import TestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
from gnuviechadmin import __version__ as gvaversion from gnuviechadmin import __version__ as gvaversion
from gnuviechadmin.context_processors import navigation from gnuviechadmin.context_processors import navigation
@ -22,48 +21,40 @@ User = get_user_model()
class NavigationContextProcessorTest(TestCase): class NavigationContextProcessorTest(TestCase):
EXPECTED_ITEMS = ( EXPECTED_ITEMS = ("webmail_url", "phpmyadmin_url", "phppgadmin_url", "active_item")
'webmail_url', 'phpmyadmin_url', 'phppgadmin_url',
'active_item'
)
def test_ajax_request(self): def test_ajax_request(self):
response = self.client.get( response = self.client.get("/", HTTP_X_REQUESTED_WITH="XMLHttpRequest")
'/', HTTP_X_REQUESTED_WITH='XMLHttpRequest')
for item in self.EXPECTED_ITEMS: for item in self.EXPECTED_ITEMS:
self.assertNotIn(item, response.context) self.assertNotIn(item, response.context)
def _check_static_urls(self, context): def _check_static_urls(self, context):
self.assertEqual( self.assertEqual(context["webmail_url"], settings.GVA_LINK_WEBMAIL)
context['webmail_url'], settings.GVA_LINK_WEBMAIL) self.assertEqual(context["phpmyadmin_url"], settings.GVA_LINK_PHPMYADMIN)
self.assertEqual( self.assertEqual(context["phppgadmin_url"], settings.GVA_LINK_PHPPGADMIN)
context['phpmyadmin_url'], settings.GVA_LINK_PHPMYADMIN)
self.assertEqual(
context['phppgadmin_url'], settings.GVA_LINK_PHPPGADMIN)
def test_index_page_context(self): def test_index_page_context(self):
response = self.client.get('/') response = self.client.get("/")
for item in self.EXPECTED_ITEMS: for item in self.EXPECTED_ITEMS:
self.assertIn(item, response.context) self.assertIn(item, response.context)
self._check_static_urls(response.context) self._check_static_urls(response.context)
self.assertEqual(response.context['active_item'], 'dashboard') self.assertEqual(response.context["active_item"], "dashboard")
def test_contact_page_context(self): def test_contact_page_context(self):
response = self.client.get(reverse('contact_form')) response = self.client.get(reverse("contact_form"))
for item in self.EXPECTED_ITEMS: for item in self.EXPECTED_ITEMS:
self.assertIn(item, response.context) self.assertIn(item, response.context)
self._check_static_urls(response.context) self._check_static_urls(response.context)
self.assertEqual(response.context['active_item'], 'contact') self.assertEqual(response.context["active_item"], "contact")
def test_hostingpackage_page_context(self): def test_hostingpackage_page_context(self):
User.objects.create_user('test', password='test') User.objects.create_user("test", password="test")
self.client.login(username='test', password='test') self.client.login(username="test", password="test")
response = self.client.get( response = self.client.get(reverse("hosting_packages", kwargs={"user": "test"}))
reverse('hosting_packages', kwargs={'user': 'test'}))
for item in self.EXPECTED_ITEMS: for item in self.EXPECTED_ITEMS:
self.assertIn(item, response.context) self.assertIn(item, response.context)
self._check_static_urls(response.context) self._check_static_urls(response.context)
self.assertEqual(response.context['active_item'], 'hostingpackage') self.assertEqual(response.context["active_item"], "hostingpackage")
def _test_page_context_by_viewmodule(self, viewmodule, expecteditem): def _test_page_context_by_viewmodule(self, viewmodule, expecteditem):
request = HttpRequest() request = HttpRequest()
@ -73,57 +64,48 @@ class NavigationContextProcessorTest(TestCase):
for item in self.EXPECTED_ITEMS: for item in self.EXPECTED_ITEMS:
self.assertIn(item, context) self.assertIn(item, context)
self._check_static_urls(context) self._check_static_urls(context)
self.assertEqual(context['active_item'], expecteditem) self.assertEqual(context["active_item"], expecteditem)
def test_osusers_page_context(self): def test_osusers_page_context(self):
self._test_page_context_by_viewmodule( self._test_page_context_by_viewmodule("osusers.views", "hostingpackage")
'osusers.views', 'hostingpackage')
def test_userdbs_page_context(self): def test_userdbs_page_context(self):
self._test_page_context_by_viewmodule( self._test_page_context_by_viewmodule("userdbs.views", "hostingpackage")
'userdbs.views', 'hostingpackage')
def test_managemails_page_context(self): def test_managemails_page_context(self):
self._test_page_context_by_viewmodule( self._test_page_context_by_viewmodule("managemails.views", "hostingpackage")
'managemails.views', 'hostingpackage')
def test_websites_page_context(self): def test_websites_page_context(self):
self._test_page_context_by_viewmodule( self._test_page_context_by_viewmodule("websites.views", "hostingpackage")
'websites.views', 'hostingpackage')
def test_domains_page_context(self): def test_domains_page_context(self):
self._test_page_context_by_viewmodule( self._test_page_context_by_viewmodule("domains.views", "hostingpackage")
'domains.views', 'hostingpackage')
def test_allauth_account_page_context(self): def test_allauth_account_page_context(self):
self._test_page_context_by_viewmodule( self._test_page_context_by_viewmodule("allauth.account.views", "account")
'allauth.account.views', 'account')
def test_allauth_socialaccount_page_context(self): def test_allauth_socialaccount_page_context(self):
self._test_page_context_by_viewmodule( self._test_page_context_by_viewmodule("allauth.socialaccount.views", "account")
'allauth.socialaccount.views', 'account')
def test_imprint_page_context(self): def test_imprint_page_context(self):
response = self.client.get(reverse('imprint')) response = self.client.get(reverse("imprint"))
for item in self.EXPECTED_ITEMS: for item in self.EXPECTED_ITEMS:
self.assertIn(item, response.context) self.assertIn(item, response.context)
self._check_static_urls(response.context) self._check_static_urls(response.context)
self.assertEqual(response.context['active_item'], 'imprint') self.assertEqual(response.context["active_item"], "imprint")
def test_no_resolver_match(self): def test_no_resolver_match(self):
request = HttpRequest() request = HttpRequest()
context = navigation(request) context = navigation(request)
self._check_static_urls(context) self._check_static_urls(context)
self.assertEqual(context['active_item'], 'dashboard') self.assertEqual(context["active_item"], "dashboard")
def test_admin_module(self): def test_admin_module(self):
self._test_page_context_by_viewmodule( self._test_page_context_by_viewmodule("django.contrib.admin.foo", "dashboard")
'django.contrib.admin.foo', 'dashboard')
class VersionInfoContextProcessorTest(TestCase): class VersionInfoContextProcessorTest(TestCase):
def test_version_info_in_context(self): def test_version_info_in_context(self):
response = self.client.get('/') response = self.client.get("/")
self.assertIn('gnuviechadmin_version', response.context) self.assertIn("gnuviechadmin_version", response.context)
self.assertEqual(response.context['gnuviechadmin_version'], gvaversion) self.assertEqual(response.context["gnuviechadmin_version"], gvaversion)

View file

@ -5,25 +5,26 @@ This module contains tests for :py:mod:`gvawebcore.forms`.
from unittest import TestCase from unittest import TestCase
from gvawebcore.forms import PasswordModelFormMixin, PASSWORD_MISMATCH_ERROR from gvawebcore.forms import PASSWORD_MISMATCH_ERROR, PasswordModelFormMixin
class PasswordModelFormMixinTest(TestCase): class PasswordModelFormMixinTest(TestCase):
def test_form_properties(self): def test_form_properties(self):
form = PasswordModelFormMixin() form = PasswordModelFormMixin()
self.assertIn('password1', form.fields) self.assertIn("password1", form.fields)
self.assertIn('password2', form.fields) self.assertIn("password2", form.fields)
def test_clean_password_same(self): def test_clean_password_same(self):
form = PasswordModelFormMixin(data={ form = PasswordModelFormMixin(
'password1': 'secret', 'password2': 'secret'}) data={"password1": "secret", "password2": "secret"}
)
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
self.assertEqual('secret', form.clean_password2()) self.assertEqual("secret", form.clean_password2())
def test_clean_password_different(self): def test_clean_password_different(self):
form = PasswordModelFormMixin(data={ form = PasswordModelFormMixin(
'password1': 'onesecret', 'password2': 'other'}) data={"password1": "onesecret", "password2": "other"}
)
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertIn('password2', form.errors) self.assertIn("password2", form.errors)
self.assertIn(PASSWORD_MISMATCH_ERROR, form.errors['password2']) self.assertIn(PASSWORD_MISMATCH_ERROR, form.errors["password2"])

View file

@ -4,31 +4,29 @@ This model contains tests for :py:mod:`gvawebcore.views`.
""" """
from unittest import TestCase from unittest import TestCase
from unittest.mock import Mock, patch
from mock import patch, Mock
from gvawebcore.views import HostingPackageAndCustomerMixin from gvawebcore.views import HostingPackageAndCustomerMixin
class HostingPackageAndCustomerMixinTest(TestCase): class HostingPackageAndCustomerMixinTest(TestCase):
class TestView(HostingPackageAndCustomerMixin): class TestView(HostingPackageAndCustomerMixin):
kwargs = {'package': '1'} kwargs = {"package": "1"}
@patch('gvawebcore.views.get_object_or_404') @patch("gvawebcore.views.get_object_or_404")
def test_get_hosting_package(self, get_object_or_404): def test_get_hosting_package(self, get_object_or_404):
get_object_or_404.return_value = 'A package' get_object_or_404.return_value = "A package"
view = self.TestView() view = self.TestView()
self.assertEqual('A package', view.get_hosting_package()) self.assertEqual("A package", view.get_hosting_package())
def test_get_hosting_package_cached(self): def test_get_hosting_package_cached(self):
view = self.TestView() view = self.TestView()
view.hostingpackage = 'Cached package' view.hostingpackage = "Cached package"
self.assertEqual('Cached package', view.get_hosting_package()) self.assertEqual("Cached package", view.get_hosting_package())
@patch('gvawebcore.views.get_object_or_404') @patch("gvawebcore.views.get_object_or_404")
def test_get_customer_object(self, get_object_or_404): def test_get_customer_object(self, get_object_or_404):
get_object_or_404.return_value = Mock(customer='A customer') get_object_or_404.return_value = Mock(customer="A customer")
view = self.TestView() view = self.TestView()
self.assertEqual('A customer', view.get_customer_object()) self.assertEqual("A customer", view.get_customer_object())

View file

@ -16,37 +16,24 @@ from model_utils.models import TimeStampedModel
from domains.models import HostingDomain from domains.models import HostingDomain
from managemails.models import Mailbox from managemails.models import Mailbox
from osusers.models import ( from osusers.models import AdditionalGroup, Group, User as OsUser
AdditionalGroup, from userdbs.models import DB_TYPES, UserDatabase
Group,
User as OsUser,
)
from userdbs.models import (
DB_TYPES,
UserDatabase,
)
DISK_SPACE_UNITS = Choices( DISK_SPACE_UNITS = Choices((0, "M", _("MiB")), (1, "G", _("GiB")), (2, "T", _("TiB")))
(0, 'M', _('MiB')),
(1, 'G', _('GiB')),
(2, 'T', _('TiB')),
)
DISK_SPACE_FACTORS = ( DISK_SPACE_FACTORS = ((1, None, None), (1024, 1, None), (1024 * 1024, 1024, 1))
(1, None, None),
(1024, 1, None),
(1024 * 1024, 1024, 1),
)
@python_2_unicode_compatible @python_2_unicode_compatible
class HostingPackageBase(TimeStampedModel): class HostingPackageBase(TimeStampedModel):
description = models.TextField(_('description'), blank=True) description = models.TextField(_("description"), blank=True)
mailboxcount = models.PositiveIntegerField(_('mailbox count')) mailboxcount = models.PositiveIntegerField(_("mailbox count"))
diskspace = models.PositiveIntegerField( diskspace = models.PositiveIntegerField(
_('disk space'), help_text=_('disk space for the hosting package')) _("disk space"), help_text=_("disk space for the hosting package")
)
diskspace_unit = models.PositiveSmallIntegerField( diskspace_unit = models.PositiveSmallIntegerField(
_('unit of disk space'), choices=DISK_SPACE_UNITS) _("unit of disk space"), choices=DISK_SPACE_UNITS
)
class Meta: class Meta:
abstract = True abstract = True
@ -56,11 +43,11 @@ class HostingPackageBase(TimeStampedModel):
class HostingPackageTemplate(HostingPackageBase): class HostingPackageTemplate(HostingPackageBase):
name = models.CharField(_('name'), max_length=128, unique=True) name = models.CharField(_("name"), max_length=128, unique=True)
class Meta: class Meta:
verbose_name = _('Hosting package') verbose_name = _("Hosting package")
verbose_name_plural = _('Hosting packages') verbose_name_plural = _("Hosting packages")
class HostingOption(TimeStampedModel): class HostingOption(TimeStampedModel):
@ -72,19 +59,21 @@ class HostingOption(TimeStampedModel):
@python_2_unicode_compatible @python_2_unicode_compatible
class DiskSpaceOptionBase(models.Model): class DiskSpaceOptionBase(models.Model):
diskspace = models.PositiveIntegerField(_('disk space')) diskspace = models.PositiveIntegerField(_("disk space"))
diskspace_unit = models.PositiveSmallIntegerField( diskspace_unit = models.PositiveSmallIntegerField(
_('unit of disk space'), choices=DISK_SPACE_UNITS) _("unit of disk space"), choices=DISK_SPACE_UNITS
)
class Meta: class Meta:
abstract = True abstract = True
ordering = ['diskspace_unit', 'diskspace'] ordering = ["diskspace_unit", "diskspace"]
verbose_name = _('Disk space option') verbose_name = _("Disk space option")
verbose_name_plural = _('Disk space options') verbose_name_plural = _("Disk space options")
def __str__(self): def __str__(self):
return _("Additional disk space {space} {unit}").format( return _("Additional disk space {space} {unit}").format(
space=self.diskspace, unit=self.get_diskspace_unit_display()) space=self.diskspace, unit=self.get_diskspace_unit_display()
)
class DiskSpaceOption(DiskSpaceOptionBase, HostingOption): class DiskSpaceOption(DiskSpaceOptionBase, HostingOption):
@ -95,30 +84,24 @@ class DiskSpaceOption(DiskSpaceOptionBase, HostingOption):
""" """
class Meta: class Meta:
unique_together = ['diskspace', 'diskspace_unit'] unique_together = ["diskspace", "diskspace_unit"]
@python_2_unicode_compatible @python_2_unicode_compatible
class UserDatabaseOptionBase(models.Model): class UserDatabaseOptionBase(models.Model):
number = models.PositiveIntegerField( number = models.PositiveIntegerField(_("number of databases"), default=1)
_('number of databases'), default=1) db_type = models.PositiveSmallIntegerField(_("database type"), choices=DB_TYPES)
db_type = models.PositiveSmallIntegerField(
_('database type'), choices=DB_TYPES)
class Meta: class Meta:
abstract = True abstract = True
ordering = ['db_type', 'number'] ordering = ["db_type", "number"]
verbose_name = _('Database option') verbose_name = _("Database option")
verbose_name_plural = _('Database options') verbose_name_plural = _("Database options")
def __str__(self): def __str__(self):
return ungettext( return ungettext(
'{type} database', "{type} database", "{count} {type} databases", self.number
'{count} {type} databases', ).format(type=self.get_db_type_display(), count=self.number)
self.number
).format(
type=self.get_db_type_display(), count=self.number
)
class UserDatabaseOption(UserDatabaseOptionBase, HostingOption): class UserDatabaseOption(UserDatabaseOptionBase, HostingOption):
@ -129,7 +112,7 @@ class UserDatabaseOption(UserDatabaseOptionBase, HostingOption):
""" """
class Meta: class Meta:
unique_together = ['number', 'db_type'] unique_together = ["number", "db_type"]
@python_2_unicode_compatible @python_2_unicode_compatible
@ -138,23 +121,19 @@ class MailboxOptionBase(models.Model):
Base class for mailbox options. Base class for mailbox options.
""" """
number = models.PositiveIntegerField(
_('number of mailboxes'), unique=True) number = models.PositiveIntegerField(_("number of mailboxes"), unique=True)
class Meta: class Meta:
abstract = True abstract = True
ordering = ['number'] ordering = ["number"]
verbose_name = _('Mailbox option') verbose_name = _("Mailbox option")
verbose_name_plural = _('Mailbox options') verbose_name_plural = _("Mailbox options")
def __str__(self): def __str__(self):
return ungettext( return ungettext(
'{count} additional mailbox', "{count} additional mailbox", "{count} additional mailboxes", self.number
'{count} additional mailboxes', ).format(count=self.number)
self.number
).format(
count=self.number
)
class MailboxOption(MailboxOptionBase, HostingOption): class MailboxOption(MailboxOptionBase, HostingOption):
@ -189,10 +168,11 @@ class CustomerHostingPackageManager(models.Manager):
""" """
package = CustomerHostingPackage( package = CustomerHostingPackage(
customer=customer, template=template, name=name) customer=customer, template=template, name=name
)
package.description = template.description package.description = template.description
package.copy_template_attributes() package.copy_template_attributes()
if 'commit' in kwargs and kwargs['commit'] is True: if "commit" in kwargs and kwargs["commit"] is True:
package.save(**kwargs) package.save(**kwargs)
return package return package
@ -203,45 +183,49 @@ class CustomerHostingPackage(HostingPackageBase):
This class defines customer specific hosting packages. This class defines customer specific hosting packages.
""" """
customer = models.ForeignKey( customer = models.ForeignKey(
settings.AUTH_USER_MODEL, verbose_name=_('customer'), settings.AUTH_USER_MODEL, verbose_name=_("customer"), on_delete=models.CASCADE
on_delete=models.CASCADE) )
template = models.ForeignKey( template = models.ForeignKey(
HostingPackageTemplate, verbose_name=_('hosting package template'), HostingPackageTemplate,
verbose_name=_("hosting package template"),
help_text=_( help_text=_(
'The hosting package template that this hosting package is based' "The hosting package template that this hosting package is based" " on"
' on'
), ),
on_delete=models.CASCADE) on_delete=models.CASCADE,
name = models.CharField(_('name'), max_length=128) )
name = models.CharField(_("name"), max_length=128)
osuser = models.OneToOneField( osuser = models.OneToOneField(
OsUser, verbose_name=_('Operating system user'), OsUser,
blank=True, null=True, on_delete=models.CASCADE) verbose_name=_("Operating system user"),
blank=True,
null=True,
on_delete=models.CASCADE,
)
objects = CustomerHostingPackageManager() objects = CustomerHostingPackageManager()
class Meta: class Meta:
unique_together = ['customer', 'name'] unique_together = ["customer", "name"]
verbose_name = _('customer hosting package') verbose_name = _("customer hosting package")
verbose_name_plural = _('customer hosting packages') verbose_name_plural = _("customer hosting packages")
def __str__(self): def __str__(self):
return _("{name} for {customer}").format( return _("{name} for {customer}").format(name=self.name, customer=self.customer)
name=self.name, customer=self.customer
)
def get_absolute_url(self): def get_absolute_url(self):
return reverse('hosting_package_details', kwargs={ return reverse(
'user': self.customer.username, "hosting_package_details",
'pk': self.id, kwargs={"user": self.customer.username, "pk": self.id},
}) )
def copy_template_attributes(self): def copy_template_attributes(self):
""" """
Copy the attributes of the hosting package's template to the package. Copy the attributes of the hosting package's template to the package.
""" """
for attrname in ('diskspace', 'diskspace_unit', 'mailboxcount'): for attrname in ("diskspace", "diskspace_unit", "mailboxcount"):
setattr(self, attrname, getattr(self.template, attrname)) setattr(self, attrname, getattr(self.template, attrname))
def get_hostingoptions(self): def get_hostingoptions(self):
@ -249,7 +233,7 @@ class CustomerHostingPackage(HostingPackageBase):
for opt_type in [ for opt_type in [
CustomerDiskSpaceOption, CustomerDiskSpaceOption,
CustomerMailboxOption, CustomerMailboxOption,
CustomerUserDatabaseOption CustomerUserDatabaseOption,
]: ]:
opts.extend(opt_type.objects.filter(hosting_package=self)) opts.extend(opt_type.objects.filter(hosting_package=self))
return opts return opts
@ -276,13 +260,13 @@ class CustomerHostingPackage(HostingPackageBase):
diskspace += option.diskspace diskspace += option.diskspace
elif option.diskspace_unit > min_unit: elif option.diskspace_unit > min_unit:
diskspace += ( diskspace += (
DISK_SPACE_FACTORS[option.diskspace_unit][min_unit] * DISK_SPACE_FACTORS[option.diskspace_unit][min_unit]
option.diskspace) * option.diskspace
)
else: else:
diskspace = ( diskspace = (
DISK_SPACE_FACTORS[min_unit][ DISK_SPACE_FACTORS[min_unit][option.diskspace_unit] * diskspace
option.diskspace_unit] * ) + option.diskspace
diskspace) + option.diskspace
min_unit = option.diskspace_unit min_unit = option.diskspace_unit
if unit is None: if unit is None:
return DISK_SPACE_FACTORS[min_unit][0] * diskspace * 1024 ** 2 return DISK_SPACE_FACTORS[min_unit][0] * diskspace * 1024 ** 2
@ -302,16 +286,16 @@ class CustomerHostingPackage(HostingPackageBase):
""" """
if unit is None: if unit is None:
return (DISK_SPACE_FACTORS[self.diskspace_unit][0] * return (
self.diskspace * 1024 ** 2) DISK_SPACE_FACTORS[self.diskspace_unit][0] * self.diskspace * 1024 ** 2
)
if unit > self.diskspace_unit: if unit > self.diskspace_unit:
return (DISK_SPACE_FACTORS[unit][self.diskspace_unit] * return DISK_SPACE_FACTORS[unit][self.diskspace_unit] * self.diskspace
self.diskspace)
return DISK_SPACE_FACTORS[self.diskspace_unit][unit] * self.diskspace return DISK_SPACE_FACTORS[self.diskspace_unit][unit] * self.diskspace
def get_quota(self): def get_quota(self):
soft = 1024 * self.get_disk_space(DISK_SPACE_UNITS.M) soft = 1024 * self.get_disk_space(DISK_SPACE_UNITS.M)
hard = soft * 105 / 100 hard = soft * 105 // 100
return (soft, hard) return (soft, hard)
def get_mailboxes(self): def get_mailboxes(self):
@ -337,12 +321,10 @@ class CustomerHostingPackage(HostingPackageBase):
of its mailbox options. of its mailbox options.
""" """
result = CustomerMailboxOption.objects.filter( result = CustomerMailboxOption.objects.filter(hosting_package=self).aggregate(
hosting_package=self mailbox_sum=models.Sum("number")
).aggregate(
mailbox_sum=models.Sum('number')
) )
return self.mailboxcount + (result['mailbox_sum'] or 0) return self.mailboxcount + (result["mailbox_sum"] or 0)
mailbox_count = property(get_mailbox_count) mailbox_count = property(get_mailbox_count)
@ -355,25 +337,23 @@ class CustomerHostingPackage(HostingPackageBase):
options for this hosting package. options for this hosting package.
""" """
return CustomerUserDatabaseOption.objects.values( return (
'db_type' CustomerUserDatabaseOption.objects.values("db_type")
).filter(hosting_package=self).annotate( .filter(hosting_package=self)
number=models.Sum('number') .annotate(number=models.Sum("number"))
).all() .all()
)
def get_databases_flat(self): def get_databases_flat(self):
if self.osuser: if self.osuser:
return UserDatabase.objects.filter( return UserDatabase.objects.filter(db_user__osuser=self.osuser).all()
db_user__osuser=self.osuser).all()
databases = property(get_databases_flat) databases = property(get_databases_flat)
def may_add_database(self): def may_add_database(self):
return ( return (
CustomerUserDatabaseOption.objects.filter( CustomerUserDatabaseOption.objects.filter(hosting_package=self).count()
hosting_package=self).count() > > UserDatabase.objects.filter(db_user__osuser=self.osuser).count()
UserDatabase.objects.filter(
db_user__osuser=self.osuser).count()
) )
@transaction.atomic @transaction.atomic
@ -409,12 +389,16 @@ class CustomerHostingPackageDomain(TimeStampedModel):
domain. domain.
""" """
hosting_package = models.ForeignKey( hosting_package = models.ForeignKey(
CustomerHostingPackage, verbose_name=_('hosting package'), CustomerHostingPackage,
related_name='domains', on_delete=models.CASCADE) verbose_name=_("hosting package"),
related_name="domains",
on_delete=models.CASCADE,
)
domain = models.OneToOneField( domain = models.OneToOneField(
HostingDomain, verbose_name=_('hosting domain'), HostingDomain, verbose_name=_("hosting domain"), on_delete=models.CASCADE
on_delete=models.CASCADE) )
def __str__(self): def __str__(self):
return self.domain.domain return self.domain.domain
@ -432,60 +416,62 @@ class CustomerHostingPackageOption(TimeStampedModel):
This class defines options for customer hosting packages. This class defines options for customer hosting packages.
""" """
hosting_package = models.ForeignKey( hosting_package = models.ForeignKey(
CustomerHostingPackage, verbose_name=_('hosting package'), CustomerHostingPackage,
on_delete=models.CASCADE) verbose_name=_("hosting package"),
on_delete=models.CASCADE,
)
class Meta: class Meta:
verbose_name = _('customer hosting option') verbose_name = _("customer hosting option")
verbose_name_plural = _('customer hosting options') verbose_name_plural = _("customer hosting options")
class CustomerDiskSpaceOption(DiskSpaceOptionBase, class CustomerDiskSpaceOption(DiskSpaceOptionBase, CustomerHostingPackageOption):
CustomerHostingPackageOption):
""" """
This is a class for customer hosting package options adding additional disk This is a class for customer hosting package options adding additional disk
space to existing customer hosting package. space to existing customer hosting package.
""" """
template = models.ForeignKey( template = models.ForeignKey(
DiskSpaceOption, DiskSpaceOption,
verbose_name=_('disk space option template'), verbose_name=_("disk space option template"),
help_text=_( help_text=_(
'The disk space option template that this disk space option is' "The disk space option template that this disk space option is" " based on"
' based on'
), ),
on_delete=models.CASCADE) on_delete=models.CASCADE,
)
class CustomerUserDatabaseOption(UserDatabaseOptionBase, class CustomerUserDatabaseOption(UserDatabaseOptionBase, CustomerHostingPackageOption):
CustomerHostingPackageOption):
""" """
This is a class for customer hosting package options adding user databases This is a class for customer hosting package options adding user databases
to existing customer hosting packages. to existing customer hosting packages.
""" """
template = models.ForeignKey( template = models.ForeignKey(
UserDatabaseOption, UserDatabaseOption,
verbose_name=_('user database option template'), verbose_name=_("user database option template"),
help_text=_( help_text=_(
'The user database option template that this database option is' "The user database option template that this database option is" " based on"
' based on'
), ),
on_delete=models.CASCADE) on_delete=models.CASCADE,
)
class CustomerMailboxOption(MailboxOptionBase, class CustomerMailboxOption(MailboxOptionBase, CustomerHostingPackageOption):
CustomerHostingPackageOption):
""" """
This is a class for customer hosting package options adding additional This is a class for customer hosting package options adding additional
mailboxes to existing customer hosting packages. mailboxes to existing customer hosting packages.
""" """
template = models.ForeignKey( template = models.ForeignKey(
MailboxOption, MailboxOption,
verbose_name=_('mailbox option template'), verbose_name=_("mailbox option template"),
help_text=_( help_text=_("The mailbox option template that this mailbox option is based on"),
'The mailbox option template that this mailbox option is based on' on_delete=models.CASCADE,
), )
on_delete=models.CASCADE)

View file

@ -5,10 +5,7 @@ Test for models.
from django.test import TestCase from django.test import TestCase
from hostingpackages.models import ( from hostingpackages.models import DISK_SPACE_UNITS, CustomerHostingPackage
DISK_SPACE_UNITS,
CustomerHostingPackage,
)
class CustomerHostingPackageTest(TestCase): class CustomerHostingPackageTest(TestCase):
@ -16,7 +13,7 @@ class CustomerHostingPackageTest(TestCase):
package = CustomerHostingPackage( package = CustomerHostingPackage(
diskspace=10, diskspace_unit=DISK_SPACE_UNITS.G diskspace=10, diskspace_unit=DISK_SPACE_UNITS.G
) )
self.assertEqual(package.get_disk_space(), 10 * 1024 * 1024**2) self.assertEqual(package.get_disk_space(), 10 * 1024 ** 3)
def test_get_disk_space_mib(self): def test_get_disk_space_mib(self):
package = CustomerHostingPackage( package = CustomerHostingPackage(

View file

@ -1,14 +1,14 @@
from django import forms from django import forms
from django.core.urlresolvers import reverse
from django.test import TestCase from django.test import TestCase
from django.test.utils import override_settings from django.test.utils import override_settings
from django.urls import reverse
from django.utils.html import format_html from django.utils.html import format_html
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from django.contrib.admin import AdminSite from django.contrib.admin import AdminSite
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from mock import Mock from unittest.mock import Mock
from osusers.models import User from osusers.models import User
@ -21,9 +21,7 @@ from managemails.admin import (
ReadOnlyPasswordHashField, ReadOnlyPasswordHashField,
ReadOnlyPasswordHashWidget, ReadOnlyPasswordHashWidget,
) )
from managemails.models import ( from managemails.models import Mailbox
Mailbox,
)
Customer = get_user_model() Customer = get_user_model()
@ -31,14 +29,14 @@ Customer = get_user_model()
class ReadOnlyPasswordHashWidgetTest(TestCase): class ReadOnlyPasswordHashWidgetTest(TestCase):
def test_render(self): def test_render(self):
widget = ReadOnlyPasswordHashWidget() widget = ReadOnlyPasswordHashWidget()
rendered = widget.render('password', 'secret', {'class': 'test'}) rendered = widget.render("password", "secret", {"class": "test"})
self.assertEqual( self.assertEqual(
rendered, rendered,
format_html( format_html(
'<div class="test">{0}</div>', '<div class="test">{0}</div>',
format_html('<strong>{0}</strong>: secret ', format_html("<strong>{0}</strong>: secret ", _("Hash")),
_('Hash')) ),
)) )
class ReadOnlyPasswordHashFieldTest(TestCase): class ReadOnlyPasswordHashFieldTest(TestCase):
@ -48,24 +46,24 @@ class ReadOnlyPasswordHashFieldTest(TestCase):
def test_bound_data(self): def test_bound_data(self):
field = ReadOnlyPasswordHashField() field = ReadOnlyPasswordHashField()
self.assertEqual(field.bound_data('new', 'old'), 'old') self.assertEqual(field.bound_data("new", "old"), "old")
def test__has_changed(self): def test__has_changed(self):
field = ReadOnlyPasswordHashField() field = ReadOnlyPasswordHashField()
self.assertFalse(field.has_changed('new', 'old')) self.assertFalse(field.has_changed("new", "old"))
class CustomerTestCase(TestCase): class CustomerTestCase(TestCase):
def setUp(self): def setUp(self):
super(CustomerTestCase, self).setUp() super(CustomerTestCase, self).setUp()
self.customer = Customer.objects.create(username='test') self.customer = Customer.objects.create(username="test")
class MailboxCreationFormTest(CustomerTestCase): class MailboxCreationFormTest(CustomerTestCase):
def test_clean_password2_same(self): def test_clean_password2_same(self):
form = MailboxCreationForm() form = MailboxCreationForm()
form.cleaned_data = {'password1': 'secret', 'password2': 'secret'} form.cleaned_data = {"password1": "secret", "password2": "secret"}
self.assertEqual(form.clean_password2(), 'secret') self.assertEqual(form.clean_password2(), "secret")
def test_clean_password2_empty(self): def test_clean_password2_empty(self):
form = MailboxCreationForm() form = MailboxCreationForm()
@ -74,59 +72,47 @@ class MailboxCreationFormTest(CustomerTestCase):
def test_clean_password2_mismatch(self): def test_clean_password2_mismatch(self):
form = MailboxCreationForm() form = MailboxCreationForm()
form.cleaned_data = {'password1': 'secretx', 'password2': 'secrety'} form.cleaned_data = {"password1": "secretx", "password2": "secrety"}
with self.assertRaises(forms.ValidationError) as cm: with self.assertRaises(forms.ValidationError) as cm:
form.clean_password2() form.clean_password2()
self.assertEqual(cm.exception.message, PASSWORD_MISMATCH_ERROR) self.assertEqual(cm.exception.message, PASSWORD_MISMATCH_ERROR)
@override_settings( @override_settings(
CELERY_ALWAYS_EAGER=True, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
CELERY_CACHE_BACKEND='memory',
BROKER_BACKEND='memory'
) )
def test_save_commit(self): def test_save_commit(self):
user = User.objects.create_user(customer=self.customer) user = User.objects.create_user(customer=self.customer)
form = MailboxCreationForm(data={ form = MailboxCreationForm(
'osuser': user.uid, data={"osuser": user.uid, "password1": "secret", "password2": "secret"}
'password1': 'secret', )
'password2': 'secret',
})
mailbox = form.save() mailbox = form.save()
self.assertIsNotNone(mailbox) self.assertIsNotNone(mailbox)
self.assertEqual( self.assertEqual(len(Mailbox.objects.filter(osuser=user)), 1)
len(Mailbox.objects.filter(osuser=user)), 1)
@override_settings( @override_settings(
CELERY_ALWAYS_EAGER=True, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
CELERY_CACHE_BACKEND='memory',
BROKER_BACKEND='memory'
) )
def test_save_no_commit(self): def test_save_no_commit(self):
user = User.objects.create_user(customer=self.customer) user = User.objects.create_user(customer=self.customer)
form = MailboxCreationForm(data={ form = MailboxCreationForm(
'osuser': user.uid, data={"osuser": user.uid, "password1": "secret", "password2": "secret"}
'password1': 'secret', )
'password2': 'secret',
})
mailbox = form.save(commit=False) mailbox = form.save(commit=False)
self.assertIsNotNone(mailbox) self.assertIsNotNone(mailbox)
self.assertEqual( self.assertEqual(len(Mailbox.objects.filter(osuser=user)), 0)
len(Mailbox.objects.filter(osuser=user)), 0)
class MailboxChangeFormTest(CustomerTestCase): class MailboxChangeFormTest(CustomerTestCase):
@override_settings( @override_settings(
CELERY_ALWAYS_EAGER=True, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
CELERY_CACHE_BACKEND='memory',
BROKER_BACKEND='memory'
) )
def test_clean_password(self): def test_clean_password(self):
mailbox = Mailbox( mailbox = Mailbox(
username='test', username="test", osuser=User.objects.create_user(customer=self.customer)
osuser=User.objects.create_user(customer=self.customer)) )
mailbox.set_password('test') mailbox.set_password("test")
mailbox.save() mailbox.save()
form = MailboxChangeForm(instance=mailbox, data={'password': 'blub'}) form = MailboxChangeForm(instance=mailbox, data={"password": "blub"})
self.assertEqual(form.clean_password(), mailbox.password) self.assertEqual(form.clean_password(), mailbox.password)
@ -151,55 +137,43 @@ class MailBoxAdminTest(CustomerTestCase):
self.mbadmin = MailboxAdmin(Mailbox, site) self.mbadmin = MailboxAdmin(Mailbox, site)
def test_get_fieldsets_without_object(self): def test_get_fieldsets_without_object(self):
self.assertEqual( self.assertEqual(self.mbadmin.get_fieldsets(Mock()), self.mbadmin.add_fieldsets)
self.mbadmin.get_fieldsets(Mock()),
self.mbadmin.add_fieldsets)
@override_settings( @override_settings(
CELERY_ALWAYS_EAGER=True, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
CELERY_CACHE_BACKEND='memory',
BROKER_BACKEND='memory'
) )
def test_get_fieldsets_with_object(self): def test_get_fieldsets_with_object(self):
mailbox = Mailbox( mailbox = Mailbox(
username='test', username="test", osuser=User.objects.create_user(customer=self.customer)
osuser=User.objects.create_user(customer=self.customer)) )
mailbox.set_password('test') mailbox.set_password("test")
mailbox.save() mailbox.save()
self.assertEqual( self.assertEqual(
self.mbadmin.get_fieldsets(Mock(), mailbox), self.mbadmin.get_fieldsets(Mock(), mailbox), self.mbadmin.fieldsets
self.mbadmin.fieldsets) )
def test_get_form_without_object(self): def test_get_form_without_object(self):
form = self.mbadmin.get_form(Mock) form = self.mbadmin.get_form(Mock)
self.assertEqual( self.assertEqual(form.Meta.fields, ["osuser", "password1", "password2"])
form.Meta.fields,
['osuser', 'password1', 'password2']
)
@override_settings( @override_settings(
CELERY_ALWAYS_EAGER=True, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
CELERY_CACHE_BACKEND='memory',
BROKER_BACKEND='memory'
) )
def test_get_form_with_object(self): def test_get_form_with_object(self):
mailbox = Mailbox( mailbox = Mailbox(
username='test', username="test", osuser=User.objects.create_user(customer=self.customer)
osuser=User.objects.create_user(customer=self.customer)) )
mailbox.set_password('test') mailbox.set_password("test")
mailbox.save() mailbox.save()
form = self.mbadmin.get_form(Mock, mailbox) form = self.mbadmin.get_form(Mock, mailbox)
self.assertEqual( self.assertEqual(form.Meta.fields, ["osuser", "username", "password", "active"])
form.Meta.fields,
['osuser', 'username', 'password', 'active']
)
def test_admin_for_mailbox(self): def test_admin_for_mailbox(self):
admin_url = reverse('admin:managemails_mailaddress_changelist') admin_url = reverse("admin:managemails_mailaddress_changelist")
self.assertIsNotNone(admin_url) self.assertIsNotNone(admin_url)
class MailAddressAdminTest(TestCase): class MailAddressAdminTest(TestCase):
def test_admin_for_mailaddress(self): def test_admin_for_mailaddress(self):
admin_url = reverse('admin:managemails_mailaddress_changelist') admin_url = reverse("admin:managemails_mailaddress_changelist")
self.assertIsNotNone(admin_url) self.assertIsNotNone(admin_url)

View file

@ -2,13 +2,11 @@
This module provides tests for :py:mod:`managemails.forms`. This module provides tests for :py:mod:`managemails.forms`.
""" """
from __future__ import absolute_import, unicode_literals from unittest.mock import MagicMock, Mock, patch, ANY
from mock import MagicMock, Mock, patch, ANY
from django.core.urlresolvers import reverse
from django.forms import ValidationError from django.forms import ValidationError
from django.test import TestCase from django.test import TestCase
from django.urls import reverse
from managemails.forms import ( from managemails.forms import (
AddMailAddressForm, AddMailAddressForm,
@ -22,7 +20,6 @@ from managemails.forms import (
class CreateMailboxFormTest(TestCase): class CreateMailboxFormTest(TestCase):
def test_constructor_needs_hostingpackage(self): def test_constructor_needs_hostingpackage(self):
instance = MagicMock() instance = MagicMock()
with self.assertRaises(KeyError): with self.assertRaises(KeyError):
@ -32,33 +29,35 @@ class CreateMailboxFormTest(TestCase):
hostingpackage = Mock(id=42) hostingpackage = Mock(id=42)
instance = MagicMock() instance = MagicMock()
form = CreateMailboxForm(instance, hostingpackage=hostingpackage) form = CreateMailboxForm(instance, hostingpackage=hostingpackage)
self.assertTrue(hasattr(form, 'hosting_package')) self.assertTrue(hasattr(form, "hosting_package"))
self.assertEqual(form.hosting_package, hostingpackage) self.assertEqual(form.hosting_package, hostingpackage)
self.assertTrue(hasattr(form, 'helper')) self.assertTrue(hasattr(form, "helper"))
self.assertEqual(form.helper.form_action, reverse( self.assertEqual(
'create_mailbox', kwargs={'package': 42})) form.helper.form_action, reverse("create_mailbox", kwargs={"package": 42})
self.assertIn('password1', form.fields) )
self.assertIn('password2', form.fields) self.assertIn("password1", form.fields)
self.assertEqual(form.helper.inputs[0].name, 'submit') self.assertIn("password2", form.fields)
self.assertEqual(form.helper.inputs[0].name, "submit")
@patch('managemails.forms.Mailbox.objects') @patch("managemails.forms.Mailbox.objects")
def test_save(self, mailbox_objects): def test_save(self, mailbox_objects):
osuser = MagicMock() osuser = MagicMock()
hostingpackage = Mock(id=42, osuser=osuser) hostingpackage = Mock(id=42, osuser=osuser)
instance = MagicMock() instance = MagicMock()
form = CreateMailboxForm( form = CreateMailboxForm(
instance=instance, hostingpackage=hostingpackage, instance=instance,
data={'password1': 'secret', 'password2': 'secret'}) hostingpackage=hostingpackage,
mailbox_objects.get_next_mailbox_name.return_value = 'mailbox23' data={"password1": "secret", "password2": "secret"},
)
mailbox_objects.get_next_mailbox_name.return_value = "mailbox23"
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
form.save(commit=False) form.save(commit=False)
self.assertEqual(osuser, form.instance.osuser) self.assertEqual(osuser, form.instance.osuser)
self.assertEqual('mailbox23', form.instance.username) self.assertEqual("mailbox23", form.instance.username)
instance.set_password.assert_called_with('secret') instance.set_password.assert_called_with("secret")
class ChangeMailboxPasswordFormTest(TestCase): class ChangeMailboxPasswordFormTest(TestCase):
def test_constructor_needs_hostingpackage(self): def test_constructor_needs_hostingpackage(self):
instance = MagicMock() instance = MagicMock()
with self.assertRaises(KeyError): with self.assertRaises(KeyError):
@ -66,72 +65,75 @@ class ChangeMailboxPasswordFormTest(TestCase):
def test_constructor(self): def test_constructor(self):
hostingpackage = Mock(id=42) hostingpackage = Mock(id=42)
instance = MagicMock(username='testuser') instance = MagicMock(username="testuser")
form = ChangeMailboxPasswordForm( form = ChangeMailboxPasswordForm(
instance=instance, hostingpackage=hostingpackage) instance=instance, hostingpackage=hostingpackage
self.assertTrue(hasattr(form, 'hosting_package')) )
self.assertTrue(hasattr(form, "hosting_package"))
self.assertEqual(form.hosting_package, hostingpackage) self.assertEqual(form.hosting_package, hostingpackage)
self.assertTrue(hasattr(form, 'helper')) self.assertTrue(hasattr(form, "helper"))
self.assertEqual(form.helper.form_action, reverse( self.assertEqual(
'change_mailbox_password', kwargs={ form.helper.form_action,
'package': 42, 'slug': 'testuser'})) reverse(
self.assertIn('password1', form.fields) "change_mailbox_password", kwargs={"package": 42, "slug": "testuser"}
self.assertIn('password2', form.fields) ),
self.assertEqual(form.helper.inputs[0].name, 'submit') )
self.assertIn("password1", form.fields)
self.assertIn("password2", form.fields)
self.assertEqual(form.helper.inputs[0].name, "submit")
def test_save(self): def test_save(self):
hostingpackage = Mock(id=42) hostingpackage = Mock(id=42)
instance = MagicMock(username='testuser') instance = MagicMock(username="testuser")
form = ChangeMailboxPasswordForm( form = ChangeMailboxPasswordForm(
instance=instance, hostingpackage=hostingpackage, instance=instance,
data={'password1': 'newsecret', 'password2': 'newsecret'}) hostingpackage=hostingpackage,
data={"password1": "newsecret", "password2": "newsecret"},
)
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
form.save(commit=False) form.save(commit=False)
instance.set_password.assert_called_with('newsecret') instance.set_password.assert_called_with("newsecret")
class MultipleEmailValidatorTest(TestCase): class MultipleEmailValidatorTest(TestCase):
def test_valid_single_address(self): def test_valid_single_address(self):
self.assertEqual( self.assertEqual(
'test@example.org', "test@example.org", multiple_email_validator("test@example.org")
multiple_email_validator('test@example.org')) )
def test_valid_multiple_addresses(self): def test_valid_multiple_addresses(self):
self.assertEqual( self.assertEqual(
'test1@example.org,test2@example.org', "test1@example.org,test2@example.org",
multiple_email_validator('test1@example.org,test2@example.org')) multiple_email_validator("test1@example.org,test2@example.org"),
)
def test_empty(self): def test_empty(self):
self.assertEqual( self.assertEqual("", multiple_email_validator(""))
'', multiple_email_validator(''))
def test_none(self): def test_none(self):
self.assertIsNone(multiple_email_validator(None)) self.assertIsNone(multiple_email_validator(None))
def test_invalid_single_address(self): def test_invalid_single_address(self):
with self.assertRaises(ValidationError): with self.assertRaises(ValidationError):
multiple_email_validator('no@ddress') multiple_email_validator("no@ddress")
def test_invalid_multiple_addresses(self): def test_invalid_multiple_addresses(self):
with self.assertRaises(ValidationError): with self.assertRaises(ValidationError):
multiple_email_validator('test1@example.org,no@ddress') multiple_email_validator("test1@example.org,no@ddress")
class MailAddressFieldMixinTest(TestCase): class MailAddressFieldMixinTest(TestCase):
def test_fields_defined(self): def test_fields_defined(self):
form = MailAddressFieldMixin() form = MailAddressFieldMixin()
self.assertIn('mailbox_or_forwards', form.fields) self.assertIn("mailbox_or_forwards", form.fields)
self.assertIn('mailbox', form.fields) self.assertIn("mailbox", form.fields)
self.assertIn('forwards', form.fields) self.assertIn("forwards", form.fields)
class AddMailAddressFormTest(TestCase): class AddMailAddressFormTest(TestCase):
def setUp(self): def setUp(self):
self.patcher1 = patch('managemails.forms.Mailbox.objects') self.patcher1 = patch("managemails.forms.Mailbox.objects")
self.patcher2 = patch('managemails.forms.MailAddress.objects') self.patcher2 = patch("managemails.forms.MailAddress.objects")
self.mailbox_objects = self.patcher1.start() self.mailbox_objects = self.patcher1.start()
self.mailaddress_objects = self.patcher2.start() self.mailaddress_objects = self.patcher2.start()
@ -151,175 +153,192 @@ class AddMailAddressFormTest(TestCase):
def test_constructor(self): def test_constructor(self):
instance = MagicMock() instance = MagicMock()
osuser = Mock(username='testuser') osuser = Mock(username="testuser")
hostingpackage = MagicMock(id=42, osuser=osuser) hostingpackage = MagicMock(id=42, osuser=osuser)
maildomain = MagicMock(domain='example.org') maildomain = MagicMock(domain="example.org")
form = AddMailAddressForm( form = AddMailAddressForm(
instance=instance, hostingpackage=hostingpackage, instance=instance, hostingpackage=hostingpackage, maildomain=maildomain
maildomain=maildomain) )
self.mailbox_objects.unused.assert_called_with(osuser=osuser) self.mailbox_objects.unused.assert_called_with(osuser=osuser)
self.assertIn('mailbox_or_forwards', form.fields) self.assertIn("mailbox_or_forwards", form.fields)
self.assertIn('mailbox', form.fields) self.assertIn("mailbox", form.fields)
self.assertIn('forwards', form.fields) self.assertIn("forwards", form.fields)
self.assertTrue(hasattr(form, 'hosting_package')) self.assertTrue(hasattr(form, "hosting_package"))
self.assertEqual(form.hosting_package, hostingpackage) self.assertEqual(form.hosting_package, hostingpackage)
self.assertTrue(hasattr(form, 'maildomain')) self.assertTrue(hasattr(form, "maildomain"))
self.assertEqual(form.maildomain, maildomain) self.assertEqual(form.maildomain, maildomain)
self.assertTrue(hasattr(form, 'helper')) self.assertTrue(hasattr(form, "helper"))
self.assertEqual(form.helper.form_action, reverse( self.assertEqual(
'add_mailaddress', kwargs={ form.helper.form_action,
'package': 42, 'domain': 'example.org'})) reverse("add_mailaddress", kwargs={"package": 42, "domain": "example.org"}),
)
self.assertEqual(len(form.helper.layout), 2) self.assertEqual(len(form.helper.layout), 2)
self.assertEqual(form.helper.layout[1].name, 'submit') self.assertEqual(form.helper.layout[1].name, "submit")
def test_clean_localpart_valid(self): def test_clean_localpart_valid(self):
instance = MagicMock() instance = MagicMock()
osuser = Mock(username='testuser') osuser = Mock(username="testuser")
hostingpackage = MagicMock(id=42, osuser=osuser) hostingpackage = MagicMock(id=42, osuser=osuser)
maildomain = MagicMock(domain='example.org') maildomain = MagicMock(domain="example.org")
form = AddMailAddressForm( form = AddMailAddressForm(
instance=instance, hostingpackage=hostingpackage, instance=instance,
hostingpackage=hostingpackage,
maildomain=maildomain, maildomain=maildomain,
data={ data={
'localpart': 'test', "localpart": "test",
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.forwards, "mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
'forwards': 'test2@example.org' "forwards": "test2@example.org",
}) },
)
self.mailaddress_objects.filter( self.mailaddress_objects.filter(
domain=maildomain, localpart='test' domain=maildomain, localpart="test"
).exists.return_value = False ).exists.return_value = False
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
self.assertEqual('test', form.clean_localpart()) self.assertEqual("test", form.clean_localpart())
def test_clean_localpart_duplicate(self): def test_clean_localpart_duplicate(self):
instance = MagicMock() instance = MagicMock()
osuser = Mock(username='testuser') osuser = Mock(username="testuser")
hostingpackage = MagicMock(id=42, osuser=osuser) hostingpackage = MagicMock(id=42, osuser=osuser)
maildomain = MagicMock(domain='example.org') maildomain = MagicMock(domain="example.org")
form = AddMailAddressForm( form = AddMailAddressForm(
instance=instance, hostingpackage=hostingpackage, instance=instance,
hostingpackage=hostingpackage,
maildomain=maildomain, maildomain=maildomain,
data={ data={
'localpart': 'test', "localpart": "test",
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.forwards, "mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
'forwards': 'test2@example.org' "forwards": "test2@example.org",
}) },
)
self.mailaddress_objects.filter( self.mailaddress_objects.filter(
domain=maildomain, localpart='test' domain=maildomain, localpart="test"
).exists.return_value = True ).exists.return_value = True
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertIn('localpart', form.errors) self.assertIn("localpart", form.errors)
def test_clean_no_mailbox_choice(self): def test_clean_no_mailbox_choice(self):
instance = MagicMock() instance = MagicMock()
osuser = Mock(username='testuser') osuser = Mock(username="testuser")
hostingpackage = MagicMock(id=42, osuser=osuser) hostingpackage = MagicMock(id=42, osuser=osuser)
maildomain = MagicMock(domain='example.org') maildomain = MagicMock(domain="example.org")
form = AddMailAddressForm( form = AddMailAddressForm(
instance=instance, hostingpackage=hostingpackage, instance=instance,
hostingpackage=hostingpackage,
maildomain=maildomain, maildomain=maildomain,
data={ data={
'localpart': 'test', "localpart": "test",
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.mailbox, "mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
}) },
)
self.mailaddress_objects.filter( self.mailaddress_objects.filter(
domain=maildomain, localpart='test' domain=maildomain, localpart="test"
).exists.return_value = False ).exists.return_value = False
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertIn('mailbox', form.errors) self.assertIn("mailbox", form.errors)
def test_clean_no_forward_address_choice(self): def test_clean_no_forward_address_choice(self):
instance = MagicMock() instance = MagicMock()
osuser = Mock(username='testuser') osuser = Mock(username="testuser")
hostingpackage = MagicMock(id=42, osuser=osuser) hostingpackage = MagicMock(id=42, osuser=osuser)
maildomain = MagicMock(domain='example.org') maildomain = MagicMock(domain="example.org")
form = AddMailAddressForm( form = AddMailAddressForm(
instance=instance, hostingpackage=hostingpackage, instance=instance,
hostingpackage=hostingpackage,
maildomain=maildomain, maildomain=maildomain,
data={ data={
'localpart': 'test', "localpart": "test",
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.forwards, "mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
}) },
)
self.mailaddress_objects.filter( self.mailaddress_objects.filter(
domain=maildomain, localpart='test' domain=maildomain, localpart="test"
).exists.return_value = False ).exists.return_value = False
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertIn('forwards', form.errors) self.assertIn("forwards", form.errors)
def test_save_with_forwards_no_commit(self): def test_save_with_forwards_no_commit(self):
instance = MagicMock() instance = MagicMock()
osuser = Mock(username='testuser') osuser = Mock(username="testuser")
hostingpackage = MagicMock(id=42, osuser=osuser) hostingpackage = MagicMock(id=42, osuser=osuser)
maildomain = MagicMock(domain='example.org') maildomain = MagicMock(domain="example.org")
form = AddMailAddressForm( form = AddMailAddressForm(
instance=instance, hostingpackage=hostingpackage, instance=instance,
hostingpackage=hostingpackage,
maildomain=maildomain, maildomain=maildomain,
data={ data={
'localpart': 'test', "localpart": "test",
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.forwards, "mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
'forwards': 'test2@example.org,test3@example.org' "forwards": "test2@example.org,test3@example.org",
}) },
)
self.mailaddress_objects.filter( self.mailaddress_objects.filter(
domain=maildomain, localpart='test' domain=maildomain, localpart="test"
).exists.return_value = False ).exists.return_value = False
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
address1 = MagicMock(mailaddress='test2@example.org') address1 = MagicMock(mailaddress="test2@example.org")
address2 = MagicMock(mailaddress='test3@example.org') address2 = MagicMock(mailaddress="test3@example.org")
instance.set_forward_addresses.return_value = [address1, address2] instance.set_forward_addresses.return_value = [address1, address2]
form.save(commit=False) form.save(commit=False)
self.assertEqual(maildomain, instance.domain) self.assertEqual(maildomain, instance.domain)
instance.set_forward_addresses.assert_called_with([ instance.set_forward_addresses.assert_called_with(
'test2@example.org', 'test3@example.org'], commit=False) ["test2@example.org", "test3@example.org"], commit=False
)
address1.save.assert_not_called() address1.save.assert_not_called()
address2.save.assert_not_called() address2.save.assert_not_called()
instance.save.assert_not_called() instance.save.assert_not_called()
def test_save_with_forwards_commit(self): def test_save_with_forwards_commit(self):
instance = MagicMock() instance = MagicMock()
osuser = Mock(username='testuser') osuser = Mock(username="testuser")
hostingpackage = MagicMock(id=42, osuser=osuser) hostingpackage = MagicMock(id=42, osuser=osuser)
maildomain = MagicMock(domain='example.org') maildomain = MagicMock(domain="example.org")
form = AddMailAddressForm( form = AddMailAddressForm(
instance=instance, hostingpackage=hostingpackage, instance=instance,
hostingpackage=hostingpackage,
maildomain=maildomain, maildomain=maildomain,
data={ data={
'localpart': 'test', "localpart": "test",
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.forwards, "mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
'forwards': 'test2@example.org,test3@example.org' "forwards": "test2@example.org,test3@example.org",
}) },
)
self.mailaddress_objects.filter( self.mailaddress_objects.filter(
domain=maildomain, localpart='test' domain=maildomain, localpart="test"
).exists.return_value = False ).exists.return_value = False
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
address1 = MagicMock(mailaddress='test2@example.org') address1 = MagicMock(mailaddress="test2@example.org")
address2 = MagicMock(mailaddress='test3@example.org') address2 = MagicMock(mailaddress="test3@example.org")
instance.set_forward_addresses.return_value = [address1, address2] instance.set_forward_addresses.return_value = [address1, address2]
form.save(commit=True) form.save(commit=True)
self.assertEqual(maildomain, instance.domain) self.assertEqual(maildomain, instance.domain)
instance.set_forward_addresses.assert_called_with([ instance.set_forward_addresses.assert_called_with(
'test2@example.org', 'test3@example.org'], commit=False) ["test2@example.org", "test3@example.org"], commit=False
)
address1.save.assert_called_with() address1.save.assert_called_with()
address2.save.assert_called_with() address2.save.assert_called_with()
instance.save.assert_called_with() instance.save.assert_called_with()
def test_save_with_mailbox_no_commit(self): def test_save_with_mailbox_no_commit(self):
instance = MagicMock() instance = MagicMock()
osuser = Mock(username='testuser') osuser = Mock(username="testuser")
hostingpackage = MagicMock(id=42, osuser=osuser) hostingpackage = MagicMock(id=42, osuser=osuser)
maildomain = MagicMock(domain='example.org') maildomain = MagicMock(domain="example.org")
form = AddMailAddressForm( form = AddMailAddressForm(
instance=instance, hostingpackage=hostingpackage, instance=instance,
hostingpackage=hostingpackage,
maildomain=maildomain, maildomain=maildomain,
data={ data={
'localpart': 'test', "localpart": "test",
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.mailbox, "mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
'mailbox': 'mailbox23', "mailbox": "mailbox23",
}) },
)
self.mailaddress_objects.filter( self.mailaddress_objects.filter(
domain=maildomain, localpart='test' domain=maildomain, localpart="test"
).exists.return_value = False ).exists.return_value = False
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
mailbox = MagicMock(osuser=osuser, username='testuserp01') mailbox = MagicMock(osuser=osuser, username="testuserp01")
instance.set_mailbox.return_value = mailbox instance.set_mailbox.return_value = mailbox
form.save(commit=False) form.save(commit=False)
self.assertEqual(maildomain, instance.domain) self.assertEqual(maildomain, instance.domain)
@ -329,22 +348,24 @@ class AddMailAddressFormTest(TestCase):
def test_save_with_mailbox_commit(self): def test_save_with_mailbox_commit(self):
instance = MagicMock() instance = MagicMock()
osuser = Mock(username='testuser') osuser = Mock(username="testuser")
hostingpackage = MagicMock(id=42, osuser=osuser) hostingpackage = MagicMock(id=42, osuser=osuser)
maildomain = MagicMock(domain='example.org') maildomain = MagicMock(domain="example.org")
form = AddMailAddressForm( form = AddMailAddressForm(
instance=instance, hostingpackage=hostingpackage, instance=instance,
hostingpackage=hostingpackage,
maildomain=maildomain, maildomain=maildomain,
data={ data={
'localpart': 'test', "localpart": "test",
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.mailbox, "mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
'mailbox': 'mailbox23', "mailbox": "mailbox23",
}) },
)
self.mailaddress_objects.filter( self.mailaddress_objects.filter(
domain=maildomain, localpart='test' domain=maildomain, localpart="test"
).exists.return_value = False ).exists.return_value = False
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
mailbox = MagicMock(osuser=osuser, username='testuserp01') mailbox = MagicMock(osuser=osuser, username="testuserp01")
instance.set_mailbox.return_value = mailbox instance.set_mailbox.return_value = mailbox
form.save(commit=True) form.save(commit=True)
self.assertEqual(maildomain, instance.domain) self.assertEqual(maildomain, instance.domain)
@ -355,26 +376,28 @@ class AddMailAddressFormTest(TestCase):
def test_save_with_other_choice(self): def test_save_with_other_choice(self):
instance = MagicMock() instance = MagicMock()
osuser = Mock(username='testuser') osuser = Mock(username="testuser")
hostingpackage = MagicMock(id=42, osuser=osuser) hostingpackage = MagicMock(id=42, osuser=osuser)
maildomain = MagicMock(domain='example.org') maildomain = MagicMock(domain="example.org")
form = AddMailAddressForm( form = AddMailAddressForm(
instance=instance, hostingpackage=hostingpackage, instance=instance,
hostingpackage=hostingpackage,
maildomain=maildomain, maildomain=maildomain,
data={ data={
'localpart': 'test', "localpart": "test",
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.mailbox, "mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
'mailbox': 'mailbox23', "mailbox": "mailbox23",
}) },
)
self.mailaddress_objects.filter( self.mailaddress_objects.filter(
domain=maildomain, localpart='test' domain=maildomain, localpart="test"
).exists.return_value = False ).exists.return_value = False
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
form.cleaned_data['mailbox_or_forwards'] = -1 form.cleaned_data["mailbox_or_forwards"] = -1
address1 = MagicMock(mailaddress='test2@example.org') address1 = MagicMock(mailaddress="test2@example.org")
address2 = MagicMock(mailaddress='test3@example.org') address2 = MagicMock(mailaddress="test3@example.org")
instance.set_forward_addresses.return_value = [address1, address2] instance.set_forward_addresses.return_value = [address1, address2]
mailbox = MagicMock(osuser=osuser, username='testuserp01') mailbox = MagicMock(osuser=osuser, username="testuserp01")
instance.set_mailbox.return_value = mailbox instance.set_mailbox.return_value = mailbox
form.save(commit=True) form.save(commit=True)
instance.set_mailbox.assert_not_called() instance.set_mailbox.assert_not_called()
@ -386,10 +409,9 @@ class AddMailAddressFormTest(TestCase):
class EditMailAddressFormTest(TestCase): class EditMailAddressFormTest(TestCase):
def setUp(self): def setUp(self):
self.patcher1 = patch('managemails.forms.Mailbox.objects') self.patcher1 = patch("managemails.forms.Mailbox.objects")
self.patcher2 = patch('managemails.forms.MailAddress.objects') self.patcher2 = patch("managemails.forms.MailAddress.objects")
self.mailbox_objects = self.patcher1.start() self.mailbox_objects = self.patcher1.start()
self.mailaddress_objects = self.patcher2.start() self.mailaddress_objects = self.patcher2.start()
@ -409,115 +431,125 @@ class EditMailAddressFormTest(TestCase):
def test_constructor(self): def test_constructor(self):
instance = MagicMock(id=23) instance = MagicMock(id=23)
osuser = Mock(username='testuser') osuser = Mock(username="testuser")
hostingpackage = MagicMock(id=42, osuser=osuser) hostingpackage = MagicMock(id=42, osuser=osuser)
maildomain = MagicMock(domain='example.org') maildomain = MagicMock(domain="example.org")
form = EditMailAddressForm( form = EditMailAddressForm(
instance=instance, maildomain=maildomain, instance=instance, maildomain=maildomain, hostingpackage=hostingpackage
hostingpackage=hostingpackage) )
self.mailbox_objects.unused_or_own.assert_called_with(instance, osuser) self.mailbox_objects.unused_or_own.assert_called_with(instance, osuser)
self.assertIn('mailbox_or_forwards', form.fields) self.assertIn("mailbox_or_forwards", form.fields)
self.assertIn('mailbox', form.fields) self.assertIn("mailbox", form.fields)
self.assertIn('forwards', form.fields) self.assertIn("forwards", form.fields)
self.assertTrue(hasattr(form, 'hosting_package')) self.assertTrue(hasattr(form, "hosting_package"))
self.assertEqual(form.hosting_package, hostingpackage) self.assertEqual(form.hosting_package, hostingpackage)
self.assertTrue(hasattr(form, 'maildomain')) self.assertTrue(hasattr(form, "maildomain"))
self.assertEqual(form.maildomain, maildomain) self.assertEqual(form.maildomain, maildomain)
self.assertTrue(hasattr(form, 'helper')) self.assertTrue(hasattr(form, "helper"))
self.assertEqual(form.helper.form_action, reverse( self.assertEqual(
'edit_mailaddress', kwargs={ form.helper.form_action,
'package': 42, reverse(
'domain': 'example.org', "edit_mailaddress",
'pk': 23})) kwargs={"package": 42, "domain": "example.org", "pk": 23},
),
)
self.assertEqual(len(form.helper.layout), 2) self.assertEqual(len(form.helper.layout), 2)
self.assertEqual(form.helper.layout[1].name, 'submit') self.assertEqual(form.helper.layout[1].name, "submit")
def test_clean_no_mailbox_choice(self): def test_clean_no_mailbox_choice(self):
instance = MagicMock(id=23) instance = MagicMock(id=23)
osuser = Mock(username='testuser') osuser = Mock(username="testuser")
hostingpackage = MagicMock(id=42, osuser=osuser) hostingpackage = MagicMock(id=42, osuser=osuser)
maildomain = MagicMock(domain='example.org') maildomain = MagicMock(domain="example.org")
form = EditMailAddressForm( form = EditMailAddressForm(
instance=instance, maildomain=maildomain, instance=instance,
maildomain=maildomain,
hostingpackage=hostingpackage, hostingpackage=hostingpackage,
data={ data={"mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox},
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.mailbox, )
})
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertIn('mailbox', form.errors) self.assertIn("mailbox", form.errors)
def test_clean_no_forward_address_choice(self): def test_clean_no_forward_address_choice(self):
instance = MagicMock(id=23) instance = MagicMock(id=23)
osuser = Mock(username='testuser') osuser = Mock(username="testuser")
hostingpackage = MagicMock(id=42, osuser=osuser) hostingpackage = MagicMock(id=42, osuser=osuser)
maildomain = MagicMock(domain='example.org') maildomain = MagicMock(domain="example.org")
form = EditMailAddressForm( form = EditMailAddressForm(
instance=instance, maildomain=maildomain, instance=instance,
maildomain=maildomain,
hostingpackage=hostingpackage, hostingpackage=hostingpackage,
data={ data={"mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards},
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.forwards, )
})
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertIn('forwards', form.errors) self.assertIn("forwards", form.errors)
def test_save_with_forwards_no_commit(self): def test_save_with_forwards_no_commit(self):
instance = MagicMock(id=23) instance = MagicMock(id=23)
osuser = Mock(username='testuser') osuser = Mock(username="testuser")
hostingpackage = MagicMock(id=42, osuser=osuser) hostingpackage = MagicMock(id=42, osuser=osuser)
maildomain = MagicMock(domain='example.org') maildomain = MagicMock(domain="example.org")
form = EditMailAddressForm( form = EditMailAddressForm(
instance=instance, maildomain=maildomain, instance=instance,
maildomain=maildomain,
hostingpackage=hostingpackage, hostingpackage=hostingpackage,
data={ data={
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.forwards, "mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
'forwards': 'test2@example.org,test3@example.org' "forwards": "test2@example.org,test3@example.org",
}) },
)
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
address1 = MagicMock(mailaddress='test2@example.org') address1 = MagicMock(mailaddress="test2@example.org")
address2 = MagicMock(mailaddress='test3@example.org') address2 = MagicMock(mailaddress="test3@example.org")
instance.set_forward_addresses.return_value = [address1, address2] instance.set_forward_addresses.return_value = [address1, address2]
form.save(commit=False) form.save(commit=False)
instance.set_forward_addresses.assert_called_with( instance.set_forward_addresses.assert_called_with(
['test2@example.org', 'test3@example.org'], False) ["test2@example.org", "test3@example.org"], False
)
address1.save.assert_not_called() address1.save.assert_not_called()
address2.save.assert_not_called() address2.save.assert_not_called()
instance.save.assert_not_called() instance.save.assert_not_called()
def test_save_with_forwards_commit(self): def test_save_with_forwards_commit(self):
instance = MagicMock(id=23) instance = MagicMock(id=23)
osuser = Mock(username='testuser') osuser = Mock(username="testuser")
hostingpackage = MagicMock(id=42, osuser=osuser) hostingpackage = MagicMock(id=42, osuser=osuser)
maildomain = MagicMock(domain='example.org') maildomain = MagicMock(domain="example.org")
form = EditMailAddressForm( form = EditMailAddressForm(
instance=instance, maildomain=maildomain, instance=instance,
maildomain=maildomain,
hostingpackage=hostingpackage, hostingpackage=hostingpackage,
data={ data={
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.forwards, "mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
'forwards': 'test2@example.org,test3@example.org' "forwards": "test2@example.org,test3@example.org",
}) },
)
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
address1 = MagicMock(mailaddress='test2@example.org') address1 = MagicMock(mailaddress="test2@example.org")
address2 = MagicMock(mailaddress='test3@example.org') address2 = MagicMock(mailaddress="test3@example.org")
instance.set_forward_addresses.return_value = [address1, address2] instance.set_forward_addresses.return_value = [address1, address2]
form.save(commit=True) form.save(commit=True)
instance.set_forward_addresses.assert_called_with( instance.set_forward_addresses.assert_called_with(
['test2@example.org', 'test3@example.org'], True) ["test2@example.org", "test3@example.org"], True
)
instance.save.assert_called_with() instance.save.assert_called_with()
def test_save_with_mailbox_no_commit(self): def test_save_with_mailbox_no_commit(self):
instance = MagicMock(id=23) instance = MagicMock(id=23)
osuser = Mock(username='testuser') osuser = Mock(username="testuser")
hostingpackage = MagicMock(id=42, osuser=osuser) hostingpackage = MagicMock(id=42, osuser=osuser)
maildomain = MagicMock(domain='example.org') maildomain = MagicMock(domain="example.org")
form = EditMailAddressForm( form = EditMailAddressForm(
instance=instance, maildomain=maildomain, instance=instance,
maildomain=maildomain,
hostingpackage=hostingpackage, hostingpackage=hostingpackage,
data={ data={
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.mailbox, "mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
'mailbox': 'mailbox23', "mailbox": "mailbox23",
}) },
)
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
mailbox = MagicMock(osuser=osuser, username='testuserp01') mailbox = MagicMock(osuser=osuser, username="testuserp01")
instance.set_mailbox.return_value = mailbox instance.set_mailbox.return_value = mailbox
form.save(commit=False) form.save(commit=False)
instance.set_mailbox.assert_called_with(ANY, False) instance.set_mailbox.assert_called_with(ANY, False)
@ -526,18 +558,20 @@ class EditMailAddressFormTest(TestCase):
def test_save_with_mailbox_commit(self): def test_save_with_mailbox_commit(self):
instance = MagicMock(id=23) instance = MagicMock(id=23)
osuser = Mock(username='testuser') osuser = Mock(username="testuser")
hostingpackage = MagicMock(id=42, osuser=osuser) hostingpackage = MagicMock(id=42, osuser=osuser)
maildomain = MagicMock(domain='example.org') maildomain = MagicMock(domain="example.org")
form = EditMailAddressForm( form = EditMailAddressForm(
instance=instance, maildomain=maildomain, instance=instance,
maildomain=maildomain,
hostingpackage=hostingpackage, hostingpackage=hostingpackage,
data={ data={
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.mailbox, "mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
'mailbox': 'mailbox23', "mailbox": "mailbox23",
}) },
)
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
mailbox = MagicMock(osuser=osuser, username='testuserp01') mailbox = MagicMock(osuser=osuser, username="testuserp01")
instance.set_mailbox.return_value = mailbox instance.set_mailbox.return_value = mailbox
self.mailbox_objects.unused_or_own.get.return_value = mailbox self.mailbox_objects.unused_or_own.get.return_value = mailbox
form.save(commit=True) form.save(commit=True)
@ -546,18 +580,20 @@ class EditMailAddressFormTest(TestCase):
def test_save_with_other_choice(self): def test_save_with_other_choice(self):
instance = MagicMock(id=23) instance = MagicMock(id=23)
osuser = Mock(username='testuser') osuser = Mock(username="testuser")
hostingpackage = MagicMock(id=42, osuser=osuser) hostingpackage = MagicMock(id=42, osuser=osuser)
maildomain = MagicMock(domain='example.org') maildomain = MagicMock(domain="example.org")
form = EditMailAddressForm( form = EditMailAddressForm(
instance=instance, maildomain=maildomain, instance=instance,
maildomain=maildomain,
hostingpackage=hostingpackage, hostingpackage=hostingpackage,
data={ data={
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.mailbox, "mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
'mailbox': 'mailbox23', "mailbox": "mailbox23",
}) },
)
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
form.cleaned_data['mailbox_or_forwards'] = -1 form.cleaned_data["mailbox_or_forwards"] = -1
form.save(commit=True) form.save(commit=True)
instance.set_mailbox.assert_not_called() instance.set_mailbox.assert_not_called()
instance.save.assert_called_with() instance.save.assert_called_with()

View file

@ -1,9 +1,7 @@
""" """
This module contains tests for :py:mod:`managemails.models` This module contains tests for :py:mod:`managemails.models`
""" """
from __future__ import unicode_literals from unittest.mock import patch
from mock import patch
from django.test import TestCase, TransactionTestCase from django.test import TestCase, TransactionTestCase
from django.test.utils import override_settings from django.test.utils import override_settings
@ -14,59 +12,51 @@ from passlib.hash import sha512_crypt
from domains.models import MailDomain from domains.models import MailDomain
from osusers.models import User from osusers.models import User
from managemails.models import ( from managemails.models import MailAddress, Mailbox
MailAddress,
Mailbox,
)
Customer = get_user_model() Customer = get_user_model()
@override_settings( @override_settings(
CELERY_ALWAYS_EAGER=True, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
CELERY_CACHE_BACKEND='memory',
BROKER_BACKEND='memory'
) )
class MailboxTest(TestCase): class MailboxTest(TestCase):
def setUp(self): def setUp(self):
super(MailboxTest, self).setUp() super(MailboxTest, self).setUp()
self.customer = Customer.objects.create_user('test') self.customer = Customer.objects.create_user("test")
def test_set_password(self): def test_set_password(self):
user = User.objects.create_user(self.customer) user = User.objects.create_user(self.customer)
mb = Mailbox.objects.create(username='test', osuser=user) mb = Mailbox.objects.create(username="test", osuser=user)
mb.set_password('test') mb.set_password("test")
self.assertTrue(sha512_crypt.verify('test', mb.password)) self.assertTrue(sha512_crypt.verify("test", mb.password))
def test___str__(self): def test___str__(self):
user = User.objects.create_user(self.customer) user = User.objects.create_user(self.customer)
mb = Mailbox.objects.create(username='test', osuser=user) mb = Mailbox.objects.create(username="test", osuser=user)
mb.set_password('test') mb.set_password("test")
self.assertEqual(str(mb), 'test') self.assertEqual(str(mb), "test")
@patch('managemails.models.create_file_mailbox') @patch("managemails.models.create_file_mailbox")
def test_save(self, create_file_mailbox_task): def test_save(self, create_file_mailbox_task):
user = User.objects.create_user(self.customer) user = User.objects.create_user(self.customer)
mb = Mailbox.objects.create_mailbox(user) mb = Mailbox.objects.create_mailbox(user)
self.assertIsNotNone(mb.pk) self.assertIsNotNone(mb.pk)
create_file_mailbox_task.delay.assert_called_with( create_file_mailbox_task.delay.assert_called_with(user.username, mb.username)
user.username, mb.username)
@patch('managemails.models.delete_file_mailbox') @patch("managemails.models.delete_file_mailbox")
def test_delete(self, delete_file_mailbox_task): def test_delete(self, delete_file_mailbox_task):
user = User.objects.create_user(self.customer) user = User.objects.create_user(self.customer)
mb = Mailbox.objects.create_mailbox(user) mb = Mailbox.objects.create_mailbox(user)
mb.delete() mb.delete()
self.assertIsNone(mb.pk) self.assertIsNone(mb.pk)
delete_file_mailbox_task.delay.assert_called_with( delete_file_mailbox_task.delay.assert_called_with(user.username, mb.username)
user.username, mb.username)
def test_get_mailaddresses(self): def test_get_mailaddresses(self):
user = User.objects.create_user(self.customer) user = User.objects.create_user(self.customer)
mb = Mailbox.objects.create_mailbox(user) mb = Mailbox.objects.create_mailbox(user)
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
address = MailAddress.objects.create(localpart='test', domain=md) address = MailAddress.objects.create(localpart="test", domain=md)
address.set_mailbox(mb) address.set_mailbox(mb)
mailaddresses = mb.get_mailaddresses() mailaddresses = mb.get_mailaddresses()
self.assertEqual(len(mailaddresses), 1) self.assertEqual(len(mailaddresses), 1)
@ -74,31 +64,28 @@ class MailboxTest(TestCase):
@override_settings( @override_settings(
CELERY_ALWAYS_EAGER=True, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
CELERY_CACHE_BACKEND='memory',
BROKER_BACKEND='memory'
) )
class MailAddressTest(TransactionTestCase): class MailAddressTest(TransactionTestCase):
def test__str__(self): def test__str__(self):
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
ma = MailAddress.objects.create(localpart='test', domain=md) ma = MailAddress.objects.create(localpart="test", domain=md)
self.assertEqual(str(ma), 'test@example.org') self.assertEqual(str(ma), "test@example.org")
def test_set_mailbox_fresh(self): def test_set_mailbox_fresh(self):
customer = Customer.objects.create_user('test') customer = Customer.objects.create_user("test")
user = User.objects.create_user(customer) user = User.objects.create_user(customer)
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
ma = MailAddress.objects.create(localpart='test', domain=md) ma = MailAddress.objects.create(localpart="test", domain=md)
mb = Mailbox.objects.create_mailbox(user) mb = Mailbox.objects.create_mailbox(user)
ma.set_mailbox(mb) ma.set_mailbox(mb)
self.assertIn(ma, mb.get_mailaddresses()) self.assertIn(ma, mb.get_mailaddresses())
def test_set_mailbox_reassing(self): def test_set_mailbox_reassing(self):
customer = Customer.objects.create_user('test') customer = Customer.objects.create_user("test")
user = User.objects.create_user(customer) user = User.objects.create_user(customer)
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
ma = MailAddress.objects.create(localpart='test', domain=md) ma = MailAddress.objects.create(localpart="test", domain=md)
mb = Mailbox.objects.create_mailbox(user) mb = Mailbox.objects.create_mailbox(user)
ma.set_mailbox(mb) ma.set_mailbox(mb)
mb2 = Mailbox.objects.create_mailbox(user) mb2 = Mailbox.objects.create_mailbox(user)
@ -107,168 +94,178 @@ class MailAddressTest(TransactionTestCase):
self.assertNotIn(ma, mb.get_mailaddresses()) self.assertNotIn(ma, mb.get_mailaddresses())
def test_set_mailbox_with_forwards(self): def test_set_mailbox_with_forwards(self):
customer = Customer.objects.create_user('test') customer = Customer.objects.create_user("test")
user = User.objects.create_user(customer) user = User.objects.create_user(customer)
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
ma = MailAddress.objects.create(localpart='test', domain=md) ma = MailAddress.objects.create(localpart="test", domain=md)
mb = Mailbox.objects.create_mailbox(user) mb = Mailbox.objects.create_mailbox(user)
ma.set_forward_addresses(['test2@example.org']) ma.set_forward_addresses(["test2@example.org"])
ma.set_mailbox(mb) ma.set_mailbox(mb)
self.assertEqual(ma.mailaddressforward_set.count(), 0) self.assertEqual(ma.mailaddressforward_set.count(), 0)
self.assertIn(ma, mb.get_mailaddresses()) self.assertIn(ma, mb.get_mailaddresses())
def test_set_mailbox_with_unsaved_address(self): def test_set_mailbox_with_unsaved_address(self):
customer = Customer.objects.create_user('test') customer = Customer.objects.create_user("test")
user = User.objects.create_user(customer) user = User.objects.create_user(customer)
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
ma = MailAddress(localpart='test', domain=md) ma = MailAddress(localpart="test", domain=md)
mb = Mailbox.objects.create_mailbox(user) mb = Mailbox.objects.create_mailbox(user)
ma.set_mailbox(mb) ma.set_mailbox(mb)
self.assertIn(ma, mb.get_mailaddresses()) self.assertIn(ma, mb.get_mailaddresses())
def test_set_mailbox_fresh_no_commit(self): def test_set_mailbox_fresh_no_commit(self):
customer = Customer.objects.create_user('test') customer = Customer.objects.create_user("test")
user = User.objects.create_user(customer) user = User.objects.create_user(customer)
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
ma = MailAddress.objects.create(localpart='test', domain=md) ma = MailAddress.objects.create(localpart="test", domain=md)
mb = Mailbox.objects.create_mailbox(user) mb = Mailbox.objects.create_mailbox(user)
ma.set_mailbox(mb, commit=False) ma.set_mailbox(mb, commit=False)
self.assertNotIn(ma, mb.get_mailaddresses()) self.assertNotIn(ma, mb.get_mailaddresses())
def test_set_mailbox_with_unsaved_address_no_commit(self): def test_set_mailbox_with_unsaved_address_no_commit(self):
customer = Customer.objects.create_user('test') customer = Customer.objects.create_user("test")
user = User.objects.create_user(customer) user = User.objects.create_user(customer)
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
ma = MailAddress(localpart='test', domain=md) ma = MailAddress(localpart="test", domain=md)
mb = Mailbox.objects.create_mailbox(user) mb = Mailbox.objects.create_mailbox(user)
ma.set_mailbox(mb, commit=False) ma.set_mailbox(mb, commit=False)
self.assertNotIn(ma, mb.get_mailaddresses()) self.assertNotIn(ma, mb.get_mailaddresses())
def test_set_forward_addresses_fresh(self): def test_set_forward_addresses_fresh(self):
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
ma = MailAddress.objects.create(localpart='test', domain=md) ma = MailAddress.objects.create(localpart="test", domain=md)
ma.set_forward_addresses(['test2@example.org']) ma.set_forward_addresses(["test2@example.org"])
def get_target(maf):
return maf.target
self.assertQuerysetEqual( self.assertQuerysetEqual(
ma.mailaddressforward_set.all(), ['test2@example.org'], ma.mailaddressforward_set.all(), ["test2@example.org"], get_target
lambda(maf): maf.target) )
def test_set_forward_addresses_unsaved(self): def test_set_forward_addresses_unsaved(self):
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
ma = MailAddress(localpart='test', domain=md) ma = MailAddress(localpart="test", domain=md)
ma.set_forward_addresses(['test2@example.org']) ma.set_forward_addresses(["test2@example.org"])
def get_target(maf):
return maf.target
self.assertQuerysetEqual( self.assertQuerysetEqual(
ma.mailaddressforward_set.all(), ['test2@example.org'], ma.mailaddressforward_set.all(), ["test2@example.org"], get_target
lambda(maf): maf.target) )
def test_set_forward_addresses_replace_forwards(self): def test_set_forward_addresses_replace_forwards(self):
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
ma = MailAddress.objects.create(localpart='test', domain=md) ma = MailAddress.objects.create(localpart="test", domain=md)
ma.set_forward_addresses(['test2@example.org']) ma.set_forward_addresses(["test2@example.org"])
ma.set_forward_addresses(['test3@example.org']) ma.set_forward_addresses(["test3@example.org"])
def get_target(maf):
return maf.target
self.assertQuerysetEqual( self.assertQuerysetEqual(
ma.mailaddressforward_set.all(), ['test3@example.org'], ma.mailaddressforward_set.all(), ["test3@example.org"], get_target
lambda(maf): maf.target) )
def test_set_forward_addresses_add_forwards(self): def test_set_forward_addresses_add_forwards(self):
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
ma = MailAddress.objects.create(localpart='test', domain=md) ma = MailAddress.objects.create(localpart="test", domain=md)
ma.set_forward_addresses(['test2@example.org']) ma.set_forward_addresses(["test2@example.org"])
ma.set_forward_addresses(['test2@example.org', 'test3@example.org']) ma.set_forward_addresses(["test2@example.org", "test3@example.org"])
def get_target(maf):
return maf.target
self.assertQuerysetEqual( self.assertQuerysetEqual(
ma.mailaddressforward_set.all(), ma.mailaddressforward_set.all(),
['test2@example.org', 'test3@example.org'], ["test2@example.org", "test3@example.org"],
lambda(maf): maf.target, get_target,
ordered=False) ordered=False,
)
def test_set_forward_addresses_replace_mailbox(self): def test_set_forward_addresses_replace_mailbox(self):
customer = Customer.objects.create_user('test') customer = Customer.objects.create_user("test")
user = User.objects.create_user(customer) user = User.objects.create_user(customer)
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
ma = MailAddress.objects.create(localpart='test', domain=md) ma = MailAddress.objects.create(localpart="test", domain=md)
mb = Mailbox.objects.create_mailbox(user) mb = Mailbox.objects.create_mailbox(user)
ma.set_mailbox(mb) ma.set_mailbox(mb)
ma.set_forward_addresses(['test2@example.org']) ma.set_forward_addresses(["test2@example.org"])
self.assertNotIn(ma, mb.get_mailaddresses()) self.assertNotIn(ma, mb.get_mailaddresses())
def get_target(maf):
return maf.target
self.assertQuerysetEqual( self.assertQuerysetEqual(
ma.mailaddressforward_set.all(), ['test2@example.org'], ma.mailaddressforward_set.all(), ["test2@example.org"], get_target
lambda(maf): maf.target) )
def test_set_forward_addresses_fresh_no_commit(self): def test_set_forward_addresses_fresh_no_commit(self):
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
ma = MailAddress.objects.create(localpart='test', domain=md) ma = MailAddress.objects.create(localpart="test", domain=md)
mafwds = ma.set_forward_addresses(['test2@example.org'], commit=False) mafwds = ma.set_forward_addresses(["test2@example.org"], commit=False)
self.assertEqual(ma.mailaddressforward_set.count(), 0) self.assertEqual(ma.mailaddressforward_set.count(), 0)
self.assertEqual(mafwds[0].target, 'test2@example.org') self.assertEqual(mafwds[0].target, "test2@example.org")
def test_set_forward_address_unsaved_no_commit(self): def test_set_forward_address_unsaved_no_commit(self):
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
ma = MailAddress(localpart='test', domain=md) ma = MailAddress(localpart="test", domain=md)
mafwds = ma.set_forward_addresses(['test2@example.org'], commit=False) mafwds = ma.set_forward_addresses(["test2@example.org"], commit=False)
self.assertEqual(ma.mailaddressforward_set.count(), 0) self.assertEqual(ma.mailaddressforward_set.count(), 0)
self.assertEqual(mafwds[0].target, 'test2@example.org') self.assertEqual(mafwds[0].target, "test2@example.org")
@override_settings( @override_settings(
CELERY_ALWAYS_EAGER=True, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
CELERY_CACHE_BACKEND='memory',
BROKER_BACKEND='memory'
) )
class MailboxManagerTest(TransactionTestCase): class MailboxManagerTest(TransactionTestCase):
def setUp(self): def setUp(self):
super(MailboxManagerTest, self).setUp() super(MailboxManagerTest, self).setUp()
self.customer = Customer.objects.create_user('test') self.customer = Customer.objects.create_user("test")
self.user = User.objects.create_user(self.customer) self.user = User.objects.create_user(self.customer)
def test_get_next_mailbox_name_fresh(self): def test_get_next_mailbox_name_fresh(self):
mailboxname = Mailbox.objects.get_next_mailbox_name(self.user) mailboxname = Mailbox.objects.get_next_mailbox_name(self.user)
self.assertEqual(mailboxname, '{}p01'.format(self.user.username)) self.assertEqual(mailboxname, "{}p01".format(self.user.username))
def test_get_next_mailbox_name_second(self): def test_get_next_mailbox_name_second(self):
Mailbox.objects.create_mailbox(self.user) Mailbox.objects.create_mailbox(self.user)
mailboxname = Mailbox.objects.get_next_mailbox_name(self.user) mailboxname = Mailbox.objects.get_next_mailbox_name(self.user)
self.assertEqual(mailboxname, '{}p02'.format(self.user.username)) self.assertEqual(mailboxname, "{}p02".format(self.user.username))
def test_get_next_mailbox_name_gap_detection(self): def test_get_next_mailbox_name_gap_detection(self):
mailboxes = [ mailboxes = [Mailbox.objects.create_mailbox(self.user) for _ in range(3)]
Mailbox.objects.create_mailbox(self.user) for i in range(3)
]
mailboxes[1].delete() mailboxes[1].delete()
mailboxname = Mailbox.objects.get_next_mailbox_name(self.user) mailboxname = Mailbox.objects.get_next_mailbox_name(self.user)
self.assertEqual(mailboxname, '{}p02'.format(self.user.username)) self.assertEqual(mailboxname, "{}p02".format(self.user.username))
def test_unused_or_own_fresh(self): def test_unused_or_own_fresh(self):
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
address = MailAddress.objects.create(localpart='test', domain=md) address = MailAddress.objects.create(localpart="test", domain=md)
mailboxes = Mailbox.objects.unused_or_own(address, self.user) mailboxes = Mailbox.objects.unused_or_own(address, self.user)
self.assertQuerysetEqual(mailboxes, []) self.assertQuerysetEqual(mailboxes, [])
def test_unused_or_own_unassigned(self): def test_unused_or_own_unassigned(self):
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
address = MailAddress.objects.create(localpart='test', domain=md) address = MailAddress.objects.create(localpart="test", domain=md)
mailboxes = [ mailboxes = [Mailbox.objects.create_mailbox(self.user) for _ in range(2)]
Mailbox.objects.create_mailbox(self.user) for i in range(2)
]
assignable = Mailbox.objects.unused_or_own(address, self.user) assignable = Mailbox.objects.unused_or_own(address, self.user)
self.assertQuerysetEqual(assignable, [repr(mb) for mb in mailboxes]) self.assertQuerysetEqual(assignable, [repr(mb) for mb in mailboxes])
def test_unused_or_own_assigned(self): def test_unused_or_own_assigned(self):
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
address = MailAddress.objects.create(localpart='test', domain=md) address = MailAddress.objects.create(localpart="test", domain=md)
mailboxes = [ mailboxes = [Mailbox.objects.create_mailbox(self.user) for _ in range(2)]
Mailbox.objects.create_mailbox(self.user) for i in range(2)
]
address.set_mailbox(mailboxes[0]) address.set_mailbox(mailboxes[0])
assignable = Mailbox.objects.unused_or_own(address, self.user) assignable = Mailbox.objects.unused_or_own(address, self.user)
self.assertQuerysetEqual(assignable, [repr(mb) for mb in mailboxes]) self.assertQuerysetEqual(assignable, [repr(mb) for mb in mailboxes])
def test_unused_or_own_assigned_other(self): def test_unused_or_own_assigned_other(self):
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
address = MailAddress.objects.create(localpart='test', domain=md) address = MailAddress.objects.create(localpart="test", domain=md)
address2 = MailAddress.objects.create(localpart='test2', domain=md) address2 = MailAddress.objects.create(localpart="test2", domain=md)
mailboxes = [ mailboxes = [Mailbox.objects.create_mailbox(self.user) for _ in range(2)]
Mailbox.objects.create_mailbox(self.user) for i in range(2)
]
address2.set_mailbox(mailboxes[0]) address2.set_mailbox(mailboxes[0])
assignable = Mailbox.objects.unused_or_own(address, self.user) assignable = Mailbox.objects.unused_or_own(address, self.user)
self.assertQuerysetEqual(assignable, [repr(mailboxes[1])]) self.assertQuerysetEqual(assignable, [repr(mailboxes[1])])
@ -283,11 +280,9 @@ class MailboxManagerTest(TransactionTestCase):
self.assertQuerysetEqual(mailboxes, [repr(mailbox)]) self.assertQuerysetEqual(mailboxes, [repr(mailbox)])
def test_unused_assigned(self): def test_unused_assigned(self):
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
address = MailAddress.objects.create(localpart='test', domain=md) address = MailAddress.objects.create(localpart="test", domain=md)
mailboxes = [ mailboxes = [Mailbox.objects.create_mailbox(self.user) for _ in range(2)]
Mailbox.objects.create_mailbox(self.user) for i in range(2)
]
address.set_mailbox(mailboxes[0]) address.set_mailbox(mailboxes[0])
assignable = Mailbox.objects.unused(self.user) assignable = Mailbox.objects.unused(self.user)
self.assertQuerysetEqual(assignable, [repr(mailboxes[1])]) self.assertQuerysetEqual(assignable, [repr(mailboxes[1])])
@ -295,31 +290,28 @@ class MailboxManagerTest(TransactionTestCase):
def test_create_mailbox_no_password(self): def test_create_mailbox_no_password(self):
mailbox = Mailbox.objects.create_mailbox(self.user) mailbox = Mailbox.objects.create_mailbox(self.user)
self.assertEqual(mailbox.osuser, self.user) self.assertEqual(mailbox.osuser, self.user)
self.assertEqual(mailbox.username, '{}p01'.format(self.user.username)) self.assertEqual(mailbox.username, "{}p01".format(self.user.username))
self.assertEqual(mailbox.password, '') self.assertEqual(mailbox.password, "")
def test_create_mailbox_with_password(self): def test_create_mailbox_with_password(self):
mailbox = Mailbox.objects.create_mailbox(self.user, 'test') mailbox = Mailbox.objects.create_mailbox(self.user, "test")
self.assertEqual(mailbox.osuser, self.user) self.assertEqual(mailbox.osuser, self.user)
self.assertEqual(mailbox.username, '{}p01'.format(self.user.username)) self.assertEqual(mailbox.username, "{}p01".format(self.user.username))
self.assertTrue(sha512_crypt.verify('test', mailbox.password)) self.assertTrue(sha512_crypt.verify("test", mailbox.password))
@override_settings( @override_settings(
CELERY_ALWAYS_EAGER=True, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
CELERY_CACHE_BACKEND='memory',
BROKER_BACKEND='memory'
) )
class MailAddressMailboxTest(TestCase): class MailAddressMailboxTest(TestCase):
def setUp(self): def setUp(self):
super(MailAddressMailboxTest, self).setUp() super(MailAddressMailboxTest, self).setUp()
self.customer = Customer.objects.create_user('test') self.customer = Customer.objects.create_user("test")
def test___str__(self): def test___str__(self):
user = User.objects.create_user(self.customer) user = User.objects.create_user(self.customer)
md = MailDomain.objects.create(domain='example.org') md = MailDomain.objects.create(domain="example.org")
ma = MailAddress(localpart='test', domain=md) ma = MailAddress(localpart="test", domain=md)
mb = Mailbox.objects.create_mailbox(user) mb = Mailbox.objects.create_mailbox(user)
ma.set_mailbox(mb) ma.set_mailbox(mb)
self.assertEqual(str(ma.mailaddressmailbox), mb.username) self.assertEqual(str(ma.mailaddressmailbox), mb.username)

File diff suppressed because it is too large Load diff

View file

@ -7,26 +7,14 @@ The module starts Celery_ tasks.
""" """
from django import forms from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib import admin from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from fileservertasks.tasks import set_file_ssh_authorized_keys from fileservertasks.tasks import set_file_ssh_authorized_keys
from gvawebcore.forms import ( from gvawebcore.forms import PASSWORD_MISMATCH_ERROR
PASSWORD_MISMATCH_ERROR
)
from taskresults.models import TaskResult from taskresults.models import TaskResult
from .forms import DUPLICATE_SSH_PUBLIC_KEY_FOR_USER, INVALID_SSH_PUBLIC_KEY
from .forms import ( from .models import AdditionalGroup, Group, Shadow, SshPublicKey, User
INVALID_SSH_PUBLIC_KEY,
DUPLICATE_SSH_PUBLIC_KEY_FOR_USER,
)
from .models import (
AdditionalGroup,
Group,
Shadow,
SshPublicKey,
User,
)
class AdditionalGroupInline(admin.TabularInline): class AdditionalGroupInline(admin.TabularInline):
@ -34,6 +22,7 @@ class AdditionalGroupInline(admin.TabularInline):
Inline for :py:class:`osusers.models.AdditionalGroup` instances. Inline for :py:class:`osusers.models.AdditionalGroup` instances.
""" """
model = AdditionalGroup model = AdditionalGroup
@ -42,8 +31,9 @@ class ShadowInline(admin.TabularInline):
Inline for :py:class:`osusers.models.ShadowInline` instances. Inline for :py:class:`osusers.models.ShadowInline` instances.
""" """
model = Shadow model = Shadow
readonly_fields = ['passwd'] readonly_fields = ["passwd"]
can_delete = False can_delete = False
@ -53,18 +43,17 @@ class UserCreationForm(forms.ModelForm):
<osusers.models.User>`. <osusers.models.User>`.
""" """
password1 = forms.CharField( password1 = forms.CharField(
label=_('Password'), widget=forms.PasswordInput, label=_("Password"), widget=forms.PasswordInput, required=False
required=False,
) )
password2 = forms.CharField( password2 = forms.CharField(
label=_('Password (again)'), widget=forms.PasswordInput, label=_("Password (again)"), widget=forms.PasswordInput, required=False
required=False,
) )
class Meta: class Meta:
model = User model = User
fields = ['customer'] fields = ["customer"]
def clean_password2(self): def clean_password2(self):
""" """
@ -74,8 +63,8 @@ class UserCreationForm(forms.ModelForm):
:rtype: str or None :rtype: str or None
""" """
password1 = self.cleaned_data.get('password1') password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get('password2') password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2: if password1 and password2 and password1 != password2:
raise forms.ValidationError(PASSWORD_MISMATCH_ERROR) raise forms.ValidationError(PASSWORD_MISMATCH_ERROR)
return password2 return password2
@ -90,8 +79,10 @@ class UserCreationForm(forms.ModelForm):
""" """
user = User.objects.create_user( user = User.objects.create_user(
customer=self.cleaned_data['customer'], customer=self.cleaned_data["customer"],
password=self.cleaned_data['password1'], commit=commit) password=self.cleaned_data["password1"],
commit=commit,
)
return user return user
def save_m2m(self): def save_m2m(self):
@ -108,14 +99,16 @@ class UserAdmin(admin.ModelAdmin):
<osusers.models.User>`. <osusers.models.User>`.
""" """
actions = ['perform_delete_selected']
actions = ["perform_delete_selected"]
add_form = UserCreationForm add_form = UserCreationForm
inlines = [AdditionalGroupInline, ShadowInline] inlines = [AdditionalGroupInline, ShadowInline]
add_fieldsets = ( add_fieldsets = (
(None, { (
'classes': ('wide',), None,
'fields': ('customer', 'password1', 'password2')}), {"classes": ("wide",), "fields": ("customer", "password1", "password2")},
),
) )
def get_form(self, request, obj=None, **kwargs): def get_form(self, request, obj=None, **kwargs):
@ -132,10 +125,12 @@ class UserAdmin(admin.ModelAdmin):
""" """
defaults = {} defaults = {}
if obj is None: if obj is None:
defaults.update({ defaults.update(
'form': self.add_form, {
'fields': admin.options.flatten_fieldsets(self.add_fieldsets), "form": self.add_form,
}) "fields": admin.options.flatten_fieldsets(self.add_fieldsets),
}
)
defaults.update(kwargs) defaults.update(kwargs)
return super(UserAdmin, self).get_form(request, obj, **defaults) return super(UserAdmin, self).get_form(request, obj, **defaults)
@ -151,7 +146,7 @@ class UserAdmin(admin.ModelAdmin):
""" """
if obj: if obj:
return ['uid'] return ["uid"]
return [] return []
def perform_delete_selected(self, request, queryset): def perform_delete_selected(self, request, queryset):
@ -167,7 +162,8 @@ class UserAdmin(admin.ModelAdmin):
""" """
for user in queryset.all(): for user in queryset.all():
user.delete() user.delete()
perform_delete_selected.short_description = _('Delete selected users')
perform_delete_selected.short_description = _("Delete selected users")
def get_actions(self, request): def get_actions(self, request):
""" """
@ -182,8 +178,8 @@ class UserAdmin(admin.ModelAdmin):
""" """
actions = super(UserAdmin, self).get_actions(request) actions = super(UserAdmin, self).get_actions(request)
if 'delete_selected' in actions: # pragma: no cover if "delete_selected" in actions: # pragma: no cover
del actions['delete_selected'] del actions["delete_selected"]
return actions return actions
@ -193,7 +189,8 @@ class GroupAdmin(admin.ModelAdmin):
<osusers.models.Group>`. <osusers.models.Group>`.
""" """
actions = ['perform_delete_selected']
actions = ["perform_delete_selected"]
def perform_delete_selected(self, request, queryset): def perform_delete_selected(self, request, queryset):
""" """
@ -208,7 +205,8 @@ class GroupAdmin(admin.ModelAdmin):
""" """
for group in queryset.all(): for group in queryset.all():
group.delete() group.delete()
perform_delete_selected.short_description = _('Delete selected groups')
perform_delete_selected.short_description = _("Delete selected groups")
def get_actions(self, request): def get_actions(self, request):
""" """
@ -223,8 +221,8 @@ class GroupAdmin(admin.ModelAdmin):
""" """
actions = super(GroupAdmin, self).get_actions(request) actions = super(GroupAdmin, self).get_actions(request)
if 'delete_selected' in actions: # pragma: no cover if "delete_selected" in actions: # pragma: no cover
del actions['delete_selected'] del actions["delete_selected"]
return actions return actions
@ -234,33 +232,37 @@ class SshPublicKeyCreationForm(forms.ModelForm):
<osusers.models.SshPublicKey>`. <osusers.models.SshPublicKey>`.
""" """
publickeytext = forms.CharField( publickeytext = forms.CharField(
label=_('Key text'), widget=forms.Textarea, label=_("Key text"),
help_text=_('A SSH public key in either OpenSSH or RFC 4716 format')) widget=forms.Textarea,
help_text=_("A SSH public key in either OpenSSH or RFC 4716 format"),
)
class Meta: class Meta:
model = SshPublicKey model = SshPublicKey
fields = ['user'] fields = ["user"]
def clean_publickeytext(self): def clean_publickeytext(self):
keytext = self.cleaned_data.get('publickeytext') keytext = self.cleaned_data.get("publickeytext")
try: try:
SshPublicKey.objects.parse_keytext(keytext) SshPublicKey.objects.parse_key_text(keytext)
except: except:
raise forms.ValidationError(INVALID_SSH_PUBLIC_KEY) raise forms.ValidationError(INVALID_SSH_PUBLIC_KEY)
return keytext return keytext
def clean(self): def clean(self):
user = self.cleaned_data.get('user') user = self.cleaned_data.get("user")
keytext = self.cleaned_data.get('publickeytext') keytext = self.cleaned_data.get("publickeytext")
if user and keytext: if user and keytext:
alg, data, comment = SshPublicKey.objects.parse_keytext(keytext) alg, data, comment = SshPublicKey.objects.parse_key_text(keytext)
if SshPublicKey.objects.filter( if SshPublicKey.objects.filter(
user=user, algorithm=alg, data=data user=user, algorithm=alg, data=data
).exists(): ).exists():
self.add_error( self.add_error(
'publickeytext', "publickeytext",
forms.ValidationError(DUPLICATE_SSH_PUBLIC_KEY_FOR_USER)) forms.ValidationError(DUPLICATE_SSH_PUBLIC_KEY_FOR_USER),
)
super(SshPublicKeyCreationForm, self).clean() super(SshPublicKeyCreationForm, self).clean()
def save(self, commit=True): def save(self, commit=True):
@ -272,8 +274,9 @@ class SshPublicKeyCreationForm(forms.ModelForm):
:rtype: :py:class:`osusers.models.SshPublicKey` :rtype: :py:class:`osusers.models.SshPublicKey`
""" """
algorithm, keydata, comment = SshPublicKey.objects.parse_keytext( algorithm, keydata, comment = SshPublicKey.objects.parse_key_text(
self.cleaned_data.get('publickeytext')) self.cleaned_data.get("publickeytext")
)
self.instance.algorithm = algorithm self.instance.algorithm = algorithm
self.instance.data = keydata self.instance.data = keydata
self.instance.comment = comment self.instance.comment = comment
@ -286,14 +289,13 @@ class SshPublicKeyAdmin(admin.ModelAdmin):
<osusers.models.SshPublicKey>`. <osusers.models.SshPublicKey>`.
""" """
actions = ['perform_delete_selected']
actions = ["perform_delete_selected"]
add_form = SshPublicKeyCreationForm add_form = SshPublicKeyCreationForm
list_display = ['user', 'algorithm', 'comment'] list_display = ["user", "algorithm", "comment"]
add_fieldsets = ( add_fieldsets = (
(None, { (None, {"classes": ("wide",), "fields": ("user", "publickeytext")}),
'classes': ('wide',),
'fields': ('user', 'publickeytext')}),
) )
def get_form(self, request, obj=None, **kwargs): def get_form(self, request, obj=None, **kwargs):
@ -311,13 +313,14 @@ class SshPublicKeyAdmin(admin.ModelAdmin):
""" """
defaults = {} defaults = {}
if obj is None: if obj is None:
defaults.update({ defaults.update(
'form': self.add_form, {
'fields': admin.options.flatten_fieldsets(self.add_fieldsets), "form": self.add_form,
}) "fields": admin.options.flatten_fieldsets(self.add_fieldsets),
}
)
defaults.update(kwargs) defaults.update(kwargs)
return super(SshPublicKeyAdmin, self).get_form( return super(SshPublicKeyAdmin, self).get_form(request, obj, **defaults)
request, obj, **defaults)
def get_readonly_fields(self, request, obj=None): def get_readonly_fields(self, request, obj=None):
""" """
@ -332,7 +335,7 @@ class SshPublicKeyAdmin(admin.ModelAdmin):
""" """
if obj: if obj:
return ['algorithm', 'data'] return ["algorithm", "data"]
return [] return []
def perform_delete_selected(self, request, queryset): def perform_delete_selected(self, request, queryset):
@ -370,23 +373,19 @@ class SshPublicKeyAdmin(admin.ModelAdmin):
} }
""" """
users = set([ users = set([item["user"] for item in queryset.values("user").distinct()])
item['user'] for item in
queryset.values('user').distinct()
])
queryset.delete() queryset.delete()
for user in users: for user in users:
# TODO: move to model/signal # TODO: move to model/signal
TaskResult.objects.create_task_result( TaskResult.objects.create_task_result(
'perform_delete_selected', "perform_delete_selected",
set_file_ssh_authorized_keys.s( set_file_ssh_authorized_keys.s(
User.objects.get(uid=user).username, User.objects.get(uid=user).username,
[str(key) for key in SshPublicKey.objects.filter( [str(key) for key in SshPublicKey.objects.filter(user_id=user)],
user_id=user)] ),
) )
)
perform_delete_selected.short_description = _( perform_delete_selected.short_description = _("Delete selected SSH public keys")
'Delete selected SSH public keys')
def get_actions(self, request): def get_actions(self, request):
""" """
@ -401,8 +400,8 @@ class SshPublicKeyAdmin(admin.ModelAdmin):
""" """
actions = super(SshPublicKeyAdmin, self).get_actions(request) actions = super(SshPublicKeyAdmin, self).get_actions(request)
if 'delete_selected' in actions: # pragma: no cover if "delete_selected" in actions: # pragma: no cover
del actions['delete_selected'] del actions["delete_selected"]
return actions return actions

View file

@ -13,14 +13,12 @@ from crispy_forms.layout import Submit
from gvawebcore.forms import PasswordModelFormMixin from gvawebcore.forms import PasswordModelFormMixin
from .models import ( from .models import SshPublicKey, User
SshPublicKey,
User,
)
INVALID_SSH_PUBLIC_KEY = _('Invalid SSH public key data format.') INVALID_SSH_PUBLIC_KEY = _("Invalid SSH public key data format.")
DUPLICATE_SSH_PUBLIC_KEY_FOR_USER = _( DUPLICATE_SSH_PUBLIC_KEY_FOR_USER = _(
'This SSH public key is already assigned to this user.') "This SSH public key is already assigned to this user."
)
class ChangeOsUserPasswordForm(PasswordModelFormMixin, forms.ModelForm): class ChangeOsUserPasswordForm(PasswordModelFormMixin, forms.ModelForm):
@ -28,6 +26,7 @@ class ChangeOsUserPasswordForm(PasswordModelFormMixin, forms.ModelForm):
A form for setting an OS user's password. A form for setting an OS user's password.
""" """
class Meta: class Meta:
model = User model = User
fields = [] fields = []
@ -36,8 +35,9 @@ class ChangeOsUserPasswordForm(PasswordModelFormMixin, forms.ModelForm):
self.helper = FormHelper() self.helper = FormHelper()
super(ChangeOsUserPasswordForm, self).__init__(*args, **kwargs) super(ChangeOsUserPasswordForm, self).__init__(*args, **kwargs)
self.helper.form_action = reverse( self.helper.form_action = reverse(
'set_osuser_password', kwargs={'slug': self.instance.username}) "set_osuser_password", kwargs={"slug": self.instance.username}
self.helper.add_input(Submit('submit', _('Set password'))) )
self.helper.add_input(Submit("submit", _("Set password")))
def save(self, commit=True): def save(self, commit=True):
""" """
@ -48,7 +48,7 @@ class ChangeOsUserPasswordForm(PasswordModelFormMixin, forms.ModelForm):
:rtype: :py:class:`osusers.models.User` :rtype: :py:class:`osusers.models.User`
""" """
self.instance.set_password(self.cleaned_data['password1']) self.instance.set_password(self.cleaned_data["password1"])
return super(ChangeOsUserPasswordForm, self).save(commit=commit) return super(ChangeOsUserPasswordForm, self).save(commit=commit)
@ -58,41 +58,45 @@ class AddSshPublicKeyForm(forms.ModelForm):
<osusers.models.SshPublicKey>`. <osusers.models.SshPublicKey>`.
""" """
publickeytext = forms.CharField( publickeytext = forms.CharField(
label=_('Key text'), widget=forms.Textarea, label=_("Key text"),
help_text=_('A SSH public key in either OpenSSH or RFC 4716 format')) widget=forms.Textarea,
help_text=_("A SSH public key in either OpenSSH or RFC 4716 format"),
)
class Meta: class Meta:
model = SshPublicKey model = SshPublicKey
fields = [] fields = []
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
hosting_package = kwargs.pop('hostingpackage') hosting_package = kwargs.pop("hostingpackage")
self.osuser = hosting_package.osuser self.osuser = hosting_package.osuser
super(AddSshPublicKeyForm, self).__init__(*args, **kwargs) super(AddSshPublicKeyForm, self).__init__(*args, **kwargs)
self.helper = FormHelper() self.helper = FormHelper()
self.helper.form_action = reverse( self.helper.form_action = reverse(
'add_ssh_key', kwargs={'package': hosting_package.id}) "add_ssh_key", kwargs={"package": hosting_package.id}
self.helper.add_input(Submit('submit', _('Add SSH public key'))) )
self.helper.add_input(Submit("submit", _("Add SSH public key")))
def clean_publickeytext(self): def clean_publickeytext(self):
keytext = self.cleaned_data.get('publickeytext') keytext = self.cleaned_data.get("publickeytext")
try: try:
SshPublicKey.objects.parse_keytext(keytext) SshPublicKey.objects.parse_key_text(keytext)
except ValueError: except ValueError:
raise forms.ValidationError(INVALID_SSH_PUBLIC_KEY) raise forms.ValidationError(INVALID_SSH_PUBLIC_KEY)
return keytext return keytext
def clean(self): def clean(self):
keytext = self.cleaned_data.get('publickeytext') keytext = self.cleaned_data.get("publickeytext")
if keytext is not None: if keytext is not None:
alg, data, comment = SshPublicKey.objects.parse_keytext(keytext) alg, data, comment = SshPublicKey.objects.parse_key_text(keytext)
if SshPublicKey.objects.filter( if SshPublicKey.objects.filter(
user=self.osuser, algorithm=alg, data=data user=self.osuser, algorithm=alg, data=data
).exists(): ).exists():
self.add_error( self.add_error(
'publickeytext', "publickeytext",
forms.ValidationError(DUPLICATE_SSH_PUBLIC_KEY_FOR_USER) forms.ValidationError(DUPLICATE_SSH_PUBLIC_KEY_FOR_USER),
) )
def save(self, commit=True): def save(self, commit=True):
@ -104,8 +108,9 @@ class AddSshPublicKeyForm(forms.ModelForm):
:rtype: :py:class:`osusers.models.SshPublicKey` :rtype: :py:class:`osusers.models.SshPublicKey`
""" """
algorithm, keydata, comment = SshPublicKey.objects.parse_keytext( algorithm, keydata, comment = SshPublicKey.objects.parse_key_text(
self.cleaned_data.get('publickeytext')) self.cleaned_data.get("publickeytext")
)
self.instance.user = self.osuser self.instance.user = self.osuser
self.instance.algorithm = algorithm self.instance.algorithm = algorithm
self.instance.data = keydata self.instance.data = keydata
@ -119,17 +124,19 @@ class EditSshPublicKeyCommentForm(forms.ModelForm):
<osusers.models.SshPublicKey>` comment fields. <osusers.models.SshPublicKey>` comment fields.
""" """
class Meta: class Meta:
model = SshPublicKey model = SshPublicKey
fields = ['comment'] fields = ["comment"]
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
hosting_package = kwargs.pop('hostingpackage') hosting_package = kwargs.pop("hostingpackage")
self.osuser = hosting_package.osuser self.osuser = hosting_package.osuser
super(EditSshPublicKeyCommentForm, self).__init__(*args, **kwargs) super(EditSshPublicKeyCommentForm, self).__init__(*args, **kwargs)
self.fields['comment'].widget = forms.TextInput() self.fields["comment"].widget = forms.TextInput()
self.helper = FormHelper() self.helper = FormHelper()
self.helper.form_action = reverse( self.helper.form_action = reverse(
'edit_ssh_key_comment', "edit_ssh_key_comment",
kwargs={'package': hosting_package.id, 'pk': self.instance.id}) kwargs={"package": hosting_package.id, "pk": self.instance.id},
self.helper.add_input(Submit('submit', _('Change Comment'))) )
self.helper.add_input(Submit("submit", _("Change Comment")))

View file

@ -2,20 +2,16 @@
This module defines the database models of operating system users. This module defines the database models of operating system users.
""" """
from __future__ import unicode_literals
import base64 import base64
from datetime import date from datetime import date
import logging import logging
import os import os
import six
from django.db import models, transaction from django.db import models, transaction
from django.conf import settings from django.conf import settings
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.dispatch import Signal from django.dispatch import Signal
from django.utils import timezone from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from model_utils.models import TimeStampedModel from model_utils.models import TimeStampedModel
@ -27,11 +23,10 @@ from passlib.utils import generate_password
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
password_set = Signal(providing_args=['instance', 'password']) password_set = Signal(providing_args=["instance", "password"])
CANNOT_USE_PRIMARY_GROUP_AS_ADDITIONAL = _( CANNOT_USE_PRIMARY_GROUP_AS_ADDITIONAL = _("You can not use a user's primary group.")
"You can not use a user's primary group.")
class GroupManager(models.Manager): class GroupManager(models.Manager):
@ -48,34 +43,31 @@ class GroupManager(models.Manager):
:rtype: int :rtype: int
""" """
q = self.aggregate(models.Max('gid')) q = self.aggregate(models.Max("gid"))
if q['gid__max'] is None: if q["gid__max"] is None:
return settings.OSUSER_MINGID return settings.OSUSER_MINGID
return max(settings.OSUSER_MINGID, q['gid__max'] + 1) return max(settings.OSUSER_MINGID, q["gid__max"] + 1)
@python_2_unicode_compatible
class Group(TimeStampedModel, models.Model): class Group(TimeStampedModel, models.Model):
""" """
This entity class corresponds to an operating system group. This entity class corresponds to an operating system group.
""" """
groupname = models.CharField(
_('Group name'), max_length=16, unique=True) groupname = models.CharField(_("Group name"), max_length=16, unique=True)
gid = models.PositiveSmallIntegerField( gid = models.PositiveSmallIntegerField(_("Group ID"), unique=True, primary_key=True)
_('Group ID'), unique=True, primary_key=True) descr = models.TextField(_("Description"), blank=True)
descr = models.TextField(_('Description'), blank=True) passwd = models.CharField(_("Group password"), max_length=128, blank=True)
passwd = models.CharField(
_('Group password'), max_length=128, blank=True)
objects = GroupManager() objects = GroupManager()
class Meta: class Meta:
verbose_name = _('Group') verbose_name = _("Group")
verbose_name_plural = _('Groups') verbose_name_plural = _("Groups")
def __str__(self): def __str__(self):
return '{0} ({1})'.format(self.groupname, self.gid) return "{0} ({1})".format(self.groupname, self.gid)
@transaction.atomic @transaction.atomic
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
@ -122,10 +114,10 @@ class UserManager(models.Manager):
:rtype: int :rtype: int
""" """
q = self.aggregate(models.Max('uid')) q = self.aggregate(models.Max("uid"))
if q['uid__max'] is None: if q["uid__max"] is None:
return settings.OSUSER_MINUID return settings.OSUSER_MINUID
return max(settings.OSUSER_MINUID, q['uid__max'] + 1) return max(settings.OSUSER_MINUID, q["uid__max"] + 1)
def get_next_username(self): def get_next_username(self):
""" """
@ -137,23 +129,21 @@ class UserManager(models.Manager):
""" """
count = 1 count = 1
usernameformat = "{0}{1:02d}" usernameformat = "{0}{1:02d}"
nextuser = usernameformat.format(settings.OSUSER_USERNAME_PREFIX, nextuser = usernameformat.format(settings.OSUSER_USERNAME_PREFIX, count)
count) for user in (
for user in self.values('username').filter( self.values("username")
username__startswith=settings.OSUSER_USERNAME_PREFIX .filter(username__startswith=settings.OSUSER_USERNAME_PREFIX)
).order_by('username'): .order_by("username")
if user['username'] == nextuser: ):
if user["username"] == nextuser:
count += 1 count += 1
nextuser = usernameformat.format( nextuser = usernameformat.format(settings.OSUSER_USERNAME_PREFIX, count)
settings.OSUSER_USERNAME_PREFIX, count)
else: else:
break break
return nextuser return nextuser
@transaction.atomic @transaction.atomic
def create_user( def create_user(self, customer, username=None, password=None, commit=False):
self, customer, username=None, password=None, commit=False
):
""" """
Create a new user with a primary group named the same as the user and Create a new user with a primary group named the same as the user and
an initial password. an initial password.
@ -179,41 +169,42 @@ class UserManager(models.Manager):
password = generate_password() password = generate_password()
homedir = os.path.join(settings.OSUSER_HOME_BASEPATH, username) homedir = os.path.join(settings.OSUSER_HOME_BASEPATH, username)
group = Group.objects.create(groupname=username, gid=gid) group = Group.objects.create(groupname=username, gid=gid)
user = self.create(username=username, group=group, uid=uid, user = self.create(
homedir=homedir, customer=customer, username=username,
shell=settings.OSUSER_DEFAULT_SHELL) group=group,
uid=uid,
homedir=homedir,
customer=customer,
shell=settings.OSUSER_DEFAULT_SHELL,
)
user.set_password(password) user.set_password(password)
if commit: if commit:
user.save() user.save()
return user return user
@python_2_unicode_compatible
class User(TimeStampedModel, models.Model): class User(TimeStampedModel, models.Model):
""" """
This entity class corresponds to an operating system user. This entity class corresponds to an operating system user.
""" """
username = models.CharField(
_('User name'), max_length=64, unique=True) username = models.CharField(_("User name"), max_length=64, unique=True)
uid = models.PositiveSmallIntegerField( uid = models.PositiveSmallIntegerField(_("User ID"), unique=True, primary_key=True)
_('User ID'), unique=True, primary_key=True) group = models.ForeignKey(Group, verbose_name=_("Group"), on_delete=models.CASCADE)
group = models.ForeignKey( gecos = models.CharField(_("Gecos field"), max_length=128, blank=True)
Group, verbose_name=_('Group'), on_delete=models.CASCADE) homedir = models.CharField(_("Home directory"), max_length=256)
gecos = models.CharField(_('Gecos field'), max_length=128, blank=True) shell = models.CharField(_("Login shell"), max_length=64)
homedir = models.CharField(_('Home directory'), max_length=256) customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
shell = models.CharField(_('Login shell'), max_length=64)
customer = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
objects = UserManager() objects = UserManager()
class Meta: class Meta:
verbose_name = _('User') verbose_name = _("User")
verbose_name_plural = _('Users') verbose_name_plural = _("Users")
def __str__(self): def __str__(self):
return '{0} ({1})'.format(self.username, self.uid) return "{0} ({1})".format(self.username, self.uid)
@transaction.atomic @transaction.atomic
def set_password(self, password): def set_password(self, password):
@ -226,17 +217,15 @@ class User(TimeStampedModel, models.Model):
:param str password: the new password :param str password: the new password
""" """
if hasattr(self, 'shadow'): if hasattr(self, "shadow"):
self.shadow.set_password(password) self.shadow.set_password(password)
else: else:
self.shadow = Shadow.objects.create_shadow( self.shadow = Shadow.objects.create_shadow(user=self, password=password)
user=self, password=password password_set.send(sender=self.__class__, password=password, instance=self)
)
password_set.send(
sender=self.__class__, password=password, instance=self)
return True return True
def is_sftp_user(self): def is_sftp_user(self):
# noinspection PyUnresolvedReferences
return self.additionalgroup_set.filter( return self.additionalgroup_set.filter(
group__groupname=settings.OSUSER_SFTP_GROUP group__groupname=settings.OSUSER_SFTP_GROUP
).exists() ).exists()
@ -269,6 +258,7 @@ class User(TimeStampedModel, models.Model):
:py:meth:`django.db.Model.delete` :py:meth:`django.db.Model.delete`
""" """
# noinspection PyUnresolvedReferences
self.group.delete() self.group.delete()
super(User, self).delete(*args, **kwargs) super(User, self).delete(*args, **kwargs)
@ -293,64 +283,84 @@ class ShadowManager(models.Manager):
""" """
changedays = (timezone.now().date() - date(1970, 1, 1)).days changedays = (timezone.now().date() - date(1970, 1, 1)).days
shadow = self.create( shadow = self.create(
user=user, changedays=changedays, user=user,
minage=0, maxage=None, gracedays=7, changedays=changedays,
inactdays=30, expiredays=None minage=0,
maxage=None,
gracedays=7,
inactdays=30,
expiredays=None,
) )
shadow.set_password(password) shadow.set_password(password)
shadow.save() shadow.save()
return shadow return shadow
@python_2_unicode_compatible
class Shadow(TimeStampedModel, models.Model): class Shadow(TimeStampedModel, models.Model):
""" """
This entity class corresponds to an operating system user's shadow file This entity class corresponds to an operating system user's shadow file
entry. entry.
""" """
user = models.OneToOneField( user = models.OneToOneField(
User, primary_key=True, verbose_name=_('User'), User, primary_key=True, verbose_name=_("User"), on_delete=models.CASCADE
on_delete=models.CASCADE) )
passwd = models.CharField(_('Encrypted password'), max_length=128) passwd = models.CharField(_("Encrypted password"), max_length=128)
changedays = models.PositiveSmallIntegerField( changedays = models.PositiveSmallIntegerField(
_('Date of last change'), _("Date of last change"),
help_text=_('This is expressed in days since Jan 1, 1970'), help_text=_("This is expressed in days since Jan 1, 1970"),
blank=True, null=True) blank=True,
null=True,
)
minage = models.PositiveSmallIntegerField( minage = models.PositiveSmallIntegerField(
_('Minimum age'), _("Minimum age"),
help_text=_('Minimum number of days before the password can be' help_text=_("Minimum number of days before the password can be" " changed"),
' changed'), blank=True,
blank=True, null=True) null=True,
)
maxage = models.PositiveSmallIntegerField( maxage = models.PositiveSmallIntegerField(
_('Maximum age'), _("Maximum age"),
help_text=_('Maximum number of days after which the password has to' help_text=_(
' be changed'), "Maximum number of days after which the password has to" " be changed"
blank=True, null=True) ),
blank=True,
null=True,
)
gracedays = models.PositiveSmallIntegerField( gracedays = models.PositiveSmallIntegerField(
_('Grace period'), _("Grace period"),
help_text=_('The number of days before the password is going to' help_text=_("The number of days before the password is going to" " expire"),
' expire'), blank=True,
blank=True, null=True) null=True,
)
inactdays = models.PositiveSmallIntegerField( inactdays = models.PositiveSmallIntegerField(
_('Inactivity period'), _("Inactivity period"),
help_text=_('The number of days after the password has expired during' help_text=_(
' which the password should still be accepted'), "The number of days after the password has expired during"
blank=True, null=True) " which the password should still be accepted"
),
blank=True,
null=True,
)
expiredays = models.PositiveSmallIntegerField( expiredays = models.PositiveSmallIntegerField(
_('Account expiration date'), _("Account expiration date"),
help_text=_('The date of expiration of the account, expressed as' help_text=_(
' number of days since Jan 1, 1970'), "The date of expiration of the account, expressed as"
blank=True, null=True, default=None) " number of days since Jan 1, 1970"
),
blank=True,
null=True,
default=None,
)
objects = ShadowManager() objects = ShadowManager()
class Meta: class Meta:
verbose_name = _('Shadow password') verbose_name = _("Shadow password")
verbose_name_plural = _('Shadow passwords') verbose_name_plural = _("Shadow passwords")
def __str__(self): def __str__(self):
return 'for user {0}'.format(self.user) return "for user {0}".format(self.user)
def set_password(self, password): def set_password(self, password):
""" """
@ -361,23 +371,23 @@ class Shadow(TimeStampedModel, models.Model):
self.passwd = sha512_crypt.encrypt(password) self.passwd = sha512_crypt.encrypt(password)
@python_2_unicode_compatible
class AdditionalGroup(TimeStampedModel, models.Model): class AdditionalGroup(TimeStampedModel, models.Model):
""" """
This entity class corresponds to additional group assignments for an This entity class corresponds to additional group assignments for an
:py:class:`operating system user <osusers.models.User>`. :py:class:`operating system user <osusers.models.User>`.
""" """
user = models.ForeignKey(User, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE)
class Meta: class Meta:
unique_together = ('user', 'group') unique_together = ("user", "group")
verbose_name = _('Additional group') verbose_name = _("Additional group")
verbose_name_plural = _('Additional groups') verbose_name_plural = _("Additional groups")
def __str__(self): def __str__(self):
return '{0} in {1}'.format(self.user, self.group) return "{0} in {1}".format(self.user, self.group)
def clean(self): def clean(self):
""" """
@ -385,6 +395,7 @@ class AdditionalGroup(TimeStampedModel, models.Model):
group. group.
""" """
# noinspection PyUnresolvedReferences
if self.user.group == self.group: if self.user.group == self.group:
raise ValidationError(CANNOT_USE_PRIMARY_GROUP_AS_ADDITIONAL) raise ValidationError(CANNOT_USE_PRIMARY_GROUP_AS_ADDITIONAL)
@ -423,60 +434,62 @@ class SshPublicKeyManager(models.Manager):
""" """
def parse_keytext(self, keytext): def parse_key_text(self, key_text: str):
""" """
Parse a SSH public key in OpenSSH or :rfc:`4716` format into its Parse a SSH public key in OpenSSH or :rfc:`4716` format into its
components algorithm, key data and comment. components algorithm, key data and comment.
:param str keytext: key text :param str key_text: key text
:return: triple of algorithm name, key data and comment :return: triple of algorithm name, key data and comment
:rtype: triple of str :rtype: triple of str
""" """
if keytext.startswith('---- BEGIN SSH2 PUBLIC KEY ----'): if key_text.startswith("---- BEGIN SSH2 PUBLIC KEY ----"):
comment = '' comment = ""
data = '' data = ""
continued = '' continued = ""
headers = {} headers = {}
for line in keytext.splitlines(): header_tag = None
if line == '---- BEGIN SSH2 PUBLIC KEY ----': for line in key_text.splitlines():
if line == "---- BEGIN SSH2 PUBLIC KEY ----":
continue continue
elif ':' in line: # a header line elif ":" in line: # a header line
header_tag, header_value = [ header_tag, header_value = [
item.strip() for item in line.split(':', 1)] item.strip() for item in line.split(":", 1)
if header_value.endswith('\\'): ]
if header_value.endswith("\\"):
continued = header_value[:-1] continued = header_value[:-1]
else: else:
headers[header_tag.lower()] = header_value headers[header_tag.lower()] = header_value
elif continued: elif continued:
if line.endswith('\\'): if line.endswith("\\"):
continued += line[:-1] continued += line[:-1]
continue continue
header_value = continued + line header_value = continued + line
headers[header_tag.lower()] = header_value headers[header_tag.lower()] = header_value
continued = '' continued = ""
elif line == '---- END SSH2 PUBLIC KEY ----': elif line == "---- END SSH2 PUBLIC KEY ----":
break break
elif line: # ignore empty lines elif line: # ignore empty lines
data += line data += line
if 'comment' in headers: if "comment" in headers:
comment = headers['comment'] comment = headers["comment"]
else: else:
parts = keytext.split(None, 2) parts = key_text.split(None, 2)
if len(parts) < 2: if len(parts) < 2:
raise ValueError('invalid SSH public key') raise ValueError("invalid SSH public key")
data = parts[1] data = parts[1]
comment = len(parts) == 3 and parts[2] or "" comment = len(parts) == 3 and parts[2] or ""
try: try:
keybytes = base64.b64decode(data) keybytes = base64.b64decode(data)
except TypeError: except TypeError:
raise ValueError('invalid SSH public key') raise ValueError("invalid SSH public key")
parts = keybytes.split(b'\x00' * 3) parts = keybytes.split(b"\x00" * 3)
if len(parts) < 2: if len(parts) < 2:
raise ValueError('invalid SSH public key') raise ValueError("invalid SSH public key")
alglength = six.byte2int(parts[1]) key_length = int.from_bytes(parts[1], byteorder="big")
algname = parts[1][1:1+alglength] key_algorithm = parts[1][1 : 1 + key_length].decode("utf-8")
return algname, data, comment return key_algorithm, data, comment
def create_ssh_public_key(self, user, keytext): def create_ssh_public_key(self, user, keytext):
""" """
@ -490,31 +503,28 @@ class SshPublicKeyManager(models.Manager):
:retype: :py:class:`osusers.models.SshPublicKey` :retype: :py:class:`osusers.models.SshPublicKey`
""" """
algorithm, data, comment = self.parse_keytext(keytext) algorithm, data, comment = self.parse_key_text(keytext)
return self.create( return self.create(user=user, algorithm=algorithm, data=data, comment=comment)
user=user, algorithm=algorithm, data=data, comment=comment)
@python_2_unicode_compatible
class SshPublicKey(TimeStampedModel): class SshPublicKey(TimeStampedModel):
""" """
This entity class represents single SSH keys for an :py:class:`operating This entity class represents single SSH keys for an :py:class:`operating
system user <osusers.models.User>`. system user <osusers.models.User>`.
""" """
user = models.ForeignKey(
User, verbose_name=_('User'), on_delete=models.CASCADE) user = models.ForeignKey(User, verbose_name=_("User"), on_delete=models.CASCADE)
algorithm = models.CharField(_('Algorithm'), max_length=20) algorithm = models.CharField(_("Algorithm"), max_length=20)
data = models.TextField(_('Key bytes'), data = models.TextField(_("Key bytes"), help_text=_("Base64 encoded key bytes"))
help_text=_('Base64 encoded key bytes')) comment = models.TextField(_("Comment"), blank=True)
comment = models.TextField(_('Comment'), blank=True)
objects = SshPublicKeyManager() objects = SshPublicKeyManager()
class Meta: class Meta:
verbose_name = _('SSH public key') verbose_name = _("SSH public key")
verbose_name_plural = _('SSH public keys') verbose_name_plural = _("SSH public keys")
unique_together = [('user', 'algorithm', 'data')] unique_together = [("user", "algorithm", "data")]
def __str__(self): def __str__(self):
return "{algorithm} {data} {comment}".format( return "{algorithm} {data} {comment}".format(

View file

@ -5,17 +5,10 @@ from django.test.utils import override_settings
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from mock import MagicMock, Mock, patch from unittest.mock import MagicMock, Mock, patch
from osusers.forms import ( from osusers.forms import INVALID_SSH_PUBLIC_KEY, DUPLICATE_SSH_PUBLIC_KEY_FOR_USER
INVALID_SSH_PUBLIC_KEY, from osusers.models import Group, SshPublicKey, User
DUPLICATE_SSH_PUBLIC_KEY_FOR_USER,
)
from osusers.models import (
Group,
SshPublicKey,
User,
)
from osusers.admin import ( from osusers.admin import (
GroupAdmin, GroupAdmin,
PASSWORD_MISMATCH_ERROR, PASSWORD_MISMATCH_ERROR,
@ -30,20 +23,19 @@ Customer = get_user_model()
class CustomerTestCase(TestCase): class CustomerTestCase(TestCase):
def setUp(self): def setUp(self):
self.customer = Customer.objects.create_user('test') self.customer = Customer.objects.create_user("test")
super(CustomerTestCase, self).setUp() super(CustomerTestCase, self).setUp()
class UserCreationFormTest(CustomerTestCase): class UserCreationFormTest(CustomerTestCase):
def test_clean_password2_same(self): def test_clean_password2_same(self):
form = UserCreationForm() form = UserCreationForm()
form.cleaned_data = { form.cleaned_data = {
'customer': self.customer, "customer": self.customer,
'password1': 'secret', "password1": "secret",
'password2': 'secret' "password2": "secret",
} }
self.assertEqual(form.clean_password2(), 'secret') self.assertEqual(form.clean_password2(), "secret")
def test_clean_password2_empty(self): def test_clean_password2_empty(self):
form = UserCreationForm() form = UserCreationForm()
@ -53,25 +45,23 @@ class UserCreationFormTest(CustomerTestCase):
def test_clean_password2_mismatch(self): def test_clean_password2_mismatch(self):
form = UserCreationForm() form = UserCreationForm()
form.cleaned_data = { form.cleaned_data = {
'customer': self.customer, "customer": self.customer,
'password1': 'secretx', "password1": "secretx",
'password2': 'secrety' "password2": "secrety",
} }
with self.assertRaises(forms.ValidationError) as cm: with self.assertRaises(forms.ValidationError) as cm:
form.clean_password2() form.clean_password2()
self.assertEqual(cm.exception.message, PASSWORD_MISMATCH_ERROR) self.assertEqual(cm.exception.message, PASSWORD_MISMATCH_ERROR)
@override_settings( @override_settings(
CELERY_ALWAYS_EAGER=True, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
CELERY_CACHE_BACKEND='memory',
BROKER_BACKEND='memory'
) )
def test_save_commit(self): def test_save_commit(self):
form = UserCreationForm() form = UserCreationForm()
form.cleaned_data = { form.cleaned_data = {
'customer': self.customer, "customer": self.customer,
'password1': 'secret', "password1": "secret",
'password2': 'secret' "password2": "secret",
} }
user = form.save() user = form.save()
self.assertIsNotNone(user) self.assertIsNotNone(user)
@ -89,121 +79,99 @@ class UserAdminTest(CustomerTestCase):
super(UserAdminTest, self).setUp() super(UserAdminTest, self).setUp()
def test_get_form_without_object(self): def test_get_form_without_object(self):
form = self.uadmin.get_form(Mock(name='request')) form = self.uadmin.get_form(Mock(name="request"))
self.assertEqual( self.assertEqual(form.Meta.fields, ["customer", "password1", "password2"])
form.Meta.fields,
['customer', 'password1', 'password2']
)
@override_settings( @override_settings(
CELERY_ALWAYS_EAGER=True, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
CELERY_CACHE_BACKEND='memory',
BROKER_BACKEND='memory'
) )
def test_get_form_with_object(self): def test_get_form_with_object(self):
user = User.objects.create_user(customer=self.customer) user = User.objects.create_user(customer=self.customer)
form = self.uadmin.get_form(Mock(name='request'), user) form = self.uadmin.get_form(Mock(name="request"), user)
self.assertEqual( self.assertEqual(
form.Meta.fields, form.Meta.fields,
['username', 'group', 'gecos', 'homedir', 'shell', 'customer', ["username", "group", "gecos", "homedir", "shell", "customer", "uid"],
'uid']
) )
def test_get_inline_instances_without_object(self): def test_get_inline_instances_without_object(self):
inlines = self.uadmin.get_inline_instances(Mock(name='request')) inlines = self.uadmin.get_inline_instances(Mock(name="request"))
self.assertEqual(len(inlines), 2) self.assertEqual(len(inlines), 2)
@override_settings( @override_settings(
CELERY_ALWAYS_EAGER=True, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
CELERY_CACHE_BACKEND='memory',
BROKER_BACKEND='memory'
) )
def test_get_inline_instances_with_object(self): def test_get_inline_instances_with_object(self):
user = User.objects.create_user(customer=self.customer) user = User.objects.create_user(customer=self.customer)
inlines = self.uadmin.get_inline_instances( inlines = self.uadmin.get_inline_instances(Mock(name="request"), user)
Mock(name='request'), user)
self.assertEqual(len(inlines), len(UserAdmin.inlines)) self.assertEqual(len(inlines), len(UserAdmin.inlines))
for index in range(len(inlines)): for index in range(len(inlines)):
self.assertIsInstance(inlines[index], UserAdmin.inlines[index]) self.assertIsInstance(inlines[index], UserAdmin.inlines[index])
@override_settings( @override_settings(
CELERY_ALWAYS_EAGER=True, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
CELERY_CACHE_BACKEND='memory',
BROKER_BACKEND='memory'
) )
def test_perform_delete_selected(self): def test_perform_delete_selected(self):
user = User.objects.create_user(customer=self.customer) user = User.objects.create_user(customer=self.customer)
self.uadmin.perform_delete_selected( self.uadmin.perform_delete_selected(
Mock(name='request'), User.objects.filter(uid=user.uid)) Mock(name="request"), User.objects.filter(uid=user.uid)
)
self.assertEqual(User.objects.filter(uid=user.uid).count(), 0) self.assertEqual(User.objects.filter(uid=user.uid).count(), 0)
def test_get_actions(self): def test_get_actions(self):
requestmock = MagicMock(name='request') requestmock = MagicMock(name="request")
self.assertNotIn( self.assertNotIn("delete_selected", self.uadmin.get_actions(requestmock))
'delete_selected', self.assertIn("perform_delete_selected", self.uadmin.get_actions(requestmock))
self.uadmin.get_actions(requestmock))
self.assertIn(
'perform_delete_selected',
self.uadmin.get_actions(requestmock))
class GroupAdminTest(TestCase): class GroupAdminTest(TestCase):
def setUp(self): def setUp(self):
site = AdminSite() site = AdminSite()
self.gadmin = GroupAdmin(Group, site) self.gadmin = GroupAdmin(Group, site)
super(GroupAdminTest, self).setUp() super(GroupAdminTest, self).setUp()
def test_get_inline_instances_without_object(self): def test_get_inline_instances_without_object(self):
inlines = self.gadmin.get_inline_instances(Mock(name='request')) inlines = self.gadmin.get_inline_instances(Mock(name="request"))
self.assertEqual(inlines, []) self.assertEqual(inlines, [])
@override_settings( @override_settings(
CELERY_ALWAYS_EAGER=True, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
CELERY_CACHE_BACKEND='memory',
BROKER_BACKEND='memory'
) )
def test_get_inline_instances_with_object(self): def test_get_inline_instances_with_object(self):
group = Group.objects.create(gid=1000, groupname='test') group = Group.objects.create(gid=1000, groupname="test")
inlines = self.gadmin.get_inline_instances( inlines = self.gadmin.get_inline_instances(Mock(name="request"), group)
Mock(name='request'), group)
self.assertEqual(len(inlines), len(GroupAdmin.inlines)) self.assertEqual(len(inlines), len(GroupAdmin.inlines))
for index in range(len(inlines)): for index in range(len(inlines)):
self.assertIsInstance(inlines[index], GroupAdmin.inlines[index]) self.assertIsInstance(inlines[index], GroupAdmin.inlines[index])
def test_perform_delete_selected(self): def test_perform_delete_selected(self):
group = Group.objects.create(gid=1000, groupname='test') group = Group.objects.create(gid=1000, groupname="test")
self.gadmin.perform_delete_selected( self.gadmin.perform_delete_selected(
Mock(name='request'), Group.objects.filter(gid=group.gid)) Mock(name="request"), Group.objects.filter(gid=group.gid)
)
self.assertEqual(Group.objects.filter(gid=group.gid).count(), 0) self.assertEqual(Group.objects.filter(gid=group.gid).count(), 0)
def test_get_actions(self): def test_get_actions(self):
requestmock = MagicMock(name='request') requestmock = MagicMock(name="request")
self.assertNotIn( self.assertNotIn("delete_selected", self.gadmin.get_actions(requestmock))
'delete_selected', self.assertIn("perform_delete_selected", self.gadmin.get_actions(requestmock))
self.gadmin.get_actions(requestmock))
self.assertIn(
'perform_delete_selected',
self.gadmin.get_actions(requestmock))
class SshPublicKeyCreationFormTest(CustomerTestCase): class SshPublicKeyCreationFormTest(CustomerTestCase):
@patch("osusers.admin.SshPublicKey.objects")
@patch('osusers.admin.SshPublicKey.objects')
def test_clean_publickeytext_valid_key(self, sshpkmanager): def test_clean_publickeytext_valid_key(self, sshpkmanager):
form = SshPublicKeyCreationForm() form = SshPublicKeyCreationForm()
sshpkmanager.parse_keytext = MagicMock(side_effect=ValueError) sshpkmanager.parse_key_text = MagicMock(side_effect=ValueError)
form.cleaned_data = {'publickeytext': 'wrongkey'} form.cleaned_data = {"publickeytext": "wrongkey"}
with self.assertRaises(forms.ValidationError) as ve: with self.assertRaises(forms.ValidationError) as ve:
form.clean_publickeytext() form.clean_publickeytext()
self.assertEqual(ve.exception.message, INVALID_SSH_PUBLIC_KEY) self.assertEqual(ve.exception.message, INVALID_SSH_PUBLIC_KEY)
@patch('osusers.admin.SshPublicKey.objects') @patch("osusers.admin.SshPublicKey.objects")
def test_clean_publickeytext_invalid_key(self, sshpkmanager): def test_clean_publickeytext_invalid_key(self, sshpkmanager):
form = SshPublicKeyCreationForm() form = SshPublicKeyCreationForm()
sshpkmanager.parse_keytext = MagicMock(return_value='goodkey') sshpkmanager.parse_key_text = MagicMock(return_value="goodkey")
form.cleaned_data = {'publickeytext': 'goodkey'} form.cleaned_data = {"publickeytext": "goodkey"}
self.assertEqual(form.clean_publickeytext(), 'goodkey') self.assertEqual(form.clean_publickeytext(), "goodkey")
def test_clean_missing_data(self): def test_clean_missing_data(self):
form = SshPublicKeyCreationForm() form = SshPublicKeyCreationForm()
@ -211,95 +179,83 @@ class SshPublicKeyCreationFormTest(CustomerTestCase):
form.clean() form.clean()
self.assertEqual(len(form.errors), 0) self.assertEqual(len(form.errors), 0)
@patch('osusers.admin.SshPublicKey.objects.parse_keytext') @patch("osusers.admin.SshPublicKey.objects.parse_key_text")
def test_clean_once(self, parse_keytext): def test_clean_once(self, parse_key_text):
parse_keytext.return_value = ('good', 'key', 'comment') parse_key_text.return_value = ("good", "key", "comment")
user = User.objects.create_user(customer=self.customer) user = User.objects.create_user(customer=self.customer)
form = SshPublicKeyCreationForm() form = SshPublicKeyCreationForm()
form.cleaned_data = { form.cleaned_data = {"user": user, "publickeytext": "good key comment"}
'user': user,
'publickeytext': 'good key comment'
}
form.clean() form.clean()
self.assertEqual(len(form.errors), 0) self.assertEqual(len(form.errors), 0)
@patch('osusers.admin.SshPublicKey.objects.parse_keytext') @patch("osusers.admin.SshPublicKey.objects.parse_key_text")
def test_clean_again(self, parse_keytext): def test_clean_again(self, parse_key_text):
parse_keytext.return_value = ('good', 'key', 'comment') parse_key_text.return_value = ("good", "key", "comment")
user = User.objects.create_user(customer=self.customer) user = User.objects.create_user(customer=self.customer)
SshPublicKey.objects.create( SshPublicKey.objects.create(
user=user, algorithm='good', data='key', comment='comment') user=user, algorithm="good", data="key", comment="comment"
)
form = SshPublicKeyCreationForm() form = SshPublicKeyCreationForm()
form.cleaned_data = { form.cleaned_data = {"user": user, "publickeytext": "good key comment"}
'user': user,
'publickeytext': 'good key comment'
}
form.clean() form.clean()
self.assertIn('publickeytext', form.errors) self.assertIn("publickeytext", form.errors)
self.assertEqual( self.assertEqual(
form.errors['publickeytext'], form.errors["publickeytext"], [DUPLICATE_SSH_PUBLIC_KEY_FOR_USER]
[DUPLICATE_SSH_PUBLIC_KEY_FOR_USER]) )
@patch('osusers.admin.SshPublicKey.objects.parse_keytext') @patch("osusers.admin.SshPublicKey.objects.parse_key_text")
def test_save(self, parse_keytext): def test_save(self, parse_key_text):
parse_keytext.return_value = ('good', 'key', 'comment') parse_key_text.return_value = ("good", "key", "comment")
user = User.objects.create_user(customer=self.customer) user = User.objects.create_user(customer=self.customer)
form = SshPublicKeyCreationForm() form = SshPublicKeyCreationForm()
form.cleaned_data = { form.cleaned_data = {"user": user, "publickeytext": "good key comment"}
'user': user,
'publickeytext': 'good key comment'
}
form.instance.user = user form.instance.user = user
form.save() form.save()
self.assertTrue( self.assertTrue(
SshPublicKey.objects.filter( SshPublicKey.objects.filter(user=user, algorithm="good", data="key")
user=user, algorithm='good', data='key')) )
class SshPublicKeyAdminTest(CustomerTestCase): class SshPublicKeyAdminTest(CustomerTestCase):
def setUp(self): def setUp(self):
site = AdminSite() site = AdminSite()
self.sadmin = SshPublicKeyAdmin(SshPublicKey, site) self.sadmin = SshPublicKeyAdmin(SshPublicKey, site)
super(SshPublicKeyAdminTest, self).setUp() super(SshPublicKeyAdminTest, self).setUp()
def test_get_form_no_instance(self): def test_get_form_no_instance(self):
form = self.sadmin.get_form(request=Mock(name='request')) form = self.sadmin.get_form(request=Mock(name="request"))
self.assertEqual(form.Meta.model, SshPublicKey) self.assertEqual(form.Meta.model, SshPublicKey)
def test_get_form_with_instance(self): def test_get_form_with_instance(self):
user = User.objects.create_user(customer=self.customer) user = User.objects.create_user(customer=self.customer)
key = SshPublicKey.objects.create( key = SshPublicKey.objects.create(
user=user, algorithm='good', data='key', comment='comment') user=user, algorithm="good", data="key", comment="comment"
form = self.sadmin.get_form(request=Mock(name='request'), obj=key) )
form = self.sadmin.get_form(request=Mock(name="request"), obj=key)
self.assertEqual(form.Meta.model, SshPublicKey) self.assertEqual(form.Meta.model, SshPublicKey)
self.assertEqual( self.assertEqual(form.Meta.fields, ["user", "comment", "algorithm", "data"])
form.Meta.fields,
['user', 'comment', 'algorithm', 'data'])
def test_get_readonly_fields_no_instance(self): def test_get_readonly_fields_no_instance(self):
readonly_fields = self.sadmin.get_readonly_fields( readonly_fields = self.sadmin.get_readonly_fields(request=Mock(name="request"))
request=Mock(name='request'))
self.assertEqual(readonly_fields, []) self.assertEqual(readonly_fields, [])
def test_get_readonly_fields_with_instance(self): def test_get_readonly_fields_with_instance(self):
readonly_fields = self.sadmin.get_readonly_fields( readonly_fields = self.sadmin.get_readonly_fields(
request=Mock(name='request'), obj=Mock()) request=Mock(name="request"), obj=Mock()
self.assertEqual(readonly_fields, ['algorithm', 'data']) )
self.assertEqual(readonly_fields, ["algorithm", "data"])
def test_perform_delete_selected(self): def test_perform_delete_selected(self):
user = User.objects.create_user(customer=self.customer) user = User.objects.create_user(customer=self.customer)
key = SshPublicKey.objects.create( key = SshPublicKey.objects.create(
user=user, algorithm='good', data='key', comment='comment') user=user, algorithm="good", data="key", comment="comment"
)
self.sadmin.perform_delete_selected( self.sadmin.perform_delete_selected(
Mock(name='request'), SshPublicKey.objects.filter(id=key.id)) Mock(name="request"), SshPublicKey.objects.filter(id=key.id)
)
self.assertFalse(SshPublicKey.objects.filter(id=key.id).exists()) self.assertFalse(SshPublicKey.objects.filter(id=key.id).exists())
def test_get_actions(self): def test_get_actions(self):
requestmock = MagicMock(name='request') requestmock = MagicMock(name="request")
self.assertNotIn( self.assertNotIn("delete_selected", self.sadmin.get_actions(requestmock))
'delete_selected', self.assertIn("perform_delete_selected", self.sadmin.get_actions(requestmock))
self.sadmin.get_actions(requestmock))
self.assertIn(
'perform_delete_selected',
self.sadmin.get_actions(requestmock))

View file

@ -2,15 +2,13 @@
This module provides tests for :py:mod:`osusers.forms`. This module provides tests for :py:mod:`osusers.forms`.
""" """
from __future__ import absolute_import, unicode_literals from unittest.mock import MagicMock, Mock, patch
from mock import MagicMock, Mock, patch
from django import forms from django import forms
from django.core.urlresolvers import reverse
from django.test import TestCase from django.test import TestCase
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.urls import reverse
from passlib.hash import sha512_crypt from passlib.hash import sha512_crypt
@ -34,7 +32,7 @@ class AddSshPublicKeyFormTest(TestCase):
""" """
def _setup_hostingpackage(self): def _setup_hostingpackage(self):
customer = Customer.objects.create_user('test') customer = Customer.objects.create_user("test")
user = User.objects.create_user(customer=customer) user = User.objects.create_user(customer=customer)
self.hostingpackage = Mock(id=42, osuser=user) self.hostingpackage = Mock(id=42, osuser=user)
@ -42,97 +40,92 @@ class AddSshPublicKeyFormTest(TestCase):
instance = MagicMock() instance = MagicMock()
with self.assertRaises(KeyError) as ke: with self.assertRaises(KeyError) as ke:
AddSshPublicKeyForm(instance) AddSshPublicKeyForm(instance)
self.assertEqual(ke.exception.args[0], 'hostingpackage') self.assertEqual(ke.exception.args[0], "hostingpackage")
def test_constructor(self): def test_constructor(self):
self._setup_hostingpackage() self._setup_hostingpackage()
instance = MagicMock() instance = MagicMock()
form = AddSshPublicKeyForm( form = AddSshPublicKeyForm(instance, hostingpackage=self.hostingpackage)
instance, hostingpackage=self.hostingpackage) self.assertTrue(hasattr(form, "osuser"))
self.assertTrue(hasattr(form, 'osuser'))
self.assertEqual(form.osuser, self.hostingpackage.osuser) self.assertEqual(form.osuser, self.hostingpackage.osuser)
self.assertTrue(hasattr(form, 'helper')) self.assertTrue(hasattr(form, "helper"))
self.assertEqual(form.helper.form_action, reverse( self.assertEqual(
'add_ssh_key', kwargs={'package': self.hostingpackage.id})) form.helper.form_action,
self.assertIn('publickeytext', form.fields) reverse("add_ssh_key", kwargs={"package": self.hostingpackage.id}),
self.assertEqual(form.helper.inputs[0].name, 'submit') )
self.assertIn("publickeytext", form.fields)
self.assertEqual(form.helper.inputs[0].name, "submit")
@patch('osusers.forms.SshPublicKey.objects.parse_keytext') @patch("osusers.forms.SshPublicKey.objects.parse_key_text")
def test_clean_publickeytext_invalid(self, parse_keytext): def test_clean_publickeytext_invalid(self, parse_key_text):
self._setup_hostingpackage() self._setup_hostingpackage()
instance = MagicMock() instance = MagicMock()
form = AddSshPublicKeyForm( form = AddSshPublicKeyForm(instance, hostingpackage=self.hostingpackage)
instance, hostingpackage=self.hostingpackage) form.cleaned_data = {"publickeytext": "a bad key"}
form.cleaned_data = {'publickeytext': 'a bad key'} parse_key_text.side_effect = ValueError
parse_keytext.side_effect = ValueError
with self.assertRaises(forms.ValidationError) as ve: with self.assertRaises(forms.ValidationError) as ve:
form.clean_publickeytext() form.clean_publickeytext()
self.assertEqual(ve.exception.message, INVALID_SSH_PUBLIC_KEY) self.assertEqual(ve.exception.message, INVALID_SSH_PUBLIC_KEY)
@patch('osusers.forms.SshPublicKey.objects.parse_keytext') @patch("osusers.forms.SshPublicKey.objects.parse_key_text")
def test_clean_publickeytext_valid(self, parse_keytext): def test_clean_publickeytext_valid(self, _):
self._setup_hostingpackage() self._setup_hostingpackage()
instance = MagicMock() instance = MagicMock()
form = AddSshPublicKeyForm( form = AddSshPublicKeyForm(instance, hostingpackage=self.hostingpackage)
instance, hostingpackage=self.hostingpackage) form.cleaned_data = {"publickeytext": "good key comment"}
form.cleaned_data = {'publickeytext': 'good key comment'}
retval = form.clean_publickeytext() retval = form.clean_publickeytext()
self.assertEqual(retval, 'good key comment') self.assertEqual(retval, "good key comment")
def test_clean_none(self): def test_clean_none(self):
self._setup_hostingpackage() self._setup_hostingpackage()
instance = MagicMock() instance = MagicMock()
form = AddSshPublicKeyForm( form = AddSshPublicKeyForm(instance, hostingpackage=self.hostingpackage)
instance, hostingpackage=self.hostingpackage) form.cleaned_data = {"publickeytext": None}
form.cleaned_data = {'publickeytext': None}
form.clean() form.clean()
self.assertIsNone(form.cleaned_data['publickeytext']) self.assertIsNone(form.cleaned_data["publickeytext"])
@patch('osusers.forms.SshPublicKey.objects.parse_keytext') @patch("osusers.forms.SshPublicKey.objects.parse_key_text")
def test_clean_fresh(self, parse_keytext): def test_clean_fresh(self, parse_key_text):
self._setup_hostingpackage() self._setup_hostingpackage()
instance = MagicMock() instance = MagicMock()
form = AddSshPublicKeyForm( form = AddSshPublicKeyForm(instance, hostingpackage=self.hostingpackage)
instance, hostingpackage=self.hostingpackage) sshpubkey = "good key comment"
sshpubkey = 'good key comment' form.cleaned_data = {"publickeytext": sshpubkey}
form.cleaned_data = {'publickeytext': sshpubkey} parse_key_text.return_value = sshpubkey.split(" ")
parse_keytext.return_value = sshpubkey.split(' ')
form.clean() form.clean()
self.assertEqual( self.assertEqual(form.cleaned_data["publickeytext"], "good key comment")
form.cleaned_data['publickeytext'], 'good key comment')
@patch('osusers.forms.SshPublicKey.objects.parse_keytext') @patch("osusers.forms.SshPublicKey.objects.parse_key_text")
def test_clean_duplicate(self, parse_keytext): def test_clean_duplicate(self, parse_key_text):
self._setup_hostingpackage() self._setup_hostingpackage()
instance = MagicMock() instance = MagicMock()
form = AddSshPublicKeyForm( form = AddSshPublicKeyForm(instance, hostingpackage=self.hostingpackage)
instance, hostingpackage=self.hostingpackage)
SshPublicKey.objects.create( SshPublicKey.objects.create(
user=self.hostingpackage.osuser, algorithm='good', data='key', user=self.hostingpackage.osuser,
comment='comment') algorithm="good",
sshpubkey = 'good key comment' data="key",
form.cleaned_data = {'publickeytext': sshpubkey} comment="comment",
parse_keytext.return_value = sshpubkey.split(' ') )
sshpubkey = "good key comment"
form.cleaned_data = {"publickeytext": sshpubkey}
parse_key_text.return_value = sshpubkey.split(" ")
form.clean() form.clean()
self.assertIn('publickeytext', form.errors) self.assertIn("publickeytext", form.errors)
self.assertIn( self.assertIn(DUPLICATE_SSH_PUBLIC_KEY_FOR_USER, form.errors["publickeytext"])
DUPLICATE_SSH_PUBLIC_KEY_FOR_USER,
form.errors['publickeytext'])
@patch('osusers.admin.SshPublicKey.objects.parse_keytext') @patch("osusers.admin.SshPublicKey.objects.parse_key_text")
def test_save(self, parse_keytext): def test_save(self, parse_key_text):
self._setup_hostingpackage() self._setup_hostingpackage()
instance = MagicMock() instance = MagicMock()
form = AddSshPublicKeyForm( form = AddSshPublicKeyForm(instance, hostingpackage=self.hostingpackage)
instance, hostingpackage=self.hostingpackage) sshpubkey = "good key comment"
sshpubkey = 'good key comment' form.cleaned_data = {"publickeytext": sshpubkey}
form.cleaned_data = {'publickeytext': sshpubkey} parse_key_text.return_value = sshpubkey.split(" ")
parse_keytext.return_value = sshpubkey.split(' ')
retval = form.save() retval = form.save()
self.assertTrue(isinstance(retval, SshPublicKey)) self.assertTrue(isinstance(retval, SshPublicKey))
self.assertEqual(retval.algorithm, 'good') self.assertEqual(retval.algorithm, "good")
self.assertEqual(retval.data, 'key') self.assertEqual(retval.data, "key")
self.assertEqual(retval.comment, 'comment') self.assertEqual(retval.comment, "comment")
class ChangeOsUserPasswordFormTest(TestCase): class ChangeOsUserPasswordFormTest(TestCase):
@ -142,25 +135,27 @@ class ChangeOsUserPasswordFormTest(TestCase):
""" """
def _setup_user(self): def _setup_user(self):
customer = Customer.objects.create_user('test') customer = Customer.objects.create_user("test")
self.user = User.objects.create_user(customer=customer) self.user = User.objects.create_user(customer=customer)
def test_constructor(self): def test_constructor(self):
self._setup_user() self._setup_user()
form = ChangeOsUserPasswordForm(instance=self.user) form = ChangeOsUserPasswordForm(instance=self.user)
self.assertTrue(hasattr(form, 'instance')) self.assertTrue(hasattr(form, "instance"))
self.assertEqual(form.instance, self.user) self.assertEqual(form.instance, self.user)
self.assertTrue(hasattr(form, 'helper')) self.assertTrue(hasattr(form, "helper"))
self.assertEqual(form.helper.form_action, reverse( self.assertEqual(
'set_osuser_password', kwargs={'slug': self.user.username})) form.helper.form_action,
self.assertEqual(form.helper.inputs[0].name, 'submit') reverse("set_osuser_password", kwargs={"slug": self.user.username}),
)
self.assertEqual(form.helper.inputs[0].name, "submit")
def test_save(self): def test_save(self):
self._setup_user() self._setup_user()
form = ChangeOsUserPasswordForm(instance=self.user) form = ChangeOsUserPasswordForm(instance=self.user)
form.cleaned_data = {'password1': 'test'} form.cleaned_data = {"password1": "test"}
user = form.save() user = form.save()
self.assertTrue(sha512_crypt.verify('test', user.shadow.passwd)) self.assertTrue(sha512_crypt.verify("test", user.shadow.passwd))
class EditSshPublicKeyCommentFormTest(TestCase): class EditSshPublicKeyCommentFormTest(TestCase):
@ -170,7 +165,7 @@ class EditSshPublicKeyCommentFormTest(TestCase):
""" """
def _setup_hostingpackage(self): def _setup_hostingpackage(self):
customer = Customer.objects.create_user('test') customer = Customer.objects.create_user("test")
user = User.objects.create_user(customer=customer) user = User.objects.create_user(customer=customer)
self.hostingpackage = Mock(id=42, osuser=user) self.hostingpackage = Mock(id=42, osuser=user)
@ -178,18 +173,23 @@ class EditSshPublicKeyCommentFormTest(TestCase):
instance = MagicMock() instance = MagicMock()
with self.assertRaises(KeyError) as ke: with self.assertRaises(KeyError) as ke:
EditSshPublicKeyCommentForm(instance) EditSshPublicKeyCommentForm(instance)
self.assertEqual(ke.exception.args[0], 'hostingpackage') self.assertEqual(ke.exception.args[0], "hostingpackage")
def test_constructor(self): def test_constructor(self):
self._setup_hostingpackage() self._setup_hostingpackage()
instance = MagicMock(id=1) instance = MagicMock(id=1)
form = EditSshPublicKeyCommentForm( form = EditSshPublicKeyCommentForm(
instance=instance, hostingpackage=self.hostingpackage) instance=instance, hostingpackage=self.hostingpackage
self.assertTrue(hasattr(form, 'osuser')) )
self.assertTrue(hasattr(form, "osuser"))
self.assertEqual(form.osuser, self.hostingpackage.osuser) self.assertEqual(form.osuser, self.hostingpackage.osuser)
self.assertIn('comment', form.fields) self.assertIn("comment", form.fields)
self.assertTrue(hasattr(form, 'helper')) self.assertTrue(hasattr(form, "helper"))
self.assertEqual(form.helper.form_action, reverse( self.assertEqual(
'edit_ssh_key_comment', form.helper.form_action,
kwargs={'package': self.hostingpackage.id, 'pk': instance.id})) reverse(
self.assertEqual(form.helper.inputs[0].name, 'submit') "edit_ssh_key_comment",
kwargs={"package": self.hostingpackage.id, "pk": instance.id},
),
)
self.assertEqual(form.helper.inputs[0].name, "submit")

View file

@ -1,19 +1,17 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import date from datetime import date
from django.conf import settings from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.test import TestCase from django.test import TestCase
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils import timezone from django.utils import timezone
from django.contrib.auth import get_user_model
from passlib.hash import sha512_crypt from passlib.hash import sha512_crypt
from osusers.models import ( from osusers.models import (
CANNOT_USE_PRIMARY_GROUP_AS_ADDITIONAL,
AdditionalGroup, AdditionalGroup,
CANNOT_USE_PRIMARY_GROUP_AS_ADDITIONAL,
Group, Group,
Shadow, Shadow,
SshPublicKey, SshPublicKey,
@ -21,7 +19,6 @@ from osusers.models import (
) )
from taskresults.models import TaskResult from taskresults.models import TaskResult
EXAMPLE_KEY_1_RFC4716 = """---- BEGIN SSH2 PUBLIC KEY ---- EXAMPLE_KEY_1_RFC4716 = """---- BEGIN SSH2 PUBLIC KEY ----
Comment: "1024-bit RSA, converted from OpenSSH by me@example.com" Comment: "1024-bit RSA, converted from OpenSSH by me@example.com"
x-command: /home/me/bin/lock-in-guest.sh x-command: /home/me/bin/lock-in-guest.sh
@ -57,12 +54,14 @@ n24VYtYtsMu74qXviYjziVucWKjjKEb11juqnF0GDlB3VVmxHLmxnAz643WK42Z7dLM5
sY29ouezv4Xz2PuMch5VGPP+CDqzCM4loWgV sY29ouezv4Xz2PuMch5VGPP+CDqzCM4loWgV
---- END SSH2 PUBLIC KEY ----""" ---- END SSH2 PUBLIC KEY ----"""
EXAMPLE_KEY_4_OPENSSH = "".join(( EXAMPLE_KEY_4_OPENSSH = "".join(
(
"ssh-rsa ", "ssh-rsa ",
"AAAAB3NzaC1yc2EAAAABIwAAAIEA1on8gxCGJJWSRT4uOrR13mUaUk0hRf4RzxSZ1zRb", "AAAAB3NzaC1yc2EAAAABIwAAAIEA1on8gxCGJJWSRT4uOrR13mUaUk0hRf4RzxSZ1zRb",
"YYFw8pfGesIFoEuVth4HKyF8k1y4mRUnYHP1XNMNMJl1JcEArC2asV8sHf6zSPVffozZ", "YYFw8pfGesIFoEuVth4HKyF8k1y4mRUnYHP1XNMNMJl1JcEArC2asV8sHf6zSPVffozZ",
"5TT4SfsUu/iKy9lUcCfXzwre4WWZSXXcPff+EHtWshahu3WzBdnGxm5Xoi89zcE=" "5TT4SfsUu/iKy9lUcCfXzwre4WWZSXXcPff+EHtWshahu3WzBdnGxm5Xoi89zcE=",
)) )
)
EXAMPLE_KEY_5_RFC4716_MULTILINE = """---- BEGIN SSH2 PUBLIC KEY ---- EXAMPLE_KEY_5_RFC4716_MULTILINE = """---- BEGIN SSH2 PUBLIC KEY ----
Comment: DSA Public Key \\ Comment: DSA Public Key \\
@ -99,10 +98,7 @@ YYFw8pfGesIFoEuVth4HKyF8k1y4mRUnYHP1XNMNMJl1JcEArC2asV8sHf6zSPVffozZ
5TT4SfsUu/iKy9lUcCfXzwre4WWZSXXcPff+EHtWshahu3WzBdnGxm5Xoi89zcE= 5TT4SfsUu/iKy9lUcCfXzwre4WWZSXXcPff+EHtWshahu3WzBdnGxm5Xoi89zcE=
---- END SSH2 PUBLIC KEY ----""" ---- END SSH2 PUBLIC KEY ----"""
EXAMPLE_KEY_8_OPENSSH_BROKEN = "".join(( EXAMPLE_KEY_8_OPENSSH_BROKEN = "".join(("ssh-rsa ", "AschrÖdderöd"))
"ssh-rsa ",
"AschrÖdderöd"
))
EXAMPLE_KEY_9_RFC4716_ONLY_HEADER = "---- BEGIN SSH2 PUBLIC KEY ----" EXAMPLE_KEY_9_RFC4716_ONLY_HEADER = "---- BEGIN SSH2 PUBLIC KEY ----"
@ -110,9 +106,7 @@ Customer = get_user_model()
@override_settings( @override_settings(
CELERY_ALWAYS_EAGER=True, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
CELERY_CACHE_BACKEND='memory',
BROKER_BACKEND='memory'
) )
class TestCaseWithCeleryTasks(TestCase): class TestCaseWithCeleryTasks(TestCase):
pass pass
@ -120,38 +114,44 @@ class TestCaseWithCeleryTasks(TestCase):
class AdditionalGroupTest(TestCaseWithCeleryTasks): class AdditionalGroupTest(TestCaseWithCeleryTasks):
def setUp(self): def setUp(self):
customer = Customer.objects.create(username='test') customer = Customer.objects.create(username="test")
self.group1 = Group.objects.create(groupname='test1', gid=1000) self.group1 = Group.objects.create(groupname="test1", gid=1000)
self.user = User.objects.create( self.user = User.objects.create(
customer=customer, username='test', uid=1000, group=self.group1, customer=customer,
homedir='/home/test', shell='/bin/bash') username="test",
uid=1000,
group=self.group1,
homedir="/home/test",
shell="/bin/bash",
)
def test_clean_primary_group(self): def test_clean_primary_group(self):
testsubj = AdditionalGroup(user=self.user, group=self.group1) testsubj = AdditionalGroup(user=self.user, group=self.group1)
with self.assertRaises(ValidationError) as cm: with self.assertRaises(ValidationError) as cm:
testsubj.clean() testsubj.clean()
self.assertEqual( self.assertEqual(cm.exception.message, CANNOT_USE_PRIMARY_GROUP_AS_ADDITIONAL)
cm.exception.message, CANNOT_USE_PRIMARY_GROUP_AS_ADDITIONAL)
def test_clean_other_group(self): def test_clean_other_group(self):
group2 = Group.objects.create(groupname='test2', gid=1001) group2 = Group.objects.create(groupname="test2", gid=1001)
testsubj = AdditionalGroup(user=self.user, group=group2) testsubj = AdditionalGroup(user=self.user, group=group2)
testsubj.clean() testsubj.clean()
def test_save(self): def test_save(self):
group2 = Group.objects.create(groupname='test2', gid=1001) group2 = Group.objects.create(groupname="test2", gid=1001)
addgroup = AdditionalGroup(user=self.user, group=group2) addgroup = AdditionalGroup(user=self.user, group=group2)
addgroup.save() addgroup.save()
taskres = TaskResult.objects.all() taskres = TaskResult.objects.all()
self.assertTrue(len(taskres), 4) self.assertTrue(len(taskres), 4)
creators = [r.creator for r in taskres] creators = [r.creator for r in taskres]
for tcount, tcreator in [ for tcount, tcreator in [
(2, 'handle_group_created'), (1, 'handle_user_created'), (2, "handle_group_created"),
(1, 'handle_user_added_to_group')]: (1, "handle_user_created"),
(1, "handle_user_added_to_group"),
]:
self.assertEqual(creators.count(tcreator), tcount) self.assertEqual(creators.count(tcreator), tcount)
def test_save_again(self): def test_save_again(self):
group2 = Group.objects.create(groupname='test2', gid=1001) group2 = Group.objects.create(groupname="test2", gid=1001)
TaskResult.objects.all().delete() TaskResult.objects.all().delete()
addgroup = AdditionalGroup(user=self.user, group=group2) addgroup = AdditionalGroup(user=self.user, group=group2)
addgroup.save() addgroup.save()
@ -161,15 +161,18 @@ class AdditionalGroupTest(TestCaseWithCeleryTasks):
self.assertEqual(len(taskres), 0) self.assertEqual(len(taskres), 0)
def test_delete(self): def test_delete(self):
group2 = Group.objects.create(groupname='test2', gid=1001) group2 = Group.objects.create(groupname="test2", gid=1001)
# noinspection PyUnresolvedReferences
addgroup = AdditionalGroup.objects.create(user=self.user, group=group2) addgroup = AdditionalGroup.objects.create(user=self.user, group=group2)
addgroup.delete() addgroup.delete()
# noinspection PyUnresolvedReferences
self.assertEqual(len(AdditionalGroup.objects.all()), 0) self.assertEqual(len(AdditionalGroup.objects.all()), 0)
def test___str__(self): def test___str__(self):
group2 = Group.objects.create(groupname='test2', gid=1001) group2 = Group.objects.create(groupname="test2", gid=1001)
# noinspection PyUnresolvedReferences
addgroup = AdditionalGroup.objects.create(user=self.user, group=group2) addgroup = AdditionalGroup.objects.create(user=self.user, group=group2)
self.assertEqual(str(addgroup), 'test (1000) in test2 (1001)') self.assertEqual(str(addgroup), "test (1000) in test2 (1001)")
@override_settings(OSUSER_MINGID=10000) @override_settings(OSUSER_MINGID=10000)
@ -178,56 +181,61 @@ class GroupManagerTest(TestCaseWithCeleryTasks):
self.assertEqual(Group.objects.get_next_gid(), 10000) self.assertEqual(Group.objects.get_next_gid(), 10000)
def test_get_next_gid_second(self): def test_get_next_gid_second(self):
Group.objects.create(gid=10010, groupname='test') Group.objects.create(gid=10010, groupname="test")
self.assertEqual(Group.objects.get_next_gid(), 10011) self.assertEqual(Group.objects.get_next_gid(), 10011)
class GroupTest(TestCaseWithCeleryTasks): class GroupTest(TestCaseWithCeleryTasks):
def test___str__(self): def test___str__(self):
group = Group.objects.create(gid=10000, groupname='test') group = Group.objects.create(gid=10000, groupname="test")
self.assertEqual(str(group), 'test (10000)') self.assertEqual(str(group), "test (10000)")
def test_save(self): def test_save(self):
group = Group(gid=10000, groupname='test') group = Group(gid=10000, groupname="test")
self.assertIs(group.save(), group) self.assertIs(group.save(), group)
taskres = TaskResult.objects.all() taskres = TaskResult.objects.all()
self.assertTrue(len(taskres), 1) self.assertTrue(len(taskres), 1)
creators = [r.creator for r in taskres] creators = [r.creator for r in taskres]
for tcount, tcreator in [ for tcount, tcreator in [(1, "handle_group_created")]:
(1, 'handle_group_created')]:
self.assertEqual(creators.count(tcreator), tcount) self.assertEqual(creators.count(tcreator), tcount)
def test_save_again(self): def test_save_again(self):
group = Group.objects.create(gid=10000, groupname='test') group = Group.objects.create(gid=10000, groupname="test")
taskres = TaskResult.objects.all().delete() TaskResult.objects.all().delete()
group.save() group.save()
taskres = TaskResult.objects.all() taskres = TaskResult.objects.all()
self.assertEqual(len(taskres), 0) self.assertEqual(len(taskres), 0)
def test_delete(self): def test_delete(self):
group = Group.objects.create(gid=10000, groupname='test') group = Group.objects.create(gid=10000, groupname="test")
self.assertEqual(len(Group.objects.all()), 1) self.assertEqual(len(Group.objects.all()), 1)
group.delete() group.delete()
self.assertEqual(len(Group.objects.all()), 0) self.assertEqual(len(Group.objects.all()), 0)
self.assertEqual(len(TaskResult.objects.all()), 2) self.assertEqual(len(TaskResult.objects.all()), 2)
tr = TaskResult.objects.first() tr = TaskResult.objects.first()
self.assertEqual(tr.creator, 'handle_group_created') self.assertEqual(tr.creator, "handle_group_created")
class ShadowManagerTest(TestCaseWithCeleryTasks): class ShadowManagerTest(TestCaseWithCeleryTasks):
def setUp(self): def setUp(self):
self.customer = Customer.objects.create(username='test') self.customer = Customer.objects.create(username="test")
super(ShadowManagerTest, self).setUp() super(ShadowManagerTest, self).setUp()
def test_create_shadow(self): def test_create_shadow(self):
user = User( group = Group.objects.create(gid=1000, groupname="test")
customer=self.customer, username='test', uid=1000, user = User.objects.create(
group=Group(gid=1000, groupname='test'), homedir='/home/test', customer=self.customer,
shell='/bin/fooshell') username="test",
shadow = Shadow.objects.create_shadow(user, 'test') uid=1000,
self.assertTrue(sha512_crypt.verify('test', shadow.passwd)) group=group,
self.assertEqual(shadow.changedays, homedir="/home/test",
(timezone.now().date() - date(1970, 1, 1)).days) shell="/bin/fooshell",
)
shadow = Shadow.objects.create_shadow(user, "test")
self.assertTrue(sha512_crypt.verify("test", shadow.passwd))
self.assertEqual(
shadow.changedays, (timezone.now().date() - date(1970, 1, 1)).days
)
self.assertEqual(shadow.user, user) self.assertEqual(shadow.user, user)
self.assertEqual(shadow.minage, 0) self.assertEqual(shadow.minage, 0)
self.assertIsNone(shadow.maxage) self.assertIsNone(shadow.maxage)
@ -238,39 +246,50 @@ class ShadowManagerTest(TestCaseWithCeleryTasks):
class ShadowTest(TestCaseWithCeleryTasks): class ShadowTest(TestCaseWithCeleryTasks):
def setUp(self): def setUp(self):
self.customer = Customer.objects.create(username='test') self.customer = Customer.objects.create(username="test")
super(ShadowTest, self).setUp() super(ShadowTest, self).setUp()
def test___str__(self): def test___str__(self):
group = Group.objects.create( group = Group.objects.create(groupname="test", gid=1000)
groupname='test', gid=1000)
user = User.objects.create( user = User.objects.create(
customer=self.customer, username='test', uid=1000, group=group, customer=self.customer,
homedir='/home/test', shell='/bin/bash') username="test",
uid=1000,
group=group,
homedir="/home/test",
shell="/bin/bash",
)
shadow = Shadow(user=user) shadow = Shadow(user=user)
self.assertEqual(str(shadow), 'for user test (1000)') self.assertEqual(str(shadow), "for user test (1000)")
def test_set_password(self): def test_set_password(self):
group = Group.objects.create( group = Group.objects.create(groupname="test", gid=1000)
groupname='test', gid=1000)
user = User.objects.create( user = User.objects.create(
customer=self.customer, username='test', uid=1000, group=group, customer=self.customer,
homedir='/home/test', shell='/bin/bash') username="test",
uid=1000,
group=group,
homedir="/home/test",
shell="/bin/bash",
)
shadow = Shadow(user=user) shadow = Shadow(user=user)
shadow.set_password('test') shadow.set_password("test")
self.assertTrue(sha512_crypt.verify('test', shadow.passwd)) self.assertTrue(sha512_crypt.verify("test", shadow.passwd))
@override_settings( @override_settings(
OSUSER_MINUID=10000, OSUSER_MINGID=10000, OSUSER_USERNAME_PREFIX='test', OSUSER_MINUID=10000,
OSUSER_HOME_BASEPATH='/home', OSUSER_DEFAULT_SHELL='/bin/fooshell' OSUSER_MINGID=10000,
OSUSER_USERNAME_PREFIX="test",
OSUSER_HOME_BASEPATH="/home",
OSUSER_DEFAULT_SHELL="/bin/fooshell",
) )
class UserManagerTest(TestCaseWithCeleryTasks): class UserManagerTest(TestCaseWithCeleryTasks):
def _create_group(self): def _create_group(self):
return Group.objects.create(gid=10000, groupname='foo') return Group.objects.create(gid=10000, groupname="foo")
def setUp(self): def setUp(self):
self.customer = Customer.objects.create(username='test') self.customer = Customer.objects.create(username="test")
super(UserManagerTest, self).setUp() super(UserManagerTest, self).setUp()
def test_get_next_uid_first(self): def test_get_next_uid_first(self):
@ -278,40 +297,58 @@ class UserManagerTest(TestCaseWithCeleryTasks):
def test_get_next_uid_second(self): def test_get_next_uid_second(self):
User.objects.create( User.objects.create(
customer=self.customer, uid=10010, username='foo', customer=self.customer,
group=self._create_group(), homedir='/home/foo', uid=10010,
shell='/bin/fooshell') username="foo",
group=self._create_group(),
homedir="/home/foo",
shell="/bin/fooshell",
)
self.assertEqual(User.objects.get_next_uid(), 10011) self.assertEqual(User.objects.get_next_uid(), 10011)
def test_get_next_username_first(self): def test_get_next_username_first(self):
self.assertEqual(User.objects.get_next_username(), 'test01') self.assertEqual(User.objects.get_next_username(), "test01")
def test_get_next_username_second(self): def test_get_next_username_second(self):
User.objects.create( User.objects.create(
customer=self.customer, uid=10000, username='test01', customer=self.customer,
group=self._create_group(), homedir='/home/foo', uid=10000,
shell='/bin/fooshell') username="test01",
self.assertEqual(User.objects.get_next_username(), 'test02') group=self._create_group(),
homedir="/home/foo",
shell="/bin/fooshell",
)
self.assertEqual(User.objects.get_next_username(), "test02")
def test_get_next_username_gaps(self): def test_get_next_username_gaps(self):
group = self._create_group() group = self._create_group()
User.objects.create( User.objects.create(
customer=self.customer, uid=10000, username='test01', group=group, customer=self.customer,
homedir='/home/foo', shell='/bin/fooshell') uid=10000,
username="test01",
group=group,
homedir="/home/foo",
shell="/bin/fooshell",
)
User.objects.create( User.objects.create(
customer=self.customer, uid=10002, username='test03', group=group, customer=self.customer,
homedir='/home/foo', shell='/bin/fooshell') uid=10002,
self.assertEqual(User.objects.get_next_username(), 'test02') username="test03",
group=group,
homedir="/home/foo",
shell="/bin/fooshell",
)
self.assertEqual(User.objects.get_next_username(), "test02")
def test_create_user_first(self): def test_create_user_first(self):
user = User.objects.create_user(customer=self.customer) user = User.objects.create_user(customer=self.customer)
self.assertIsInstance(user, User) self.assertIsInstance(user, User)
self.assertEqual(user.uid, 10000) self.assertEqual(user.uid, 10000)
self.assertEqual(user.group.gid, 10000) self.assertEqual(user.group.gid, 10000)
self.assertEqual(user.group.groupname, 'test01') self.assertEqual(user.group.groupname, "test01")
self.assertEqual(user.username, 'test01') self.assertEqual(user.username, "test01")
self.assertEqual(user.homedir, '/home/test01') self.assertEqual(user.homedir, "/home/test01")
self.assertEqual(user.shell, '/bin/fooshell') self.assertEqual(user.shell, "/bin/fooshell")
self.assertIsNotNone(user.shadow) self.assertIsNotNone(user.shadow)
def test_create_user_tasks(self): def test_create_user_tasks(self):
@ -320,8 +357,10 @@ class UserManagerTest(TestCaseWithCeleryTasks):
self.assertEqual(len(taskres), 3) self.assertEqual(len(taskres), 3)
creators = [r.creator for r in taskres] creators = [r.creator for r in taskres]
for creator in [ for creator in [
'handle_group_created', 'handle_user_created', "handle_group_created",
'handle_user_password_set']: "handle_user_created",
"handle_user_password_set",
]:
self.assertIn(creator, creators) self.assertIn(creator, creators)
def test_create_user_second(self): def test_create_user_second(self):
@ -330,36 +369,34 @@ class UserManagerTest(TestCaseWithCeleryTasks):
self.assertIsInstance(user, User) self.assertIsInstance(user, User)
self.assertEqual(user.uid, 10001) self.assertEqual(user.uid, 10001)
self.assertEqual(user.group.gid, 10001) self.assertEqual(user.group.gid, 10001)
self.assertEqual(user.group.groupname, 'test02') self.assertEqual(user.group.groupname, "test02")
self.assertEqual(user.username, 'test02') self.assertEqual(user.username, "test02")
self.assertEqual(user.homedir, '/home/test02') self.assertEqual(user.homedir, "/home/test02")
self.assertEqual(user.shell, '/bin/fooshell') self.assertEqual(user.shell, "/bin/fooshell")
self.assertIsNotNone(user.shadow) self.assertIsNotNone(user.shadow)
self.assertEqual(len(User.objects.all()), 2) self.assertEqual(len(User.objects.all()), 2)
def test_create_user_known_password(self): def test_create_user_known_password(self):
user = User.objects.create_user( user = User.objects.create_user(customer=self.customer, password="foobar")
customer=self.customer, password='foobar')
self.assertIsInstance(user, User) self.assertIsInstance(user, User)
self.assertEqual(user.uid, 10000) self.assertEqual(user.uid, 10000)
self.assertEqual(user.group.gid, 10000) self.assertEqual(user.group.gid, 10000)
self.assertEqual(user.group.groupname, 'test01') self.assertEqual(user.group.groupname, "test01")
self.assertEqual(user.username, 'test01') self.assertEqual(user.username, "test01")
self.assertEqual(user.homedir, '/home/test01') self.assertEqual(user.homedir, "/home/test01")
self.assertEqual(user.shell, '/bin/fooshell') self.assertEqual(user.shell, "/bin/fooshell")
self.assertIsNotNone(user.shadow) self.assertIsNotNone(user.shadow)
self.assertTrue(sha512_crypt.verify('foobar', user.shadow.passwd)) self.assertTrue(sha512_crypt.verify("foobar", user.shadow.passwd))
def test_create_user_predefined_username(self): def test_create_user_predefined_username(self):
user = User.objects.create_user( user = User.objects.create_user(customer=self.customer, username="tester")
customer=self.customer, username='tester')
self.assertIsInstance(user, User) self.assertIsInstance(user, User)
self.assertEqual(user.uid, 10000) self.assertEqual(user.uid, 10000)
self.assertEqual(user.group.gid, 10000) self.assertEqual(user.group.gid, 10000)
self.assertEqual(user.group.groupname, 'tester') self.assertEqual(user.group.groupname, "tester")
self.assertEqual(user.username, 'tester') self.assertEqual(user.username, "tester")
self.assertEqual(user.homedir, '/home/tester') self.assertEqual(user.homedir, "/home/tester")
self.assertEqual(user.shell, '/bin/fooshell') self.assertEqual(user.shell, "/bin/fooshell")
self.assertIsNotNone(user.shadow) self.assertIsNotNone(user.shadow)
def test_create_user_commit(self): def test_create_user_commit(self):
@ -367,31 +404,34 @@ class UserManagerTest(TestCaseWithCeleryTasks):
self.assertIsInstance(user, User) self.assertIsInstance(user, User)
self.assertEqual(user.uid, 10000) self.assertEqual(user.uid, 10000)
self.assertEqual(user.group.gid, 10000) self.assertEqual(user.group.gid, 10000)
self.assertEqual(user.group.groupname, 'test01') self.assertEqual(user.group.groupname, "test01")
self.assertEqual(user.username, 'test01') self.assertEqual(user.username, "test01")
self.assertEqual(user.homedir, '/home/test01') self.assertEqual(user.homedir, "/home/test01")
self.assertEqual(user.shell, '/bin/fooshell') self.assertEqual(user.shell, "/bin/fooshell")
self.assertIsNotNone(user.shadow) self.assertIsNotNone(user.shadow)
@override_settings( @override_settings(
OSUSER_MINUID=10000, OSUSER_MINGID=10000, OSUSER_USERNAME_PREFIX='test', OSUSER_MINUID=10000,
OSUSER_HOME_BASEPATH='/home', OSUSER_DEFAULT_SHELL='/bin/fooshell' OSUSER_MINGID=10000,
OSUSER_USERNAME_PREFIX="test",
OSUSER_HOME_BASEPATH="/home",
OSUSER_DEFAULT_SHELL="/bin/fooshell",
) )
class UserTest(TestCaseWithCeleryTasks): class UserTest(TestCaseWithCeleryTasks):
def setUp(self): def setUp(self):
self.customer = Customer.objects.create_user('test') self.customer = Customer.objects.create_user("test")
super(UserTest, self).setUp() super(UserTest, self).setUp()
def test___str__(self): def test___str__(self):
user = User.objects.create_user(self.customer) user = User.objects.create_user(self.customer)
self.assertEqual(str(user), 'test01 (10000)') self.assertEqual(str(user), "test01 (10000)")
def test_set_password(self): def test_set_password(self):
user = User.objects.create_user(self.customer) user = User.objects.create_user(self.customer)
self.assertFalse(sha512_crypt.verify('test', user.shadow.passwd)) self.assertFalse(sha512_crypt.verify("test", user.shadow.passwd))
user.set_password('test') user.set_password("test")
self.assertTrue(sha512_crypt.verify('test', user.shadow.passwd)) self.assertTrue(sha512_crypt.verify("test", user.shadow.passwd))
def test_save(self): def test_save(self):
user = User.objects.create_user(self.customer) user = User.objects.create_user(self.customer)
@ -400,8 +440,10 @@ class UserTest(TestCaseWithCeleryTasks):
self.assertEqual(len(taskres), 3) self.assertEqual(len(taskres), 3)
creators = [r.creator for r in taskres] creators = [r.creator for r in taskres]
for task in [ for task in [
'handle_group_created', 'handle_user_created', "handle_group_created",
'handle_user_password_set']: "handle_user_created",
"handle_user_password_set",
]:
self.assertIn(task, creators) self.assertIn(task, creators)
def test_delete_only_user(self): def test_delete_only_user(self):
@ -411,30 +453,38 @@ class UserTest(TestCaseWithCeleryTasks):
self.assertEqual(len(taskres), 6) self.assertEqual(len(taskres), 6)
creators = [r.creator for r in taskres] creators = [r.creator for r in taskres]
for task in [ for task in [
'handle_group_created', 'handle_user_created', "handle_group_created",
'handle_user_password_set', 'handle_user_deleted', "handle_user_created",
'handle_group_deleted', 'handle_user_deleted']: "handle_user_password_set",
"handle_user_deleted",
"handle_group_deleted",
"handle_user_deleted",
]:
self.assertIn(task, creators) self.assertIn(task, creators)
self.assertEqual(len(User.objects.all()), 0) self.assertEqual(len(User.objects.all()), 0)
def test_delete_additional_groups(self): def test_delete_additional_groups(self):
group1 = Group.objects.create(gid=2000, groupname='group1') group1 = Group.objects.create(gid=2000, groupname="group1")
group2 = Group.objects.create(gid=2001, groupname='group2') group2 = Group.objects.create(gid=2001, groupname="group2")
user = User.objects.create_user(self.customer) user = User.objects.create_user(self.customer)
for group in [group1, group2]: for group in [group1, group2]:
# noinspection PyUnresolvedReferences
user.additionalgroup_set.add( user.additionalgroup_set.add(
AdditionalGroup.objects.create(user=user, group=group)) AdditionalGroup.objects.create(user=user, group=group)
)
TaskResult.objects.all().delete() TaskResult.objects.all().delete()
user.delete() user.delete()
taskres = TaskResult.objects.all() taskres = TaskResult.objects.all()
self.assertEqual(len(taskres), 5) self.assertEqual(len(taskres), 5)
creators = [t.creator for t in taskres] creators = [t.creator for t in taskres]
for tcount, tcreator in [ for tcount, tcreator in [
(2, 'handle_user_removed_from_group'), (2, "handle_user_removed_from_group"),
(2, 'handle_user_deleted'), (2, "handle_user_deleted"),
(1, 'handle_group_deleted')]: (1, "handle_group_deleted"),
]:
self.assertEqual(creators.count(tcreator), tcount) self.assertEqual(creators.count(tcreator), tcount)
self.assertEqual(len(User.objects.all()), 0) self.assertEqual(len(User.objects.all()), 0)
# noinspection PyUnresolvedReferences
self.assertEqual(len(AdditionalGroup.objects.all()), 0) self.assertEqual(len(AdditionalGroup.objects.all()), 0)
def test_is_sftp_user(self): def test_is_sftp_user(self):
@ -442,138 +492,140 @@ class UserTest(TestCaseWithCeleryTasks):
self.assertFalse(user.is_sftp_user()) self.assertFalse(user.is_sftp_user())
sftp_group = Group.objects.create( sftp_group = Group.objects.create(
gid=2000, groupname=settings.OSUSER_SFTP_GROUP) gid=2000, groupname=settings.OSUSER_SFTP_GROUP
)
# noinspection PyUnresolvedReferences
user.additionalgroup_set.add( user.additionalgroup_set.add(
AdditionalGroup.objects.create(user=user, group=sftp_group)) AdditionalGroup.objects.create(user=user, group=sftp_group)
)
self.assertTrue(user.is_sftp_user()) self.assertTrue(user.is_sftp_user())
class SshPublicKeyManagerTest(TestCaseWithCeleryTasks): class SshPublicKeyManagerTest(TestCaseWithCeleryTasks):
def test_parse_keytext_rfc4716_1(self): def test_parse_keytext_rfc4716_1(self):
res = SshPublicKey.objects.parse_keytext(EXAMPLE_KEY_1_RFC4716) res = SshPublicKey.objects.parse_key_text(EXAMPLE_KEY_1_RFC4716)
self.assertEqual(len(res), 3) self.assertEqual(len(res), 3)
self.assertGreater(len(res[1]), 40) self.assertGreater(len(res[1]), 40)
self.assertEqual(res[0], 'ssh-rsa') self.assertEqual(res[0], "ssh-rsa")
self.assertEqual( self.assertEqual(
res[2], '"1024-bit RSA, converted from OpenSSH by me@example.com"') res[2], '"1024-bit RSA, converted from OpenSSH by me@example.com"'
)
def test_parse_keytext_rfc4716_2(self): def test_parse_keytext_rfc4716_2(self):
res = SshPublicKey.objects.parse_keytext(EXAMPLE_KEY_2_RFC4716) res = SshPublicKey.objects.parse_key_text(EXAMPLE_KEY_2_RFC4716)
self.assertEqual(len(res), 3) self.assertEqual(len(res), 3)
self.assertEqual(res[0], 'ssh-dss') self.assertEqual(res[0], "ssh-dss")
self.assertGreater(len(res[1]), 40) self.assertGreater(len(res[1]), 40)
self.assertEqual( self.assertEqual(
res[2], res[2], "This is my public key for use on servers which I don't like."
"This is my public key for use on servers which I don't like.") )
def test_parse_keytext_rfc4716_3(self): def test_parse_keytext_rfc4716_3(self):
res = SshPublicKey.objects.parse_keytext(EXAMPLE_KEY_3_RFC4716) res = SshPublicKey.objects.parse_key_text(EXAMPLE_KEY_3_RFC4716)
self.assertEqual(len(res), 3) self.assertEqual(len(res), 3)
self.assertEqual(res[0], 'ssh-dss') self.assertEqual(res[0], "ssh-dss")
self.assertGreater(len(res[1]), 40) self.assertGreater(len(res[1]), 40)
self.assertEqual(res[2], "DSA Public Key for use with MyIsp") self.assertEqual(res[2], "DSA Public Key for use with MyIsp")
def test_parse_keytext_openssh(self): def test_parse_keytext_openssh(self):
res = SshPublicKey.objects.parse_keytext(EXAMPLE_KEY_4_OPENSSH) res = SshPublicKey.objects.parse_key_text(EXAMPLE_KEY_4_OPENSSH)
self.assertEquals(len(res), 3) self.assertEquals(len(res), 3)
self.assertEqual(res[0], 'ssh-rsa') self.assertEqual(res[0], "ssh-rsa")
self.assertGreater(len(res[1]), 40) self.assertGreater(len(res[1]), 40)
self.assertEqual(res[2], '') self.assertEqual(res[2], "")
def test_parse_keytext_invalid_multiline(self): def test_parse_keytext_invalid_multiline(self):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
SshPublicKey.objects.parse_keytext("\r\n".join(["xx"]*10)) SshPublicKey.objects.parse_key_text("\r\n".join(["xx"] * 10))
def test_parse_keytext_empty_line(self): def test_parse_keytext_empty_line(self):
res = SshPublicKey.objects.parse_keytext( res = SshPublicKey.objects.parse_key_text(EXAMPLE_KEY_6_RFC4716_EMPTY_LINE)
EXAMPLE_KEY_6_RFC4716_EMPTY_LINE)
self.assertEqual(len(res), 3) self.assertEqual(len(res), 3)
self.assertEqual(res[0], 'ssh-dss') self.assertEqual(res[0], "ssh-dss")
self.assertGreater(len(res[1]), 40) self.assertGreater(len(res[1]), 40)
self.assertEqual(res[2], "DSA Public Key for use with MyIsp") self.assertEqual(res[2], "DSA Public Key for use with MyIsp")
def test_parse_keytext_invalid_empty_rfc4716_header(self): def test_parse_keytext_invalid_empty_rfc4716_header(self):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
SshPublicKey.objects.parse_keytext( SshPublicKey.objects.parse_key_text(EXAMPLE_KEY_9_RFC4716_ONLY_HEADER)
EXAMPLE_KEY_9_RFC4716_ONLY_HEADER)
def test_parse_keytext_no_comment(self): def test_parse_keytext_no_comment(self):
res = SshPublicKey.objects.parse_keytext( res = SshPublicKey.objects.parse_key_text(EXAMPLE_KEY_7_NO_COMMENT)
EXAMPLE_KEY_7_NO_COMMENT)
self.assertEqual(len(res), 3) self.assertEqual(len(res), 3)
self.assertEqual(res[0], 'ssh-rsa') self.assertEqual(res[0], "ssh-rsa")
self.assertGreater(len(res[1]), 40) self.assertGreater(len(res[1]), 40)
self.assertEqual(res[2], '') self.assertEqual(res[2], "")
def test_parse_keytext_multiline_comment(self): def test_parse_keytext_multiline_comment(self):
res = SshPublicKey.objects.parse_keytext( res = SshPublicKey.objects.parse_key_text(EXAMPLE_KEY_5_RFC4716_MULTILINE)
EXAMPLE_KEY_5_RFC4716_MULTILINE)
self.assertEqual(len(res), 3) self.assertEqual(len(res), 3)
self.assertEqual(res[0], 'ssh-dss') self.assertEqual(res[0], "ssh-dss")
self.assertGreater(len(res[1]), 40) self.assertGreater(len(res[1]), 40)
self.assertEqual(res[2], "DSA Public Key for use with MyIsp") self.assertEqual(res[2], "DSA Public Key for use with MyIsp")
def test_parse_keytext_invalid(self): def test_parse_keytext_invalid(self):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
SshPublicKey.objects.parse_keytext('invalid') SshPublicKey.objects.parse_key_text("invalid")
def test_parse_keytext_invalid_openssh(self): def test_parse_keytext_invalid_openssh(self):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
SshPublicKey.objects.parse_keytext(EXAMPLE_KEY_8_OPENSSH_BROKEN) SshPublicKey.objects.parse_key_text(EXAMPLE_KEY_8_OPENSSH_BROKEN)
def test_create_ssh_public_key(self): def test_create_ssh_public_key(self):
customer = Customer.objects.create_user('test') customer = Customer.objects.create_user("test")
user = User.objects.create_user(customer) user = User.objects.create_user(customer)
key = SshPublicKey.objects.create_ssh_public_key( key = SshPublicKey.objects.create_ssh_public_key(user, EXAMPLE_KEY_4_OPENSSH)
user, EXAMPLE_KEY_4_OPENSSH)
self.assertIsInstance(key, SshPublicKey) self.assertIsInstance(key, SshPublicKey)
self.assertEqual(key.user, user) self.assertEqual(key.user, user)
self.assertEqual(key.algorithm, 'ssh-rsa') self.assertEqual(key.algorithm, "ssh-rsa")
self.assertEqual(key.data, EXAMPLE_KEY_4_OPENSSH.split()[1]) self.assertEqual(key.data, EXAMPLE_KEY_4_OPENSSH.split()[1])
self.assertEqual(key.comment, '') self.assertEqual(key.comment, "")
class SshPublicKeyTest(TestCaseWithCeleryTasks): class SshPublicKeyTest(TestCaseWithCeleryTasks):
def setUp(self): def setUp(self):
super(SshPublicKeyTest, self).setUp() super(SshPublicKeyTest, self).setUp()
customer = Customer.objects.create_user('test') customer = Customer.objects.create_user("test")
self.user = User.objects.create_user(customer) self.user = User.objects.create_user(customer)
TaskResult.objects.all().delete() TaskResult.objects.all().delete()
def test__str__rfc4716(self): def test__str__rfc4716(self):
res = SshPublicKey.objects.create_ssh_public_key( res = SshPublicKey.objects.create_ssh_public_key(
self.user, EXAMPLE_KEY_3_RFC4716) self.user, EXAMPLE_KEY_3_RFC4716
)
self.maxDiff = None
self.assertEqual( self.assertEqual(
str(res), 'ssh-dss AAAAB3NzaC1kc3MAAACBAPY8ZOHY2yFSJA6XYC9HRwNHxae' str(res),
'hvx5wOJ0rzZdzoSOXxbETW6ToHv8D1UJ/z+zHo9Fiko5XybZnDIaBDHtblQ+Yp7St' "ssh-dss AAAAB3NzaC1kc3MAAACBAPY8ZOHY2yFSJA6XYC9HRwNHxae"
'xyltHnXF1YLfKD1G4T6JYrdHYI14Om1eg9e4NnCRleaqoZPF3UGfZia6bXrGTQf3g' "hvx5wOJ0rzZdzoSOXxbETW6ToHv8D1UJ/z+zHo9Fiko5XybZnDIaBDHtblQ+Yp7St"
'Jq2e7Yisk/gF+1VAAAAFQDb8D5cvwHWTZDPfX0D2s9Rd7NBvQAAAIEAlN92+Bb7D4' "xyltHnXF1YLfKD1G4T6JYrdHYI14Om1eg9e4NnCRleaqoZPF3UGfZia6bXrGTQf3g"
'KLYk3IwRbXblwXdkPggA4pfdtW9vGfJ0/RHd+NjB4eo1D+0dix6tXwYGN7PKS5R/F' "Jq2e7Yisk/gF+1VAAAAFQDb8D5cvwHWTZDPfX0D2s9Rd7NBvQAAAIEAlN92+Bb7D4"
'XPNwxHPapcj9uL1Jn2AWQ2dsknf+i/FAAvioUPkmdMc0zuWoSOEsSNhVDtX3WdvVc' "KLYk3IwRbXblwXdkPggA4pfdtW9vGfJ0/RHd+NjB4eo1D+0dix6tXwYGN7PKS5R/F"
'GcBq9cetzrtOKWOocJmJ80qadxTRHtUAAACBAN7CY+KKv1gHpRzFwdQm7HK9bb1LA' "XPNwxHPapcj9uL1Jn2AWQ2dsknf+i/FAAvioUPkmdMc0zuWoSOEsSNhVDtX3WdvVc"
'o2KwaoXnadFgeptNBQeSXG1vO+JsvphVMBJc9HSn24VYtYtsMu74qXviYjziVucWK' "GcBq9cetzrtOKWOocJmJ80qadxTRHtUAAACBAN7CY+KKv1gHpRzFwdQm7HK9bb1LA"
'jjKEb11juqnF0GDlB3VVmxHLmxnAz643WK42Z7dLM5sY29ouezv4Xz2PuMch5VGPP' "o2KwaoXnadFgeptNBQeSXG1vO+JsvphVMBJc9HSn24VYtYtsMu74qXviYjziVucWK"
'+CDqzCM4loWgV DSA Public Key for use with MyIsp') "jjKEb11juqnF0GDlB3VVmxHLmxnAz643WK42Z7dLM5sY29ouezv4Xz2PuMch5VGPP"
"+CDqzCM4loWgV DSA Public Key for use with MyIsp",
)
def test__str__openssh(self): def test__str__openssh(self):
res = SshPublicKey.objects.create_ssh_public_key( res = SshPublicKey.objects.create_ssh_public_key(
self.user, EXAMPLE_KEY_4_OPENSSH) self.user, EXAMPLE_KEY_4_OPENSSH
)
self.assertEqual(str(res), EXAMPLE_KEY_4_OPENSSH) self.assertEqual(str(res), EXAMPLE_KEY_4_OPENSSH)
def test_call_tasks_on_save(self): def test_call_tasks_on_save(self):
SshPublicKey.objects.create_ssh_public_key( SshPublicKey.objects.create_ssh_public_key(self.user, EXAMPLE_KEY_4_OPENSSH)
self.user, EXAMPLE_KEY_4_OPENSSH)
taskresults = TaskResult.objects.all() taskresults = TaskResult.objects.all()
self.assertEqual(len(taskresults), 1) self.assertEqual(len(taskresults), 1)
self.assertEqual( self.assertEqual(taskresults[0].creator, "handle_ssh_keys_changed")
taskresults[0].creator, 'handle_ssh_keys_changed')
def test_call_tasks_on_delete(self): def test_call_tasks_on_delete(self):
key = SshPublicKey.objects.create_ssh_public_key( key = SshPublicKey.objects.create_ssh_public_key(
self.user, EXAMPLE_KEY_4_OPENSSH) self.user, EXAMPLE_KEY_4_OPENSSH
)
TaskResult.objects.all().delete() TaskResult.objects.all().delete()
key.delete() key.delete()
taskresults = TaskResult.objects.all() taskresults = TaskResult.objects.all()
self.assertEqual(len(taskresults), 1) self.assertEqual(len(taskresults), 1)
self.assertEqual( self.assertEqual(taskresults[0].creator, "handle_ssh_keys_changed")
taskresults[0].creator, 'handle_ssh_keys_changed')

View file

@ -2,66 +2,59 @@
This module provides tests for :py:mod:`osusers.views`. This module provides tests for :py:mod:`osusers.views`.
""" """
from __future__ import absolute_import, unicode_literals
try:
from unittest.mock import patch, MagicMock from unittest.mock import patch, MagicMock
except ImportError:
from mock import patch, MagicMock
from django.core.urlresolvers import reverse
from django.test import TestCase, TransactionTestCase from django.test import TestCase, TransactionTestCase
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.urls import reverse
from hostingpackages.models import ( from hostingpackages.models import CustomerHostingPackage, HostingPackageTemplate
CustomerHostingPackage,
HostingPackageTemplate,
)
from osusers.models import SshPublicKey from osusers.models import SshPublicKey
from osusers.views import ( from osusers.views import AddSshPublicKey, DeleteSshPublicKey, EditSshPublicKeyComment
AddSshPublicKey,
DeleteSshPublicKey,
EditSshPublicKeyComment,
)
User = get_user_model() User = get_user_model()
TEST_USER = 'test' TEST_USER = "test"
TEST_PASSWORD = 'secret' TEST_PASSWORD = "secret"
TEST_EMAIL = 'test@example.org' TEST_EMAIL = "test@example.org"
EXAMPLE_KEY = "".join(( EXAMPLE_KEY = "".join(
(
"ssh-rsa ", "ssh-rsa ",
"AAAAB3NzaC1yc2EAAAABIwAAAIEA1on8gxCGJJWSRT4uOrR13mUaUk0hRf4RzxSZ1zRb", "AAAAB3NzaC1yc2EAAAABIwAAAIEA1on8gxCGJJWSRT4uOrR13mUaUk0hRf4RzxSZ1zRb",
"YYFw8pfGesIFoEuVth4HKyF8k1y4mRUnYHP1XNMNMJl1JcEArC2asV8sHf6zSPVffozZ", "YYFw8pfGesIFoEuVth4HKyF8k1y4mRUnYHP1XNMNMJl1JcEArC2asV8sHf6zSPVffozZ",
"5TT4SfsUu/iKy9lUcCfXzwre4WWZSXXcPff+EHtWshahu3WzBdnGxm5Xoi89zcE=" "5TT4SfsUu/iKy9lUcCfXzwre4WWZSXXcPff+EHtWshahu3WzBdnGxm5Xoi89zcE=",
)) )
)
class HostingPackageAwareTestMixin(object): class HostingPackageAwareTestMixin(object):
# noinspection PyMethodMayBeStatic
def _setup_hosting_package(self, customer): def _setup_hosting_package(self, customer):
template = HostingPackageTemplate.objects.create( template = HostingPackageTemplate.objects.create(
name='testpackagetemplate', mailboxcount=10, diskspace=1, name="testpackagetemplate", mailboxcount=10, diskspace=1, diskspace_unit=0
diskspace_unit=0) )
package = CustomerHostingPackage.objects.create_from_template( package = CustomerHostingPackage.objects.create_from_template(
customer, template, 'testpackage') customer, template, "testpackage"
with patch('hostingpackages.models.settings') as hmsettings: )
with patch("hostingpackages.models.settings") as hmsettings:
hmsettings.OSUSER_DEFAULT_GROUPS = [] hmsettings.OSUSER_DEFAULT_GROUPS = []
package.save() package.save()
return package return package
class AddSshPublicKeyTest(HostingPackageAwareTestMixin, TestCase): class AddSshPublicKeyTest(HostingPackageAwareTestMixin, TestCase):
def setUp(self): def setUp(self):
self.customer = User.objects.create_user( self.customer = User.objects.create_user(
username=TEST_USER, password=TEST_PASSWORD) username=TEST_USER, password=TEST_PASSWORD
)
self.package = self._setup_hosting_package(self.customer) self.package = self._setup_hosting_package(self.customer)
def _get_url(self): def _get_url(self):
return reverse('add_ssh_key', kwargs={'package': self.package.id}) return reverse("add_ssh_key", kwargs={"package": self.package.id})
def test_get_anonymous(self): def test_get_anonymous(self):
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
@ -73,77 +66,75 @@ class AddSshPublicKeyTest(HostingPackageAwareTestMixin, TestCase):
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_get_other_regular_user(self): def test_get_other_regular_user(self):
User.objects.create_user( User.objects.create_user("test2", password=TEST_PASSWORD)
'test2', password=TEST_PASSWORD) self.client.login(username="test2", password=TEST_PASSWORD)
self.client.login(username='test2', password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertEqual(response.status_code, 403) self.assertEqual(response.status_code, 403)
def test_get_staff_user(self): def test_get_staff_user(self):
User.objects.create_superuser( User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
'admin', email=TEST_EMAIL, password=TEST_PASSWORD) self.client.login(username="admin", password=TEST_PASSWORD)
self.client.login(username='admin', password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_get_template(self): def test_get_template(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertTemplateUsed(response, 'osusers/sshpublickey_create.html') self.assertTemplateUsed(response, "osusers/sshpublickey_create.html")
def test_get_form_kwargs(self): def test_get_form_kwargs(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
view = AddSshPublicKey( view = AddSshPublicKey(
request=MagicMock(), kwargs={'package': str(self.package.pk)}) request=MagicMock(), kwargs={"package": str(self.package.pk)}
)
the_kwargs = view.get_form_kwargs() the_kwargs = view.get_form_kwargs()
self.assertIn('hostingpackage', the_kwargs) self.assertIn("hostingpackage", the_kwargs)
self.assertEqual(the_kwargs['hostingpackage'], self.package) self.assertEqual(the_kwargs["hostingpackage"], self.package)
def test_get_context_data(self): def test_get_context_data(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertIn('customer', response.context) self.assertIn("customer", response.context)
self.assertEqual(response.context['customer'], self.customer) self.assertEqual(response.context["customer"], self.customer)
self.assertIn('osuser', response.context) self.assertIn("osuser", response.context)
self.assertEqual( self.assertEqual(response.context["osuser"], self.package.osuser.username)
response.context['osuser'], self.package.osuser.username)
def test_form_valid_redirect(self): def test_form_valid_redirect(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.post( response = self.client.post(
self._get_url(), self._get_url(), data={"publickeytext": EXAMPLE_KEY}
data={'publickeytext': EXAMPLE_KEY}) )
self.assertRedirects(response, self.package.get_absolute_url()) self.assertRedirects(response, self.package.get_absolute_url())
def test_form_valid_message(self): def test_form_valid_message(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.post( response = self.client.post(
self._get_url(), follow=True, self._get_url(), follow=True, data={"publickeytext": EXAMPLE_KEY}
data={'publickeytext': EXAMPLE_KEY}) )
messages = list(response.context['messages']) messages = list(response.context["messages"])
self.assertEqual(len(messages), 1) self.assertEqual(len(messages), 1)
self.assertEqual( self.assertEqual(
'Successfully added new ssh-rsa SSH public key.'.format( "Successfully added new ssh-rsa SSH public key.".format(
username=self.package.osuser.username username=self.package.osuser.username
), str(messages[0])) ),
str(messages[0]),
)
class DeleteSshPublicKeyTest(HostingPackageAwareTestMixin, TestCase): class DeleteSshPublicKeyTest(HostingPackageAwareTestMixin, TestCase):
def setUp(self): def setUp(self):
self.customer = User.objects.create_user( self.customer = User.objects.create_user(
username=TEST_USER, password=TEST_PASSWORD) username=TEST_USER, password=TEST_PASSWORD
)
self.package = self._setup_hosting_package(self.customer) self.package = self._setup_hosting_package(self.customer)
self.sshkey = SshPublicKey.objects.create( self.sshkey = SshPublicKey.objects.create(
user=self.package.osuser, algorithm='good', data='key', user=self.package.osuser, algorithm="good", data="key", comment="comment"
comment='comment') )
def _get_url(self): def _get_url(self):
return reverse( return reverse(
'delete_ssh_key', kwargs={ "delete_ssh_key", kwargs={"package": self.package.id, "pk": self.sshkey.id}
'package': self.package.id, )
'pk': self.sshkey.id
})
def test_get_anonymous(self): def test_get_anonymous(self):
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
@ -155,71 +146,63 @@ class DeleteSshPublicKeyTest(HostingPackageAwareTestMixin, TestCase):
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_get_other_regular_user(self): def test_get_other_regular_user(self):
User.objects.create_user( User.objects.create_user("test2", password=TEST_PASSWORD)
'test2', password=TEST_PASSWORD) self.client.login(username="test2", password=TEST_PASSWORD)
self.client.login(username='test2', password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertEqual(response.status_code, 403) self.assertEqual(response.status_code, 403)
def test_get_staff_user(self): def test_get_staff_user(self):
User.objects.create_superuser( User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
'admin', email=TEST_EMAIL, password=TEST_PASSWORD) self.client.login(username="admin", password=TEST_PASSWORD)
self.client.login(username='admin', password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_get_template(self): def test_get_template(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertTemplateUsed( self.assertTemplateUsed(response, "osusers/sshpublickey_confirm_delete.html")
response, 'osusers/sshpublickey_confirm_delete.html')
def test_get_queryset(self): def test_get_queryset(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
view = DeleteSshPublicKey( view = DeleteSshPublicKey(
request=MagicMock(), kwargs={ request=MagicMock(),
'package': str(self.package.pk), kwargs={"package": str(self.package.pk), "pk": str(self.sshkey.pk)},
'pk': str(self.sshkey.pk) )
})
queryset = view.get_queryset() queryset = view.get_queryset()
self.assertQuerysetEqual(queryset, [repr(self.sshkey)]) self.assertQuerysetEqual(queryset, [repr(self.sshkey)])
def test_get_context_data(self): def test_get_context_data(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
for key in ('hostingpackage', 'customer', 'osuser'): for key in ("hostingpackage", "customer", "osuser"):
self.assertIn(key, response.context) self.assertIn(key, response.context)
self.assertEqual(response.context['hostingpackage'], self.package) self.assertEqual(response.context["hostingpackage"], self.package)
self.assertEqual(response.context['customer'], self.customer) self.assertEqual(response.context["customer"], self.customer)
self.assertEqual( self.assertEqual(response.context["osuser"], self.package.osuser.username)
response.context['osuser'], self.package.osuser.username)
def test_get_success_url(self): def test_get_success_url(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.post( response = self.client.post(self._get_url(), data={"comment": "new comment"})
self._get_url(), self.assertRedirects(
data={'comment': 'new comment'}) response, reverse("list_ssh_keys", kwargs={"package": self.package.id})
self.assertRedirects(response, reverse('list_ssh_keys', kwargs={ )
'package': self.package.id}))
class EditSshPublicKeyCommentTest( class EditSshPublicKeyCommentTest(HostingPackageAwareTestMixin, TransactionTestCase):
HostingPackageAwareTestMixin, TransactionTestCase):
def setUp(self): def setUp(self):
self.customer = User.objects.create_user( self.customer = User.objects.create_user(
username=TEST_USER, password=TEST_PASSWORD) username=TEST_USER, password=TEST_PASSWORD
)
self.package = self._setup_hosting_package(self.customer) self.package = self._setup_hosting_package(self.customer)
self.sshkey = SshPublicKey.objects.create( self.sshkey = SshPublicKey.objects.create(
user=self.package.osuser, algorithm='good', data='key', user=self.package.osuser, algorithm="good", data="key", comment="comment"
comment='comment') )
def _get_url(self): def _get_url(self):
return reverse( return reverse(
'edit_ssh_key_comment', kwargs={ "edit_ssh_key_comment",
'package': self.package.id, kwargs={"package": self.package.id, "pk": self.sshkey.id},
'pk': self.sshkey.id )
})
def test_get_anonymous(self): def test_get_anonymous(self):
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
@ -231,74 +214,67 @@ class EditSshPublicKeyCommentTest(
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_get_other_regular_user(self): def test_get_other_regular_user(self):
User.objects.create_user( User.objects.create_user("test2", password=TEST_PASSWORD)
'test2', password=TEST_PASSWORD) self.client.login(username="test2", password=TEST_PASSWORD)
self.client.login(username='test2', password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertEqual(response.status_code, 403) self.assertEqual(response.status_code, 403)
def test_get_staff_user(self): def test_get_staff_user(self):
User.objects.create_superuser( User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
'admin', email=TEST_EMAIL, password=TEST_PASSWORD) self.client.login(username="admin", password=TEST_PASSWORD)
self.client.login(username='admin', password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_get_template(self): def test_get_template(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertTemplateUsed( self.assertTemplateUsed(response, "osusers/sshpublickey_edit_comment.html")
response, 'osusers/sshpublickey_edit_comment.html')
def test_get_queryset(self): def test_get_queryset(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
view = EditSshPublicKeyComment( view = EditSshPublicKeyComment(
request=MagicMock(), kwargs={ request=MagicMock(),
'package': str(self.package.pk), kwargs={"package": str(self.package.pk), "pk": str(self.sshkey.pk)},
'pk': str(self.sshkey.pk) )
})
queryset = view.get_queryset() queryset = view.get_queryset()
self.assertQuerysetEqual(queryset, [repr(self.sshkey)]) self.assertQuerysetEqual(queryset, [repr(self.sshkey)])
def test_get_form_kwargs(self): def test_get_form_kwargs(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
view = EditSshPublicKeyComment( view = EditSshPublicKeyComment(
request=MagicMock(), kwargs={ request=MagicMock(),
'package': str(self.package.pk), kwargs={"package": str(self.package.pk), "pk": str(self.sshkey.pk)},
'pk': str(self.sshkey.pk) )
})
the_kwargs = view.get_form_kwargs() the_kwargs = view.get_form_kwargs()
self.assertIn('hostingpackage', the_kwargs) self.assertIn("hostingpackage", the_kwargs)
self.assertEqual(the_kwargs['hostingpackage'], self.package) self.assertEqual(the_kwargs["hostingpackage"], self.package)
def test_get_context_data(self): def test_get_context_data(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
for key in ('hostingpackage', 'customer', 'osuser'): for key in ("hostingpackage", "customer", "osuser"):
self.assertIn(key, response.context) self.assertIn(key, response.context)
self.assertEqual(response.context['hostingpackage'], self.package) self.assertEqual(response.context["hostingpackage"], self.package)
self.assertEqual(response.context['customer'], self.customer) self.assertEqual(response.context["customer"], self.customer)
self.assertEqual( self.assertEqual(response.context["osuser"], self.package.osuser.username)
response.context['osuser'], self.package.osuser.username)
def test_get_success_url(self): def test_get_success_url(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.post( response = self.client.post(self._get_url(), data={"comment": "new comment"})
self._get_url(), self.assertRedirects(
data={'comment': 'new comment'}) response, reverse("list_ssh_keys", kwargs={"package": self.package.id})
self.assertRedirects(response, reverse('list_ssh_keys', kwargs={ )
'package': self.package.id}))
class ListSshPublicKeysTest(HostingPackageAwareTestMixin, TestCase): class ListSshPublicKeysTest(HostingPackageAwareTestMixin, TestCase):
def setUp(self): def setUp(self):
self.customer = User.objects.create_user( self.customer = User.objects.create_user(
username=TEST_USER, password=TEST_PASSWORD) username=TEST_USER, password=TEST_PASSWORD
)
self.package = self._setup_hosting_package(self.customer) self.package = self._setup_hosting_package(self.customer)
def _get_url(self): def _get_url(self):
return reverse('list_ssh_keys', kwargs={'package': self.package.id}) return reverse("list_ssh_keys", kwargs={"package": self.package.id})
def test_get_anonymous(self): def test_get_anonymous(self):
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
@ -310,45 +286,43 @@ class ListSshPublicKeysTest(HostingPackageAwareTestMixin, TestCase):
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_get_other_regular_user(self): def test_get_other_regular_user(self):
User.objects.create_user( User.objects.create_user("test2", password=TEST_PASSWORD)
'test2', password=TEST_PASSWORD) self.client.login(username="test2", password=TEST_PASSWORD)
self.client.login(username='test2', password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertEqual(response.status_code, 403) self.assertEqual(response.status_code, 403)
def test_get_staff_user(self): def test_get_staff_user(self):
User.objects.create_superuser( User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
'admin', email=TEST_EMAIL, password=TEST_PASSWORD) self.client.login(username="admin", password=TEST_PASSWORD)
self.client.login(username='admin', password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_get_template(self): def test_get_template(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertTemplateUsed(response, 'osusers/sshpublickey_list.html') self.assertTemplateUsed(response, "osusers/sshpublickey_list.html")
def test_get_context_data(self): def test_get_context_data(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
for key in ('hostingpackage', 'customer', 'osuser'): for key in ("hostingpackage", "customer", "osuser"):
self.assertIn(key, response.context) self.assertIn(key, response.context)
self.assertEqual(response.context['hostingpackage'], self.package) self.assertEqual(response.context["hostingpackage"], self.package)
self.assertEqual(response.context['customer'], self.customer) self.assertEqual(response.context["customer"], self.customer)
self.assertEqual( self.assertEqual(response.context["osuser"], self.package.osuser.username)
response.context['osuser'], self.package.osuser.username)
class SetOsUserPasswordTest(HostingPackageAwareTestMixin, TestCase): class SetOsUserPasswordTest(HostingPackageAwareTestMixin, TestCase):
def setUp(self): def setUp(self):
self.customer = User.objects.create_user( self.customer = User.objects.create_user(
username=TEST_USER, password=TEST_PASSWORD) username=TEST_USER, password=TEST_PASSWORD
)
self.package = self._setup_hosting_package(self.customer) self.package = self._setup_hosting_package(self.customer)
def _get_url(self): def _get_url(self):
return reverse('set_osuser_password', kwargs={ return reverse(
'slug': self.package.osuser.username}) "set_osuser_password", kwargs={"slug": self.package.osuser.username}
)
def test_get_anonymous(self): def test_get_anonymous(self):
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
@ -360,45 +334,48 @@ class SetOsUserPasswordTest(HostingPackageAwareTestMixin, TestCase):
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_get_other_regular_user(self): def test_get_other_regular_user(self):
User.objects.create_user( User.objects.create_user("test2", password=TEST_PASSWORD)
'test2', password=TEST_PASSWORD) self.client.login(username="test2", password=TEST_PASSWORD)
self.client.login(username='test2', password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertEqual(response.status_code, 403) self.assertEqual(response.status_code, 403)
def test_get_staff_user(self): def test_get_staff_user(self):
User.objects.create_superuser( User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
'admin', email=TEST_EMAIL, password=TEST_PASSWORD) self.client.login(username="admin", password=TEST_PASSWORD)
self.client.login(username='admin', password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_get_template(self): def test_get_template(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertTemplateUsed(response, 'osusers/user_setpassword.html') self.assertTemplateUsed(response, "osusers/user_setpassword.html")
def test_get_context_data(self): def test_get_context_data(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertIn('customer', response.context) self.assertIn("customer", response.context)
self.assertEqual(response.context['customer'], self.customer) self.assertEqual(response.context["customer"], self.customer)
def test_form_valid_redirect(self): def test_form_valid_redirect(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.post( response = self.client.post(
self._get_url(), self._get_url(),
data={'password1': TEST_PASSWORD, 'password2': TEST_PASSWORD}) data={"password1": TEST_PASSWORD, "password2": TEST_PASSWORD},
)
self.assertRedirects(response, self.package.get_absolute_url()) self.assertRedirects(response, self.package.get_absolute_url())
def test_form_valid_message(self): def test_form_valid_message(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.post( response = self.client.post(
self._get_url(), follow=True, self._get_url(),
data={'password1': TEST_PASSWORD, 'password2': TEST_PASSWORD}) follow=True,
messages = list(response.context['messages']) data={"password1": TEST_PASSWORD, "password2": TEST_PASSWORD},
)
messages = list(response.context["messages"])
self.assertEqual(len(messages), 1) self.assertEqual(len(messages), 1)
self.assertEqual( self.assertEqual(
'New password for {username} has been set successfully.'.format( "New password for {username} has been set successfully.".format(
username=self.package.osuser.username username=self.package.osuser.username
), str(messages[0])) ),
str(messages[0]),
)

View file

@ -4,39 +4,32 @@ This module provides tests for the
command. command.
""" """
from __future__ import unicode_literals
try: from unittest.mock import MagicMock, patch
from unittest.mock import patch, MagicMock
except ImportError:
from mock import patch, MagicMock
from django.test import TestCase from django.test import TestCase
from taskresults.management.commands.fetch_taskresults import Command
from taskresults.models import TaskResult from taskresults.models import TaskResult
from taskresults.management.commands.fetch_taskresults import Command TEST_TASK_UUID = "3120f6a8-2665-4fa3-a785-79efd28bfe92"
TEST_TASK_NAME = "test.task"
TEST_TASK_RESULT = "4ll y0ur b453 4r3 b3l0ng t0 u5"
TEST_TASK_UUID = '3120f6a8-2665-4fa3-a785-79efd28bfe92' @patch("taskresults.models.app.AsyncResult")
TEST_TASK_NAME = 'test.task'
TEST_TASK_RESULT = '4ll y0ur b453 4r3 b3l0ng t0 u5'
@patch('taskresults.models.app.AsyncResult')
class FetchTaskResultsCommandTest(TestCase): class FetchTaskResultsCommandTest(TestCase):
def test_handle_unfinished(self, asyncresult): def test_handle_unfinished(self, asyncresult):
resultmock = MagicMock(task_id=TEST_TASK_UUID) resultmock = MagicMock(task_id=TEST_TASK_UUID)
sigmock = MagicMock() sigmock = MagicMock()
sigmock.apply_async.return_value = resultmock sigmock.apply_async.return_value = resultmock
tr = TaskResult.objects.create_task_result(TEST_TASK_NAME, sigmock) tr = TaskResult.objects.create_task_result(TEST_TASK_NAME, sigmock)
self.assertFalse(tr.finished) self.assertFalse(tr.finished)
self.assertEqual(tr.result, '') self.assertEqual(tr.result, "")
self.assertEqual(tr.state, '') self.assertEqual(tr.state, "")
aresult = asyncresult.return_value aresult = asyncresult.return_value
aresult.state = 'PENDING' aresult.state = "PENDING"
aresult.ready.return_value = False aresult.ready.return_value = False
Command().handle() Command().handle()
@ -45,8 +38,8 @@ class FetchTaskResultsCommandTest(TestCase):
self.assertTrue(asyncresult.called_with(TEST_TASK_UUID)) self.assertTrue(asyncresult.called_with(TEST_TASK_UUID))
self.assertTrue(aresult.ready.called_with()) self.assertTrue(aresult.ready.called_with())
self.assertFalse(tr.finished) self.assertFalse(tr.finished)
self.assertEqual(tr.result, '') self.assertEqual(tr.result, "")
self.assertEqual(tr.state, 'PENDING') self.assertEqual(tr.state, "PENDING")
def test_handle_finished(self, asyncresult): def test_handle_finished(self, asyncresult):
resultmock = MagicMock(task_id=TEST_TASK_UUID) resultmock = MagicMock(task_id=TEST_TASK_UUID)
@ -54,11 +47,11 @@ class FetchTaskResultsCommandTest(TestCase):
sigmock.apply_async.return_value = resultmock sigmock.apply_async.return_value = resultmock
tr = TaskResult.objects.create_task_result(TEST_TASK_NAME, sigmock) tr = TaskResult.objects.create_task_result(TEST_TASK_NAME, sigmock)
self.assertFalse(tr.finished) self.assertFalse(tr.finished)
self.assertEqual(tr.result, '') self.assertEqual(tr.result, "")
self.assertEqual(tr.state, '') self.assertEqual(tr.state, "")
aresult = asyncresult.return_value aresult = asyncresult.return_value
aresult.state = 'SUCCESS' aresult.state = "SUCCESS"
aresult.ready.return_value = True aresult.ready.return_value = True
aresult.get.return_value = TEST_TASK_RESULT aresult.get.return_value = TEST_TASK_RESULT
@ -70,4 +63,4 @@ class FetchTaskResultsCommandTest(TestCase):
self.assertTrue(aresult.get.called_with()) self.assertTrue(aresult.get.called_with())
self.assertTrue(tr.finished) self.assertTrue(tr.finished)
self.assertEqual(tr.result, TEST_TASK_RESULT) self.assertEqual(tr.result, TEST_TASK_RESULT)
self.assertEqual(tr.state, 'SUCCESS') self.assertEqual(tr.state, "SUCCESS")

View file

@ -2,25 +2,19 @@
This module provides tests for :py:mod:`taskresults.models`. This module provides tests for :py:mod:`taskresults.models`.
""" """
from __future__ import absolute_import, unicode_literals from unittest.mock import MagicMock, patch
try:
from unittest.mock import patch, MagicMock
except ImportError:
from mock import patch, MagicMock
from django.test import TestCase from django.test import TestCase
from taskresults.models import TaskResult from taskresults.models import TaskResult
TEST_TASK_UUID = "3120f6a8-2665-4fa3-a785-79efd28bfe92"
TEST_TASK_UUID = '3120f6a8-2665-4fa3-a785-79efd28bfe92' TEST_TASK_NAME = "test.task"
TEST_TASK_NAME = 'test.task' TEST_TASK_RESULT = "4ll y0ur b453 4r3 b3l0ng t0 u5"
TEST_TASK_RESULT = '4ll y0ur b453 4r3 b3l0ng t0 u5'
class TaskResultTest(TestCase): class TaskResultTest(TestCase):
@patch('taskresults.models.app.AsyncResult') @patch("taskresults.models.app.AsyncResult")
def test_update_taskstatus_unfinished(self, asyncresult): def test_update_taskstatus_unfinished(self, asyncresult):
resultmock = MagicMock(task_id=TEST_TASK_UUID) resultmock = MagicMock(task_id=TEST_TASK_UUID)
sigmock = MagicMock() sigmock = MagicMock()
@ -28,13 +22,13 @@ class TaskResultTest(TestCase):
tr = TaskResult.objects.create_task_result(TEST_TASK_NAME, sigmock) tr = TaskResult.objects.create_task_result(TEST_TASK_NAME, sigmock)
self.assertFalse(tr.finished) self.assertFalse(tr.finished)
mymock = asyncresult.return_value mymock = asyncresult.return_value
mymock.state = 'PENDING' mymock.state = "PENDING"
mymock.ready.return_value = False mymock.ready.return_value = False
tr.fetch_result() tr.fetch_result()
mymock.get.assert_not_called() mymock.get.assert_not_called()
self.assertFalse(tr.finished) self.assertFalse(tr.finished)
@patch('taskresults.models.app.AsyncResult') @patch("taskresults.models.app.AsyncResult")
def test_update_taskstatus_finished(self, asyncresult): def test_update_taskstatus_finished(self, asyncresult):
resultmock = MagicMock(task_id=TEST_TASK_UUID) resultmock = MagicMock(task_id=TEST_TASK_UUID)
sigmock = MagicMock() sigmock = MagicMock()
@ -43,7 +37,7 @@ class TaskResultTest(TestCase):
tr = TaskResult.objects.create_task_result(TEST_TASK_NAME, sigmock) tr = TaskResult.objects.create_task_result(TEST_TASK_NAME, sigmock)
self.assertFalse(tr.finished) self.assertFalse(tr.finished)
aresult = asyncresult.return_value aresult = asyncresult.return_value
aresult.state = 'SUCCESS' aresult.state = "SUCCESS"
aresult.ready.return_value = True aresult.ready.return_value = True
aresult.get.return_value = TEST_TASK_RESULT aresult.get.return_value = TEST_TASK_RESULT
tr.fetch_result() tr.fetch_result()
@ -61,11 +55,15 @@ class TaskResultTest(TestCase):
sigmock = MagicMock() sigmock = MagicMock()
sigmock.apply_async.return_value = resultmock sigmock.apply_async.return_value = resultmock
tr = TaskResult.objects.create_task_result(TEST_TASK_NAME, sigmock) tr = TaskResult.objects.create_task_result(TEST_TASK_NAME, sigmock)
self.assertEqual(str(tr), "{name} ({taskid}): no".format( self.assertEqual(
name=TEST_TASK_NAME, taskid=TEST_TASK_UUID)) str(tr),
"{name} ({taskid}): no".format(name=TEST_TASK_NAME, taskid=TEST_TASK_UUID),
)
tr.finished = True tr.finished = True
self.assertEqual(str(tr), "{name} ({taskid}): yes".format( self.assertEqual(
name=TEST_TASK_NAME, taskid=TEST_TASK_UUID)) str(tr),
"{name} ({taskid}): yes".format(name=TEST_TASK_NAME, taskid=TEST_TASK_UUID),
)
TEST_RESULT = MagicMock() TEST_RESULT = MagicMock()

View file

@ -2,35 +2,33 @@
This module provides tests for :py:mod:`userdbs.admin`. This module provides tests for :py:mod:`userdbs.admin`.
""" """
from __future__ import absolute_import from unittest.mock import MagicMock, Mock, patch
from django.contrib.admin import AdminSite from django.contrib.admin import AdminSite
from django.test import TestCase from django.test import TestCase
from userdbs.admin import (DatabaseUserAdmin, DatabaseUserCreationForm, from userdbs.admin import (
UserDatabaseAdmin, UserDatabaseCreationForm) DatabaseUserAdmin,
DatabaseUserCreationForm,
UserDatabaseAdmin,
UserDatabaseCreationForm,
)
from userdbs.models import DB_TYPES, DatabaseUser, UserDatabase from userdbs.models import DB_TYPES, DatabaseUser, UserDatabase
try:
from unittest.mock import MagicMock, Mock, patch
except ImportError:
from mock import MagicMock, Mock, patch
class DatabaseUserCreationFormTest(TestCase): class DatabaseUserCreationFormTest(TestCase):
@patch("userdbs.admin.DatabaseUser.objects.create_database_user")
@patch('userdbs.admin.DatabaseUser.objects.create_database_user')
def test_save(self, create_database_user): def test_save(self, create_database_user):
create_database_user.return_value = Mock() create_database_user.return_value = Mock()
form = DatabaseUserCreationForm() form = DatabaseUserCreationForm()
mockuser = Mock(name='osuser') mockuser = Mock(name="osuser")
form.cleaned_data = { form.cleaned_data = {"osuser": mockuser, "db_type": DB_TYPES.pgsql}
'osuser': mockuser,
'db_type': DB_TYPES.pgsql
}
retval = form.save() retval = form.save()
self.assertTrue(create_database_user.called_with( self.assertTrue(
osuser=mockuser, db_type=DB_TYPES.pgsql, commit=True)) create_database_user.called_with(
osuser=mockuser, db_type=DB_TYPES.pgsql, commit=True
)
)
self.assertEqual(retval, create_database_user.return_value) self.assertEqual(retval, create_database_user.return_value)
def test_save_m2m_returns_none(self): def test_save_m2m_returns_none(self):
@ -39,16 +37,14 @@ class DatabaseUserCreationFormTest(TestCase):
class UserDatabaseCreationFormTest(TestCase): class UserDatabaseCreationFormTest(TestCase):
@patch("userdbs.admin.UserDatabase.objects.create_userdatabase")
@patch('userdbs.admin.UserDatabase.objects.create_userdatabase')
def test_save(self, create_userdatabase): def test_save(self, create_userdatabase):
create_userdatabase.return_value = Mock() create_userdatabase.return_value = Mock()
form = UserDatabaseCreationForm() form = UserDatabaseCreationForm()
mockuser = Mock(name='mockuser') mockuser = Mock(name="mockuser")
form.cleaned_data = {'db_user': mockuser} form.cleaned_data = {"db_user": mockuser}
retval = form.save() retval = form.save()
self.assertTrue(create_userdatabase.called_with( self.assertTrue(create_userdatabase.called_with(db_user=mockuser, commit=True))
db_user=mockuser, commit=True))
self.assertEqual(retval, create_userdatabase.return_value) self.assertEqual(retval, create_userdatabase.return_value)
def test_save_m2m_returns_none(self): def test_save_m2m_returns_none(self):
@ -57,116 +53,96 @@ class UserDatabaseCreationFormTest(TestCase):
class DatabaseUserAdminTest(TestCase): class DatabaseUserAdminTest(TestCase):
def setUp(self): def setUp(self):
site = AdminSite() site = AdminSite()
self.dbuadmin = DatabaseUserAdmin(DatabaseUser, site) self.dbuadmin = DatabaseUserAdmin(DatabaseUser, site)
super(DatabaseUserAdminTest, self).setUp() super(DatabaseUserAdminTest, self).setUp()
def test_get_form_with_instance(self): def test_get_form_with_instance(self):
form = self.dbuadmin.get_form( form = self.dbuadmin.get_form(Mock(name="request"), obj=Mock(name="dbuser"))
Mock(name='request'), obj=Mock(name='dbuser')) self.assertEqual(form.Meta.fields, ["osuser", "name", "db_type"])
self.assertEqual(
form.Meta.fields,
['osuser', 'name', 'db_type']
)
def test_get_form_without_instance(self): def test_get_form_without_instance(self):
form = self.dbuadmin.get_form(Mock(name='request')) form = self.dbuadmin.get_form(Mock(name="request"))
self.assertEqual( self.assertEqual(form.Meta.fields, ["osuser", "db_type"])
form.Meta.fields,
['osuser', 'db_type']
)
def test_get_readonly_fields_with_instance(self): def test_get_readonly_fields_with_instance(self):
fields = self.dbuadmin.get_readonly_fields( fields = self.dbuadmin.get_readonly_fields(
Mock(name='request'), obj=Mock(name='dbuser')) Mock(name="request"), obj=Mock(name="dbuser")
self.assertEqual( )
fields, ['osuser', 'name', 'db_type']) self.assertEqual(fields, ["osuser", "name", "db_type"])
def test_get_readonly_fields_without_instance(self): def test_get_readonly_fields_without_instance(self):
fields = self.dbuadmin.get_readonly_fields( fields = self.dbuadmin.get_readonly_fields(Mock(name="request"))
Mock(name='request'))
self.assertEqual(fields, []) self.assertEqual(fields, [])
def test_save_model_change(self): def test_save_model_change(self):
objmock = Mock() objmock = Mock()
self.dbuadmin.save_model(Mock(name='request'), objmock, Mock(), True) self.dbuadmin.save_model(Mock(name="request"), objmock, Mock(), True)
self.assertTrue(objmock.create_in_database.not_called()) self.assertTrue(objmock.create_in_database.not_called())
def test_save_model_no_change(self): def test_save_model_no_change(self):
objmock = Mock() objmock = Mock()
self.dbuadmin.save_model(Mock(name='request'), objmock, Mock(), False) self.dbuadmin.save_model(Mock(name="request"), objmock, Mock(), False)
self.assertTrue(objmock.create_in_database.called_with()) self.assertTrue(objmock.create_in_database.called_with())
def test_perform_delete_selected(self): def test_perform_delete_selected(self):
usermock = Mock() usermock = Mock()
selected = Mock() selected = Mock()
selected.all.return_value = [usermock] selected.all.return_value = [usermock]
self.dbuadmin.perform_delete_selected(Mock(name='request'), selected) self.dbuadmin.perform_delete_selected(Mock(name="request"), selected)
self.assertTrue(selected.all.called_with()) self.assertTrue(selected.all.called_with())
self.assertTrue(usermock.delete.called_with()) self.assertTrue(usermock.delete.called_with())
def test_get_actions(self): def test_get_actions(self):
requestmock = MagicMock(name='request') requestmock = MagicMock(name="request")
self.assertNotIn( self.assertNotIn("delete_selected", self.dbuadmin.get_actions(requestmock))
'delete_selected', self.assertIn("perform_delete_selected", self.dbuadmin.get_actions(requestmock))
self.dbuadmin.get_actions(requestmock))
self.assertIn(
'perform_delete_selected',
self.dbuadmin.get_actions(requestmock))
class UserDatabaseAdminTest(TestCase): class UserDatabaseAdminTest(TestCase):
def setUp(self): def setUp(self):
site = AdminSite() site = AdminSite()
self.udbadmin = UserDatabaseAdmin(UserDatabase, site) self.udbadmin = UserDatabaseAdmin(UserDatabase, site)
super(UserDatabaseAdminTest, self).setUp() super(UserDatabaseAdminTest, self).setUp()
def test_get_form_with_instance(self): def test_get_form_with_instance(self):
form = self.udbadmin.get_form( form = self.udbadmin.get_form(Mock(name="request"), obj=Mock(name="userdb"))
Mock(name='request'), obj=Mock(name='userdb')) self.assertEqual(form.Meta.fields, ["db_name", "db_user"])
self.assertEqual(form.Meta.fields, ['db_name', 'db_user'])
def test_get_form_without_instance(self): def test_get_form_without_instance(self):
form = self.udbadmin.get_form(Mock(name='request')) form = self.udbadmin.get_form(Mock(name="request"))
self.assertEqual(form.Meta.fields, ['db_user']) self.assertEqual(form.Meta.fields, ["db_user"])
def test_get_readonly_fields_with_instance(self): def test_get_readonly_fields_with_instance(self):
fields = self.udbadmin.get_readonly_fields( fields = self.udbadmin.get_readonly_fields(
Mock(name='request'), obj=Mock(name='userdb')) Mock(name="request"), obj=Mock(name="userdb")
self.assertEqual( )
fields, ['db_name', 'db_user']) self.assertEqual(fields, ["db_name", "db_user"])
def test_get_readonly_fields_without_instance(self): def test_get_readonly_fields_without_instance(self):
fields = self.udbadmin.get_readonly_fields( fields = self.udbadmin.get_readonly_fields(Mock(name="request"))
Mock(name='request'))
self.assertEqual(fields, []) self.assertEqual(fields, [])
def test_save_model_change(self): def test_save_model_change(self):
objmock = Mock() objmock = Mock()
self.udbadmin.save_model(Mock(name='request'), objmock, Mock(), True) self.udbadmin.save_model(Mock(name="request"), objmock, Mock(), True)
self.assertTrue(objmock.create_in_database.not_called()) self.assertTrue(objmock.create_in_database.not_called())
def test_save_model_no_change(self): def test_save_model_no_change(self):
objmock = Mock() objmock = Mock()
self.udbadmin.save_model(Mock(name='request'), objmock, Mock(), False) self.udbadmin.save_model(Mock(name="request"), objmock, Mock(), False)
self.assertTrue(objmock.create_in_database.called_with()) self.assertTrue(objmock.create_in_database.called_with())
def test_perform_delete_selected(self): def test_perform_delete_selected(self):
userdbmock = Mock() userdbmock = Mock()
selected = Mock() selected = Mock()
selected.all.return_value = [userdbmock] selected.all.return_value = [userdbmock]
self.udbadmin.perform_delete_selected(Mock(name='request'), selected) self.udbadmin.perform_delete_selected(Mock(name="request"), selected)
self.assertTrue(selected.all.called_with()) self.assertTrue(selected.all.called_with())
self.assertTrue(userdbmock.delete.called_with()) self.assertTrue(userdbmock.delete.called_with())
def test_get_actions(self): def test_get_actions(self):
requestmock = MagicMock(name='request') requestmock = MagicMock(name="request")
self.assertNotIn( self.assertNotIn("delete_selected", self.udbadmin.get_actions(requestmock))
'delete_selected', self.assertIn("perform_delete_selected", self.udbadmin.get_actions(requestmock))
self.udbadmin.get_actions(requestmock))
self.assertIn(
'perform_delete_selected',
self.udbadmin.get_actions(requestmock))

View file

@ -2,20 +2,15 @@
This module provides tests for :py:mod:`userdbs.forms`. This module provides tests for :py:mod:`userdbs.forms`.
""" """
from __future__ import unicode_literals
from django import forms from django import forms
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from django.test import TestCase from django.test import TestCase
from django.urls import reverse
from userdbs.forms import AddUserDatabaseForm, ChangeDatabaseUserPasswordForm from userdbs.forms import AddUserDatabaseForm, ChangeDatabaseUserPasswordForm
from userdbs.models import DB_TYPES from userdbs.models import DB_TYPES
try:
from unittest.mock import MagicMock, Mock, patch from unittest.mock import MagicMock, Mock, patch
except ImportError:
from mock import MagicMock, Mock, patch
Customer = get_user_model() Customer = get_user_model()
@ -33,66 +28,68 @@ class AddUserDatabaseFormTest(TestCase):
def test_constructor_needs_hostingpackage(self): def test_constructor_needs_hostingpackage(self):
with self.assertRaises(KeyError) as ke: with self.assertRaises(KeyError) as ke:
AddUserDatabaseForm(instance=Mock()) AddUserDatabaseForm(instance=Mock())
self.assertEqual(ke.exception.args[0], 'hostingpackage') self.assertEqual(ke.exception.args[0], "hostingpackage")
def test_constructor_needs_dbtypes(self): def test_constructor_needs_dbtypes(self):
with self.assertRaises(KeyError) as ke: with self.assertRaises(KeyError) as ke:
AddUserDatabaseForm(instance=Mock(), hostingpackage=Mock()) AddUserDatabaseForm(instance=Mock(), hostingpackage=Mock())
self.assertEqual(ke.exception.args[0], 'dbtypes') self.assertEqual(ke.exception.args[0], "dbtypes")
def test_constructor_one_dbtype(self): def test_constructor_one_dbtype(self):
self._setup_hostingpackage() self._setup_hostingpackage()
dbtypes = [(DB_TYPES.pgsql, DB_TYPES[DB_TYPES.pgsql])] dbtypes = [(DB_TYPES.pgsql, DB_TYPES[DB_TYPES.pgsql])]
form = AddUserDatabaseForm( form = AddUserDatabaseForm(
instance=MagicMock(), hostingpackage=self.hostingpackage, instance=MagicMock(), hostingpackage=self.hostingpackage, dbtypes=dbtypes
dbtypes=dbtypes) )
self.assertIn('db_type', form.fields) self.assertIn("db_type", form.fields)
self.assertEqual(form.fields['db_type'].choices, dbtypes) self.assertEqual(form.fields["db_type"].choices, dbtypes)
self.assertTrue(isinstance( self.assertTrue(isinstance(form.fields["db_type"].widget, forms.HiddenInput))
form.fields['db_type'].widget, self.assertTrue(hasattr(form, "helper"))
forms.HiddenInput)) self.assertEqual(
self.assertTrue(hasattr(form, 'helper')) form.helper.form_action,
self.assertEqual(form.helper.form_action, reverse( reverse("add_userdatabase", kwargs={"package": self.hostingpackage.id}),
'add_userdatabase', kwargs={'package': self.hostingpackage.id})) )
self.assertEqual(form.helper.inputs[0].name, 'submit') self.assertEqual(form.helper.inputs[0].name, "submit")
def test_constructor_multiple_dbtypes(self): def test_constructor_multiple_dbtypes(self):
self._setup_hostingpackage() self._setup_hostingpackage()
dbtypes = [ dbtypes = [
(DB_TYPES.pgsql, DB_TYPES[DB_TYPES.pgsql]), (DB_TYPES.pgsql, DB_TYPES[DB_TYPES.pgsql]),
(DB_TYPES.mysql, DB_TYPES[DB_TYPES.mysql]) (DB_TYPES.mysql, DB_TYPES[DB_TYPES.mysql]),
] ]
form = AddUserDatabaseForm( form = AddUserDatabaseForm(
instance=MagicMock(), hostingpackage=self.hostingpackage, instance=MagicMock(), hostingpackage=self.hostingpackage, dbtypes=dbtypes
dbtypes=dbtypes) )
self.assertIn('db_type', form.fields) self.assertIn("db_type", form.fields)
self.assertEqual(form.fields['db_type'].choices, dbtypes) self.assertEqual(form.fields["db_type"].choices, dbtypes)
self.assertTrue(isinstance( self.assertTrue(isinstance(form.fields["db_type"].widget, forms.RadioSelect))
form.fields['db_type'].widget, self.assertTrue(hasattr(form, "helper"))
forms.RadioSelect)) self.assertEqual(
self.assertTrue(hasattr(form, 'helper')) form.helper.form_action,
self.assertEqual(form.helper.form_action, reverse( reverse("add_userdatabase", kwargs={"package": self.hostingpackage.id}),
'add_userdatabase', kwargs={'package': self.hostingpackage.id})) )
self.assertEqual(form.helper.inputs[0].name, 'submit') self.assertEqual(form.helper.inputs[0].name, "submit")
@patch('userdbs.forms.UserDatabase.objects.create_userdatabase_with_user') @patch("userdbs.forms.UserDatabase.objects.create_userdatabase_with_user")
def test_save(self, create_userdatabase_with_user): def test_save(self, create_userdatabase_with_user):
self._setup_hostingpackage() self._setup_hostingpackage()
dbtypes = [ dbtypes = [
(DB_TYPES.pgsql, DB_TYPES[DB_TYPES.pgsql]), (DB_TYPES.pgsql, DB_TYPES[DB_TYPES.pgsql]),
(DB_TYPES.mysql, DB_TYPES[DB_TYPES.mysql]) (DB_TYPES.mysql, DB_TYPES[DB_TYPES.mysql]),
] ]
form = AddUserDatabaseForm( form = AddUserDatabaseForm(
instance=MagicMock(), hostingpackage=self.hostingpackage, instance=MagicMock(), hostingpackage=self.hostingpackage, dbtypes=dbtypes
dbtypes=dbtypes) )
form.cleaned_data = { form.cleaned_data = {"db_type": DB_TYPES.pgsql, "password1": "secret"}
'db_type': DB_TYPES.pgsql,
'password1': 'secret',
}
form.save() form.save()
self.assertTrue(create_userdatabase_with_user.called_with( self.assertTrue(
DB_TYPES.pgsql, self.hostingpackage.osuser, create_userdatabase_with_user.called_with(
password='secret', commit=True)) DB_TYPES.pgsql,
self.hostingpackage.osuser,
password="secret",
commit=True,
)
)
class ChangeDatabaseUserPasswordFormTest(TestCase): class ChangeDatabaseUserPasswordFormTest(TestCase):
@ -107,29 +104,31 @@ class ChangeDatabaseUserPasswordFormTest(TestCase):
def test_constructor_needs_hostingpackage(self): def test_constructor_needs_hostingpackage(self):
with self.assertRaises(KeyError) as ke: with self.assertRaises(KeyError) as ke:
ChangeDatabaseUserPasswordForm(instance=Mock()) ChangeDatabaseUserPasswordForm(instance=Mock())
self.assertEqual(ke.exception.args[0], 'hostingpackage') self.assertEqual(ke.exception.args[0], "hostingpackage")
def test_constructor(self): def test_constructor(self):
self._setup_hostingpackage() self._setup_hostingpackage()
instance = MagicMock() instance = MagicMock()
instance.name = 'test' instance.name = "test"
form = ChangeDatabaseUserPasswordForm( form = ChangeDatabaseUserPasswordForm(
instance=instance, hostingpackage=self.hostingpackage) instance=instance, hostingpackage=self.hostingpackage
self.assertIn('password1', form.fields) )
self.assertIn('password2', form.fields) self.assertIn("password1", form.fields)
self.assertTrue(hasattr(form, 'helper')) self.assertIn("password2", form.fields)
self.assertEqual(form.helper.form_action, reverse( self.assertTrue(hasattr(form, "helper"))
'change_dbuser_password', kwargs={ self.assertEqual(
'slug': 'test', 'package': 42 form.helper.form_action,
})) reverse("change_dbuser_password", kwargs={"slug": "test", "package": 42}),
self.assertEqual(form.helper.inputs[0].name, 'submit') )
self.assertEqual(form.helper.inputs[0].name, "submit")
def test_save(self): def test_save(self):
instance = MagicMock() instance = MagicMock()
instance.name = 'test' instance.name = "test"
self._setup_hostingpackage() self._setup_hostingpackage()
form = ChangeDatabaseUserPasswordForm( form = ChangeDatabaseUserPasswordForm(
instance=instance, hostingpackage=self.hostingpackage) instance=instance, hostingpackage=self.hostingpackage
form.cleaned_data = {'password1': 'secret'} )
form.cleaned_data = {"password1": "secret"}
form.save() form.save()
self.assertTrue(instance.set_password.called_with('secret')) self.assertTrue(instance.set_password.called_with("secret"))

View file

@ -2,8 +2,6 @@
This module provides tests for :py:mod:`userdbs.models`. This module provides tests for :py:mod:`userdbs.models`.
""" """
from __future__ import unicode_literals
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.test import TestCase from django.test import TestCase
from django.test.utils import override_settings from django.test.utils import override_settings
@ -16,9 +14,7 @@ Customer = get_user_model()
@override_settings( @override_settings(
CELERY_ALWAYS_EAGER=True, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
CELERY_CACHE_BACKEND='memory',
BROKER_BACKEND='memory'
) )
class TestCaseWithCeleryTasks(TestCase): class TestCaseWithCeleryTasks(TestCase):
pass pass
@ -29,93 +25,85 @@ class DatabaseUserManagerTest(TestCaseWithCeleryTasks):
Test case for :py:class:`userdbs.models.DatabaseUserManager`. Test case for :py:class:`userdbs.models.DatabaseUserManager`.
""" """
def setUp(self): def setUp(self):
self.customer = Customer.objects.create_user(username='testcustomer') self.customer = Customer.objects.create_user(username="testcustomer")
self.osuser = User.objects.create_user(customer=self.customer) self.osuser = User.objects.create_user(customer=self.customer)
TaskResult.objects.all().delete() TaskResult.objects.all().delete()
def test_create_database_user_with_name(self): def test_create_database_user_with_name(self):
dbu = DatabaseUser.objects.create_database_user( dbu = DatabaseUser.objects.create_database_user(
self.osuser, DB_TYPES.pgsql, 'testname', 'secret') self.osuser, DB_TYPES.pgsql, "testname", "secret"
self.assertEqual(dbu.name, 'testname') )
self.assertEqual(dbu.name, "testname")
self.assertEqual(dbu.osuser, self.osuser) self.assertEqual(dbu.osuser, self.osuser)
self.assertEqual(dbu.db_type, DB_TYPES.pgsql) self.assertEqual(dbu.db_type, DB_TYPES.pgsql)
taskres = TaskResult.objects.all() taskres = TaskResult.objects.all()
self.assertEqual(len(taskres), 1) self.assertEqual(len(taskres), 1)
self.assertEqual(taskres[0].creator, 'handle_dbuser_created') self.assertEqual(taskres[0].creator, "handle_dbuser_created")
self.assertEqual(taskres[0].notes, 'pgsql user creation') self.assertEqual(taskres[0].notes, "pgsql user creation")
def test_create_database_user_with_name_no_commit(self): def test_create_database_user_with_name_no_commit(self):
dbu = DatabaseUser.objects.create_database_user( dbu = DatabaseUser.objects.create_database_user(
self.osuser, DB_TYPES.pgsql, 'testname', 'secret', False) self.osuser, DB_TYPES.pgsql, "testname", "secret", False
self.assertEqual(dbu.name, 'testname') )
self.assertEqual(dbu.name, "testname")
self.assertEqual(dbu.osuser, self.osuser) self.assertEqual(dbu.osuser, self.osuser)
self.assertEqual(dbu.db_type, DB_TYPES.pgsql) self.assertEqual(dbu.db_type, DB_TYPES.pgsql)
self.assertFalse(TaskResult.objects.exists()) self.assertFalse(TaskResult.objects.exists())
def test_create_database_user_generate_name(self): def test_create_database_user_generate_name(self):
dbu = DatabaseUser.objects.create_database_user( dbu = DatabaseUser.objects.create_database_user(self.osuser, DB_TYPES.pgsql)
self.osuser, DB_TYPES.pgsql) self.assertEqual(dbu.name, "{user}db01".format(user=self.osuser.username))
self.assertEqual(dbu.name, '{user}db01'.format(
user=self.osuser.username))
self.assertEqual(dbu.osuser, self.osuser) self.assertEqual(dbu.osuser, self.osuser)
self.assertEqual(dbu.db_type, DB_TYPES.pgsql) self.assertEqual(dbu.db_type, DB_TYPES.pgsql)
taskres = TaskResult.objects.all() taskres = TaskResult.objects.all()
self.assertEqual(len(taskres), 1) self.assertEqual(len(taskres), 1)
self.assertEqual(taskres[0].creator, 'handle_dbuser_created') self.assertEqual(taskres[0].creator, "handle_dbuser_created")
self.assertEqual(taskres[0].notes, 'pgsql user creation') self.assertEqual(taskres[0].notes, "pgsql user creation")
def test_create_database_user_multiple_generate_name(self): def test_create_database_user_multiple_generate_name(self):
dbu = DatabaseUser.objects.create_database_user( dbu = DatabaseUser.objects.create_database_user(self.osuser, DB_TYPES.mysql)
self.osuser, DB_TYPES.mysql) self.assertEqual(dbu.name, "{user}db01".format(user=self.osuser.username))
self.assertEqual(dbu.name, '{user}db01'.format(
user=self.osuser.username))
self.assertEqual(dbu.osuser, self.osuser) self.assertEqual(dbu.osuser, self.osuser)
self.assertEqual(dbu.db_type, DB_TYPES.mysql) self.assertEqual(dbu.db_type, DB_TYPES.mysql)
dbu = DatabaseUser.objects.create_database_user( dbu = DatabaseUser.objects.create_database_user(self.osuser, DB_TYPES.mysql)
self.osuser, DB_TYPES.mysql) self.assertEqual(dbu.name, "{user}db02".format(user=self.osuser.username))
self.assertEqual(dbu.name, '{user}db02'.format(
user=self.osuser.username))
self.assertEqual(dbu.osuser, self.osuser) self.assertEqual(dbu.osuser, self.osuser)
self.assertEqual(dbu.db_type, DB_TYPES.mysql) self.assertEqual(dbu.db_type, DB_TYPES.mysql)
taskres = TaskResult.objects.all() taskres = TaskResult.objects.all()
self.assertEqual(len(taskres), 2) self.assertEqual(len(taskres), 2)
self.assertEqual(taskres[0].creator, 'handle_dbuser_created') self.assertEqual(taskres[0].creator, "handle_dbuser_created")
self.assertEqual(taskres[0].notes, 'mysql user creation') self.assertEqual(taskres[0].notes, "mysql user creation")
self.assertEqual(taskres[1].creator, 'handle_dbuser_created') self.assertEqual(taskres[1].creator, "handle_dbuser_created")
self.assertEqual(taskres[1].notes, 'mysql user creation') self.assertEqual(taskres[1].notes, "mysql user creation")
def test_create_database_user_multiple_gap_generate_name(self): def test_create_database_user_multiple_gap_generate_name(self):
dbu = DatabaseUser.objects.create_database_user( dbu = DatabaseUser.objects.create_database_user(self.osuser, DB_TYPES.mysql)
self.osuser, DB_TYPES.mysql) self.assertEqual(dbu.name, "{user}db01".format(user=self.osuser.username))
self.assertEqual(dbu.name, '{user}db01'.format(
user=self.osuser.username))
self.assertEqual(dbu.osuser, self.osuser) self.assertEqual(dbu.osuser, self.osuser)
self.assertEqual(dbu.db_type, DB_TYPES.mysql) self.assertEqual(dbu.db_type, DB_TYPES.mysql)
dbu = DatabaseUser.objects.create_database_user( dbu = DatabaseUser.objects.create_database_user(self.osuser, DB_TYPES.mysql)
self.osuser, DB_TYPES.mysql) self.assertEqual(dbu.name, "{user}db02".format(user=self.osuser.username))
self.assertEqual(dbu.name, '{user}db02'.format(
user=self.osuser.username))
self.assertEqual(dbu.osuser, self.osuser) self.assertEqual(dbu.osuser, self.osuser)
self.assertEqual(dbu.db_type, DB_TYPES.mysql) self.assertEqual(dbu.db_type, DB_TYPES.mysql)
DatabaseUser.objects.get( DatabaseUser.objects.get(
name='{user}db01'.format(user=self.osuser.username)).delete() name="{user}db01".format(user=self.osuser.username)
dbu = DatabaseUser.objects.create_database_user( ).delete()
self.osuser, DB_TYPES.mysql) dbu = DatabaseUser.objects.create_database_user(self.osuser, DB_TYPES.mysql)
self.assertEqual(dbu.name, '{user}db01'.format( self.assertEqual(dbu.name, "{user}db01".format(user=self.osuser.username))
user=self.osuser.username))
self.assertEqual(dbu.osuser, self.osuser) self.assertEqual(dbu.osuser, self.osuser)
self.assertEqual(dbu.db_type, DB_TYPES.mysql) self.assertEqual(dbu.db_type, DB_TYPES.mysql)
taskres = TaskResult.objects.all() taskres = TaskResult.objects.all()
self.assertEqual(len(taskres), 4) self.assertEqual(len(taskres), 4)
self.assertEqual(taskres[0].creator, 'handle_dbuser_created') self.assertEqual(taskres[0].creator, "handle_dbuser_created")
self.assertEqual(taskres[0].notes, 'mysql user creation') self.assertEqual(taskres[0].notes, "mysql user creation")
self.assertEqual(taskres[1].creator, 'handle_dbuser_created') self.assertEqual(taskres[1].creator, "handle_dbuser_created")
self.assertEqual(taskres[1].notes, 'mysql user creation') self.assertEqual(taskres[1].notes, "mysql user creation")
self.assertEqual(taskres[2].creator, 'handle_dbuser_deleted') self.assertEqual(taskres[2].creator, "handle_dbuser_deleted")
self.assertEqual(taskres[2].notes, 'mysql user deletion') self.assertEqual(taskres[2].notes, "mysql user deletion")
self.assertEqual(taskres[3].creator, 'handle_dbuser_created') self.assertEqual(taskres[3].creator, "handle_dbuser_created")
self.assertEqual(taskres[3].notes, 'mysql user creation') self.assertEqual(taskres[3].notes, "mysql user creation")
class DatabaseUserTest(TestCaseWithCeleryTasks): class DatabaseUserTest(TestCaseWithCeleryTasks):
@ -123,41 +111,43 @@ class DatabaseUserTest(TestCaseWithCeleryTasks):
Test case for :py:class:`userdbs.models.DatabaseUser`. Test case for :py:class:`userdbs.models.DatabaseUser`.
""" """
def setUp(self): def setUp(self):
self.customer = Customer.objects.create_user(username='testcustomer') self.customer = Customer.objects.create_user(username="testcustomer")
self.osuser = User.objects.create_user(customer=self.customer) self.osuser = User.objects.create_user(customer=self.customer)
self.dbu = DatabaseUser.objects.create_database_user( self.dbu = DatabaseUser.objects.create_database_user(
self.osuser, DB_TYPES.pgsql) self.osuser, DB_TYPES.pgsql
)
TaskResult.objects.all().delete() TaskResult.objects.all().delete()
def test___str__(self): def test___str__(self):
self.assertEqual( self.assertEqual(
str(self.dbu), str(self.dbu),
'{user}db01 (PostgreSQL for {user})'.format( "{user}db01 (PostgreSQL for {user})".format(user=self.osuser.username),
user=self.osuser.username)) )
def test_set_password_pgsql(self): def test_set_password_pgsql(self):
self.dbu.set_password('secret') self.dbu.set_password("secret")
taskres = TaskResult.objects.all() taskres = TaskResult.objects.all()
self.assertEqual(len(taskres), 1) self.assertEqual(len(taskres), 1)
self.assertEqual(taskres[0].creator, 'handle_dbuser_password_set') self.assertEqual(taskres[0].creator, "handle_dbuser_password_set")
self.assertEqual(taskres[0].notes, 'pgsql password change') self.assertEqual(taskres[0].notes, "pgsql password change")
def test_set_password_mysql(self): def test_set_password_mysql(self):
self.dbu.db_type = DB_TYPES.mysql self.dbu.db_type = DB_TYPES.mysql
self.dbu.save() self.dbu.save()
self.dbu.set_password('secret') self.dbu.set_password("secret")
taskres = TaskResult.objects.all() taskres = TaskResult.objects.all()
self.assertEqual(len(taskres), 1) self.assertEqual(len(taskres), 1)
self.assertEqual(taskres[0].creator, 'handle_dbuser_password_set') self.assertEqual(taskres[0].creator, "handle_dbuser_password_set")
self.assertEqual(taskres[0].notes, 'mysql password change') self.assertEqual(taskres[0].notes, "mysql password change")
def test_delete_no_dbs(self): def test_delete_no_dbs(self):
self.dbu.delete() self.dbu.delete()
taskres = TaskResult.objects.all() taskres = TaskResult.objects.all()
self.assertEqual(len(taskres), 1) self.assertEqual(len(taskres), 1)
self.assertEqual(taskres[0].creator, 'handle_dbuser_deleted') self.assertEqual(taskres[0].creator, "handle_dbuser_deleted")
self.assertEqual(taskres[0].notes, 'pgsql user deletion') self.assertEqual(taskres[0].notes, "pgsql user deletion")
def test_delete_with_dbs(self): def test_delete_with_dbs(self):
db = UserDatabase.objects.create_userdatabase(self.dbu) db = UserDatabase.objects.create_userdatabase(self.dbu)
@ -166,12 +156,12 @@ class DatabaseUserTest(TestCaseWithCeleryTasks):
self.assertFalse(UserDatabase.objects.filter(id=dbid).exists()) self.assertFalse(UserDatabase.objects.filter(id=dbid).exists())
taskres = TaskResult.objects.all() taskres = TaskResult.objects.all()
self.assertEqual(len(taskres), 3) self.assertEqual(len(taskres), 3)
self.assertEqual(taskres[0].creator, 'handle_userdb_created') self.assertEqual(taskres[0].creator, "handle_userdb_created")
self.assertEqual(taskres[0].notes, 'pgsql database creation') self.assertEqual(taskres[0].notes, "pgsql database creation")
self.assertEqual(taskres[1].creator, 'handle_userdb_deleted') self.assertEqual(taskres[1].creator, "handle_userdb_deleted")
self.assertEqual(taskres[1].notes, 'pgsql database deletion') self.assertEqual(taskres[1].notes, "pgsql database deletion")
self.assertEqual(taskres[2].creator, 'handle_dbuser_deleted') self.assertEqual(taskres[2].creator, "handle_dbuser_deleted")
self.assertEqual(taskres[2].notes, 'pgsql user deletion') self.assertEqual(taskres[2].notes, "pgsql user deletion")
class UserDatabaseManagerTest(TestCaseWithCeleryTasks): class UserDatabaseManagerTest(TestCaseWithCeleryTasks):
@ -179,50 +169,52 @@ class UserDatabaseManagerTest(TestCaseWithCeleryTasks):
Test case for :py:class:`userdbs.models.UserDatabaseManager`. Test case for :py:class:`userdbs.models.UserDatabaseManager`.
""" """
def setUp(self): def setUp(self):
self.customer = Customer.objects.create_user(username='testcustomer') self.customer = Customer.objects.create_user(username="testcustomer")
self.osuser = User.objects.create_user(customer=self.customer) self.osuser = User.objects.create_user(customer=self.customer)
TaskResult.objects.all().delete() TaskResult.objects.all().delete()
def _create_database_user(self, dbtype): def _create_database_user(self, dbtype):
self.dbu = DatabaseUser.objects.create_database_user( self.dbu = DatabaseUser.objects.create_database_user(self.osuser, dbtype)
self.osuser, dbtype)
TaskResult.objects.all().delete() TaskResult.objects.all().delete()
def test_create_userdatabase_with_user_mysql(self): def test_create_userdatabase_with_user_mysql(self):
db = UserDatabase.objects.create_userdatabase_with_user( db = UserDatabase.objects.create_userdatabase_with_user(
DB_TYPES.mysql, self.osuser) DB_TYPES.mysql, self.osuser
self.assertEqual(db.db_name, '{user}db01'.format( )
user=self.osuser.username)) self.assertEqual(db.db_name, "{user}db01".format(user=self.osuser.username))
self.assertEqual(db.db_user.name, '{user}db01'.format( self.assertEqual(
user=self.osuser.username)) db.db_user.name, "{user}db01".format(user=self.osuser.username)
)
taskres = TaskResult.objects.all() taskres = TaskResult.objects.all()
self.assertEqual(len(taskres), 2) self.assertEqual(len(taskres), 2)
self.assertEqual(taskres[0].creator, 'handle_dbuser_created') self.assertEqual(taskres[0].creator, "handle_dbuser_created")
self.assertEqual(taskres[0].notes, 'mysql user creation') self.assertEqual(taskres[0].notes, "mysql user creation")
self.assertEqual(taskres[1].creator, 'handle_userdb_created') self.assertEqual(taskres[1].creator, "handle_userdb_created")
self.assertEqual(taskres[1].notes, 'mysql database creation') self.assertEqual(taskres[1].notes, "mysql database creation")
def test_create_userdatabase_with_user_pgsql(self): def test_create_userdatabase_with_user_pgsql(self):
db = UserDatabase.objects.create_userdatabase_with_user( db = UserDatabase.objects.create_userdatabase_with_user(
DB_TYPES.pgsql, self.osuser) DB_TYPES.pgsql, self.osuser
self.assertEqual(db.db_name, '{user}db01'.format( )
user=self.osuser.username)) self.assertEqual(db.db_name, "{user}db01".format(user=self.osuser.username))
self.assertEqual(db.db_user.name, '{user}db01'.format( self.assertEqual(
user=self.osuser.username)) db.db_user.name, "{user}db01".format(user=self.osuser.username)
)
taskres = TaskResult.objects.all() taskres = TaskResult.objects.all()
self.assertEqual(len(taskres), 2) self.assertEqual(len(taskres), 2)
self.assertEqual(taskres[0].creator, 'handle_dbuser_created') self.assertEqual(taskres[0].creator, "handle_dbuser_created")
self.assertEqual(taskres[0].notes, 'pgsql user creation') self.assertEqual(taskres[0].notes, "pgsql user creation")
self.assertEqual(taskres[1].creator, 'handle_userdb_created') self.assertEqual(taskres[1].creator, "handle_userdb_created")
self.assertEqual(taskres[1].notes, 'pgsql database creation') self.assertEqual(taskres[1].notes, "pgsql database creation")
def test_create_userdatabase_given_name_no_new_write(self): def test_create_userdatabase_given_name_no_new_write(self):
self._create_database_user(DB_TYPES.pgsql) self._create_database_user(DB_TYPES.pgsql)
db = UserDatabase.objects.create_userdatabase(self.dbu, db_name='test') db = UserDatabase.objects.create_userdatabase(self.dbu, db_name="test")
taskres = TaskResult.objects.all() taskres = TaskResult.objects.all()
self.assertEqual(len(taskres), 1) self.assertEqual(len(taskres), 1)
self.assertEqual(db.db_name, 'test') self.assertEqual(db.db_name, "test")
TaskResult.objects.all().delete() TaskResult.objects.all().delete()
db.save() db.save()
taskres = TaskResult.objects.all() taskres = TaskResult.objects.all()
@ -230,11 +222,11 @@ class UserDatabaseManagerTest(TestCaseWithCeleryTasks):
def test_create_userdatabase_given_name(self): def test_create_userdatabase_given_name(self):
self._create_database_user(DB_TYPES.pgsql) self._create_database_user(DB_TYPES.pgsql)
db = UserDatabase.objects.create_userdatabase(self.dbu, db_name='test') db = UserDatabase.objects.create_userdatabase(self.dbu, db_name="test")
self.assertEqual(db.db_name, 'test') self.assertEqual(db.db_name, "test")
taskres = TaskResult.objects.all() taskres = TaskResult.objects.all()
self.assertEqual(len(taskres), 1) self.assertEqual(len(taskres), 1)
self.assertEqual(db.db_name, 'test') self.assertEqual(db.db_name, "test")
def test_create_userdatabase_generate_name_no_commit(self): def test_create_userdatabase_generate_name_no_commit(self):
self._create_database_user(DB_TYPES.pgsql) self._create_database_user(DB_TYPES.pgsql)
@ -252,19 +244,19 @@ class UserDatabaseManagerTest(TestCaseWithCeleryTasks):
db = UserDatabase.objects.create_userdatabase(self.dbu) db = UserDatabase.objects.create_userdatabase(self.dbu)
self.assertEqual(db.db_name, self.dbu.name) self.assertEqual(db.db_name, self.dbu.name)
db = UserDatabase.objects.create_userdatabase(self.dbu) db = UserDatabase.objects.create_userdatabase(self.dbu)
self.assertEqual(db.db_name, '{user}_02'.format(user=self.dbu.name)) self.assertEqual(db.db_name, "{user}_02".format(user=self.dbu.name))
def test_create_userdatabase_multiple_gap_generate_name(self): def test_create_userdatabase_multiple_gap_generate_name(self):
self._create_database_user(DB_TYPES.pgsql) self._create_database_user(DB_TYPES.pgsql)
db = UserDatabase.objects.create_userdatabase(self.dbu) db = UserDatabase.objects.create_userdatabase(self.dbu)
self.assertEqual(db.db_name, self.dbu.name) self.assertEqual(db.db_name, self.dbu.name)
dbx = UserDatabase.objects.create_userdatabase(self.dbu) dbx = UserDatabase.objects.create_userdatabase(self.dbu)
self.assertEqual(dbx.db_name, '{user}_02'.format(user=self.dbu.name)) self.assertEqual(dbx.db_name, "{user}_02".format(user=self.dbu.name))
db = UserDatabase.objects.create_userdatabase(self.dbu) db = UserDatabase.objects.create_userdatabase(self.dbu)
self.assertEqual(db.db_name, '{user}_03'.format(user=self.dbu.name)) self.assertEqual(db.db_name, "{user}_03".format(user=self.dbu.name))
dbx.delete() dbx.delete()
db = UserDatabase.objects.create_userdatabase(self.dbu) db = UserDatabase.objects.create_userdatabase(self.dbu)
self.assertEqual(db.db_name, '{user}_02'.format(user=self.dbu.name)) self.assertEqual(db.db_name, "{user}_02".format(user=self.dbu.name))
class UserDatabaseTest(TestCaseWithCeleryTasks): class UserDatabaseTest(TestCaseWithCeleryTasks):
@ -272,24 +264,23 @@ class UserDatabaseTest(TestCaseWithCeleryTasks):
Test case for :py:class:`userdbs.models.UserDabase`. Test case for :py:class:`userdbs.models.UserDabase`.
""" """
def test___str__(self): def test___str__(self):
customer = Customer.objects.create_user(username='testcustomer') customer = Customer.objects.create_user(username="testcustomer")
osuser = User.objects.create_user(customer=customer) osuser = User.objects.create_user(customer=customer)
db = UserDatabase.objects.create_userdatabase_with_user( db = UserDatabase.objects.create_userdatabase_with_user(DB_TYPES.pgsql, osuser)
DB_TYPES.pgsql, osuser)
self.assertEqual( self.assertEqual(
str(db), str(db),
'{user}db01 ({dbuser})'.format( "{user}db01 ({dbuser})".format(user=osuser.username, dbuser=db.db_user),
user=osuser.username, dbuser=db.db_user)) )
def test_delete_mysql_db(self): def test_delete_mysql_db(self):
customer = Customer.objects.create_user(username='testcustomer') customer = Customer.objects.create_user(username="testcustomer")
osuser = User.objects.create_user(customer=customer) osuser = User.objects.create_user(customer=customer)
TaskResult.objects.all().delete() TaskResult.objects.all().delete()
db = UserDatabase.objects.create_userdatabase_with_user( db = UserDatabase.objects.create_userdatabase_with_user(DB_TYPES.mysql, osuser)
DB_TYPES.mysql, osuser)
db.delete() db.delete()
taskres = TaskResult.objects.all() taskres = TaskResult.objects.all()
self.assertEqual(len(taskres), 3) self.assertEqual(len(taskres), 3)
self.assertEqual(taskres[2].creator, 'handle_userdb_deleted') self.assertEqual(taskres[2].creator, "handle_userdb_deleted")
self.assertEqual(taskres[2].notes, 'mysql database deletion') self.assertEqual(taskres[2].notes, "mysql database deletion")

View file

@ -4,63 +4,60 @@ This module contains explicit tests for corner cases in
:py:mod:`userdbs.tests.test_models`. :py:mod:`userdbs.tests.test_models`.
""" """
from __future__ import unicode_literals from unittest.mock import Mock
from django.test import TestCase from django.test import TestCase
from django.test.utils import override_settings from django.test.utils import override_settings
from taskresults.models import TaskResult from taskresults.models import TaskResult
from userdbs.signals import (handle_dbuser_created, handle_dbuser_deleted, from userdbs.signals import (
handle_dbuser_password_set, handle_userdb_created, handle_dbuser_created,
handle_userdb_deleted) handle_dbuser_deleted,
handle_dbuser_password_set,
try: handle_userdb_created,
from unittest.mock import Mock handle_userdb_deleted,
except ImportError: )
from mock import Mock
@override_settings( @override_settings(
CELERY_ALWAYS_EAGER=True, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
CELERY_CACHE_BACKEND='memory',
BROKER_BACKEND='memory'
) )
class TestCaseWithCeleryTasks(TestCase): class TestCaseWithCeleryTasks(TestCase):
pass pass
class TestWithUnknownDBType(TestCaseWithCeleryTasks): class TestWithUnknownDBType(TestCaseWithCeleryTasks):
def test_handle_dbuser_password_set_unknown(self): def test_handle_dbuser_password_set_unknown(self):
instance = Mock(data={'name': 'test', 'db_type': -1}) instance = Mock(data={"name": "test", "db_type": -1})
handle_dbuser_password_set(Mock(name='sender'), instance, 'secret') handle_dbuser_password_set(Mock(name="sender"), instance, "secret")
self.assertFalse(TaskResult.objects.exists()) self.assertFalse(TaskResult.objects.exists())
def test_handle_dbuser_create_unknown(self): def test_handle_dbuser_create_unknown(self):
instance = Mock(data={'name': 'test', 'db_type': -1}) instance = Mock(data={"name": "test", "db_type": -1})
handle_dbuser_created( handle_dbuser_created(Mock(name="sender"), instance, True, password="secret")
Mock(name='sender'), instance, True, password='secret')
self.assertFalse(TaskResult.objects.exists()) self.assertFalse(TaskResult.objects.exists())
def test_handle_dbuser_deleted_unknown(self): def test_handle_dbuser_deleted_unknown(self):
instance = Mock(data={'name': 'test', 'db_type': -1}) instance = Mock(data={"name": "test", "db_type": -1})
handle_dbuser_deleted(Mock(name='sender'), instance) handle_dbuser_deleted(Mock(name="sender"), instance)
self.assertFalse(TaskResult.objects.exists()) self.assertFalse(TaskResult.objects.exists())
def test_handle_userdb_created_unknown(self): def test_handle_userdb_created_unknown(self):
instance = Mock( instance = Mock(
data={ data={
'db_name': 'test', "db_name": "test",
'db_user': Mock(data={'name': 'test', 'db_type': -1, }) "db_user": Mock(data={"name": "test", "db_type": -1}),
}) }
handle_userdb_created(Mock(name='sender'), instance, True) )
handle_userdb_created(Mock(name="sender"), instance, True)
self.assertFalse(TaskResult.objects.exists()) self.assertFalse(TaskResult.objects.exists())
def test_handle_userdb_deleted_unknown(self): def test_handle_userdb_deleted_unknown(self):
instance = Mock( instance = Mock(
data={ data={
'db_name': 'test', "db_name": "test",
'db_user': Mock(data={'name': 'test', 'db_type': -1, }) "db_user": Mock(data={"name": "test", "db_type": -1}),
}) }
handle_userdb_deleted(Mock(name='sender'), instance) )
handle_userdb_deleted(Mock(name="sender"), instance)
self.assertFalse(TaskResult.objects.exists()) self.assertFalse(TaskResult.objects.exists())

View file

@ -2,16 +2,11 @@
This module provides tests for :py:mod:`userdbs.views`. This module provides tests for :py:mod:`userdbs.views`.
""" """
from __future__ import absolute_import, unicode_literals
try:
from unittest.mock import patch, MagicMock from unittest.mock import patch, MagicMock
except ImportError:
from mock import patch, MagicMock
from django.core.urlresolvers import reverse
from django.test import TestCase from django.test import TestCase
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.urls import reverse
from hostingpackages.models import ( from hostingpackages.models import (
CustomerHostingPackage, CustomerHostingPackage,
@ -26,58 +21,61 @@ from userdbs.views import AddUserDatabase, ChangeDatabaseUserPassword
User = get_user_model() User = get_user_model()
TEST_USER = 'test' TEST_USER = "test"
TEST_PASSWORD = 'secret' TEST_PASSWORD = "secret"
TEST_EMAIL = 'test@example.org' TEST_EMAIL = "test@example.org"
class HostingPackageAwareTestMixin(object): class HostingPackageAwareTestMixin(object):
# noinspection PyMethodMayBeStatic
def _setup_hosting_package(self, customer): def _setup_hosting_package(self, customer):
template = HostingPackageTemplate.objects.create( template = HostingPackageTemplate.objects.create(
name='testpackagetemplate', mailboxcount=10, diskspace=1, name="testpackagetemplate", mailboxcount=10, diskspace=1, diskspace_unit=0
diskspace_unit=0) )
package = CustomerHostingPackage.objects.create_from_template( package = CustomerHostingPackage.objects.create_from_template(
customer, template, 'testpackage') customer, template, "testpackage"
with patch('hostingpackages.models.settings') as hmsettings: )
with patch("hostingpackages.models.settings") as hmsettings:
hmsettings.OSUSER_DEFAULT_GROUPS = [] hmsettings.OSUSER_DEFAULT_GROUPS = []
package.save() package.save()
return package return package
class CustomerUserDatabaseOptionAwareTestMixin(object): class CustomerUserDatabaseOptionAwareTestMixin(object):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(CustomerUserDatabaseOptionAwareTestMixin, self).__init__( super(CustomerUserDatabaseOptionAwareTestMixin, self).__init__(*args, **kwargs)
*args, **kwargs)
self._templates = {} self._templates = {}
def _setup_userdatabaseoption(self, number, dbtype): def _setup_userdatabaseoption(self, number, dbtype):
key = "{}_{}".format(dbtype, number) key = "{}_{}".format(dbtype, number)
if key not in self._templates: if key not in self._templates:
self._templates[key] = UserDatabaseOption.objects.create( self._templates[key] = UserDatabaseOption.objects.create(
number=number, db_type=dbtype) number=number, db_type=dbtype
)
return self._templates[key] return self._templates[key]
def _create_userdatabase_option(self, number=1, dbtype=DB_TYPES.pgsql): def _create_userdatabase_option(self, number=1, dbtype=DB_TYPES.pgsql):
# noinspection PyUnresolvedReferences
return CustomerUserDatabaseOption.objects.create( return CustomerUserDatabaseOption.objects.create(
template=self._setup_userdatabaseoption(number, dbtype), template=self._setup_userdatabaseoption(number, dbtype),
number=number, db_type=dbtype, hosting_package=self.package) number=number,
db_type=dbtype,
hosting_package=self.package,
)
class AddUserDatabaseTest( class AddUserDatabaseTest(
HostingPackageAwareTestMixin, CustomerUserDatabaseOptionAwareTestMixin, HostingPackageAwareTestMixin, CustomerUserDatabaseOptionAwareTestMixin, TestCase
TestCase
): ):
def setUp(self): def setUp(self):
self.customer = User.objects.create_user( self.customer = User.objects.create_user(
username=TEST_USER, password=TEST_PASSWORD) username=TEST_USER, password=TEST_PASSWORD
)
self.package = self._setup_hosting_package(self.customer) self.package = self._setup_hosting_package(self.customer)
def _get_url(self): def _get_url(self):
return reverse( return reverse("add_userdatabase", kwargs={"package": self.package.id})
'add_userdatabase', kwargs={'package': self.package.id})
def test_get_anonymous(self): def test_get_anonymous(self):
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
@ -95,31 +93,29 @@ class AddUserDatabaseTest(
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_get_other_regular_user(self): def test_get_other_regular_user(self):
User.objects.create_user( User.objects.create_user("test2", password=TEST_PASSWORD)
'test2', password=TEST_PASSWORD) self.client.login(username="test2", password=TEST_PASSWORD)
self.client.login(username='test2', password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertEqual(response.status_code, 403) self.assertEqual(response.status_code, 403)
def test_get_staff_user_nodboption(self): def test_get_staff_user_nodboption(self):
User.objects.create_superuser( User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
'admin', email=TEST_EMAIL, password=TEST_PASSWORD) self.client.login(username="admin", password=TEST_PASSWORD)
self.client.login(username='admin', password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertEqual(response.status_code, 400) self.assertEqual(response.status_code, 400)
def test_get_staff_user(self): def test_get_staff_user(self):
self._create_userdatabase_option() self._create_userdatabase_option()
User.objects.create_superuser( User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
'admin', email=TEST_EMAIL, password=TEST_PASSWORD) self.client.login(username="admin", password=TEST_PASSWORD)
self.client.login(username='admin', password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_get_regular_user_nofree_db(self): def test_get_regular_user_nofree_db(self):
db_option = self._create_userdatabase_option() db_option = self._create_userdatabase_option()
UserDatabase.objects.create_userdatabase_with_user( UserDatabase.objects.create_userdatabase_with_user(
db_option.db_type, self.package.osuser) db_option.db_type, self.package.osuser
)
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertEqual(response.status_code, 400) self.assertEqual(response.status_code, 400)
@ -128,21 +124,21 @@ class AddUserDatabaseTest(
db_option = self._create_userdatabase_option() db_option = self._create_userdatabase_option()
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
view = AddUserDatabase( view = AddUserDatabase(
request=MagicMock(), kwargs={'package': str(self.package.pk)}) request=MagicMock(), kwargs={"package": str(self.package.pk)}
)
the_kwargs = view.get_form_kwargs() the_kwargs = view.get_form_kwargs()
self.assertIn('hostingpackage', the_kwargs) self.assertIn("hostingpackage", the_kwargs)
self.assertEqual(the_kwargs['hostingpackage'], self.package) self.assertEqual(the_kwargs["hostingpackage"], self.package)
self.assertIn('dbtypes', the_kwargs) self.assertIn("dbtypes", the_kwargs)
self.assertEqual( self.assertEqual(
the_kwargs['dbtypes'], the_kwargs["dbtypes"], [(db_option.db_type, DB_TYPES[db_option.db_type])]
[(db_option.db_type, DB_TYPES[db_option.db_type])],
) )
def test_get_template(self): def test_get_template(self):
self._create_userdatabase_option() self._create_userdatabase_option()
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get(self._get_url()) response = self.client.get(self._get_url())
self.assertTemplateUsed(response, 'userdbs/userdatabase_create.html') self.assertTemplateUsed(response, "userdbs/userdatabase_create.html")
def test_form_valid_redirect(self): def test_form_valid_redirect(self):
db_option = self._create_userdatabase_option() db_option = self._create_userdatabase_option()
@ -150,48 +146,55 @@ class AddUserDatabaseTest(
response = self.client.post( response = self.client.post(
self._get_url(), self._get_url(),
data={ data={
'db_type': db_option.db_type, 'password1': TEST_PASSWORD, "db_type": db_option.db_type,
'password2': TEST_PASSWORD}) "password1": TEST_PASSWORD,
"password2": TEST_PASSWORD,
},
)
self.assertRedirects(response, self.package.get_absolute_url()) self.assertRedirects(response, self.package.get_absolute_url())
def test_form_valid_message(self): def test_form_valid_message(self):
db_option = self._create_userdatabase_option() db_option = self._create_userdatabase_option()
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.post( response = self.client.post(
self._get_url(), follow=True, self._get_url(),
follow=True,
data={ data={
'db_type': db_option.db_type, 'password1': TEST_PASSWORD, "db_type": db_option.db_type,
'password2': TEST_PASSWORD}) "password1": TEST_PASSWORD,
db = UserDatabase.objects.filter( "password2": TEST_PASSWORD,
db_user__osuser=self.package.osuser).get() },
messages = list(response.context['messages']) )
db = UserDatabase.objects.filter(db_user__osuser=self.package.osuser).get()
messages = list(response.context["messages"])
self.assertEqual(len(messages), 1) self.assertEqual(len(messages), 1)
self.assertEqual( self.assertEqual(
str(messages[0]), ( str(messages[0]),
'Successfully create new {type} database {dbname} for user ' (
'{dbuser}.').format( "Successfully create new {type} database {dbname} for user " "{dbuser}."
type=db.db_user.db_type, dbname=db.db_name, ).format(type=db.db_user.db_type, dbname=db.db_name, dbuser=db.db_user),
dbuser=db.db_user)) )
class ChangeDatabaseUserPasswordTest( class ChangeDatabaseUserPasswordTest(
HostingPackageAwareTestMixin, CustomerUserDatabaseOptionAwareTestMixin, HostingPackageAwareTestMixin, CustomerUserDatabaseOptionAwareTestMixin, TestCase
TestCase
): ):
def setUp(self): def setUp(self):
self.customer = User.objects.create_user( self.customer = User.objects.create_user(
username=TEST_USER, password=TEST_PASSWORD) username=TEST_USER, password=TEST_PASSWORD
)
self.package = self._setup_hosting_package(self.customer) self.package = self._setup_hosting_package(self.customer)
template = self._create_userdatabase_option() template = self._create_userdatabase_option()
database = UserDatabase.objects.create_userdatabase_with_user( database = UserDatabase.objects.create_userdatabase_with_user(
template.db_type, self.package.osuser) template.db_type, self.package.osuser
)
self.dbuser = database.db_user self.dbuser = database.db_user
def _get_url(self, dbuser): def _get_url(self, dbuser):
return reverse( return reverse(
'change_dbuser_password', kwargs={ "change_dbuser_password",
'package': self.package.id, 'slug': dbuser.name}) kwargs={"package": self.package.id, "slug": dbuser.name},
)
def test_get_anonymous(self): def test_get_anonymous(self):
response = self.client.get(self._get_url(self.dbuser)) response = self.client.get(self._get_url(self.dbuser))
@ -203,80 +206,85 @@ class ChangeDatabaseUserPasswordTest(
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_get_other_regular_user(self): def test_get_other_regular_user(self):
User.objects.create_user( User.objects.create_user("test2", password=TEST_PASSWORD)
'test2', password=TEST_PASSWORD) self.client.login(username="test2", password=TEST_PASSWORD)
self.client.login(username='test2', password=TEST_PASSWORD)
response = self.client.get(self._get_url(self.dbuser)) response = self.client.get(self._get_url(self.dbuser))
self.assertEqual(response.status_code, 403) self.assertEqual(response.status_code, 403)
def test_get_staff_user(self): def test_get_staff_user(self):
User.objects.create_superuser( User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
'admin', email=TEST_EMAIL, password=TEST_PASSWORD) self.client.login(username="admin", password=TEST_PASSWORD)
self.client.login(username='admin', password=TEST_PASSWORD)
response = self.client.get(self._get_url(self.dbuser)) response = self.client.get(self._get_url(self.dbuser))
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_get_template(self): def test_get_template(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get(self._get_url(self.dbuser)) response = self.client.get(self._get_url(self.dbuser))
self.assertTemplateUsed( self.assertTemplateUsed(response, "userdbs/databaseuser_setpassword.html")
response, 'userdbs/databaseuser_setpassword.html')
def test_get_form_kwargs(self): def test_get_form_kwargs(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
view = ChangeDatabaseUserPassword(request=MagicMock(), kwargs={ view = ChangeDatabaseUserPassword(
'package': str(self.package.pk), 'slug': self.dbuser.name}) request=MagicMock(),
kwargs={"package": str(self.package.pk), "slug": self.dbuser.name},
)
the_kwargs = view.get_form_kwargs() the_kwargs = view.get_form_kwargs()
self.assertIn('hostingpackage', the_kwargs) self.assertIn("hostingpackage", the_kwargs)
self.assertEqual(the_kwargs['hostingpackage'], self.package) self.assertEqual(the_kwargs["hostingpackage"], self.package)
def test_get_context_data(self): def test_get_context_data(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get(self._get_url(self.dbuser)) response = self.client.get(self._get_url(self.dbuser))
self.assertIn('dbuser', response.context) self.assertIn("dbuser", response.context)
self.assertEqual(response.context['dbuser'], self.dbuser) self.assertEqual(response.context["dbuser"], self.dbuser)
self.assertIn('hostingpackage', response.context) self.assertIn("hostingpackage", response.context)
self.assertEqual(response.context['hostingpackage'], self.package) self.assertEqual(response.context["hostingpackage"], self.package)
self.assertIn('customer', response.context) self.assertIn("customer", response.context)
self.assertEqual(response.context['customer'], self.customer) self.assertEqual(response.context["customer"], self.customer)
def test_form_valid_redirect(self): def test_form_valid_redirect(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.post(self._get_url(self.dbuser), data={ response = self.client.post(
'password1': TEST_PASSWORD, 'password2': TEST_PASSWORD}) self._get_url(self.dbuser),
data={"password1": TEST_PASSWORD, "password2": TEST_PASSWORD},
)
self.assertRedirects(response, self.package.get_absolute_url()) self.assertRedirects(response, self.package.get_absolute_url())
def test_form_valid_message(self): def test_form_valid_message(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.post( response = self.client.post(
self._get_url(self.dbuser), follow=True, data={ self._get_url(self.dbuser),
'password1': TEST_PASSWORD, 'password2': TEST_PASSWORD}) follow=True,
messages = list(response.context['messages']) data={"password1": TEST_PASSWORD, "password2": TEST_PASSWORD},
)
messages = list(response.context["messages"])
self.assertEqual(len(messages), 1) self.assertEqual(len(messages), 1)
self.assertEqual( self.assertEqual(
str(messages[0]), str(messages[0]),
'Successfully changed password of database user {dbuser}.'.format( "Successfully changed password of database user {dbuser}.".format(
dbuser=self.dbuser.name)) dbuser=self.dbuser.name
),
)
class DeleteUserDatabaseTest( class DeleteUserDatabaseTest(
HostingPackageAwareTestMixin, CustomerUserDatabaseOptionAwareTestMixin, HostingPackageAwareTestMixin, CustomerUserDatabaseOptionAwareTestMixin, TestCase
TestCase
): ):
def setUp(self): def setUp(self):
self.customer = User.objects.create_user( self.customer = User.objects.create_user(
username=TEST_USER, password=TEST_PASSWORD) username=TEST_USER, password=TEST_PASSWORD
)
self.package = self._setup_hosting_package(self.customer) self.package = self._setup_hosting_package(self.customer)
template = self._create_userdatabase_option() template = self._create_userdatabase_option()
self.database = UserDatabase.objects.create_userdatabase_with_user( self.database = UserDatabase.objects.create_userdatabase_with_user(
template.db_type, self.package.osuser) template.db_type, self.package.osuser
)
def _get_url(self, userdatabase): def _get_url(self, userdatabase):
return reverse( return reverse(
'delete_userdatabase', kwargs={ "delete_userdatabase",
'package': self.package.id, kwargs={"package": self.package.id, "slug": userdatabase.db_name},
'slug': userdatabase.db_name}) )
def test_get_anonymous(self): def test_get_anonymous(self):
response = self.client.get(self._get_url(self.database)) response = self.client.get(self._get_url(self.database))
@ -288,34 +296,31 @@ class DeleteUserDatabaseTest(
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_get_other_regular_user(self): def test_get_other_regular_user(self):
User.objects.create_user( User.objects.create_user("test2", password=TEST_PASSWORD)
'test2', password=TEST_PASSWORD) self.client.login(username="test2", password=TEST_PASSWORD)
self.client.login(username='test2', password=TEST_PASSWORD)
response = self.client.get(self._get_url(self.database)) response = self.client.get(self._get_url(self.database))
self.assertEqual(response.status_code, 403) self.assertEqual(response.status_code, 403)
def test_get_staff_user(self): def test_get_staff_user(self):
User.objects.create_superuser( User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
'admin', email=TEST_EMAIL, password=TEST_PASSWORD) self.client.login(username="admin", password=TEST_PASSWORD)
self.client.login(username='admin', password=TEST_PASSWORD)
response = self.client.get(self._get_url(self.database)) response = self.client.get(self._get_url(self.database))
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_get_template(self): def test_get_template(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get(self._get_url(self.database)) response = self.client.get(self._get_url(self.database))
self.assertTemplateUsed( self.assertTemplateUsed(response, "userdbs/userdatabase_confirm_delete.html")
response, 'userdbs/userdatabase_confirm_delete.html')
def test_get_context_data(self): def test_get_context_data(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.get(self._get_url(self.database)) response = self.client.get(self._get_url(self.database))
self.assertIn('database', response.context) self.assertIn("database", response.context)
self.assertEqual(response.context['database'], self.database) self.assertEqual(response.context["database"], self.database)
self.assertIn('hostingpackage', response.context) self.assertIn("hostingpackage", response.context)
self.assertEqual(response.context['hostingpackage'], self.package) self.assertEqual(response.context["hostingpackage"], self.package)
self.assertIn('customer', response.context) self.assertIn("customer", response.context)
self.assertEqual(response.context['customer'], self.customer) self.assertEqual(response.context["customer"], self.customer)
def test_form_valid_redirect(self): def test_form_valid_redirect(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
@ -325,6 +330,6 @@ class DeleteUserDatabaseTest(
def test_form_valid_message(self): def test_form_valid_message(self):
self.client.login(username=TEST_USER, password=TEST_PASSWORD) self.client.login(username=TEST_USER, password=TEST_PASSWORD)
response = self.client.post(self._get_url(self.database), follow=True) response = self.client.post(self._get_url(self.database), follow=True)
messages = list(response.context['messages']) messages = list(response.context["messages"])
self.assertEqual(len(messages), 1) self.assertEqual(len(messages), 1)
self.assertEqual(str(messages[0]), "Database deleted.") self.assertEqual(str(messages[0]), "Database deleted.")