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:
parent
ddec6b4184
commit
3d18392b67
32 changed files with 2707 additions and 2675 deletions
|
@ -2,26 +2,18 @@
|
|||
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.test import TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from contact_form.forms import ContactForm
|
||||
|
||||
TEST_DATA = {
|
||||
'name': 'Test User',
|
||||
'email': 'test@example.org',
|
||||
'body': 'Test message'
|
||||
}
|
||||
TEST_DATA = {"name": "Test User", "email": "test@example.org", "body": "Test message"}
|
||||
|
||||
|
||||
class ContactFormTest(TestCase):
|
||||
|
||||
def test_constructor_needs_request(self):
|
||||
with self.assertRaises(KeyError):
|
||||
ContactForm()
|
||||
|
@ -29,63 +21,63 @@ class ContactFormTest(TestCase):
|
|||
def test_constructor(self):
|
||||
request = MagicMock()
|
||||
form = ContactForm(request=request)
|
||||
self.assertTrue(hasattr(form, 'request'))
|
||||
self.assertTrue(hasattr(form, "request"))
|
||||
self.assertEqual(form.request, request)
|
||||
self.assertTrue(hasattr(form, 'helper'))
|
||||
self.assertEqual(form.helper.form_action, reverse('contact_form'))
|
||||
self.assertTrue(hasattr(form, "helper"))
|
||||
self.assertEqual(form.helper.form_action, reverse("contact_form"))
|
||||
self.assertEqual(len(form.helper.inputs), 1)
|
||||
self.assertEqual(form.helper.inputs[0].name, 'submit')
|
||||
self.assertEqual(form.helper.inputs[0].name, "submit")
|
||||
|
||||
def test_constructor_fields(self):
|
||||
request = MagicMock()
|
||||
form = ContactForm(request=request)
|
||||
self.assertEqual(len(form.fields), 3)
|
||||
self.assertIn('email', form.fields)
|
||||
self.assertIn('name', form.fields)
|
||||
self.assertIn('body', form.fields)
|
||||
self.assertIn("email", form.fields)
|
||||
self.assertIn("name", form.fields)
|
||||
self.assertIn("body", form.fields)
|
||||
self.assertEqual(len(form.data), 0)
|
||||
|
||||
def test_get_context_invalid(self):
|
||||
request = MagicMock()
|
||||
form = ContactForm(request=request)
|
||||
with self.assertRaisesMessage(
|
||||
ValueError,
|
||||
'Cannot generate context from invalid contact form'):
|
||||
ValueError, "Cannot generate context from invalid contact form"
|
||||
):
|
||||
form.get_context()
|
||||
|
||||
def test_get_context_valid_site_installed(self):
|
||||
request = MagicMock()
|
||||
form = ContactForm(request=request, data=TEST_DATA)
|
||||
context = form.get_context()
|
||||
self.assertIn('site', context)
|
||||
self.assertIn('name', context)
|
||||
self.assertIn('email', context)
|
||||
self.assertIn('body', context)
|
||||
self.assertIn("site", context)
|
||||
self.assertIn("name", context)
|
||||
self.assertIn("email", context)
|
||||
self.assertIn("body", context)
|
||||
|
||||
def test_get_context_valid_site_not_installed(self):
|
||||
request = MagicMock()
|
||||
form = ContactForm(request=request, data=TEST_DATA)
|
||||
with mock.patch('contact_form.forms.Site') as sitemock:
|
||||
with patch("contact_form.forms.Site") as sitemock:
|
||||
sitemock._meta.installed = False
|
||||
context = form.get_context()
|
||||
self.assertIn('site', context)
|
||||
self.assertIn('name', context)
|
||||
self.assertIn('email', context)
|
||||
self.assertIn('body', context)
|
||||
self.assertIn("site", context)
|
||||
self.assertIn("name", context)
|
||||
self.assertIn("email", context)
|
||||
self.assertIn("body", context)
|
||||
|
||||
def test_message(self):
|
||||
request = Mock()
|
||||
request.META = {'REMOTE_ADDR': '127.0.0.1'}
|
||||
request.META = {"REMOTE_ADDR": "127.0.0.1"}
|
||||
form = ContactForm(request=request, data=TEST_DATA)
|
||||
message = form.message()
|
||||
self.assertIn(TEST_DATA['name'], message)
|
||||
self.assertIn(TEST_DATA['email'], message)
|
||||
self.assertIn(TEST_DATA['body'], message)
|
||||
self.assertIn('127.0.0.1', message)
|
||||
self.assertIn(TEST_DATA["name"], message)
|
||||
self.assertIn(TEST_DATA["email"], message)
|
||||
self.assertIn(TEST_DATA["body"], message)
|
||||
self.assertIn("127.0.0.1", message)
|
||||
|
||||
def test_subject(self):
|
||||
request = Mock()
|
||||
form = ContactForm(request=request, data=TEST_DATA)
|
||||
subject = form.subject()
|
||||
self.assertIn(Site.objects.get_current().name, subject)
|
||||
self.assertIn(TEST_DATA['name'], subject)
|
||||
self.assertIn(TEST_DATA["name"], subject)
|
||||
|
|
|
@ -2,126 +2,122 @@
|
|||
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.core import mail
|
||||
from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
User = get_user_model()
|
||||
|
||||
TEST_USER = 'test'
|
||||
TEST_PASSWORD = 'secret'
|
||||
TEST_EMAIL = 'test@example.org'
|
||||
TEST_NAME = 'Example Tester'.split()
|
||||
TEST_MESSAGE = '''
|
||||
TEST_USER = "test"
|
||||
TEST_PASSWORD = "secret"
|
||||
TEST_EMAIL = "test@example.org"
|
||||
TEST_NAME = "Example Tester".split()
|
||||
TEST_MESSAGE = """
|
||||
This is a really unimportant test message.
|
||||
'''
|
||||
"""
|
||||
|
||||
|
||||
class ContactFormViewTest(TestCase):
|
||||
|
||||
def _setup_user(self, **kwargs):
|
||||
return User.objects.create_user(
|
||||
TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD,
|
||||
**kwargs)
|
||||
TEST_USER, email=TEST_EMAIL, password=TEST_PASSWORD, **kwargs
|
||||
)
|
||||
|
||||
def test_get_contact_form_template(self):
|
||||
response = self.client.get(reverse('contact_form'))
|
||||
self.assertTemplateUsed(response, 'contact_form/contact_form.html')
|
||||
response = self.client.get(reverse("contact_form"))
|
||||
self.assertTemplateUsed(response, "contact_form/contact_form.html")
|
||||
|
||||
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)
|
||||
|
||||
def test_get_contact_form_anonymous_has_empty_form(self):
|
||||
response = self.client.get(reverse('contact_form'))
|
||||
self.assertIn('form', response.context)
|
||||
form = response.context['form']
|
||||
response = self.client.get(reverse("contact_form"))
|
||||
self.assertIn("form", response.context)
|
||||
form = response.context["form"]
|
||||
self.assertEqual(len(form.initial), 0)
|
||||
|
||||
def test_get_contact_form_fields_anonymous(self):
|
||||
response = self.client.get(reverse('contact_form'))
|
||||
for name in ('name', 'email', 'body'):
|
||||
self.assertIn(name, response.context['form'].fields)
|
||||
response = self.client.get(reverse("contact_form"))
|
||||
for name in ("name", "email", "body"):
|
||||
self.assertIn(name, response.context["form"].fields)
|
||||
|
||||
def test_post_empty_form_template(self):
|
||||
response = self.client.post(reverse('contact_form'), {})
|
||||
self.assertTemplateUsed(response, 'contact_form/contact_form.html')
|
||||
response = self.client.post(reverse("contact_form"), {})
|
||||
self.assertTemplateUsed(response, "contact_form/contact_form.html")
|
||||
|
||||
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)
|
||||
|
||||
def test_post_empty_form_validation_errors(self):
|
||||
response = self.client.post(reverse('contact_form'), {})
|
||||
self.assertIn('form', response.context)
|
||||
form = response.context['form']
|
||||
response = self.client.post(reverse("contact_form"), {})
|
||||
self.assertIn("form", response.context)
|
||||
form = response.context["form"]
|
||||
self.assertFalse(form.is_valid())
|
||||
self.assertEqual(len(form.errors), 3)
|
||||
|
||||
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)
|
||||
|
||||
def test_get_contact_form_logged_in_no_fullname_initial(self):
|
||||
self._setup_user()
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.get(reverse('contact_form'))
|
||||
self.assertIn('form', response.context)
|
||||
form = response.context['form']
|
||||
self.assertEqual(
|
||||
form.initial, {'name': TEST_USER, 'email': TEST_EMAIL})
|
||||
response = self.client.get(reverse("contact_form"))
|
||||
self.assertIn("form", response.context)
|
||||
form = response.context["form"]
|
||||
self.assertEqual(form.initial, {"name": TEST_USER, "email": TEST_EMAIL})
|
||||
|
||||
def test_get_contact_form_logged_in_fullname_initial(self):
|
||||
self._setup_user(
|
||||
first_name=TEST_NAME[0], last_name=TEST_NAME[1])
|
||||
self._setup_user(first_name=TEST_NAME[0], last_name=TEST_NAME[1])
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.get(reverse('contact_form'))
|
||||
self.assertIn('form', response.context)
|
||||
form = response.context['form']
|
||||
response = self.client.get(reverse("contact_form"))
|
||||
self.assertIn("form", response.context)
|
||||
form = response.context["form"]
|
||||
self.assertEqual(
|
||||
form.initial,
|
||||
{'name': " ".join(TEST_NAME), 'email': TEST_EMAIL})
|
||||
form.initial, {"name": " ".join(TEST_NAME), "email": TEST_EMAIL}
|
||||
)
|
||||
|
||||
def test_post_filled_form_anonymous_redirects(self):
|
||||
response = self.client.post(reverse('contact_form'), {
|
||||
'name': TEST_USER, 'email': TEST_EMAIL, 'body': TEST_MESSAGE})
|
||||
self.assertRedirects(response, reverse('contact_success'))
|
||||
response = self.client.post(
|
||||
reverse("contact_form"),
|
||||
{"name": TEST_USER, "email": TEST_EMAIL, "body": TEST_MESSAGE},
|
||||
)
|
||||
self.assertRedirects(response, reverse("contact_success"))
|
||||
|
||||
def test_post_filled_form_anonymous_mail(self):
|
||||
self.client.post(reverse('contact_form'), {
|
||||
'name': TEST_USER, 'email': TEST_EMAIL, 'body': TEST_MESSAGE})
|
||||
self.client.post(
|
||||
reverse("contact_form"),
|
||||
{"name": TEST_USER, "email": TEST_EMAIL, "body": TEST_MESSAGE},
|
||||
)
|
||||
self.assertEqual(len(mail.outbox), 1)
|
||||
|
||||
def test_post_filled_form_logged_in_redirects(self):
|
||||
self._setup_user(
|
||||
first_name=TEST_NAME[0], last_name=TEST_NAME[1])
|
||||
self._setup_user(first_name=TEST_NAME[0], last_name=TEST_NAME[1])
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.post(reverse('contact_form'), {
|
||||
'name': " ".join(TEST_NAME), 'email': TEST_EMAIL,
|
||||
'body': TEST_MESSAGE})
|
||||
self.assertRedirects(response, reverse('contact_success'))
|
||||
response = self.client.post(
|
||||
reverse("contact_form"),
|
||||
{"name": " ".join(TEST_NAME), "email": TEST_EMAIL, "body": TEST_MESSAGE},
|
||||
)
|
||||
self.assertRedirects(response, reverse("contact_success"))
|
||||
|
||||
def test_post_filled_form_logged_in_mail(self):
|
||||
self._setup_user(
|
||||
first_name=TEST_NAME[0], last_name=TEST_NAME[1])
|
||||
self._setup_user(first_name=TEST_NAME[0], last_name=TEST_NAME[1])
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
self.client.post(reverse('contact_form'), {
|
||||
'name': " ".join(TEST_NAME), 'email': TEST_EMAIL,
|
||||
'body': TEST_MESSAGE})
|
||||
self.client.post(
|
||||
reverse("contact_form"),
|
||||
{"name": " ".join(TEST_NAME), "email": TEST_EMAIL, "body": TEST_MESSAGE},
|
||||
)
|
||||
self.assertEqual(len(mail.outbox), 1)
|
||||
|
||||
|
||||
class ContactSuccessViewTest(TestCase):
|
||||
|
||||
def test_get_template(self):
|
||||
response = self.client.get(reverse('contact_success'))
|
||||
self.assertTemplateUsed(response, 'contact_form/contact_success.html')
|
||||
response = self.client.get(reverse("contact_success"))
|
||||
self.assertTemplateUsed(response, "contact_form/contact_success.html")
|
||||
|
||||
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)
|
||||
|
|
|
@ -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.test import TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
User = get_user_model()
|
||||
|
||||
TEST_USER = 'test'
|
||||
TEST_PASSWORD = 'secret'
|
||||
TEST_USER = "test"
|
||||
TEST_PASSWORD = "secret"
|
||||
|
||||
|
||||
class IndexViewTest(TestCase):
|
||||
|
||||
def test_index_view(self):
|
||||
response = self.client.get(reverse('dashboard'))
|
||||
response = self.client.get(reverse("dashboard"))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertTemplateUsed(response, 'dashboard/index.html')
|
||||
self.assertTemplateUsed(response, "dashboard/index.html")
|
||||
|
||||
|
||||
class UserDashboardViewTest(TestCase):
|
||||
|
||||
def _create_test_user(self):
|
||||
self.user = User.objects.create(username=TEST_USER)
|
||||
self.user.set_password(TEST_PASSWORD)
|
||||
self.user.save()
|
||||
|
||||
def test_user_dashboard_view_no_user(self):
|
||||
response = self.client.get(reverse(
|
||||
'customer_dashboard', kwargs={'slug': TEST_USER}))
|
||||
response = self.client.get(
|
||||
reverse("customer_dashboard", kwargs={"slug": TEST_USER})
|
||||
)
|
||||
self.assertEqual(response.status_code, 404)
|
||||
|
||||
def test_user_dashboard_view_anonymous(self):
|
||||
User.objects.create(username=TEST_USER)
|
||||
response = self.client.get(reverse(
|
||||
'customer_dashboard', kwargs={'slug': TEST_USER}))
|
||||
response = self.client.get(
|
||||
reverse("customer_dashboard", kwargs={"slug": TEST_USER})
|
||||
)
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_user_dashboard_view_logged_in_ok(self):
|
||||
self._create_test_user()
|
||||
self.assertTrue(
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD))
|
||||
response = self.client.get(reverse(
|
||||
'customer_dashboard', kwargs={'slug': TEST_USER}))
|
||||
self.assertTrue(self.client.login(username=TEST_USER, password=TEST_PASSWORD))
|
||||
response = self.client.get(
|
||||
reverse("customer_dashboard", kwargs={"slug": TEST_USER})
|
||||
)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_user_dashboard_view_logged_in_template(self):
|
||||
self._create_test_user()
|
||||
self.assertTrue(
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD))
|
||||
response = self.client.get(reverse(
|
||||
'customer_dashboard', kwargs={'slug': TEST_USER}))
|
||||
self.assertTemplateUsed(response, 'dashboard/user_dashboard.html')
|
||||
self.assertTrue(self.client.login(username=TEST_USER, password=TEST_PASSWORD))
|
||||
response = self.client.get(
|
||||
reverse("customer_dashboard", kwargs={"slug": TEST_USER})
|
||||
)
|
||||
self.assertTemplateUsed(response, "dashboard/user_dashboard.html")
|
||||
|
||||
def test_user_dashboard_view_logged_in_context_fresh(self):
|
||||
self._create_test_user()
|
||||
self.assertTrue(
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD))
|
||||
response = self.client.get(reverse(
|
||||
'customer_dashboard', kwargs={'slug': TEST_USER}))
|
||||
self.assertIn('dashboard_user', response.context)
|
||||
self.assertEqual(self.user, response.context['dashboard_user'])
|
||||
self.assertIn('hosting_packages', response.context)
|
||||
self.assertEqual(len(response.context['hosting_packages']), 0)
|
||||
self.assertTrue(self.client.login(username=TEST_USER, password=TEST_PASSWORD))
|
||||
response = self.client.get(
|
||||
reverse("customer_dashboard", kwargs={"slug": TEST_USER})
|
||||
)
|
||||
self.assertIn("dashboard_user", response.context)
|
||||
self.assertEqual(self.user, response.context["dashboard_user"])
|
||||
self.assertIn("hosting_packages", response.context)
|
||||
self.assertEqual(len(response.context["hosting_packages"]), 0)
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
from django.test import TestCase
|
||||
from django.core.urlresolvers import reverse
|
||||
from django.urls import reverse
|
||||
|
||||
|
||||
class TestMailDomainAdmin(TestCase):
|
||||
def test_admin_for_maildomain(self):
|
||||
admin_url = reverse('admin:domains_maildomain_changelist')
|
||||
admin_url = reverse("admin:domains_maildomain_changelist")
|
||||
self.assertIsNotNone(admin_url)
|
||||
|
|
|
@ -2,51 +2,42 @@
|
|||
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.test import TestCase
|
||||
from django.urls import reverse
|
||||
from django.utils.translation import ugettext as _
|
||||
|
||||
from domains.forms import relative_domain_validator, CreateHostingDomainForm
|
||||
|
||||
|
||||
class RelativeDomainValidatorTest(TestCase):
|
||||
|
||||
def test_valid_domainname(self):
|
||||
relative_domain_validator('example.org')
|
||||
relative_domain_validator("example.org")
|
||||
|
||||
def test_domain_name_too_long(self):
|
||||
with self.assertRaisesMessage(
|
||||
ValidationError, _('host name too long')):
|
||||
relative_domain_validator('e' * 255)
|
||||
with self.assertRaisesMessage(ValidationError, _("host name too long")):
|
||||
relative_domain_validator("e" * 255)
|
||||
|
||||
def test_domain_name_part_too_long(self):
|
||||
with self.assertRaisesMessage(
|
||||
ValidationError, _('invalid domain name')):
|
||||
relative_domain_validator('a' * 64 + '.org')
|
||||
with self.assertRaisesMessage(ValidationError, _("invalid domain name")):
|
||||
relative_domain_validator("a" * 64 + ".org")
|
||||
|
||||
def test_domain_name_illegal_characters(self):
|
||||
with self.assertRaisesMessage(
|
||||
ValidationError, _('invalid domain name')):
|
||||
relative_domain_validator('eXampl3.org')
|
||||
with self.assertRaisesMessage(ValidationError, _("invalid domain name")):
|
||||
relative_domain_validator("eXampl3.org")
|
||||
|
||||
def test_domain_name_starts_with_dash(self):
|
||||
with self.assertRaisesMessage(
|
||||
ValidationError, _('invalid domain name')):
|
||||
relative_domain_validator('-example.org')
|
||||
with self.assertRaisesMessage(ValidationError, _("invalid domain name")):
|
||||
relative_domain_validator("-example.org")
|
||||
|
||||
def test_domain_name_ends_with_dash(self):
|
||||
with self.assertRaisesMessage(
|
||||
ValidationError, _('invalid domain name')):
|
||||
relative_domain_validator('example-.org')
|
||||
with self.assertRaisesMessage(ValidationError, _("invalid domain name")):
|
||||
relative_domain_validator("example-.org")
|
||||
|
||||
|
||||
class CreateHostingDomainFormTest(TestCase):
|
||||
|
||||
def test_constructor_needs_hostingpackage(self):
|
||||
instance = MagicMock()
|
||||
with self.assertRaises(KeyError):
|
||||
|
@ -56,50 +47,53 @@ class CreateHostingDomainFormTest(TestCase):
|
|||
hostingpackage = Mock(id=42)
|
||||
instance = MagicMock()
|
||||
form = CreateHostingDomainForm(instance, hostingpackage=hostingpackage)
|
||||
self.assertTrue(hasattr(form, 'hosting_package'))
|
||||
self.assertTrue(hasattr(form, "hosting_package"))
|
||||
self.assertEqual(form.hosting_package, hostingpackage)
|
||||
self.assertTrue(hasattr(form, 'helper'))
|
||||
self.assertEqual(form.helper.form_action, reverse(
|
||||
'create_hosting_domain', kwargs={'package': 42}))
|
||||
self.assertTrue(hasattr(form, "helper"))
|
||||
self.assertEqual(
|
||||
form.helper.form_action,
|
||||
reverse("create_hosting_domain", kwargs={"package": 42}),
|
||||
)
|
||||
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):
|
||||
hostingpackage = Mock(id=42)
|
||||
instance = MagicMock()
|
||||
form = CreateHostingDomainForm(instance, hostingpackage=hostingpackage)
|
||||
self.assertIn(
|
||||
relative_domain_validator, form.fields['domain'].validators)
|
||||
self.assertIn(relative_domain_validator, form.fields["domain"].validators)
|
||||
|
||||
def test_clean(self):
|
||||
hostingpackage = Mock(id=42)
|
||||
instance = MagicMock()
|
||||
form = CreateHostingDomainForm(
|
||||
instance, hostingpackage=hostingpackage,
|
||||
data={'domain': 'example.org'})
|
||||
instance, hostingpackage=hostingpackage, data={"domain": "example.org"}
|
||||
)
|
||||
self.assertTrue(form.is_valid())
|
||||
self.assertIn('hosting_package', form.cleaned_data)
|
||||
self.assertEqual(hostingpackage, form.cleaned_data['hosting_package'])
|
||||
self.assertIn("hosting_package", form.cleaned_data)
|
||||
self.assertEqual(hostingpackage, form.cleaned_data["hosting_package"])
|
||||
|
||||
def test_save(self):
|
||||
hostingpackage = Mock(id=42)
|
||||
instance = MagicMock()
|
||||
form = CreateHostingDomainForm(
|
||||
instance, hostingpackage=hostingpackage,
|
||||
data={'domain': 'example.org'})
|
||||
instance, hostingpackage=hostingpackage, data={"domain": "example.org"}
|
||||
)
|
||||
self.assertTrue(form.is_valid())
|
||||
with patch('domains.forms.HostingDomain') as domain:
|
||||
with patch("domains.forms.HostingDomain") as domain:
|
||||
form.save()
|
||||
domain.objects.create_for_hosting_package.assert_called_with(
|
||||
commit=True, **form.cleaned_data)
|
||||
commit=True, **form.cleaned_data
|
||||
)
|
||||
form.save(commit=False)
|
||||
domain.objects.create_for_hosting_package.assert_called_with(
|
||||
commit=False, **form.cleaned_data)
|
||||
commit=False, **form.cleaned_data
|
||||
)
|
||||
|
||||
def test_save_m2m(self):
|
||||
hostingpackage = Mock(id=42)
|
||||
instance = MagicMock()
|
||||
form = CreateHostingDomainForm(
|
||||
instance, hostingpackage=hostingpackage,
|
||||
data={'domain': 'example.org'})
|
||||
instance, hostingpackage=hostingpackage, data={"domain": "example.org"}
|
||||
)
|
||||
form.save_m2m()
|
||||
|
|
|
@ -2,9 +2,7 @@
|
|||
Tests for :py:mod:`domains.models`.
|
||||
|
||||
"""
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
from mock import patch
|
||||
from unittest.mock import patch
|
||||
|
||||
from django.test import TestCase
|
||||
from django.contrib.auth import get_user_model
|
||||
|
@ -20,41 +18,38 @@ from domains.models import (
|
|||
HostingDomain,
|
||||
MailDomain,
|
||||
)
|
||||
from hostingpackages.models import (
|
||||
CustomerHostingPackage,
|
||||
HostingPackageTemplate,
|
||||
)
|
||||
from hostingpackages.models import CustomerHostingPackage, HostingPackageTemplate
|
||||
|
||||
|
||||
User = get_user_model()
|
||||
|
||||
TEST_USER = 'test'
|
||||
TEST_USER = "test"
|
||||
|
||||
|
||||
class MailDomainTest(TestCase):
|
||||
|
||||
def test___str__(self):
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
self.assertEqual(str(md), 'example.org')
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
self.assertEqual(str(md), "example.org")
|
||||
|
||||
def test_get_mailaddresses(self):
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
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.mailaddresses)
|
||||
|
||||
|
||||
class HostingDomainManagerTest(TestCase):
|
||||
|
||||
def _setup_hosting_package(self):
|
||||
template = HostingPackageTemplate.objects.create(
|
||||
name='testpackagetemplate', mailboxcount=0, diskspace=1,
|
||||
diskspace_unit=0)
|
||||
name="testpackagetemplate", mailboxcount=0, diskspace=1, diskspace_unit=0
|
||||
)
|
||||
customer = User.objects.create_user(username=TEST_USER)
|
||||
package = CustomerHostingPackage.objects.create_from_template(
|
||||
customer, template, 'testpackage')
|
||||
with patch('hostingpackages.models.settings') as hmsettings:
|
||||
customer, template, "testpackage"
|
||||
)
|
||||
with patch("hostingpackages.models.settings") as hmsettings:
|
||||
hmsettings.OSUSER_DEFAULT_GROUPS = []
|
||||
package.save()
|
||||
return package
|
||||
|
@ -62,7 +57,8 @@ class HostingDomainManagerTest(TestCase):
|
|||
def test_create_for_hosting_package_with_commit(self):
|
||||
package = self._setup_hosting_package()
|
||||
hostingdomain = HostingDomain.objects.create_for_hosting_package(
|
||||
package, 'example.org', True)
|
||||
package, "example.org", True
|
||||
)
|
||||
|
||||
self.assertIsNotNone(hostingdomain)
|
||||
self.assertTrue(hostingdomain.customer, package.customer)
|
||||
|
@ -70,70 +66,60 @@ class HostingDomainManagerTest(TestCase):
|
|||
def test_create_for_hosting_package_no_commit(self):
|
||||
package = self._setup_hosting_package()
|
||||
hostingdomain = HostingDomain.objects.create_for_hosting_package(
|
||||
package, 'example.org', False)
|
||||
package, "example.org", False
|
||||
)
|
||||
|
||||
self.assertIsNotNone(hostingdomain)
|
||||
self.assertTrue(hostingdomain.customer, package.customer)
|
||||
|
||||
|
||||
class HostingDomainTest(TestCase):
|
||||
|
||||
def test___str__(self):
|
||||
hostingdomain = HostingDomain(domain='test')
|
||||
self.assertEqual(str(hostingdomain), 'test')
|
||||
hostingdomain = HostingDomain(domain="test")
|
||||
self.assertEqual(str(hostingdomain), "test")
|
||||
|
||||
|
||||
class DNSDomainTest(TestCase):
|
||||
|
||||
def test___str__(self):
|
||||
dnsdomain = DNSDomain(domain='test')
|
||||
self.assertEqual(str(dnsdomain), 'test')
|
||||
dnsdomain = DNSDomain(domain="test")
|
||||
self.assertEqual(str(dnsdomain), "test")
|
||||
|
||||
|
||||
class DNSRecordTest(TestCase):
|
||||
|
||||
def test___str__(self):
|
||||
dnsrecord = DNSRecord(
|
||||
name='localhost', recordtype='A', content='127.0.0.1')
|
||||
self.assertEqual(str(dnsrecord), 'localhost IN A 127.0.0.1')
|
||||
dnsrecord = DNSRecord(name="localhost", recordtype="A", content="127.0.0.1")
|
||||
self.assertEqual(str(dnsrecord), "localhost IN A 127.0.0.1")
|
||||
|
||||
|
||||
class DNSSupermasterTest(TestCase):
|
||||
|
||||
def test___str__(self):
|
||||
dnssupermaster = DNSSupermaster(
|
||||
ip='127.0.0.1', nameserver='dns.example.org')
|
||||
self.assertEqual(str(dnssupermaster), '127.0.0.1 dns.example.org')
|
||||
dnssupermaster = DNSSupermaster(ip="127.0.0.1", nameserver="dns.example.org")
|
||||
self.assertEqual(str(dnssupermaster), "127.0.0.1 dns.example.org")
|
||||
|
||||
|
||||
class DNSCommentTest(TestCase):
|
||||
|
||||
def test___str__(self):
|
||||
dnscomment = DNSComment(
|
||||
name='localhost', commenttype='A', comment='good stuff')
|
||||
self.assertEqual(str(dnscomment), 'localhost IN A: good stuff')
|
||||
dnscomment = DNSComment(name="localhost", commenttype="A", comment="good stuff")
|
||||
self.assertEqual(str(dnscomment), "localhost IN A: good stuff")
|
||||
|
||||
|
||||
class DNSDomainMetadataTest(TestCase):
|
||||
|
||||
def test___str__(self):
|
||||
dnsdomain = DNSDomain(domain='test')
|
||||
dnsdomain = DNSDomain(domain="test")
|
||||
dnsdomainmetadata = DNSDomainMetadata(
|
||||
domain=dnsdomain, kind='SOA-EDIT', content='INCEPTION')
|
||||
self.assertEqual(str(dnsdomainmetadata), 'test SOA-EDIT INCEPTION')
|
||||
domain=dnsdomain, kind="SOA-EDIT", content="INCEPTION"
|
||||
)
|
||||
self.assertEqual(str(dnsdomainmetadata), "test SOA-EDIT INCEPTION")
|
||||
|
||||
|
||||
class DNSCryptoKeyTest(TestCase):
|
||||
|
||||
def test___str__(self):
|
||||
dnsdomain = DNSDomain(domain='test')
|
||||
dnscryptokey = DNSCryptoKey(domain=dnsdomain, content='testvalue')
|
||||
self.assertEqual(str(dnscryptokey), 'test testvalue')
|
||||
dnsdomain = DNSDomain(domain="test")
|
||||
dnscryptokey = DNSCryptoKey(domain=dnsdomain, content="testvalue")
|
||||
self.assertEqual(str(dnscryptokey), "test testvalue")
|
||||
|
||||
|
||||
class DNSTSIGKeyTest(TestCase):
|
||||
|
||||
def test___str__(self):
|
||||
dnstsigkey = DNSTSIGKey(
|
||||
name='testkey', algorithm='hmac-md5', secret='dummykey')
|
||||
self.assertEqual(str(dnstsigkey), 'testkey hmac-md5 XXXX')
|
||||
dnstsigkey = DNSTSIGKey(name="testkey", algorithm="hmac-md5", secret="dummykey")
|
||||
self.assertEqual(str(dnstsigkey), "testkey hmac-md5 XXXX")
|
||||
|
|
|
@ -2,149 +2,152 @@
|
|||
Tests for :py:mod:`domains.views`.
|
||||
|
||||
"""
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
from mock import patch, MagicMock
|
||||
|
||||
from django.core.urlresolvers import reverse
|
||||
from django.test import TestCase
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
|
||||
from hostingpackages.models import (
|
||||
CustomerHostingPackage,
|
||||
HostingPackageTemplate,
|
||||
)
|
||||
from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from domains.views import CreateHostingDomain
|
||||
|
||||
from hostingpackages.models import CustomerHostingPackage, HostingPackageTemplate
|
||||
|
||||
User = get_user_model()
|
||||
|
||||
TEST_USER = 'test'
|
||||
TEST_PASSWORD = 'secret'
|
||||
TEST_EMAIL = 'test@example.org'
|
||||
TEST_NAME = 'Example Tester'.split()
|
||||
TEST_USER = "test"
|
||||
TEST_PASSWORD = "secret"
|
||||
TEST_EMAIL = "test@example.org"
|
||||
TEST_NAME = "Example Tester".split()
|
||||
|
||||
|
||||
class CreateHostingDomainTest(TestCase):
|
||||
|
||||
def _setup_hosting_package(self, customer):
|
||||
template = HostingPackageTemplate.objects.create(
|
||||
name='testpackagetemplate', mailboxcount=0, diskspace=1,
|
||||
diskspace_unit=0)
|
||||
name="testpackagetemplate", mailboxcount=0, diskspace=1, diskspace_unit=0
|
||||
)
|
||||
package = CustomerHostingPackage.objects.create_from_template(
|
||||
customer, template, 'testpackage')
|
||||
with patch('hostingpackages.models.settings') as hmsettings:
|
||||
customer, template, "testpackage"
|
||||
)
|
||||
with patch("hostingpackages.models.settings") as hmsettings:
|
||||
hmsettings.OSUSER_DEFAULT_GROUPS = []
|
||||
package.save()
|
||||
return package
|
||||
|
||||
def test_get_anonymous(self):
|
||||
response = self.client.get(
|
||||
reverse('create_hosting_domain', kwargs={'package': 1}))
|
||||
reverse("create_hosting_domain", kwargs={"package": 1})
|
||||
)
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_get_regular_user(self):
|
||||
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)
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.get(
|
||||
reverse('create_hosting_domain',
|
||||
kwargs={'package': package.id}))
|
||||
reverse("create_hosting_domain", kwargs={"package": package.id})
|
||||
)
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_get_staff_user(self):
|
||||
customer = User.objects.create_user('customer')
|
||||
customer = User.objects.create_user("customer")
|
||||
package = self._setup_hosting_package(customer)
|
||||
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)
|
||||
response = self.client.get(
|
||||
reverse('create_hosting_domain',
|
||||
kwargs={'package': package.id}))
|
||||
reverse("create_hosting_domain", kwargs={"package": package.id})
|
||||
)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_get_template(self):
|
||||
customer = User.objects.create_user('customer')
|
||||
customer = User.objects.create_user("customer")
|
||||
package = self._setup_hosting_package(customer)
|
||||
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)
|
||||
response = self.client.get(
|
||||
reverse('create_hosting_domain',
|
||||
kwargs={'package': package.id}))
|
||||
self.assertTemplateUsed(response, 'domains/hostingdomain_create.html')
|
||||
reverse("create_hosting_domain", kwargs={"package": package.id})
|
||||
)
|
||||
self.assertTemplateUsed(response, "domains/hostingdomain_create.html")
|
||||
|
||||
def test_get_no_package_found(self):
|
||||
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)
|
||||
response = self.client.get(
|
||||
reverse('create_hosting_domain',
|
||||
kwargs={'package': 1}))
|
||||
reverse("create_hosting_domain", kwargs={"package": 1})
|
||||
)
|
||||
self.assertEqual(response.status_code, 404)
|
||||
|
||||
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)
|
||||
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)
|
||||
view = CreateHostingDomain(
|
||||
request=MagicMock(), kwargs={'package': str(package.id)})
|
||||
request=MagicMock(), kwargs={"package": str(package.id)}
|
||||
)
|
||||
the_kwargs = view.get_form_kwargs()
|
||||
self.assertIn('hostingpackage', the_kwargs)
|
||||
self.assertEqual(the_kwargs['hostingpackage'], package)
|
||||
self.assertIn("hostingpackage", the_kwargs)
|
||||
self.assertEqual(the_kwargs["hostingpackage"], package)
|
||||
|
||||
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)
|
||||
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)
|
||||
response = self.client.get(
|
||||
reverse('create_hosting_domain',
|
||||
kwargs={'package': package.id}))
|
||||
self.assertIn('hostingpackage', response.context)
|
||||
self.assertEqual(response.context['hostingpackage'], package)
|
||||
reverse("create_hosting_domain", kwargs={"package": package.id})
|
||||
)
|
||||
self.assertIn("hostingpackage", response.context)
|
||||
self.assertEqual(response.context["hostingpackage"], package)
|
||||
|
||||
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)
|
||||
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)
|
||||
response = self.client.get(
|
||||
reverse('create_hosting_domain',
|
||||
kwargs={'package': package.id}))
|
||||
self.assertIn('customer', response.context)
|
||||
self.assertEqual(response.context['customer'], customer)
|
||||
reverse("create_hosting_domain", kwargs={"package": package.id})
|
||||
)
|
||||
self.assertIn("customer", response.context)
|
||||
self.assertEqual(response.context["customer"], customer)
|
||||
|
||||
def test_form_valid_redirect(self):
|
||||
customer = User.objects.create_user('customer')
|
||||
customer = User.objects.create_user("customer")
|
||||
package = self._setup_hosting_package(customer)
|
||||
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)
|
||||
response = self.client.post(
|
||||
reverse('create_hosting_domain',
|
||||
kwargs={'package': package.id}),
|
||||
data={'domain': 'example.org'})
|
||||
reverse("create_hosting_domain", kwargs={"package": package.id}),
|
||||
data={"domain": "example.org"},
|
||||
)
|
||||
self.assertRedirects(response, package.get_absolute_url())
|
||||
|
||||
def test_form_valid_message(self):
|
||||
customer = User.objects.create_user('customer')
|
||||
customer = User.objects.create_user("customer")
|
||||
package = self._setup_hosting_package(customer)
|
||||
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)
|
||||
response = self.client.post(
|
||||
reverse('create_hosting_domain',
|
||||
kwargs={'package': package.id}), follow=True,
|
||||
data={'domain': 'example.org'})
|
||||
messages = list(response.context['messages'])
|
||||
reverse("create_hosting_domain", kwargs={"package": package.id}),
|
||||
follow=True,
|
||||
data={"domain": "example.org"},
|
||||
)
|
||||
messages = list(response.context["messages"])
|
||||
self.assertEqual(len(messages), 1)
|
||||
self.assertEqual(
|
||||
'Successfully created domain example.org', str(messages[0]))
|
||||
self.assertEqual("Successfully created domain example.org", str(messages[0]))
|
||||
|
|
|
@ -5,54 +5,49 @@ This module defines views related to domains.
|
|||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
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.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 .forms import CreateHostingDomainForm
|
||||
from .models import HostingDomain
|
||||
|
||||
|
||||
class CreateHostingDomain(
|
||||
LoginRequiredMixin, StaffuserRequiredMixin, CreateView
|
||||
):
|
||||
class CreateHostingDomain(StaffuserRequiredMixin, CreateView):
|
||||
"""
|
||||
This view is used for creating a new HostingDomain instance for an existing
|
||||
hosting package.
|
||||
|
||||
"""
|
||||
|
||||
model = HostingDomain
|
||||
raise_exception = True
|
||||
template_name_suffix = '_create'
|
||||
template_name_suffix = "_create"
|
||||
form_class = CreateHostingDomainForm
|
||||
|
||||
def _get_hosting_package(self):
|
||||
return get_object_or_404(
|
||||
CustomerHostingPackage, pk=int(self.kwargs['package']))
|
||||
return get_object_or_404(CustomerHostingPackage, pk=int(self.kwargs["package"]))
|
||||
|
||||
def get_form_kwargs(self):
|
||||
kwargs = super(CreateHostingDomain, self).get_form_kwargs()
|
||||
kwargs['hostingpackage'] = self._get_hosting_package()
|
||||
kwargs["hostingpackage"] = self._get_hosting_package()
|
||||
return kwargs
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super(CreateHostingDomain, self).get_context_data(**kwargs)
|
||||
hosting_package = self._get_hosting_package()
|
||||
context.update({
|
||||
'hostingpackage': hosting_package,
|
||||
'customer': hosting_package.customer,
|
||||
})
|
||||
context.update(
|
||||
{"hostingpackage": hosting_package, "customer": hosting_package.customer}
|
||||
)
|
||||
return context
|
||||
|
||||
def form_valid(self, form):
|
||||
hostingdomain = form.save()
|
||||
messages.success(
|
||||
self.request,
|
||||
_('Successfully created domain {domainname}').format(
|
||||
domainname=hostingdomain.domain)
|
||||
_("Successfully created domain {domainname}").format(
|
||||
domainname=hostingdomain.domain
|
||||
),
|
||||
)
|
||||
return redirect(self._get_hosting_package())
|
||||
|
|
|
@ -38,8 +38,10 @@ DEBUG = False
|
|||
# ######### MANAGER CONFIGURATION
|
||||
# See: https://docs.djangoproject.com/en/dev/ref/settings/#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
|
||||
|
@ -50,13 +52,13 @@ MANAGERS = ADMINS
|
|||
# ######### DATABASE CONFIGURATION
|
||||
# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.postgresql',
|
||||
'NAME': get_env_variable('GVA_PGSQL_DATABASE', default='gnuviechadmin'),
|
||||
'USER': get_env_variable('GVA_PGSQL_USER', default='gnuviechadmin'),
|
||||
'PASSWORD': get_env_variable('GVA_PGSQL_PASSWORD'),
|
||||
'HOST': get_env_variable('GVA_PGSQL_HOSTNAME', default='db'),
|
||||
'PORT': get_env_variable('GVA_PGSQL_PORT', int, default=5432),
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.postgresql",
|
||||
"NAME": get_env_variable("GVA_PGSQL_DATABASE", default="gnuviechadmin"),
|
||||
"USER": get_env_variable("GVA_PGSQL_USER", default="gnuviechadmin"),
|
||||
"PASSWORD": get_env_variable("GVA_PGSQL_PASSWORD"),
|
||||
"HOST": get_env_variable("GVA_PGSQL_HOSTNAME", default="db"),
|
||||
"PORT": get_env_variable("GVA_PGSQL_PORT", int, default=5432),
|
||||
}
|
||||
}
|
||||
# ######### END DATABASE CONFIGURATION
|
||||
|
@ -64,15 +66,15 @@ DATABASES = {
|
|||
|
||||
# ######### GENERAL CONFIGURATION
|
||||
# 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
|
||||
LANGUAGE_CODE = 'en-us'
|
||||
LANGUAGE_CODE = "en-us"
|
||||
|
||||
# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id
|
||||
SITE_ID = 1
|
||||
SITES_DOMAIN_NAME = get_env_variable('GVA_DOMAIN_NAME')
|
||||
SITES_SITE_NAME = get_env_variable('GVA_SITE_NAME')
|
||||
SITES_DOMAIN_NAME = get_env_variable("GVA_DOMAIN_NAME")
|
||||
SITES_SITE_NAME = get_env_variable("GVA_SITE_NAME")
|
||||
|
||||
# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
|
||||
USE_I18N = True
|
||||
|
@ -85,33 +87,28 @@ USE_TZ = True
|
|||
# ######### END GENERAL CONFIGURATION
|
||||
|
||||
|
||||
LOCALE_PATHS = (
|
||||
normpath(join(SITE_ROOT, 'gnuviechadmin', 'locale')),
|
||||
)
|
||||
LOCALE_PATHS = (normpath(join(SITE_ROOT, "gnuviechadmin", "locale")),)
|
||||
|
||||
|
||||
# ######### MEDIA CONFIGURATION
|
||||
# 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
|
||||
MEDIA_URL = '/media/'
|
||||
MEDIA_URL = "/media/"
|
||||
# ######### END MEDIA CONFIGURATION
|
||||
|
||||
|
||||
|
||||
# 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
|
||||
STATICFILES_DIRS = (
|
||||
normpath(join(SITE_ROOT, 'gnuviechadmin', 'assets')),
|
||||
)
|
||||
STATICFILES_DIRS = (normpath(join(SITE_ROOT, "gnuviechadmin", "assets")),)
|
||||
|
||||
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders # noqa
|
||||
STATICFILES_FINDERS = (
|
||||
'django.contrib.staticfiles.finders.FileSystemFinder',
|
||||
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
|
||||
"django.contrib.staticfiles.finders.FileSystemFinder",
|
||||
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
|
||||
)
|
||||
# ######### END STATIC FILE CONFIGURATION
|
||||
|
||||
|
@ -119,7 +116,7 @@ STATICFILES_FINDERS = (
|
|||
# ######### SECRET CONFIGURATION
|
||||
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
|
||||
# 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
|
||||
|
||||
|
||||
|
@ -132,9 +129,7 @@ ALLOWED_HOSTS = []
|
|||
|
||||
# ######### FIXTURE CONFIGURATION
|
||||
# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS # noqa
|
||||
FIXTURE_DIRS = (
|
||||
normpath(join(SITE_ROOT, 'fixtures')),
|
||||
)
|
||||
FIXTURE_DIRS = (normpath(join(SITE_ROOT, "fixtures")),)
|
||||
# ######### END FIXTURE CONFIGURATION
|
||||
|
||||
|
||||
|
@ -142,27 +137,25 @@ FIXTURE_DIRS = (
|
|||
# See: https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-TEMPLATES # noqa
|
||||
TEMPLATES = [
|
||||
{
|
||||
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
||||
'DIRS': [
|
||||
normpath(join(DJANGO_ROOT, 'templates')),
|
||||
],
|
||||
'APP_DIRS': True,
|
||||
'OPTIONS': {
|
||||
'context_processors': [
|
||||
'django.contrib.auth.context_processors.auth',
|
||||
'django.template.context_processors.debug',
|
||||
'django.template.context_processors.i18n',
|
||||
'django.template.context_processors.media',
|
||||
'django.template.context_processors.static',
|
||||
'django.template.context_processors.tz',
|
||||
'django.contrib.messages.context_processors.messages',
|
||||
'django.template.context_processors.request',
|
||||
"BACKEND": "django.template.backends.django.DjangoTemplates",
|
||||
"DIRS": [normpath(join(DJANGO_ROOT, "templates"))],
|
||||
"APP_DIRS": True,
|
||||
"OPTIONS": {
|
||||
"context_processors": [
|
||||
"django.contrib.auth.context_processors.auth",
|
||||
"django.template.context_processors.debug",
|
||||
"django.template.context_processors.i18n",
|
||||
"django.template.context_processors.media",
|
||||
"django.template.context_processors.static",
|
||||
"django.template.context_processors.tz",
|
||||
"django.contrib.messages.context_processors.messages",
|
||||
"django.template.context_processors.request",
|
||||
# custom context processors
|
||||
'gnuviechadmin.context_processors.navigation',
|
||||
'gnuviechadmin.context_processors.version_info',
|
||||
],
|
||||
},
|
||||
"gnuviechadmin.context_processors.navigation",
|
||||
"gnuviechadmin.context_processors.version_info",
|
||||
]
|
||||
},
|
||||
}
|
||||
]
|
||||
# ######### END TEMPLATE CONFIGURATION
|
||||
|
||||
|
@ -171,14 +164,14 @@ TEMPLATES = [
|
|||
# See: https://docs.djangoproject.com/en/dev/ref/settings/#middleware-classes
|
||||
MIDDLEWARE = [
|
||||
# Default Django middleware.
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.middleware.locale.LocaleMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
"django.middleware.common.CommonMiddleware",
|
||||
"django.contrib.sessions.middleware.SessionMiddleware",
|
||||
"django.middleware.csrf.CsrfViewMiddleware",
|
||||
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||
"django.middleware.locale.LocaleMiddleware",
|
||||
"django.contrib.messages.middleware.MessageMiddleware",
|
||||
# uncomment next line to enable translation to browser locale
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
||||
]
|
||||
# ######### END MIDDLEWARE CONFIGURATION
|
||||
|
||||
|
@ -186,7 +179,6 @@ MIDDLEWARE = [
|
|||
AUTHENTICATION_BACKENDS = (
|
||||
# Needed to login by username in Django admin, regardless of `allauth`
|
||||
"django.contrib.auth.backends.ModelBackend",
|
||||
|
||||
# `allauth` specific authentication methods, such as login by e-mail
|
||||
"allauth.account.auth_backends.AuthenticationBackend",
|
||||
)
|
||||
|
@ -194,87 +186,83 @@ AUTHENTICATION_BACKENDS = (
|
|||
|
||||
# ######### URL CONFIGURATION
|
||||
# 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
|
||||
|
||||
|
||||
# ######### TEST RUNNER CONFIGURATION
|
||||
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
|
||||
TEST_RUNNER = "django.test.runner.DiscoverRunner"
|
||||
# ######### END TEST RUNNER CONFIGURATION
|
||||
|
||||
|
||||
# ######### APP CONFIGURATION
|
||||
DJANGO_APPS = (
|
||||
# Default Django apps:
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.sites',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
|
||||
"django.contrib.auth",
|
||||
"django.contrib.contenttypes",
|
||||
"django.contrib.sessions",
|
||||
"django.contrib.sites",
|
||||
"django.contrib.messages",
|
||||
"django.contrib.staticfiles",
|
||||
# Useful template tags:
|
||||
'django.contrib.humanize',
|
||||
|
||||
"django.contrib.humanize",
|
||||
# Admin panel and documentation:
|
||||
'django.contrib.admin',
|
||||
|
||||
"django.contrib.admin",
|
||||
# Flatpages for about page
|
||||
'django.contrib.flatpages',
|
||||
|
||||
'crispy_forms',
|
||||
"django.contrib.flatpages",
|
||||
"crispy_forms",
|
||||
)
|
||||
|
||||
ALLAUTH_APPS = (
|
||||
'allauth',
|
||||
'allauth.account',
|
||||
'allauth.socialaccount',
|
||||
'allauth.socialaccount.providers.google',
|
||||
'allauth.socialaccount.providers.linkedin_oauth2',
|
||||
'allauth.socialaccount.providers.twitter',
|
||||
"allauth",
|
||||
"allauth.account",
|
||||
"allauth.socialaccount",
|
||||
"allauth.socialaccount.providers.google",
|
||||
"allauth.socialaccount.providers.linkedin_oauth2",
|
||||
"allauth.socialaccount.providers.twitter",
|
||||
)
|
||||
|
||||
# Apps specific for this project go here.
|
||||
LOCAL_APPS = (
|
||||
'dashboard',
|
||||
'taskresults',
|
||||
'ldaptasks',
|
||||
'mysqltasks',
|
||||
'pgsqltasks',
|
||||
'fileservertasks',
|
||||
'webtasks',
|
||||
'domains',
|
||||
'osusers',
|
||||
'managemails',
|
||||
'userdbs',
|
||||
'hostingpackages',
|
||||
'websites',
|
||||
'contact_form',
|
||||
"dashboard",
|
||||
"taskresults",
|
||||
"ldaptasks",
|
||||
"mysqltasks",
|
||||
"pgsqltasks",
|
||||
"fileservertasks",
|
||||
"webtasks",
|
||||
"domains",
|
||||
"osusers",
|
||||
"managemails",
|
||||
"userdbs",
|
||||
"hostingpackages",
|
||||
"websites",
|
||||
"contact_form",
|
||||
)
|
||||
|
||||
# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
|
||||
INSTALLED_APPS = DJANGO_APPS + ALLAUTH_APPS + LOCAL_APPS
|
||||
|
||||
MESSAGE_TAGS = {
|
||||
messages.DEBUG: '',
|
||||
messages.ERROR: 'alert-danger',
|
||||
messages.INFO: 'alert-info',
|
||||
messages.SUCCESS: 'alert-success',
|
||||
messages.WARNING: 'alert-warning',
|
||||
messages.DEBUG: "",
|
||||
messages.ERROR: "alert-danger",
|
||||
messages.INFO: "alert-info",
|
||||
messages.SUCCESS: "alert-success",
|
||||
messages.WARNING: "alert-warning",
|
||||
}
|
||||
# ######### END APP CONFIGURATION
|
||||
|
||||
|
||||
# ######### ALLAUTH CONFIGURATION
|
||||
ACCOUNT_EMAIL_REQUIRED = True
|
||||
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
|
||||
LOGIN_REDIRECT_URL = '/'
|
||||
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
|
||||
LOGIN_REDIRECT_URL = "/"
|
||||
SOCIALACCOUNT_QUERY_EMAIL = True
|
||||
# ######### END ALLAUTH CONFIGURATION
|
||||
|
||||
|
||||
# ######### CRISPY FORMS CONFIGURATION
|
||||
CRISPY_TEMPLATE_PACK = 'bootstrap3'
|
||||
CRISPY_TEMPLATE_PACK = "bootstrap3"
|
||||
# ######### END CRISPY_FORMS CONFIGURATION
|
||||
|
||||
|
||||
|
@ -286,170 +274,197 @@ CRISPY_TEMPLATE_PACK = 'bootstrap3'
|
|||
# See http://docs.djangoproject.com/en/dev/topics/logging for
|
||||
# more details on how to customize your logging configuration.
|
||||
LOGGING = {
|
||||
'version': 1,
|
||||
'disable_existing_loggers': False,
|
||||
'formatters': {
|
||||
'verbose': {
|
||||
'format': '%(levelname)s %(asctime)s %(name)s '
|
||||
'%(module)s:%(lineno)d %(process)d %(thread)d %(message)s',
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"formatters": {
|
||||
"verbose": {
|
||||
"format": "%(levelname)s %(asctime)s %(name)s "
|
||||
"%(module)s:%(lineno)d %(process)d %(thread)d %(message)s"
|
||||
},
|
||||
'simple': {
|
||||
'format': '%(levelname)s %(name)s:%(lineno)d %(message)s',
|
||||
"simple": {"format": "%(levelname)s %(name)s:%(lineno)d %(message)s"},
|
||||
},
|
||||
},
|
||||
'filters': {
|
||||
'require_debug_false': {
|
||||
'()': 'django.utils.log.RequireDebugFalse'
|
||||
"filters": {"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}},
|
||||
"handlers": {
|
||||
"mail_admins": {
|
||||
"level": "ERROR",
|
||||
"filters": ["require_debug_false"],
|
||||
"class": "django.utils.log.AdminEmailHandler",
|
||||
}
|
||||
},
|
||||
'handlers': {
|
||||
'mail_admins': {
|
||||
'level': 'ERROR',
|
||||
'filters': ['require_debug_false'],
|
||||
'class': 'django.utils.log.AdminEmailHandler'
|
||||
"loggers": {
|
||||
"django.request": {
|
||||
"handlers": ["mail_admins"],
|
||||
"level": "ERROR",
|
||||
"propagate": True,
|
||||
}
|
||||
},
|
||||
'loggers': {
|
||||
'django.request': {
|
||||
'handlers': ['mail_admins'],
|
||||
'level': 'ERROR',
|
||||
'propagate': True,
|
||||
},
|
||||
}
|
||||
}
|
||||
# ######### END LOGGING CONFIGURATION
|
||||
|
||||
|
||||
# ######### WSGI CONFIGURATION
|
||||
# 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
|
||||
|
||||
|
||||
# ######### CELERY CONFIGURATION
|
||||
BROKER_URL = get_env_variable(
|
||||
'GVA_BROKER_URL',
|
||||
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',
|
||||
"GVA_BROKER_URL", default="amqp://gnuviechadmin:gnuviechadmin@mq/gnuviechadmin"
|
||||
)
|
||||
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_ACCEPT_CONTENT = ['json']
|
||||
CELERY_TASK_SERIALIZER = 'json'
|
||||
CELERY_RESULT_SERIALIZER = 'json'
|
||||
CELERY_ACCEPT_CONTENT = ["json"]
|
||||
CELERY_TASK_SERIALIZER = "json"
|
||||
CELERY_RESULT_SERIALIZER = "json"
|
||||
# ######### END CELERY CONFIGURATION
|
||||
|
||||
|
||||
# ######### CUSTOM APP CONFIGURATION
|
||||
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_USERNAME_PREFIX = get_env_variable('GVA_OSUSER_PREFIX', default='usr')
|
||||
OSUSER_HOME_BASEPATH = get_env_variable(
|
||||
'GVA_OSUSER_HOME_BASEPATH', default='/home')
|
||||
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_USERNAME_PREFIX = get_env_variable("GVA_OSUSER_PREFIX", default="usr")
|
||||
OSUSER_HOME_BASEPATH = get_env_variable("GVA_OSUSER_HOME_BASEPATH", default="/home")
|
||||
OSUSER_DEFAULT_SHELL = get_env_variable(
|
||||
'GVA_OSUSER_DEFAULT_SHELL', default='/usr/bin/rssh')
|
||||
OSUSER_SFTP_GROUP = 'sftponly'
|
||||
OSUSER_SSH_GROUP = 'sshusers'
|
||||
"GVA_OSUSER_DEFAULT_SHELL", default="/usr/bin/rssh"
|
||||
)
|
||||
OSUSER_SFTP_GROUP = "sftponly"
|
||||
OSUSER_SSH_GROUP = "sshusers"
|
||||
OSUSER_DEFAULT_GROUPS = [OSUSER_SFTP_GROUP]
|
||||
OSUSER_UPLOAD_SERVER = get_env_variable(
|
||||
'GVA_OSUSER_UPLOADSERVER', default='file')
|
||||
OSUSER_UPLOAD_SERVER = get_env_variable("GVA_OSUSER_UPLOADSERVER", default="file")
|
||||
|
||||
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_PHPMYADMIN_URL', default='https://phpmyadmin.example.org/')
|
||||
"GVA_PHPMYADMIN_URL", default="https://phpmyadmin.example.org/"
|
||||
)
|
||||
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
|
||||
|
||||
GVA_ENVIRONMENT = get_env_variable('GVA_ENVIRONMENT', default='prod')
|
||||
GVA_ENVIRONMENT = get_env_variable("GVA_ENVIRONMENT", default="prod")
|
||||
|
||||
# ######### STATIC FILE CONFIGURATION
|
||||
# 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):
|
||||
return DEBUG == True and GVA_ENVIRONMENT == 'local'
|
||||
return DEBUG == True and GVA_ENVIRONMENT == "local"
|
||||
|
||||
|
||||
if GVA_ENVIRONMENT == 'local':
|
||||
if GVA_ENVIRONMENT == "local":
|
||||
# ######### DEBUG CONFIGURATION
|
||||
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
|
||||
DEBUG = True
|
||||
|
||||
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
|
||||
TEMPLATES[0]['OPTIONS']['debug'] = DEBUG
|
||||
TEMPLATES[0]["OPTIONS"]["debug"] = DEBUG
|
||||
# ######### END DEBUG CONFIGURATION
|
||||
|
||||
# ######### EMAIL CONFIGURATION
|
||||
# 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
|
||||
|
||||
# ######### CACHE CONFIGURATION
|
||||
# See: https://docs.djangoproject.com/en/dev/ref/settings/#caches
|
||||
CACHES = {
|
||||
'default': {
|
||||
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
|
||||
}
|
||||
}
|
||||
CACHES = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}
|
||||
# ######### END CACHE CONFIGURATION
|
||||
|
||||
# ######### TOOLBAR CONFIGURATION
|
||||
# See: http://django-debug-toolbar.readthedocs.org/en/latest/installation.html#explicit-setup # noqa
|
||||
INSTALLED_APPS += (
|
||||
'debug_toolbar',
|
||||
)
|
||||
INSTALLED_APPS += ("debug_toolbar",)
|
||||
|
||||
MIDDLEWARE += [
|
||||
'debug_toolbar.middleware.DebugToolbarMiddleware',
|
||||
]
|
||||
MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"]
|
||||
|
||||
LOGGING['handlers'].update({
|
||||
'console': {
|
||||
'level': 'DEBUG',
|
||||
'class': 'logging.StreamHandler',
|
||||
'formatter': 'simple',
|
||||
LOGGING["handlers"].update(
|
||||
{
|
||||
"console": {
|
||||
"level": "DEBUG",
|
||||
"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 [
|
||||
'dashboard', 'domains', 'fileservertasks', 'gvacommon',
|
||||
'gvawebcore', 'hostingpackages', 'ldaptasks', 'managemails',
|
||||
'mysqltasks', 'osusers', 'pgsqltasks', 'taskresults',
|
||||
'userdbs', 'websites']]))
|
||||
"dashboard",
|
||||
"domains",
|
||||
"fileservertasks",
|
||||
"gvacommon",
|
||||
"gvawebcore",
|
||||
"hostingpackages",
|
||||
"ldaptasks",
|
||||
"managemails",
|
||||
"mysqltasks",
|
||||
"osusers",
|
||||
"pgsqltasks",
|
||||
"taskresults",
|
||||
"userdbs",
|
||||
"websites",
|
||||
]
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
DEBUG_TOOLBAR_PATCH_SETTINGS = False
|
||||
DEBUG_TOOLBAR_CONFIG = {
|
||||
'SHOW_TOOLBAR_CALLBACK': 'gnuviechadmin.settings.show_debug_toolbar',
|
||||
"SHOW_TOOLBAR_CALLBACK": "gnuviechadmin.settings.show_debug_toolbar"
|
||||
}
|
||||
|
||||
# ######### END TOOLBAR CONFIGURATION
|
||||
elif GVA_ENVIRONMENT == 'test':
|
||||
PASSWORD_HASHERS = (
|
||||
'django.contrib.auth.hashers.MD5PasswordHasher',
|
||||
)
|
||||
LOGGING['handlers'].update({
|
||||
'console': {
|
||||
'level': 'ERROR',
|
||||
'class': 'logging.StreamHandler',
|
||||
'formatter': 'simple',
|
||||
elif GVA_ENVIRONMENT == "test":
|
||||
PASSWORD_HASHERS = ("django.contrib.auth.hashers.MD5PasswordHasher",)
|
||||
LOGGING["handlers"].update(
|
||||
{
|
||||
"console": {
|
||||
"level": "ERROR",
|
||||
"class": "logging.StreamHandler",
|
||||
"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 [
|
||||
'dashboard', 'domains', 'fileservertasks', 'gvacommon',
|
||||
'gvawebcore', 'hostingpackages', 'ldaptasks', 'managemails',
|
||||
'mysqltasks', 'osusers', 'pgsqltasks', 'taskresults',
|
||||
'userdbs', 'websites']]))
|
||||
BROKER_URL = BROKER_URL + '_test'
|
||||
"dashboard",
|
||||
"domains",
|
||||
"fileservertasks",
|
||||
"gvacommon",
|
||||
"gvawebcore",
|
||||
"hostingpackages",
|
||||
"ldaptasks",
|
||||
"managemails",
|
||||
"mysqltasks",
|
||||
"osusers",
|
||||
"pgsqltasks",
|
||||
"taskresults",
|
||||
"userdbs",
|
||||
"websites",
|
||||
]
|
||||
]
|
||||
)
|
||||
)
|
||||
BROKER_URL = BROKER_URL + "_test"
|
||||
CELERY_RESULT_PERSISTENT = False
|
||||
else:
|
||||
# ######### HOST CONFIGURATION
|
||||
|
@ -459,18 +474,18 @@ else:
|
|||
|
||||
# ######### EMAIL CONFIGURATION
|
||||
# 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
|
||||
EMAIL_SUBJECT_PREFIX = '[%s] ' % SITE_NAME
|
||||
EMAIL_SUBJECT_PREFIX = "[%s] " % SITE_NAME
|
||||
|
||||
# See: https://docs.djangoproject.com/en/dev/ref/settings/#default-from-email
|
||||
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
|
||||
SERVER_EMAIL = get_env_variable(
|
||||
'GVA_SITE_ADMINMAIL', default='admin@example.org')
|
||||
SERVER_EMAIL = get_env_variable("GVA_SITE_ADMINMAIL", default="admin@example.org")
|
||||
# ######### END EMAIL CONFIGURATION
|
||||
|
||||
# ######### CACHE CONFIGURATION
|
||||
|
@ -479,6 +494,6 @@ else:
|
|||
# ######### END CACHE CONFIGURATION
|
||||
|
||||
# ######### ALLAUTH PRODUCTION CONFIGURATION
|
||||
ACCOUNT_EMAIL_SUBJECT_PREFIX = '[Jan Dittberner IT-Consulting & -Solutions] '
|
||||
ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https'
|
||||
ACCOUNT_EMAIL_SUBJECT_PREFIX = "[Jan Dittberner IT-Consulting & -Solutions] "
|
||||
ACCOUNT_DEFAULT_HTTP_PROTOCOL = "https"
|
||||
# ######### END ALLAUTH PRODUCTION CONFIGURATION
|
||||
|
|
|
@ -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.core.urlresolvers import reverse
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.http import HttpRequest
|
||||
from django.test import TestCase
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.urls import reverse
|
||||
|
||||
from gnuviechadmin import __version__ as gvaversion
|
||||
from gnuviechadmin.context_processors import navigation
|
||||
|
@ -22,48 +21,40 @@ User = get_user_model()
|
|||
|
||||
class NavigationContextProcessorTest(TestCase):
|
||||
|
||||
EXPECTED_ITEMS = (
|
||||
'webmail_url', 'phpmyadmin_url', 'phppgadmin_url',
|
||||
'active_item'
|
||||
)
|
||||
EXPECTED_ITEMS = ("webmail_url", "phpmyadmin_url", "phppgadmin_url", "active_item")
|
||||
|
||||
def test_ajax_request(self):
|
||||
response = self.client.get(
|
||||
'/', HTTP_X_REQUESTED_WITH='XMLHttpRequest')
|
||||
response = self.client.get("/", HTTP_X_REQUESTED_WITH="XMLHttpRequest")
|
||||
for item in self.EXPECTED_ITEMS:
|
||||
self.assertNotIn(item, response.context)
|
||||
|
||||
def _check_static_urls(self, context):
|
||||
self.assertEqual(
|
||||
context['webmail_url'], settings.GVA_LINK_WEBMAIL)
|
||||
self.assertEqual(
|
||||
context['phpmyadmin_url'], settings.GVA_LINK_PHPMYADMIN)
|
||||
self.assertEqual(
|
||||
context['phppgadmin_url'], settings.GVA_LINK_PHPPGADMIN)
|
||||
self.assertEqual(context["webmail_url"], settings.GVA_LINK_WEBMAIL)
|
||||
self.assertEqual(context["phpmyadmin_url"], settings.GVA_LINK_PHPMYADMIN)
|
||||
self.assertEqual(context["phppgadmin_url"], settings.GVA_LINK_PHPPGADMIN)
|
||||
|
||||
def test_index_page_context(self):
|
||||
response = self.client.get('/')
|
||||
response = self.client.get("/")
|
||||
for item in self.EXPECTED_ITEMS:
|
||||
self.assertIn(item, 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):
|
||||
response = self.client.get(reverse('contact_form'))
|
||||
response = self.client.get(reverse("contact_form"))
|
||||
for item in self.EXPECTED_ITEMS:
|
||||
self.assertIn(item, 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):
|
||||
User.objects.create_user('test', password='test')
|
||||
self.client.login(username='test', password='test')
|
||||
response = self.client.get(
|
||||
reverse('hosting_packages', kwargs={'user': 'test'}))
|
||||
User.objects.create_user("test", password="test")
|
||||
self.client.login(username="test", password="test")
|
||||
response = self.client.get(reverse("hosting_packages", kwargs={"user": "test"}))
|
||||
for item in self.EXPECTED_ITEMS:
|
||||
self.assertIn(item, 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):
|
||||
request = HttpRequest()
|
||||
|
@ -73,57 +64,48 @@ class NavigationContextProcessorTest(TestCase):
|
|||
for item in self.EXPECTED_ITEMS:
|
||||
self.assertIn(item, context)
|
||||
self._check_static_urls(context)
|
||||
self.assertEqual(context['active_item'], expecteditem)
|
||||
self.assertEqual(context["active_item"], expecteditem)
|
||||
|
||||
def test_osusers_page_context(self):
|
||||
self._test_page_context_by_viewmodule(
|
||||
'osusers.views', 'hostingpackage')
|
||||
self._test_page_context_by_viewmodule("osusers.views", "hostingpackage")
|
||||
|
||||
def test_userdbs_page_context(self):
|
||||
self._test_page_context_by_viewmodule(
|
||||
'userdbs.views', 'hostingpackage')
|
||||
self._test_page_context_by_viewmodule("userdbs.views", "hostingpackage")
|
||||
|
||||
def test_managemails_page_context(self):
|
||||
self._test_page_context_by_viewmodule(
|
||||
'managemails.views', 'hostingpackage')
|
||||
self._test_page_context_by_viewmodule("managemails.views", "hostingpackage")
|
||||
|
||||
def test_websites_page_context(self):
|
||||
self._test_page_context_by_viewmodule(
|
||||
'websites.views', 'hostingpackage')
|
||||
self._test_page_context_by_viewmodule("websites.views", "hostingpackage")
|
||||
|
||||
def test_domains_page_context(self):
|
||||
self._test_page_context_by_viewmodule(
|
||||
'domains.views', 'hostingpackage')
|
||||
self._test_page_context_by_viewmodule("domains.views", "hostingpackage")
|
||||
|
||||
def test_allauth_account_page_context(self):
|
||||
self._test_page_context_by_viewmodule(
|
||||
'allauth.account.views', 'account')
|
||||
self._test_page_context_by_viewmodule("allauth.account.views", "account")
|
||||
|
||||
def test_allauth_socialaccount_page_context(self):
|
||||
self._test_page_context_by_viewmodule(
|
||||
'allauth.socialaccount.views', 'account')
|
||||
self._test_page_context_by_viewmodule("allauth.socialaccount.views", "account")
|
||||
|
||||
def test_imprint_page_context(self):
|
||||
response = self.client.get(reverse('imprint'))
|
||||
response = self.client.get(reverse("imprint"))
|
||||
for item in self.EXPECTED_ITEMS:
|
||||
self.assertIn(item, 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):
|
||||
request = HttpRequest()
|
||||
context = navigation(request)
|
||||
self._check_static_urls(context)
|
||||
self.assertEqual(context['active_item'], 'dashboard')
|
||||
self.assertEqual(context["active_item"], "dashboard")
|
||||
|
||||
def test_admin_module(self):
|
||||
self._test_page_context_by_viewmodule(
|
||||
'django.contrib.admin.foo', 'dashboard')
|
||||
self._test_page_context_by_viewmodule("django.contrib.admin.foo", "dashboard")
|
||||
|
||||
|
||||
class VersionInfoContextProcessorTest(TestCase):
|
||||
|
||||
def test_version_info_in_context(self):
|
||||
response = self.client.get('/')
|
||||
self.assertIn('gnuviechadmin_version', response.context)
|
||||
self.assertEqual(response.context['gnuviechadmin_version'], gvaversion)
|
||||
response = self.client.get("/")
|
||||
self.assertIn("gnuviechadmin_version", response.context)
|
||||
self.assertEqual(response.context["gnuviechadmin_version"], gvaversion)
|
||||
|
|
|
@ -5,25 +5,26 @@ This module contains tests for :py:mod:`gvawebcore.forms`.
|
|||
|
||||
from unittest import TestCase
|
||||
|
||||
from gvawebcore.forms import PasswordModelFormMixin, PASSWORD_MISMATCH_ERROR
|
||||
from gvawebcore.forms import PASSWORD_MISMATCH_ERROR, PasswordModelFormMixin
|
||||
|
||||
|
||||
class PasswordModelFormMixinTest(TestCase):
|
||||
|
||||
def test_form_properties(self):
|
||||
form = PasswordModelFormMixin()
|
||||
self.assertIn('password1', form.fields)
|
||||
self.assertIn('password2', form.fields)
|
||||
self.assertIn("password1", form.fields)
|
||||
self.assertIn("password2", form.fields)
|
||||
|
||||
def test_clean_password_same(self):
|
||||
form = PasswordModelFormMixin(data={
|
||||
'password1': 'secret', 'password2': 'secret'})
|
||||
form = PasswordModelFormMixin(
|
||||
data={"password1": "secret", "password2": "secret"}
|
||||
)
|
||||
self.assertTrue(form.is_valid())
|
||||
self.assertEqual('secret', form.clean_password2())
|
||||
self.assertEqual("secret", form.clean_password2())
|
||||
|
||||
def test_clean_password_different(self):
|
||||
form = PasswordModelFormMixin(data={
|
||||
'password1': 'onesecret', 'password2': 'other'})
|
||||
form = PasswordModelFormMixin(
|
||||
data={"password1": "onesecret", "password2": "other"}
|
||||
)
|
||||
self.assertFalse(form.is_valid())
|
||||
self.assertIn('password2', form.errors)
|
||||
self.assertIn(PASSWORD_MISMATCH_ERROR, form.errors['password2'])
|
||||
self.assertIn("password2", form.errors)
|
||||
self.assertIn(PASSWORD_MISMATCH_ERROR, form.errors["password2"])
|
||||
|
|
|
@ -4,31 +4,29 @@ This model contains tests for :py:mod:`gvawebcore.views`.
|
|||
"""
|
||||
|
||||
from unittest import TestCase
|
||||
|
||||
from mock import patch, Mock
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from gvawebcore.views import HostingPackageAndCustomerMixin
|
||||
|
||||
|
||||
class HostingPackageAndCustomerMixinTest(TestCase):
|
||||
|
||||
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):
|
||||
get_object_or_404.return_value = 'A package'
|
||||
get_object_or_404.return_value = "A package"
|
||||
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):
|
||||
view = self.TestView()
|
||||
view.hostingpackage = 'Cached package'
|
||||
self.assertEqual('Cached package', view.get_hosting_package())
|
||||
view.hostingpackage = "Cached 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):
|
||||
get_object_or_404.return_value = Mock(customer='A customer')
|
||||
get_object_or_404.return_value = Mock(customer="A customer")
|
||||
view = self.TestView()
|
||||
self.assertEqual('A customer', view.get_customer_object())
|
||||
self.assertEqual("A customer", view.get_customer_object())
|
||||
|
|
|
@ -16,37 +16,24 @@ from model_utils.models import TimeStampedModel
|
|||
|
||||
from domains.models import HostingDomain
|
||||
from managemails.models import Mailbox
|
||||
from osusers.models import (
|
||||
AdditionalGroup,
|
||||
Group,
|
||||
User as OsUser,
|
||||
)
|
||||
from userdbs.models import (
|
||||
DB_TYPES,
|
||||
UserDatabase,
|
||||
)
|
||||
from osusers.models import AdditionalGroup, Group, User as OsUser
|
||||
from userdbs.models import DB_TYPES, UserDatabase
|
||||
|
||||
DISK_SPACE_UNITS = Choices(
|
||||
(0, 'M', _('MiB')),
|
||||
(1, 'G', _('GiB')),
|
||||
(2, 'T', _('TiB')),
|
||||
)
|
||||
DISK_SPACE_UNITS = Choices((0, "M", _("MiB")), (1, "G", _("GiB")), (2, "T", _("TiB")))
|
||||
|
||||
DISK_SPACE_FACTORS = (
|
||||
(1, None, None),
|
||||
(1024, 1, None),
|
||||
(1024 * 1024, 1024, 1),
|
||||
)
|
||||
DISK_SPACE_FACTORS = ((1, None, None), (1024, 1, None), (1024 * 1024, 1024, 1))
|
||||
|
||||
|
||||
@python_2_unicode_compatible
|
||||
class HostingPackageBase(TimeStampedModel):
|
||||
description = models.TextField(_('description'), blank=True)
|
||||
mailboxcount = models.PositiveIntegerField(_('mailbox count'))
|
||||
description = models.TextField(_("description"), blank=True)
|
||||
mailboxcount = models.PositiveIntegerField(_("mailbox count"))
|
||||
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(
|
||||
_('unit of disk space'), choices=DISK_SPACE_UNITS)
|
||||
_("unit of disk space"), choices=DISK_SPACE_UNITS
|
||||
)
|
||||
|
||||
class Meta:
|
||||
abstract = True
|
||||
|
@ -56,11 +43,11 @@ class HostingPackageBase(TimeStampedModel):
|
|||
|
||||
|
||||
class HostingPackageTemplate(HostingPackageBase):
|
||||
name = models.CharField(_('name'), max_length=128, unique=True)
|
||||
name = models.CharField(_("name"), max_length=128, unique=True)
|
||||
|
||||
class Meta:
|
||||
verbose_name = _('Hosting package')
|
||||
verbose_name_plural = _('Hosting packages')
|
||||
verbose_name = _("Hosting package")
|
||||
verbose_name_plural = _("Hosting packages")
|
||||
|
||||
|
||||
class HostingOption(TimeStampedModel):
|
||||
|
@ -72,19 +59,21 @@ class HostingOption(TimeStampedModel):
|
|||
|
||||
@python_2_unicode_compatible
|
||||
class DiskSpaceOptionBase(models.Model):
|
||||
diskspace = models.PositiveIntegerField(_('disk space'))
|
||||
diskspace = models.PositiveIntegerField(_("disk space"))
|
||||
diskspace_unit = models.PositiveSmallIntegerField(
|
||||
_('unit of disk space'), choices=DISK_SPACE_UNITS)
|
||||
_("unit of disk space"), choices=DISK_SPACE_UNITS
|
||||
)
|
||||
|
||||
class Meta:
|
||||
abstract = True
|
||||
ordering = ['diskspace_unit', 'diskspace']
|
||||
verbose_name = _('Disk space option')
|
||||
verbose_name_plural = _('Disk space options')
|
||||
ordering = ["diskspace_unit", "diskspace"]
|
||||
verbose_name = _("Disk space option")
|
||||
verbose_name_plural = _("Disk space options")
|
||||
|
||||
def __str__(self):
|
||||
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):
|
||||
|
@ -95,30 +84,24 @@ class DiskSpaceOption(DiskSpaceOptionBase, HostingOption):
|
|||
"""
|
||||
|
||||
class Meta:
|
||||
unique_together = ['diskspace', 'diskspace_unit']
|
||||
unique_together = ["diskspace", "diskspace_unit"]
|
||||
|
||||
|
||||
@python_2_unicode_compatible
|
||||
class UserDatabaseOptionBase(models.Model):
|
||||
number = models.PositiveIntegerField(
|
||||
_('number of databases'), default=1)
|
||||
db_type = models.PositiveSmallIntegerField(
|
||||
_('database type'), choices=DB_TYPES)
|
||||
number = models.PositiveIntegerField(_("number of databases"), default=1)
|
||||
db_type = models.PositiveSmallIntegerField(_("database type"), choices=DB_TYPES)
|
||||
|
||||
class Meta:
|
||||
abstract = True
|
||||
ordering = ['db_type', 'number']
|
||||
verbose_name = _('Database option')
|
||||
verbose_name_plural = _('Database options')
|
||||
ordering = ["db_type", "number"]
|
||||
verbose_name = _("Database option")
|
||||
verbose_name_plural = _("Database options")
|
||||
|
||||
def __str__(self):
|
||||
return ungettext(
|
||||
'{type} database',
|
||||
'{count} {type} databases',
|
||||
self.number
|
||||
).format(
|
||||
type=self.get_db_type_display(), count=self.number
|
||||
)
|
||||
"{type} database", "{count} {type} databases", self.number
|
||||
).format(type=self.get_db_type_display(), count=self.number)
|
||||
|
||||
|
||||
class UserDatabaseOption(UserDatabaseOptionBase, HostingOption):
|
||||
|
@ -129,7 +112,7 @@ class UserDatabaseOption(UserDatabaseOptionBase, HostingOption):
|
|||
"""
|
||||
|
||||
class Meta:
|
||||
unique_together = ['number', 'db_type']
|
||||
unique_together = ["number", "db_type"]
|
||||
|
||||
|
||||
@python_2_unicode_compatible
|
||||
|
@ -138,23 +121,19 @@ class MailboxOptionBase(models.Model):
|
|||
Base class for mailbox options.
|
||||
|
||||
"""
|
||||
number = models.PositiveIntegerField(
|
||||
_('number of mailboxes'), unique=True)
|
||||
|
||||
number = models.PositiveIntegerField(_("number of mailboxes"), unique=True)
|
||||
|
||||
class Meta:
|
||||
abstract = True
|
||||
ordering = ['number']
|
||||
verbose_name = _('Mailbox option')
|
||||
verbose_name_plural = _('Mailbox options')
|
||||
ordering = ["number"]
|
||||
verbose_name = _("Mailbox option")
|
||||
verbose_name_plural = _("Mailbox options")
|
||||
|
||||
def __str__(self):
|
||||
return ungettext(
|
||||
'{count} additional mailbox',
|
||||
'{count} additional mailboxes',
|
||||
self.number
|
||||
).format(
|
||||
count=self.number
|
||||
)
|
||||
"{count} additional mailbox", "{count} additional mailboxes", self.number
|
||||
).format(count=self.number)
|
||||
|
||||
|
||||
class MailboxOption(MailboxOptionBase, HostingOption):
|
||||
|
@ -189,10 +168,11 @@ class CustomerHostingPackageManager(models.Manager):
|
|||
|
||||
"""
|
||||
package = CustomerHostingPackage(
|
||||
customer=customer, template=template, name=name)
|
||||
customer=customer, template=template, name=name
|
||||
)
|
||||
package.description = template.description
|
||||
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)
|
||||
return package
|
||||
|
||||
|
@ -203,45 +183,49 @@ class CustomerHostingPackage(HostingPackageBase):
|
|||
This class defines customer specific hosting packages.
|
||||
|
||||
"""
|
||||
|
||||
customer = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, verbose_name=_('customer'),
|
||||
on_delete=models.CASCADE)
|
||||
settings.AUTH_USER_MODEL, verbose_name=_("customer"), on_delete=models.CASCADE
|
||||
)
|
||||
template = models.ForeignKey(
|
||||
HostingPackageTemplate, verbose_name=_('hosting package template'),
|
||||
HostingPackageTemplate,
|
||||
verbose_name=_("hosting package template"),
|
||||
help_text=_(
|
||||
'The hosting package template that this hosting package is based'
|
||||
' on'
|
||||
"The hosting package template that this hosting package is based" " on"
|
||||
),
|
||||
on_delete=models.CASCADE)
|
||||
name = models.CharField(_('name'), max_length=128)
|
||||
on_delete=models.CASCADE,
|
||||
)
|
||||
name = models.CharField(_("name"), max_length=128)
|
||||
osuser = models.OneToOneField(
|
||||
OsUser, verbose_name=_('Operating system user'),
|
||||
blank=True, null=True, on_delete=models.CASCADE)
|
||||
OsUser,
|
||||
verbose_name=_("Operating system user"),
|
||||
blank=True,
|
||||
null=True,
|
||||
on_delete=models.CASCADE,
|
||||
)
|
||||
|
||||
objects = CustomerHostingPackageManager()
|
||||
|
||||
class Meta:
|
||||
unique_together = ['customer', 'name']
|
||||
verbose_name = _('customer hosting package')
|
||||
verbose_name_plural = _('customer hosting packages')
|
||||
unique_together = ["customer", "name"]
|
||||
verbose_name = _("customer hosting package")
|
||||
verbose_name_plural = _("customer hosting packages")
|
||||
|
||||
def __str__(self):
|
||||
return _("{name} for {customer}").format(
|
||||
name=self.name, customer=self.customer
|
||||
)
|
||||
return _("{name} for {customer}").format(name=self.name, customer=self.customer)
|
||||
|
||||
def get_absolute_url(self):
|
||||
return reverse('hosting_package_details', kwargs={
|
||||
'user': self.customer.username,
|
||||
'pk': self.id,
|
||||
})
|
||||
return reverse(
|
||||
"hosting_package_details",
|
||||
kwargs={"user": self.customer.username, "pk": self.id},
|
||||
)
|
||||
|
||||
def copy_template_attributes(self):
|
||||
"""
|
||||
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))
|
||||
|
||||
def get_hostingoptions(self):
|
||||
|
@ -249,7 +233,7 @@ class CustomerHostingPackage(HostingPackageBase):
|
|||
for opt_type in [
|
||||
CustomerDiskSpaceOption,
|
||||
CustomerMailboxOption,
|
||||
CustomerUserDatabaseOption
|
||||
CustomerUserDatabaseOption,
|
||||
]:
|
||||
opts.extend(opt_type.objects.filter(hosting_package=self))
|
||||
return opts
|
||||
|
@ -276,13 +260,13 @@ class CustomerHostingPackage(HostingPackageBase):
|
|||
diskspace += option.diskspace
|
||||
elif option.diskspace_unit > min_unit:
|
||||
diskspace += (
|
||||
DISK_SPACE_FACTORS[option.diskspace_unit][min_unit] *
|
||||
option.diskspace)
|
||||
DISK_SPACE_FACTORS[option.diskspace_unit][min_unit]
|
||||
* option.diskspace
|
||||
)
|
||||
else:
|
||||
diskspace = (
|
||||
DISK_SPACE_FACTORS[min_unit][
|
||||
option.diskspace_unit] *
|
||||
diskspace) + option.diskspace
|
||||
DISK_SPACE_FACTORS[min_unit][option.diskspace_unit] * diskspace
|
||||
) + option.diskspace
|
||||
min_unit = option.diskspace_unit
|
||||
if unit is None:
|
||||
return DISK_SPACE_FACTORS[min_unit][0] * diskspace * 1024 ** 2
|
||||
|
@ -302,16 +286,16 @@ class CustomerHostingPackage(HostingPackageBase):
|
|||
|
||||
"""
|
||||
if unit is None:
|
||||
return (DISK_SPACE_FACTORS[self.diskspace_unit][0] *
|
||||
self.diskspace * 1024 ** 2)
|
||||
return (
|
||||
DISK_SPACE_FACTORS[self.diskspace_unit][0] * self.diskspace * 1024 ** 2
|
||||
)
|
||||
if unit > self.diskspace_unit:
|
||||
return (DISK_SPACE_FACTORS[unit][self.diskspace_unit] *
|
||||
self.diskspace)
|
||||
return DISK_SPACE_FACTORS[unit][self.diskspace_unit] * self.diskspace
|
||||
return DISK_SPACE_FACTORS[self.diskspace_unit][unit] * self.diskspace
|
||||
|
||||
def get_quota(self):
|
||||
soft = 1024 * self.get_disk_space(DISK_SPACE_UNITS.M)
|
||||
hard = soft * 105 / 100
|
||||
hard = soft * 105 // 100
|
||||
return (soft, hard)
|
||||
|
||||
def get_mailboxes(self):
|
||||
|
@ -337,12 +321,10 @@ class CustomerHostingPackage(HostingPackageBase):
|
|||
of its mailbox options.
|
||||
|
||||
"""
|
||||
result = CustomerMailboxOption.objects.filter(
|
||||
hosting_package=self
|
||||
).aggregate(
|
||||
mailbox_sum=models.Sum('number')
|
||||
result = CustomerMailboxOption.objects.filter(hosting_package=self).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)
|
||||
|
||||
|
@ -355,25 +337,23 @@ class CustomerHostingPackage(HostingPackageBase):
|
|||
options for this hosting package.
|
||||
|
||||
"""
|
||||
return CustomerUserDatabaseOption.objects.values(
|
||||
'db_type'
|
||||
).filter(hosting_package=self).annotate(
|
||||
number=models.Sum('number')
|
||||
).all()
|
||||
return (
|
||||
CustomerUserDatabaseOption.objects.values("db_type")
|
||||
.filter(hosting_package=self)
|
||||
.annotate(number=models.Sum("number"))
|
||||
.all()
|
||||
)
|
||||
|
||||
def get_databases_flat(self):
|
||||
if self.osuser:
|
||||
return UserDatabase.objects.filter(
|
||||
db_user__osuser=self.osuser).all()
|
||||
return UserDatabase.objects.filter(db_user__osuser=self.osuser).all()
|
||||
|
||||
databases = property(get_databases_flat)
|
||||
|
||||
def may_add_database(self):
|
||||
return (
|
||||
CustomerUserDatabaseOption.objects.filter(
|
||||
hosting_package=self).count() >
|
||||
UserDatabase.objects.filter(
|
||||
db_user__osuser=self.osuser).count()
|
||||
CustomerUserDatabaseOption.objects.filter(hosting_package=self).count()
|
||||
> UserDatabase.objects.filter(db_user__osuser=self.osuser).count()
|
||||
)
|
||||
|
||||
@transaction.atomic
|
||||
|
@ -409,12 +389,16 @@ class CustomerHostingPackageDomain(TimeStampedModel):
|
|||
domain.
|
||||
|
||||
"""
|
||||
|
||||
hosting_package = models.ForeignKey(
|
||||
CustomerHostingPackage, verbose_name=_('hosting package'),
|
||||
related_name='domains', on_delete=models.CASCADE)
|
||||
CustomerHostingPackage,
|
||||
verbose_name=_("hosting package"),
|
||||
related_name="domains",
|
||||
on_delete=models.CASCADE,
|
||||
)
|
||||
domain = models.OneToOneField(
|
||||
HostingDomain, verbose_name=_('hosting domain'),
|
||||
on_delete=models.CASCADE)
|
||||
HostingDomain, verbose_name=_("hosting domain"), on_delete=models.CASCADE
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
return self.domain.domain
|
||||
|
@ -432,60 +416,62 @@ class CustomerHostingPackageOption(TimeStampedModel):
|
|||
This class defines options for customer hosting packages.
|
||||
|
||||
"""
|
||||
|
||||
hosting_package = models.ForeignKey(
|
||||
CustomerHostingPackage, verbose_name=_('hosting package'),
|
||||
on_delete=models.CASCADE)
|
||||
CustomerHostingPackage,
|
||||
verbose_name=_("hosting package"),
|
||||
on_delete=models.CASCADE,
|
||||
)
|
||||
|
||||
class Meta:
|
||||
verbose_name = _('customer hosting option')
|
||||
verbose_name_plural = _('customer hosting options')
|
||||
verbose_name = _("customer hosting option")
|
||||
verbose_name_plural = _("customer hosting options")
|
||||
|
||||
|
||||
class CustomerDiskSpaceOption(DiskSpaceOptionBase,
|
||||
CustomerHostingPackageOption):
|
||||
class CustomerDiskSpaceOption(DiskSpaceOptionBase, CustomerHostingPackageOption):
|
||||
"""
|
||||
This is a class for customer hosting package options adding additional disk
|
||||
space to existing customer hosting package.
|
||||
|
||||
"""
|
||||
|
||||
template = models.ForeignKey(
|
||||
DiskSpaceOption,
|
||||
verbose_name=_('disk space option template'),
|
||||
verbose_name=_("disk space option template"),
|
||||
help_text=_(
|
||||
'The disk space option template that this disk space option is'
|
||||
' based on'
|
||||
"The disk space option template that this disk space option is" " based on"
|
||||
),
|
||||
on_delete=models.CASCADE)
|
||||
on_delete=models.CASCADE,
|
||||
)
|
||||
|
||||
|
||||
class CustomerUserDatabaseOption(UserDatabaseOptionBase,
|
||||
CustomerHostingPackageOption):
|
||||
class CustomerUserDatabaseOption(UserDatabaseOptionBase, CustomerHostingPackageOption):
|
||||
"""
|
||||
This is a class for customer hosting package options adding user databases
|
||||
to existing customer hosting packages.
|
||||
|
||||
"""
|
||||
|
||||
template = models.ForeignKey(
|
||||
UserDatabaseOption,
|
||||
verbose_name=_('user database option template'),
|
||||
verbose_name=_("user database option template"),
|
||||
help_text=_(
|
||||
'The user database option template that this database option is'
|
||||
' based on'
|
||||
"The user database option template that this database option is" " based on"
|
||||
),
|
||||
on_delete=models.CASCADE)
|
||||
on_delete=models.CASCADE,
|
||||
)
|
||||
|
||||
|
||||
class CustomerMailboxOption(MailboxOptionBase,
|
||||
CustomerHostingPackageOption):
|
||||
class CustomerMailboxOption(MailboxOptionBase, CustomerHostingPackageOption):
|
||||
"""
|
||||
This is a class for customer hosting package options adding additional
|
||||
mailboxes to existing customer hosting packages.
|
||||
|
||||
"""
|
||||
|
||||
template = models.ForeignKey(
|
||||
MailboxOption,
|
||||
verbose_name=_('mailbox option template'),
|
||||
help_text=_(
|
||||
'The mailbox option template that this mailbox option is based on'
|
||||
),
|
||||
on_delete=models.CASCADE)
|
||||
verbose_name=_("mailbox option template"),
|
||||
help_text=_("The mailbox option template that this mailbox option is based on"),
|
||||
on_delete=models.CASCADE,
|
||||
)
|
||||
|
|
|
@ -5,10 +5,7 @@ Test for models.
|
|||
|
||||
from django.test import TestCase
|
||||
|
||||
from hostingpackages.models import (
|
||||
DISK_SPACE_UNITS,
|
||||
CustomerHostingPackage,
|
||||
)
|
||||
from hostingpackages.models import DISK_SPACE_UNITS, CustomerHostingPackage
|
||||
|
||||
|
||||
class CustomerHostingPackageTest(TestCase):
|
||||
|
@ -16,7 +13,7 @@ class CustomerHostingPackageTest(TestCase):
|
|||
package = CustomerHostingPackage(
|
||||
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):
|
||||
package = CustomerHostingPackage(
|
||||
|
|
|
@ -1,14 +1,14 @@
|
|||
from django import forms
|
||||
from django.core.urlresolvers import reverse
|
||||
from django.test import TestCase
|
||||
from django.test.utils import override_settings
|
||||
from django.urls import reverse
|
||||
from django.utils.html import format_html
|
||||
from django.utils.translation import ugettext as _
|
||||
|
||||
from django.contrib.admin import AdminSite
|
||||
from django.contrib.auth import get_user_model
|
||||
|
||||
from mock import Mock
|
||||
from unittest.mock import Mock
|
||||
|
||||
from osusers.models import User
|
||||
|
||||
|
@ -21,9 +21,7 @@ from managemails.admin import (
|
|||
ReadOnlyPasswordHashField,
|
||||
ReadOnlyPasswordHashWidget,
|
||||
)
|
||||
from managemails.models import (
|
||||
Mailbox,
|
||||
)
|
||||
from managemails.models import Mailbox
|
||||
|
||||
Customer = get_user_model()
|
||||
|
||||
|
@ -31,14 +29,14 @@ Customer = get_user_model()
|
|||
class ReadOnlyPasswordHashWidgetTest(TestCase):
|
||||
def test_render(self):
|
||||
widget = ReadOnlyPasswordHashWidget()
|
||||
rendered = widget.render('password', 'secret', {'class': 'test'})
|
||||
rendered = widget.render("password", "secret", {"class": "test"})
|
||||
self.assertEqual(
|
||||
rendered,
|
||||
format_html(
|
||||
'<div class="test">{0}</div>',
|
||||
format_html('<strong>{0}</strong>: secret ',
|
||||
_('Hash'))
|
||||
))
|
||||
format_html("<strong>{0}</strong>: secret ", _("Hash")),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class ReadOnlyPasswordHashFieldTest(TestCase):
|
||||
|
@ -48,24 +46,24 @@ class ReadOnlyPasswordHashFieldTest(TestCase):
|
|||
|
||||
def test_bound_data(self):
|
||||
field = ReadOnlyPasswordHashField()
|
||||
self.assertEqual(field.bound_data('new', 'old'), 'old')
|
||||
self.assertEqual(field.bound_data("new", "old"), "old")
|
||||
|
||||
def test__has_changed(self):
|
||||
field = ReadOnlyPasswordHashField()
|
||||
self.assertFalse(field.has_changed('new', 'old'))
|
||||
self.assertFalse(field.has_changed("new", "old"))
|
||||
|
||||
|
||||
class CustomerTestCase(TestCase):
|
||||
def setUp(self):
|
||||
super(CustomerTestCase, self).setUp()
|
||||
self.customer = Customer.objects.create(username='test')
|
||||
self.customer = Customer.objects.create(username="test")
|
||||
|
||||
|
||||
class MailboxCreationFormTest(CustomerTestCase):
|
||||
def test_clean_password2_same(self):
|
||||
form = MailboxCreationForm()
|
||||
form.cleaned_data = {'password1': 'secret', 'password2': 'secret'}
|
||||
self.assertEqual(form.clean_password2(), 'secret')
|
||||
form.cleaned_data = {"password1": "secret", "password2": "secret"}
|
||||
self.assertEqual(form.clean_password2(), "secret")
|
||||
|
||||
def test_clean_password2_empty(self):
|
||||
form = MailboxCreationForm()
|
||||
|
@ -74,59 +72,47 @@ class MailboxCreationFormTest(CustomerTestCase):
|
|||
|
||||
def test_clean_password2_mismatch(self):
|
||||
form = MailboxCreationForm()
|
||||
form.cleaned_data = {'password1': 'secretx', 'password2': 'secrety'}
|
||||
form.cleaned_data = {"password1": "secretx", "password2": "secrety"}
|
||||
with self.assertRaises(forms.ValidationError) as cm:
|
||||
form.clean_password2()
|
||||
self.assertEqual(cm.exception.message, PASSWORD_MISMATCH_ERROR)
|
||||
|
||||
@override_settings(
|
||||
CELERY_ALWAYS_EAGER=True,
|
||||
CELERY_CACHE_BACKEND='memory',
|
||||
BROKER_BACKEND='memory'
|
||||
CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
|
||||
)
|
||||
def test_save_commit(self):
|
||||
user = User.objects.create_user(customer=self.customer)
|
||||
form = MailboxCreationForm(data={
|
||||
'osuser': user.uid,
|
||||
'password1': 'secret',
|
||||
'password2': 'secret',
|
||||
})
|
||||
form = MailboxCreationForm(
|
||||
data={"osuser": user.uid, "password1": "secret", "password2": "secret"}
|
||||
)
|
||||
mailbox = form.save()
|
||||
self.assertIsNotNone(mailbox)
|
||||
self.assertEqual(
|
||||
len(Mailbox.objects.filter(osuser=user)), 1)
|
||||
self.assertEqual(len(Mailbox.objects.filter(osuser=user)), 1)
|
||||
|
||||
@override_settings(
|
||||
CELERY_ALWAYS_EAGER=True,
|
||||
CELERY_CACHE_BACKEND='memory',
|
||||
BROKER_BACKEND='memory'
|
||||
CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
|
||||
)
|
||||
def test_save_no_commit(self):
|
||||
user = User.objects.create_user(customer=self.customer)
|
||||
form = MailboxCreationForm(data={
|
||||
'osuser': user.uid,
|
||||
'password1': 'secret',
|
||||
'password2': 'secret',
|
||||
})
|
||||
form = MailboxCreationForm(
|
||||
data={"osuser": user.uid, "password1": "secret", "password2": "secret"}
|
||||
)
|
||||
mailbox = form.save(commit=False)
|
||||
self.assertIsNotNone(mailbox)
|
||||
self.assertEqual(
|
||||
len(Mailbox.objects.filter(osuser=user)), 0)
|
||||
self.assertEqual(len(Mailbox.objects.filter(osuser=user)), 0)
|
||||
|
||||
|
||||
class MailboxChangeFormTest(CustomerTestCase):
|
||||
@override_settings(
|
||||
CELERY_ALWAYS_EAGER=True,
|
||||
CELERY_CACHE_BACKEND='memory',
|
||||
BROKER_BACKEND='memory'
|
||||
CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
|
||||
)
|
||||
def test_clean_password(self):
|
||||
mailbox = Mailbox(
|
||||
username='test',
|
||||
osuser=User.objects.create_user(customer=self.customer))
|
||||
mailbox.set_password('test')
|
||||
username="test", osuser=User.objects.create_user(customer=self.customer)
|
||||
)
|
||||
mailbox.set_password("test")
|
||||
mailbox.save()
|
||||
form = MailboxChangeForm(instance=mailbox, data={'password': 'blub'})
|
||||
form = MailboxChangeForm(instance=mailbox, data={"password": "blub"})
|
||||
self.assertEqual(form.clean_password(), mailbox.password)
|
||||
|
||||
|
||||
|
@ -151,55 +137,43 @@ class MailBoxAdminTest(CustomerTestCase):
|
|||
self.mbadmin = MailboxAdmin(Mailbox, site)
|
||||
|
||||
def test_get_fieldsets_without_object(self):
|
||||
self.assertEqual(
|
||||
self.mbadmin.get_fieldsets(Mock()),
|
||||
self.mbadmin.add_fieldsets)
|
||||
self.assertEqual(self.mbadmin.get_fieldsets(Mock()), self.mbadmin.add_fieldsets)
|
||||
|
||||
@override_settings(
|
||||
CELERY_ALWAYS_EAGER=True,
|
||||
CELERY_CACHE_BACKEND='memory',
|
||||
BROKER_BACKEND='memory'
|
||||
CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
|
||||
)
|
||||
def test_get_fieldsets_with_object(self):
|
||||
mailbox = Mailbox(
|
||||
username='test',
|
||||
osuser=User.objects.create_user(customer=self.customer))
|
||||
mailbox.set_password('test')
|
||||
username="test", osuser=User.objects.create_user(customer=self.customer)
|
||||
)
|
||||
mailbox.set_password("test")
|
||||
mailbox.save()
|
||||
self.assertEqual(
|
||||
self.mbadmin.get_fieldsets(Mock(), mailbox),
|
||||
self.mbadmin.fieldsets)
|
||||
self.mbadmin.get_fieldsets(Mock(), mailbox), self.mbadmin.fieldsets
|
||||
)
|
||||
|
||||
def test_get_form_without_object(self):
|
||||
form = self.mbadmin.get_form(Mock)
|
||||
self.assertEqual(
|
||||
form.Meta.fields,
|
||||
['osuser', 'password1', 'password2']
|
||||
)
|
||||
self.assertEqual(form.Meta.fields, ["osuser", "password1", "password2"])
|
||||
|
||||
@override_settings(
|
||||
CELERY_ALWAYS_EAGER=True,
|
||||
CELERY_CACHE_BACKEND='memory',
|
||||
BROKER_BACKEND='memory'
|
||||
CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
|
||||
)
|
||||
def test_get_form_with_object(self):
|
||||
mailbox = Mailbox(
|
||||
username='test',
|
||||
osuser=User.objects.create_user(customer=self.customer))
|
||||
mailbox.set_password('test')
|
||||
username="test", osuser=User.objects.create_user(customer=self.customer)
|
||||
)
|
||||
mailbox.set_password("test")
|
||||
mailbox.save()
|
||||
form = self.mbadmin.get_form(Mock, mailbox)
|
||||
self.assertEqual(
|
||||
form.Meta.fields,
|
||||
['osuser', 'username', 'password', 'active']
|
||||
)
|
||||
self.assertEqual(form.Meta.fields, ["osuser", "username", "password", "active"])
|
||||
|
||||
def test_admin_for_mailbox(self):
|
||||
admin_url = reverse('admin:managemails_mailaddress_changelist')
|
||||
admin_url = reverse("admin:managemails_mailaddress_changelist")
|
||||
self.assertIsNotNone(admin_url)
|
||||
|
||||
|
||||
class MailAddressAdminTest(TestCase):
|
||||
def test_admin_for_mailaddress(self):
|
||||
admin_url = reverse('admin:managemails_mailaddress_changelist')
|
||||
admin_url = reverse("admin:managemails_mailaddress_changelist")
|
||||
self.assertIsNotNone(admin_url)
|
||||
|
|
|
@ -2,13 +2,11 @@
|
|||
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.test import TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from managemails.forms import (
|
||||
AddMailAddressForm,
|
||||
|
@ -22,7 +20,6 @@ from managemails.forms import (
|
|||
|
||||
|
||||
class CreateMailboxFormTest(TestCase):
|
||||
|
||||
def test_constructor_needs_hostingpackage(self):
|
||||
instance = MagicMock()
|
||||
with self.assertRaises(KeyError):
|
||||
|
@ -32,33 +29,35 @@ class CreateMailboxFormTest(TestCase):
|
|||
hostingpackage = Mock(id=42)
|
||||
instance = MagicMock()
|
||||
form = CreateMailboxForm(instance, hostingpackage=hostingpackage)
|
||||
self.assertTrue(hasattr(form, 'hosting_package'))
|
||||
self.assertTrue(hasattr(form, "hosting_package"))
|
||||
self.assertEqual(form.hosting_package, hostingpackage)
|
||||
self.assertTrue(hasattr(form, 'helper'))
|
||||
self.assertEqual(form.helper.form_action, reverse(
|
||||
'create_mailbox', kwargs={'package': 42}))
|
||||
self.assertIn('password1', form.fields)
|
||||
self.assertIn('password2', form.fields)
|
||||
self.assertEqual(form.helper.inputs[0].name, 'submit')
|
||||
self.assertTrue(hasattr(form, "helper"))
|
||||
self.assertEqual(
|
||||
form.helper.form_action, reverse("create_mailbox", kwargs={"package": 42})
|
||||
)
|
||||
self.assertIn("password1", form.fields)
|
||||
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):
|
||||
osuser = MagicMock()
|
||||
hostingpackage = Mock(id=42, osuser=osuser)
|
||||
instance = MagicMock()
|
||||
form = CreateMailboxForm(
|
||||
instance=instance, hostingpackage=hostingpackage,
|
||||
data={'password1': 'secret', 'password2': 'secret'})
|
||||
mailbox_objects.get_next_mailbox_name.return_value = 'mailbox23'
|
||||
instance=instance,
|
||||
hostingpackage=hostingpackage,
|
||||
data={"password1": "secret", "password2": "secret"},
|
||||
)
|
||||
mailbox_objects.get_next_mailbox_name.return_value = "mailbox23"
|
||||
self.assertTrue(form.is_valid())
|
||||
form.save(commit=False)
|
||||
self.assertEqual(osuser, form.instance.osuser)
|
||||
self.assertEqual('mailbox23', form.instance.username)
|
||||
instance.set_password.assert_called_with('secret')
|
||||
self.assertEqual("mailbox23", form.instance.username)
|
||||
instance.set_password.assert_called_with("secret")
|
||||
|
||||
|
||||
class ChangeMailboxPasswordFormTest(TestCase):
|
||||
|
||||
def test_constructor_needs_hostingpackage(self):
|
||||
instance = MagicMock()
|
||||
with self.assertRaises(KeyError):
|
||||
|
@ -66,72 +65,75 @@ class ChangeMailboxPasswordFormTest(TestCase):
|
|||
|
||||
def test_constructor(self):
|
||||
hostingpackage = Mock(id=42)
|
||||
instance = MagicMock(username='testuser')
|
||||
instance = MagicMock(username="testuser")
|
||||
form = ChangeMailboxPasswordForm(
|
||||
instance=instance, hostingpackage=hostingpackage)
|
||||
self.assertTrue(hasattr(form, 'hosting_package'))
|
||||
instance=instance, hostingpackage=hostingpackage
|
||||
)
|
||||
self.assertTrue(hasattr(form, "hosting_package"))
|
||||
self.assertEqual(form.hosting_package, hostingpackage)
|
||||
self.assertTrue(hasattr(form, 'helper'))
|
||||
self.assertEqual(form.helper.form_action, reverse(
|
||||
'change_mailbox_password', kwargs={
|
||||
'package': 42, 'slug': 'testuser'}))
|
||||
self.assertIn('password1', form.fields)
|
||||
self.assertIn('password2', form.fields)
|
||||
self.assertEqual(form.helper.inputs[0].name, 'submit')
|
||||
self.assertTrue(hasattr(form, "helper"))
|
||||
self.assertEqual(
|
||||
form.helper.form_action,
|
||||
reverse(
|
||||
"change_mailbox_password", kwargs={"package": 42, "slug": "testuser"}
|
||||
),
|
||||
)
|
||||
self.assertIn("password1", form.fields)
|
||||
self.assertIn("password2", form.fields)
|
||||
self.assertEqual(form.helper.inputs[0].name, "submit")
|
||||
|
||||
def test_save(self):
|
||||
hostingpackage = Mock(id=42)
|
||||
instance = MagicMock(username='testuser')
|
||||
instance = MagicMock(username="testuser")
|
||||
form = ChangeMailboxPasswordForm(
|
||||
instance=instance, hostingpackage=hostingpackage,
|
||||
data={'password1': 'newsecret', 'password2': 'newsecret'})
|
||||
instance=instance,
|
||||
hostingpackage=hostingpackage,
|
||||
data={"password1": "newsecret", "password2": "newsecret"},
|
||||
)
|
||||
self.assertTrue(form.is_valid())
|
||||
form.save(commit=False)
|
||||
instance.set_password.assert_called_with('newsecret')
|
||||
instance.set_password.assert_called_with("newsecret")
|
||||
|
||||
|
||||
class MultipleEmailValidatorTest(TestCase):
|
||||
|
||||
def test_valid_single_address(self):
|
||||
self.assertEqual(
|
||||
'test@example.org',
|
||||
multiple_email_validator('test@example.org'))
|
||||
"test@example.org", multiple_email_validator("test@example.org")
|
||||
)
|
||||
|
||||
def test_valid_multiple_addresses(self):
|
||||
self.assertEqual(
|
||||
'test1@example.org,test2@example.org',
|
||||
multiple_email_validator('test1@example.org,test2@example.org'))
|
||||
"test1@example.org,test2@example.org",
|
||||
multiple_email_validator("test1@example.org,test2@example.org"),
|
||||
)
|
||||
|
||||
def test_empty(self):
|
||||
self.assertEqual(
|
||||
'', multiple_email_validator(''))
|
||||
self.assertEqual("", multiple_email_validator(""))
|
||||
|
||||
def test_none(self):
|
||||
self.assertIsNone(multiple_email_validator(None))
|
||||
|
||||
def test_invalid_single_address(self):
|
||||
with self.assertRaises(ValidationError):
|
||||
multiple_email_validator('no@ddress')
|
||||
multiple_email_validator("no@ddress")
|
||||
|
||||
def test_invalid_multiple_addresses(self):
|
||||
with self.assertRaises(ValidationError):
|
||||
multiple_email_validator('test1@example.org,no@ddress')
|
||||
multiple_email_validator("test1@example.org,no@ddress")
|
||||
|
||||
|
||||
class MailAddressFieldMixinTest(TestCase):
|
||||
|
||||
def test_fields_defined(self):
|
||||
form = MailAddressFieldMixin()
|
||||
self.assertIn('mailbox_or_forwards', form.fields)
|
||||
self.assertIn('mailbox', form.fields)
|
||||
self.assertIn('forwards', form.fields)
|
||||
self.assertIn("mailbox_or_forwards", form.fields)
|
||||
self.assertIn("mailbox", form.fields)
|
||||
self.assertIn("forwards", form.fields)
|
||||
|
||||
|
||||
class AddMailAddressFormTest(TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.patcher1 = patch('managemails.forms.Mailbox.objects')
|
||||
self.patcher2 = patch('managemails.forms.MailAddress.objects')
|
||||
self.patcher1 = patch("managemails.forms.Mailbox.objects")
|
||||
self.patcher2 = patch("managemails.forms.MailAddress.objects")
|
||||
self.mailbox_objects = self.patcher1.start()
|
||||
self.mailaddress_objects = self.patcher2.start()
|
||||
|
||||
|
@ -151,175 +153,192 @@ class AddMailAddressFormTest(TestCase):
|
|||
|
||||
def test_constructor(self):
|
||||
instance = MagicMock()
|
||||
osuser = Mock(username='testuser')
|
||||
osuser = Mock(username="testuser")
|
||||
hostingpackage = MagicMock(id=42, osuser=osuser)
|
||||
maildomain = MagicMock(domain='example.org')
|
||||
maildomain = MagicMock(domain="example.org")
|
||||
form = AddMailAddressForm(
|
||||
instance=instance, hostingpackage=hostingpackage,
|
||||
maildomain=maildomain)
|
||||
instance=instance, hostingpackage=hostingpackage, maildomain=maildomain
|
||||
)
|
||||
self.mailbox_objects.unused.assert_called_with(osuser=osuser)
|
||||
self.assertIn('mailbox_or_forwards', form.fields)
|
||||
self.assertIn('mailbox', form.fields)
|
||||
self.assertIn('forwards', form.fields)
|
||||
self.assertTrue(hasattr(form, 'hosting_package'))
|
||||
self.assertIn("mailbox_or_forwards", form.fields)
|
||||
self.assertIn("mailbox", form.fields)
|
||||
self.assertIn("forwards", form.fields)
|
||||
self.assertTrue(hasattr(form, "hosting_package"))
|
||||
self.assertEqual(form.hosting_package, hostingpackage)
|
||||
self.assertTrue(hasattr(form, 'maildomain'))
|
||||
self.assertTrue(hasattr(form, "maildomain"))
|
||||
self.assertEqual(form.maildomain, maildomain)
|
||||
self.assertTrue(hasattr(form, 'helper'))
|
||||
self.assertEqual(form.helper.form_action, reverse(
|
||||
'add_mailaddress', kwargs={
|
||||
'package': 42, 'domain': 'example.org'}))
|
||||
self.assertTrue(hasattr(form, "helper"))
|
||||
self.assertEqual(
|
||||
form.helper.form_action,
|
||||
reverse("add_mailaddress", kwargs={"package": 42, "domain": "example.org"}),
|
||||
)
|
||||
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):
|
||||
instance = MagicMock()
|
||||
osuser = Mock(username='testuser')
|
||||
osuser = Mock(username="testuser")
|
||||
hostingpackage = MagicMock(id=42, osuser=osuser)
|
||||
maildomain = MagicMock(domain='example.org')
|
||||
maildomain = MagicMock(domain="example.org")
|
||||
form = AddMailAddressForm(
|
||||
instance=instance, hostingpackage=hostingpackage,
|
||||
instance=instance,
|
||||
hostingpackage=hostingpackage,
|
||||
maildomain=maildomain,
|
||||
data={
|
||||
'localpart': 'test',
|
||||
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.forwards,
|
||||
'forwards': 'test2@example.org'
|
||||
})
|
||||
"localpart": "test",
|
||||
"mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
|
||||
"forwards": "test2@example.org",
|
||||
},
|
||||
)
|
||||
self.mailaddress_objects.filter(
|
||||
domain=maildomain, localpart='test'
|
||||
domain=maildomain, localpart="test"
|
||||
).exists.return_value = False
|
||||
self.assertTrue(form.is_valid())
|
||||
self.assertEqual('test', form.clean_localpart())
|
||||
self.assertEqual("test", form.clean_localpart())
|
||||
|
||||
def test_clean_localpart_duplicate(self):
|
||||
instance = MagicMock()
|
||||
osuser = Mock(username='testuser')
|
||||
osuser = Mock(username="testuser")
|
||||
hostingpackage = MagicMock(id=42, osuser=osuser)
|
||||
maildomain = MagicMock(domain='example.org')
|
||||
maildomain = MagicMock(domain="example.org")
|
||||
form = AddMailAddressForm(
|
||||
instance=instance, hostingpackage=hostingpackage,
|
||||
instance=instance,
|
||||
hostingpackage=hostingpackage,
|
||||
maildomain=maildomain,
|
||||
data={
|
||||
'localpart': 'test',
|
||||
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.forwards,
|
||||
'forwards': 'test2@example.org'
|
||||
})
|
||||
"localpart": "test",
|
||||
"mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
|
||||
"forwards": "test2@example.org",
|
||||
},
|
||||
)
|
||||
self.mailaddress_objects.filter(
|
||||
domain=maildomain, localpart='test'
|
||||
domain=maildomain, localpart="test"
|
||||
).exists.return_value = True
|
||||
self.assertFalse(form.is_valid())
|
||||
self.assertIn('localpart', form.errors)
|
||||
self.assertIn("localpart", form.errors)
|
||||
|
||||
def test_clean_no_mailbox_choice(self):
|
||||
instance = MagicMock()
|
||||
osuser = Mock(username='testuser')
|
||||
osuser = Mock(username="testuser")
|
||||
hostingpackage = MagicMock(id=42, osuser=osuser)
|
||||
maildomain = MagicMock(domain='example.org')
|
||||
maildomain = MagicMock(domain="example.org")
|
||||
form = AddMailAddressForm(
|
||||
instance=instance, hostingpackage=hostingpackage,
|
||||
instance=instance,
|
||||
hostingpackage=hostingpackage,
|
||||
maildomain=maildomain,
|
||||
data={
|
||||
'localpart': 'test',
|
||||
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.mailbox,
|
||||
})
|
||||
"localpart": "test",
|
||||
"mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
|
||||
},
|
||||
)
|
||||
self.mailaddress_objects.filter(
|
||||
domain=maildomain, localpart='test'
|
||||
domain=maildomain, localpart="test"
|
||||
).exists.return_value = False
|
||||
self.assertFalse(form.is_valid())
|
||||
self.assertIn('mailbox', form.errors)
|
||||
self.assertIn("mailbox", form.errors)
|
||||
|
||||
def test_clean_no_forward_address_choice(self):
|
||||
instance = MagicMock()
|
||||
osuser = Mock(username='testuser')
|
||||
osuser = Mock(username="testuser")
|
||||
hostingpackage = MagicMock(id=42, osuser=osuser)
|
||||
maildomain = MagicMock(domain='example.org')
|
||||
maildomain = MagicMock(domain="example.org")
|
||||
form = AddMailAddressForm(
|
||||
instance=instance, hostingpackage=hostingpackage,
|
||||
instance=instance,
|
||||
hostingpackage=hostingpackage,
|
||||
maildomain=maildomain,
|
||||
data={
|
||||
'localpart': 'test',
|
||||
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.forwards,
|
||||
})
|
||||
"localpart": "test",
|
||||
"mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
|
||||
},
|
||||
)
|
||||
self.mailaddress_objects.filter(
|
||||
domain=maildomain, localpart='test'
|
||||
domain=maildomain, localpart="test"
|
||||
).exists.return_value = False
|
||||
self.assertFalse(form.is_valid())
|
||||
self.assertIn('forwards', form.errors)
|
||||
self.assertIn("forwards", form.errors)
|
||||
|
||||
def test_save_with_forwards_no_commit(self):
|
||||
instance = MagicMock()
|
||||
osuser = Mock(username='testuser')
|
||||
osuser = Mock(username="testuser")
|
||||
hostingpackage = MagicMock(id=42, osuser=osuser)
|
||||
maildomain = MagicMock(domain='example.org')
|
||||
maildomain = MagicMock(domain="example.org")
|
||||
form = AddMailAddressForm(
|
||||
instance=instance, hostingpackage=hostingpackage,
|
||||
instance=instance,
|
||||
hostingpackage=hostingpackage,
|
||||
maildomain=maildomain,
|
||||
data={
|
||||
'localpart': 'test',
|
||||
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.forwards,
|
||||
'forwards': 'test2@example.org,test3@example.org'
|
||||
})
|
||||
"localpart": "test",
|
||||
"mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
|
||||
"forwards": "test2@example.org,test3@example.org",
|
||||
},
|
||||
)
|
||||
self.mailaddress_objects.filter(
|
||||
domain=maildomain, localpart='test'
|
||||
domain=maildomain, localpart="test"
|
||||
).exists.return_value = False
|
||||
self.assertTrue(form.is_valid())
|
||||
address1 = MagicMock(mailaddress='test2@example.org')
|
||||
address2 = MagicMock(mailaddress='test3@example.org')
|
||||
address1 = MagicMock(mailaddress="test2@example.org")
|
||||
address2 = MagicMock(mailaddress="test3@example.org")
|
||||
instance.set_forward_addresses.return_value = [address1, address2]
|
||||
form.save(commit=False)
|
||||
self.assertEqual(maildomain, instance.domain)
|
||||
instance.set_forward_addresses.assert_called_with([
|
||||
'test2@example.org', 'test3@example.org'], commit=False)
|
||||
instance.set_forward_addresses.assert_called_with(
|
||||
["test2@example.org", "test3@example.org"], commit=False
|
||||
)
|
||||
address1.save.assert_not_called()
|
||||
address2.save.assert_not_called()
|
||||
instance.save.assert_not_called()
|
||||
|
||||
def test_save_with_forwards_commit(self):
|
||||
instance = MagicMock()
|
||||
osuser = Mock(username='testuser')
|
||||
osuser = Mock(username="testuser")
|
||||
hostingpackage = MagicMock(id=42, osuser=osuser)
|
||||
maildomain = MagicMock(domain='example.org')
|
||||
maildomain = MagicMock(domain="example.org")
|
||||
form = AddMailAddressForm(
|
||||
instance=instance, hostingpackage=hostingpackage,
|
||||
instance=instance,
|
||||
hostingpackage=hostingpackage,
|
||||
maildomain=maildomain,
|
||||
data={
|
||||
'localpart': 'test',
|
||||
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.forwards,
|
||||
'forwards': 'test2@example.org,test3@example.org'
|
||||
})
|
||||
"localpart": "test",
|
||||
"mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
|
||||
"forwards": "test2@example.org,test3@example.org",
|
||||
},
|
||||
)
|
||||
self.mailaddress_objects.filter(
|
||||
domain=maildomain, localpart='test'
|
||||
domain=maildomain, localpart="test"
|
||||
).exists.return_value = False
|
||||
self.assertTrue(form.is_valid())
|
||||
address1 = MagicMock(mailaddress='test2@example.org')
|
||||
address2 = MagicMock(mailaddress='test3@example.org')
|
||||
address1 = MagicMock(mailaddress="test2@example.org")
|
||||
address2 = MagicMock(mailaddress="test3@example.org")
|
||||
instance.set_forward_addresses.return_value = [address1, address2]
|
||||
form.save(commit=True)
|
||||
self.assertEqual(maildomain, instance.domain)
|
||||
instance.set_forward_addresses.assert_called_with([
|
||||
'test2@example.org', 'test3@example.org'], commit=False)
|
||||
instance.set_forward_addresses.assert_called_with(
|
||||
["test2@example.org", "test3@example.org"], commit=False
|
||||
)
|
||||
address1.save.assert_called_with()
|
||||
address2.save.assert_called_with()
|
||||
instance.save.assert_called_with()
|
||||
|
||||
def test_save_with_mailbox_no_commit(self):
|
||||
instance = MagicMock()
|
||||
osuser = Mock(username='testuser')
|
||||
osuser = Mock(username="testuser")
|
||||
hostingpackage = MagicMock(id=42, osuser=osuser)
|
||||
maildomain = MagicMock(domain='example.org')
|
||||
maildomain = MagicMock(domain="example.org")
|
||||
form = AddMailAddressForm(
|
||||
instance=instance, hostingpackage=hostingpackage,
|
||||
instance=instance,
|
||||
hostingpackage=hostingpackage,
|
||||
maildomain=maildomain,
|
||||
data={
|
||||
'localpart': 'test',
|
||||
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.mailbox,
|
||||
'mailbox': 'mailbox23',
|
||||
})
|
||||
"localpart": "test",
|
||||
"mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
|
||||
"mailbox": "mailbox23",
|
||||
},
|
||||
)
|
||||
self.mailaddress_objects.filter(
|
||||
domain=maildomain, localpart='test'
|
||||
domain=maildomain, localpart="test"
|
||||
).exists.return_value = False
|
||||
self.assertTrue(form.is_valid())
|
||||
mailbox = MagicMock(osuser=osuser, username='testuserp01')
|
||||
mailbox = MagicMock(osuser=osuser, username="testuserp01")
|
||||
instance.set_mailbox.return_value = mailbox
|
||||
form.save(commit=False)
|
||||
self.assertEqual(maildomain, instance.domain)
|
||||
|
@ -329,22 +348,24 @@ class AddMailAddressFormTest(TestCase):
|
|||
|
||||
def test_save_with_mailbox_commit(self):
|
||||
instance = MagicMock()
|
||||
osuser = Mock(username='testuser')
|
||||
osuser = Mock(username="testuser")
|
||||
hostingpackage = MagicMock(id=42, osuser=osuser)
|
||||
maildomain = MagicMock(domain='example.org')
|
||||
maildomain = MagicMock(domain="example.org")
|
||||
form = AddMailAddressForm(
|
||||
instance=instance, hostingpackage=hostingpackage,
|
||||
instance=instance,
|
||||
hostingpackage=hostingpackage,
|
||||
maildomain=maildomain,
|
||||
data={
|
||||
'localpart': 'test',
|
||||
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.mailbox,
|
||||
'mailbox': 'mailbox23',
|
||||
})
|
||||
"localpart": "test",
|
||||
"mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
|
||||
"mailbox": "mailbox23",
|
||||
},
|
||||
)
|
||||
self.mailaddress_objects.filter(
|
||||
domain=maildomain, localpart='test'
|
||||
domain=maildomain, localpart="test"
|
||||
).exists.return_value = False
|
||||
self.assertTrue(form.is_valid())
|
||||
mailbox = MagicMock(osuser=osuser, username='testuserp01')
|
||||
mailbox = MagicMock(osuser=osuser, username="testuserp01")
|
||||
instance.set_mailbox.return_value = mailbox
|
||||
form.save(commit=True)
|
||||
self.assertEqual(maildomain, instance.domain)
|
||||
|
@ -355,26 +376,28 @@ class AddMailAddressFormTest(TestCase):
|
|||
|
||||
def test_save_with_other_choice(self):
|
||||
instance = MagicMock()
|
||||
osuser = Mock(username='testuser')
|
||||
osuser = Mock(username="testuser")
|
||||
hostingpackage = MagicMock(id=42, osuser=osuser)
|
||||
maildomain = MagicMock(domain='example.org')
|
||||
maildomain = MagicMock(domain="example.org")
|
||||
form = AddMailAddressForm(
|
||||
instance=instance, hostingpackage=hostingpackage,
|
||||
instance=instance,
|
||||
hostingpackage=hostingpackage,
|
||||
maildomain=maildomain,
|
||||
data={
|
||||
'localpart': 'test',
|
||||
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.mailbox,
|
||||
'mailbox': 'mailbox23',
|
||||
})
|
||||
"localpart": "test",
|
||||
"mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
|
||||
"mailbox": "mailbox23",
|
||||
},
|
||||
)
|
||||
self.mailaddress_objects.filter(
|
||||
domain=maildomain, localpart='test'
|
||||
domain=maildomain, localpart="test"
|
||||
).exists.return_value = False
|
||||
self.assertTrue(form.is_valid())
|
||||
form.cleaned_data['mailbox_or_forwards'] = -1
|
||||
address1 = MagicMock(mailaddress='test2@example.org')
|
||||
address2 = MagicMock(mailaddress='test3@example.org')
|
||||
form.cleaned_data["mailbox_or_forwards"] = -1
|
||||
address1 = MagicMock(mailaddress="test2@example.org")
|
||||
address2 = MagicMock(mailaddress="test3@example.org")
|
||||
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
|
||||
form.save(commit=True)
|
||||
instance.set_mailbox.assert_not_called()
|
||||
|
@ -386,10 +409,9 @@ class AddMailAddressFormTest(TestCase):
|
|||
|
||||
|
||||
class EditMailAddressFormTest(TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.patcher1 = patch('managemails.forms.Mailbox.objects')
|
||||
self.patcher2 = patch('managemails.forms.MailAddress.objects')
|
||||
self.patcher1 = patch("managemails.forms.Mailbox.objects")
|
||||
self.patcher2 = patch("managemails.forms.MailAddress.objects")
|
||||
self.mailbox_objects = self.patcher1.start()
|
||||
self.mailaddress_objects = self.patcher2.start()
|
||||
|
||||
|
@ -409,115 +431,125 @@ class EditMailAddressFormTest(TestCase):
|
|||
|
||||
def test_constructor(self):
|
||||
instance = MagicMock(id=23)
|
||||
osuser = Mock(username='testuser')
|
||||
osuser = Mock(username="testuser")
|
||||
hostingpackage = MagicMock(id=42, osuser=osuser)
|
||||
maildomain = MagicMock(domain='example.org')
|
||||
maildomain = MagicMock(domain="example.org")
|
||||
form = EditMailAddressForm(
|
||||
instance=instance, maildomain=maildomain,
|
||||
hostingpackage=hostingpackage)
|
||||
instance=instance, maildomain=maildomain, hostingpackage=hostingpackage
|
||||
)
|
||||
self.mailbox_objects.unused_or_own.assert_called_with(instance, osuser)
|
||||
self.assertIn('mailbox_or_forwards', form.fields)
|
||||
self.assertIn('mailbox', form.fields)
|
||||
self.assertIn('forwards', form.fields)
|
||||
self.assertTrue(hasattr(form, 'hosting_package'))
|
||||
self.assertIn("mailbox_or_forwards", form.fields)
|
||||
self.assertIn("mailbox", form.fields)
|
||||
self.assertIn("forwards", form.fields)
|
||||
self.assertTrue(hasattr(form, "hosting_package"))
|
||||
self.assertEqual(form.hosting_package, hostingpackage)
|
||||
self.assertTrue(hasattr(form, 'maildomain'))
|
||||
self.assertTrue(hasattr(form, "maildomain"))
|
||||
self.assertEqual(form.maildomain, maildomain)
|
||||
self.assertTrue(hasattr(form, 'helper'))
|
||||
self.assertEqual(form.helper.form_action, reverse(
|
||||
'edit_mailaddress', kwargs={
|
||||
'package': 42,
|
||||
'domain': 'example.org',
|
||||
'pk': 23}))
|
||||
self.assertTrue(hasattr(form, "helper"))
|
||||
self.assertEqual(
|
||||
form.helper.form_action,
|
||||
reverse(
|
||||
"edit_mailaddress",
|
||||
kwargs={"package": 42, "domain": "example.org", "pk": 23},
|
||||
),
|
||||
)
|
||||
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):
|
||||
instance = MagicMock(id=23)
|
||||
osuser = Mock(username='testuser')
|
||||
osuser = Mock(username="testuser")
|
||||
hostingpackage = MagicMock(id=42, osuser=osuser)
|
||||
maildomain = MagicMock(domain='example.org')
|
||||
maildomain = MagicMock(domain="example.org")
|
||||
form = EditMailAddressForm(
|
||||
instance=instance, maildomain=maildomain,
|
||||
instance=instance,
|
||||
maildomain=maildomain,
|
||||
hostingpackage=hostingpackage,
|
||||
data={
|
||||
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.mailbox,
|
||||
})
|
||||
data={"mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox},
|
||||
)
|
||||
self.assertFalse(form.is_valid())
|
||||
self.assertIn('mailbox', form.errors)
|
||||
self.assertIn("mailbox", form.errors)
|
||||
|
||||
def test_clean_no_forward_address_choice(self):
|
||||
instance = MagicMock(id=23)
|
||||
osuser = Mock(username='testuser')
|
||||
osuser = Mock(username="testuser")
|
||||
hostingpackage = MagicMock(id=42, osuser=osuser)
|
||||
maildomain = MagicMock(domain='example.org')
|
||||
maildomain = MagicMock(domain="example.org")
|
||||
form = EditMailAddressForm(
|
||||
instance=instance, maildomain=maildomain,
|
||||
instance=instance,
|
||||
maildomain=maildomain,
|
||||
hostingpackage=hostingpackage,
|
||||
data={
|
||||
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.forwards,
|
||||
})
|
||||
data={"mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards},
|
||||
)
|
||||
self.assertFalse(form.is_valid())
|
||||
self.assertIn('forwards', form.errors)
|
||||
self.assertIn("forwards", form.errors)
|
||||
|
||||
def test_save_with_forwards_no_commit(self):
|
||||
instance = MagicMock(id=23)
|
||||
osuser = Mock(username='testuser')
|
||||
osuser = Mock(username="testuser")
|
||||
hostingpackage = MagicMock(id=42, osuser=osuser)
|
||||
maildomain = MagicMock(domain='example.org')
|
||||
maildomain = MagicMock(domain="example.org")
|
||||
form = EditMailAddressForm(
|
||||
instance=instance, maildomain=maildomain,
|
||||
instance=instance,
|
||||
maildomain=maildomain,
|
||||
hostingpackage=hostingpackage,
|
||||
data={
|
||||
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.forwards,
|
||||
'forwards': 'test2@example.org,test3@example.org'
|
||||
})
|
||||
"mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
|
||||
"forwards": "test2@example.org,test3@example.org",
|
||||
},
|
||||
)
|
||||
self.assertTrue(form.is_valid())
|
||||
address1 = MagicMock(mailaddress='test2@example.org')
|
||||
address2 = MagicMock(mailaddress='test3@example.org')
|
||||
address1 = MagicMock(mailaddress="test2@example.org")
|
||||
address2 = MagicMock(mailaddress="test3@example.org")
|
||||
instance.set_forward_addresses.return_value = [address1, address2]
|
||||
form.save(commit=False)
|
||||
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()
|
||||
address2.save.assert_not_called()
|
||||
instance.save.assert_not_called()
|
||||
|
||||
def test_save_with_forwards_commit(self):
|
||||
instance = MagicMock(id=23)
|
||||
osuser = Mock(username='testuser')
|
||||
osuser = Mock(username="testuser")
|
||||
hostingpackage = MagicMock(id=42, osuser=osuser)
|
||||
maildomain = MagicMock(domain='example.org')
|
||||
maildomain = MagicMock(domain="example.org")
|
||||
form = EditMailAddressForm(
|
||||
instance=instance, maildomain=maildomain,
|
||||
instance=instance,
|
||||
maildomain=maildomain,
|
||||
hostingpackage=hostingpackage,
|
||||
data={
|
||||
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.forwards,
|
||||
'forwards': 'test2@example.org,test3@example.org'
|
||||
})
|
||||
"mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
|
||||
"forwards": "test2@example.org,test3@example.org",
|
||||
},
|
||||
)
|
||||
self.assertTrue(form.is_valid())
|
||||
address1 = MagicMock(mailaddress='test2@example.org')
|
||||
address2 = MagicMock(mailaddress='test3@example.org')
|
||||
address1 = MagicMock(mailaddress="test2@example.org")
|
||||
address2 = MagicMock(mailaddress="test3@example.org")
|
||||
instance.set_forward_addresses.return_value = [address1, address2]
|
||||
form.save(commit=True)
|
||||
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()
|
||||
|
||||
def test_save_with_mailbox_no_commit(self):
|
||||
instance = MagicMock(id=23)
|
||||
osuser = Mock(username='testuser')
|
||||
osuser = Mock(username="testuser")
|
||||
hostingpackage = MagicMock(id=42, osuser=osuser)
|
||||
maildomain = MagicMock(domain='example.org')
|
||||
maildomain = MagicMock(domain="example.org")
|
||||
form = EditMailAddressForm(
|
||||
instance=instance, maildomain=maildomain,
|
||||
instance=instance,
|
||||
maildomain=maildomain,
|
||||
hostingpackage=hostingpackage,
|
||||
data={
|
||||
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.mailbox,
|
||||
'mailbox': 'mailbox23',
|
||||
})
|
||||
"mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
|
||||
"mailbox": "mailbox23",
|
||||
},
|
||||
)
|
||||
self.assertTrue(form.is_valid())
|
||||
mailbox = MagicMock(osuser=osuser, username='testuserp01')
|
||||
mailbox = MagicMock(osuser=osuser, username="testuserp01")
|
||||
instance.set_mailbox.return_value = mailbox
|
||||
form.save(commit=False)
|
||||
instance.set_mailbox.assert_called_with(ANY, False)
|
||||
|
@ -526,18 +558,20 @@ class EditMailAddressFormTest(TestCase):
|
|||
|
||||
def test_save_with_mailbox_commit(self):
|
||||
instance = MagicMock(id=23)
|
||||
osuser = Mock(username='testuser')
|
||||
osuser = Mock(username="testuser")
|
||||
hostingpackage = MagicMock(id=42, osuser=osuser)
|
||||
maildomain = MagicMock(domain='example.org')
|
||||
maildomain = MagicMock(domain="example.org")
|
||||
form = EditMailAddressForm(
|
||||
instance=instance, maildomain=maildomain,
|
||||
instance=instance,
|
||||
maildomain=maildomain,
|
||||
hostingpackage=hostingpackage,
|
||||
data={
|
||||
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.mailbox,
|
||||
'mailbox': 'mailbox23',
|
||||
})
|
||||
"mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
|
||||
"mailbox": "mailbox23",
|
||||
},
|
||||
)
|
||||
self.assertTrue(form.is_valid())
|
||||
mailbox = MagicMock(osuser=osuser, username='testuserp01')
|
||||
mailbox = MagicMock(osuser=osuser, username="testuserp01")
|
||||
instance.set_mailbox.return_value = mailbox
|
||||
self.mailbox_objects.unused_or_own.get.return_value = mailbox
|
||||
form.save(commit=True)
|
||||
|
@ -546,18 +580,20 @@ class EditMailAddressFormTest(TestCase):
|
|||
|
||||
def test_save_with_other_choice(self):
|
||||
instance = MagicMock(id=23)
|
||||
osuser = Mock(username='testuser')
|
||||
osuser = Mock(username="testuser")
|
||||
hostingpackage = MagicMock(id=42, osuser=osuser)
|
||||
maildomain = MagicMock(domain='example.org')
|
||||
maildomain = MagicMock(domain="example.org")
|
||||
form = EditMailAddressForm(
|
||||
instance=instance, maildomain=maildomain,
|
||||
instance=instance,
|
||||
maildomain=maildomain,
|
||||
hostingpackage=hostingpackage,
|
||||
data={
|
||||
'mailbox_or_forwards': MAILBOX_OR_FORWARDS.mailbox,
|
||||
'mailbox': 'mailbox23',
|
||||
})
|
||||
"mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
|
||||
"mailbox": "mailbox23",
|
||||
},
|
||||
)
|
||||
self.assertTrue(form.is_valid())
|
||||
form.cleaned_data['mailbox_or_forwards'] = -1
|
||||
form.cleaned_data["mailbox_or_forwards"] = -1
|
||||
form.save(commit=True)
|
||||
instance.set_mailbox.assert_not_called()
|
||||
instance.save.assert_called_with()
|
||||
|
|
|
@ -1,9 +1,7 @@
|
|||
"""
|
||||
This module contains tests for :py:mod:`managemails.models`
|
||||
"""
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from mock import patch
|
||||
from unittest.mock import patch
|
||||
|
||||
from django.test import TestCase, TransactionTestCase
|
||||
from django.test.utils import override_settings
|
||||
|
@ -14,59 +12,51 @@ from passlib.hash import sha512_crypt
|
|||
from domains.models import MailDomain
|
||||
from osusers.models import User
|
||||
|
||||
from managemails.models import (
|
||||
MailAddress,
|
||||
Mailbox,
|
||||
)
|
||||
from managemails.models import MailAddress, Mailbox
|
||||
|
||||
Customer = get_user_model()
|
||||
|
||||
|
||||
@override_settings(
|
||||
CELERY_ALWAYS_EAGER=True,
|
||||
CELERY_CACHE_BACKEND='memory',
|
||||
BROKER_BACKEND='memory'
|
||||
CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
|
||||
)
|
||||
class MailboxTest(TestCase):
|
||||
|
||||
def setUp(self):
|
||||
super(MailboxTest, self).setUp()
|
||||
self.customer = Customer.objects.create_user('test')
|
||||
self.customer = Customer.objects.create_user("test")
|
||||
|
||||
def test_set_password(self):
|
||||
user = User.objects.create_user(self.customer)
|
||||
mb = Mailbox.objects.create(username='test', osuser=user)
|
||||
mb.set_password('test')
|
||||
self.assertTrue(sha512_crypt.verify('test', mb.password))
|
||||
mb = Mailbox.objects.create(username="test", osuser=user)
|
||||
mb.set_password("test")
|
||||
self.assertTrue(sha512_crypt.verify("test", mb.password))
|
||||
|
||||
def test___str__(self):
|
||||
user = User.objects.create_user(self.customer)
|
||||
mb = Mailbox.objects.create(username='test', osuser=user)
|
||||
mb.set_password('test')
|
||||
self.assertEqual(str(mb), 'test')
|
||||
mb = Mailbox.objects.create(username="test", osuser=user)
|
||||
mb.set_password("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):
|
||||
user = User.objects.create_user(self.customer)
|
||||
mb = Mailbox.objects.create_mailbox(user)
|
||||
self.assertIsNotNone(mb.pk)
|
||||
create_file_mailbox_task.delay.assert_called_with(
|
||||
user.username, mb.username)
|
||||
create_file_mailbox_task.delay.assert_called_with(user.username, mb.username)
|
||||
|
||||
@patch('managemails.models.delete_file_mailbox')
|
||||
@patch("managemails.models.delete_file_mailbox")
|
||||
def test_delete(self, delete_file_mailbox_task):
|
||||
user = User.objects.create_user(self.customer)
|
||||
mb = Mailbox.objects.create_mailbox(user)
|
||||
mb.delete()
|
||||
self.assertIsNone(mb.pk)
|
||||
delete_file_mailbox_task.delay.assert_called_with(
|
||||
user.username, mb.username)
|
||||
delete_file_mailbox_task.delay.assert_called_with(user.username, mb.username)
|
||||
|
||||
def test_get_mailaddresses(self):
|
||||
user = User.objects.create_user(self.customer)
|
||||
mb = Mailbox.objects.create_mailbox(user)
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
address = MailAddress.objects.create(localpart='test', domain=md)
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
address = MailAddress.objects.create(localpart="test", domain=md)
|
||||
address.set_mailbox(mb)
|
||||
mailaddresses = mb.get_mailaddresses()
|
||||
self.assertEqual(len(mailaddresses), 1)
|
||||
|
@ -74,31 +64,28 @@ class MailboxTest(TestCase):
|
|||
|
||||
|
||||
@override_settings(
|
||||
CELERY_ALWAYS_EAGER=True,
|
||||
CELERY_CACHE_BACKEND='memory',
|
||||
BROKER_BACKEND='memory'
|
||||
CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
|
||||
)
|
||||
class MailAddressTest(TransactionTestCase):
|
||||
|
||||
def test__str__(self):
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
ma = MailAddress.objects.create(localpart='test', domain=md)
|
||||
self.assertEqual(str(ma), 'test@example.org')
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
ma = MailAddress.objects.create(localpart="test", domain=md)
|
||||
self.assertEqual(str(ma), "test@example.org")
|
||||
|
||||
def test_set_mailbox_fresh(self):
|
||||
customer = Customer.objects.create_user('test')
|
||||
customer = Customer.objects.create_user("test")
|
||||
user = User.objects.create_user(customer)
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
ma = MailAddress.objects.create(localpart='test', domain=md)
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
ma = MailAddress.objects.create(localpart="test", domain=md)
|
||||
mb = Mailbox.objects.create_mailbox(user)
|
||||
ma.set_mailbox(mb)
|
||||
self.assertIn(ma, mb.get_mailaddresses())
|
||||
|
||||
def test_set_mailbox_reassing(self):
|
||||
customer = Customer.objects.create_user('test')
|
||||
customer = Customer.objects.create_user("test")
|
||||
user = User.objects.create_user(customer)
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
ma = MailAddress.objects.create(localpart='test', domain=md)
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
ma = MailAddress.objects.create(localpart="test", domain=md)
|
||||
mb = Mailbox.objects.create_mailbox(user)
|
||||
ma.set_mailbox(mb)
|
||||
mb2 = Mailbox.objects.create_mailbox(user)
|
||||
|
@ -107,168 +94,178 @@ class MailAddressTest(TransactionTestCase):
|
|||
self.assertNotIn(ma, mb.get_mailaddresses())
|
||||
|
||||
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)
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
ma = MailAddress.objects.create(localpart='test', domain=md)
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
ma = MailAddress.objects.create(localpart="test", domain=md)
|
||||
mb = Mailbox.objects.create_mailbox(user)
|
||||
ma.set_forward_addresses(['test2@example.org'])
|
||||
ma.set_forward_addresses(["test2@example.org"])
|
||||
ma.set_mailbox(mb)
|
||||
self.assertEqual(ma.mailaddressforward_set.count(), 0)
|
||||
self.assertIn(ma, mb.get_mailaddresses())
|
||||
|
||||
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)
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
ma = MailAddress(localpart='test', domain=md)
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
ma = MailAddress(localpart="test", domain=md)
|
||||
mb = Mailbox.objects.create_mailbox(user)
|
||||
ma.set_mailbox(mb)
|
||||
self.assertIn(ma, mb.get_mailaddresses())
|
||||
|
||||
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)
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
ma = MailAddress.objects.create(localpart='test', domain=md)
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
ma = MailAddress.objects.create(localpart="test", domain=md)
|
||||
mb = Mailbox.objects.create_mailbox(user)
|
||||
ma.set_mailbox(mb, commit=False)
|
||||
self.assertNotIn(ma, mb.get_mailaddresses())
|
||||
|
||||
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)
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
ma = MailAddress(localpart='test', domain=md)
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
ma = MailAddress(localpart="test", domain=md)
|
||||
mb = Mailbox.objects.create_mailbox(user)
|
||||
ma.set_mailbox(mb, commit=False)
|
||||
self.assertNotIn(ma, mb.get_mailaddresses())
|
||||
|
||||
def test_set_forward_addresses_fresh(self):
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
ma = MailAddress.objects.create(localpart='test', domain=md)
|
||||
ma.set_forward_addresses(['test2@example.org'])
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
ma = MailAddress.objects.create(localpart="test", domain=md)
|
||||
ma.set_forward_addresses(["test2@example.org"])
|
||||
|
||||
def get_target(maf):
|
||||
return maf.target
|
||||
|
||||
self.assertQuerysetEqual(
|
||||
ma.mailaddressforward_set.all(), ['test2@example.org'],
|
||||
lambda(maf): maf.target)
|
||||
ma.mailaddressforward_set.all(), ["test2@example.org"], get_target
|
||||
)
|
||||
|
||||
def test_set_forward_addresses_unsaved(self):
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
ma = MailAddress(localpart='test', domain=md)
|
||||
ma.set_forward_addresses(['test2@example.org'])
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
ma = MailAddress(localpart="test", domain=md)
|
||||
ma.set_forward_addresses(["test2@example.org"])
|
||||
|
||||
def get_target(maf):
|
||||
return maf.target
|
||||
|
||||
self.assertQuerysetEqual(
|
||||
ma.mailaddressforward_set.all(), ['test2@example.org'],
|
||||
lambda(maf): maf.target)
|
||||
ma.mailaddressforward_set.all(), ["test2@example.org"], get_target
|
||||
)
|
||||
|
||||
def test_set_forward_addresses_replace_forwards(self):
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
ma = MailAddress.objects.create(localpart='test', domain=md)
|
||||
ma.set_forward_addresses(['test2@example.org'])
|
||||
ma.set_forward_addresses(['test3@example.org'])
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
ma = MailAddress.objects.create(localpart="test", domain=md)
|
||||
ma.set_forward_addresses(["test2@example.org"])
|
||||
ma.set_forward_addresses(["test3@example.org"])
|
||||
|
||||
def get_target(maf):
|
||||
return maf.target
|
||||
|
||||
self.assertQuerysetEqual(
|
||||
ma.mailaddressforward_set.all(), ['test3@example.org'],
|
||||
lambda(maf): maf.target)
|
||||
ma.mailaddressforward_set.all(), ["test3@example.org"], get_target
|
||||
)
|
||||
|
||||
def test_set_forward_addresses_add_forwards(self):
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
ma = MailAddress.objects.create(localpart='test', domain=md)
|
||||
ma.set_forward_addresses(['test2@example.org'])
|
||||
ma.set_forward_addresses(['test2@example.org', 'test3@example.org'])
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
ma = MailAddress.objects.create(localpart="test", domain=md)
|
||||
ma.set_forward_addresses(["test2@example.org"])
|
||||
ma.set_forward_addresses(["test2@example.org", "test3@example.org"])
|
||||
|
||||
def get_target(maf):
|
||||
return maf.target
|
||||
|
||||
self.assertQuerysetEqual(
|
||||
ma.mailaddressforward_set.all(),
|
||||
['test2@example.org', 'test3@example.org'],
|
||||
lambda(maf): maf.target,
|
||||
ordered=False)
|
||||
["test2@example.org", "test3@example.org"],
|
||||
get_target,
|
||||
ordered=False,
|
||||
)
|
||||
|
||||
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)
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
ma = MailAddress.objects.create(localpart='test', domain=md)
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
ma = MailAddress.objects.create(localpart="test", domain=md)
|
||||
mb = Mailbox.objects.create_mailbox(user)
|
||||
ma.set_mailbox(mb)
|
||||
ma.set_forward_addresses(['test2@example.org'])
|
||||
ma.set_forward_addresses(["test2@example.org"])
|
||||
self.assertNotIn(ma, mb.get_mailaddresses())
|
||||
|
||||
def get_target(maf):
|
||||
return maf.target
|
||||
|
||||
self.assertQuerysetEqual(
|
||||
ma.mailaddressforward_set.all(), ['test2@example.org'],
|
||||
lambda(maf): maf.target)
|
||||
ma.mailaddressforward_set.all(), ["test2@example.org"], get_target
|
||||
)
|
||||
|
||||
def test_set_forward_addresses_fresh_no_commit(self):
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
ma = MailAddress.objects.create(localpart='test', domain=md)
|
||||
mafwds = ma.set_forward_addresses(['test2@example.org'], commit=False)
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
ma = MailAddress.objects.create(localpart="test", domain=md)
|
||||
mafwds = ma.set_forward_addresses(["test2@example.org"], commit=False)
|
||||
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):
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
ma = MailAddress(localpart='test', domain=md)
|
||||
mafwds = ma.set_forward_addresses(['test2@example.org'], commit=False)
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
ma = MailAddress(localpart="test", domain=md)
|
||||
mafwds = ma.set_forward_addresses(["test2@example.org"], commit=False)
|
||||
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(
|
||||
CELERY_ALWAYS_EAGER=True,
|
||||
CELERY_CACHE_BACKEND='memory',
|
||||
BROKER_BACKEND='memory'
|
||||
CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
|
||||
)
|
||||
class MailboxManagerTest(TransactionTestCase):
|
||||
|
||||
def setUp(self):
|
||||
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)
|
||||
|
||||
def test_get_next_mailbox_name_fresh(self):
|
||||
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):
|
||||
Mailbox.objects.create_mailbox(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):
|
||||
mailboxes = [
|
||||
Mailbox.objects.create_mailbox(self.user) for i in range(3)
|
||||
]
|
||||
mailboxes = [Mailbox.objects.create_mailbox(self.user) for _ in range(3)]
|
||||
mailboxes[1].delete()
|
||||
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):
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
address = MailAddress.objects.create(localpart='test', domain=md)
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
address = MailAddress.objects.create(localpart="test", domain=md)
|
||||
mailboxes = Mailbox.objects.unused_or_own(address, self.user)
|
||||
self.assertQuerysetEqual(mailboxes, [])
|
||||
|
||||
def test_unused_or_own_unassigned(self):
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
address = MailAddress.objects.create(localpart='test', domain=md)
|
||||
mailboxes = [
|
||||
Mailbox.objects.create_mailbox(self.user) for i in range(2)
|
||||
]
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
address = MailAddress.objects.create(localpart="test", domain=md)
|
||||
mailboxes = [Mailbox.objects.create_mailbox(self.user) for _ in range(2)]
|
||||
assignable = Mailbox.objects.unused_or_own(address, self.user)
|
||||
self.assertQuerysetEqual(assignable, [repr(mb) for mb in mailboxes])
|
||||
|
||||
def test_unused_or_own_assigned(self):
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
address = MailAddress.objects.create(localpart='test', domain=md)
|
||||
mailboxes = [
|
||||
Mailbox.objects.create_mailbox(self.user) for i in range(2)
|
||||
]
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
address = MailAddress.objects.create(localpart="test", domain=md)
|
||||
mailboxes = [Mailbox.objects.create_mailbox(self.user) for _ in range(2)]
|
||||
address.set_mailbox(mailboxes[0])
|
||||
assignable = Mailbox.objects.unused_or_own(address, self.user)
|
||||
self.assertQuerysetEqual(assignable, [repr(mb) for mb in mailboxes])
|
||||
|
||||
def test_unused_or_own_assigned_other(self):
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
address = MailAddress.objects.create(localpart='test', domain=md)
|
||||
address2 = MailAddress.objects.create(localpart='test2', domain=md)
|
||||
mailboxes = [
|
||||
Mailbox.objects.create_mailbox(self.user) for i in range(2)
|
||||
]
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
address = MailAddress.objects.create(localpart="test", domain=md)
|
||||
address2 = MailAddress.objects.create(localpart="test2", domain=md)
|
||||
mailboxes = [Mailbox.objects.create_mailbox(self.user) for _ in range(2)]
|
||||
address2.set_mailbox(mailboxes[0])
|
||||
assignable = Mailbox.objects.unused_or_own(address, self.user)
|
||||
self.assertQuerysetEqual(assignable, [repr(mailboxes[1])])
|
||||
|
@ -283,11 +280,9 @@ class MailboxManagerTest(TransactionTestCase):
|
|||
self.assertQuerysetEqual(mailboxes, [repr(mailbox)])
|
||||
|
||||
def test_unused_assigned(self):
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
address = MailAddress.objects.create(localpart='test', domain=md)
|
||||
mailboxes = [
|
||||
Mailbox.objects.create_mailbox(self.user) for i in range(2)
|
||||
]
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
address = MailAddress.objects.create(localpart="test", domain=md)
|
||||
mailboxes = [Mailbox.objects.create_mailbox(self.user) for _ in range(2)]
|
||||
address.set_mailbox(mailboxes[0])
|
||||
assignable = Mailbox.objects.unused(self.user)
|
||||
self.assertQuerysetEqual(assignable, [repr(mailboxes[1])])
|
||||
|
@ -295,31 +290,28 @@ class MailboxManagerTest(TransactionTestCase):
|
|||
def test_create_mailbox_no_password(self):
|
||||
mailbox = Mailbox.objects.create_mailbox(self.user)
|
||||
self.assertEqual(mailbox.osuser, self.user)
|
||||
self.assertEqual(mailbox.username, '{}p01'.format(self.user.username))
|
||||
self.assertEqual(mailbox.password, '')
|
||||
self.assertEqual(mailbox.username, "{}p01".format(self.user.username))
|
||||
self.assertEqual(mailbox.password, "")
|
||||
|
||||
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.username, '{}p01'.format(self.user.username))
|
||||
self.assertTrue(sha512_crypt.verify('test', mailbox.password))
|
||||
self.assertEqual(mailbox.username, "{}p01".format(self.user.username))
|
||||
self.assertTrue(sha512_crypt.verify("test", mailbox.password))
|
||||
|
||||
|
||||
@override_settings(
|
||||
CELERY_ALWAYS_EAGER=True,
|
||||
CELERY_CACHE_BACKEND='memory',
|
||||
BROKER_BACKEND='memory'
|
||||
CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
|
||||
)
|
||||
class MailAddressMailboxTest(TestCase):
|
||||
|
||||
def setUp(self):
|
||||
super(MailAddressMailboxTest, self).setUp()
|
||||
self.customer = Customer.objects.create_user('test')
|
||||
self.customer = Customer.objects.create_user("test")
|
||||
|
||||
def test___str__(self):
|
||||
user = User.objects.create_user(self.customer)
|
||||
md = MailDomain.objects.create(domain='example.org')
|
||||
ma = MailAddress(localpart='test', domain=md)
|
||||
md = MailDomain.objects.create(domain="example.org")
|
||||
ma = MailAddress(localpart="test", domain=md)
|
||||
mb = Mailbox.objects.create_mailbox(user)
|
||||
ma.set_mailbox(mb)
|
||||
self.assertEqual(str(ma.mailaddressmailbox), mb.username)
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -7,26 +7,14 @@ The module starts Celery_ tasks.
|
|||
|
||||
"""
|
||||
from django import forms
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.contrib import admin
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
|
||||
from fileservertasks.tasks import set_file_ssh_authorized_keys
|
||||
from gvawebcore.forms import (
|
||||
PASSWORD_MISMATCH_ERROR
|
||||
)
|
||||
from gvawebcore.forms import PASSWORD_MISMATCH_ERROR
|
||||
from taskresults.models import TaskResult
|
||||
|
||||
from .forms import (
|
||||
INVALID_SSH_PUBLIC_KEY,
|
||||
DUPLICATE_SSH_PUBLIC_KEY_FOR_USER,
|
||||
)
|
||||
from .models import (
|
||||
AdditionalGroup,
|
||||
Group,
|
||||
Shadow,
|
||||
SshPublicKey,
|
||||
User,
|
||||
)
|
||||
from .forms import DUPLICATE_SSH_PUBLIC_KEY_FOR_USER, INVALID_SSH_PUBLIC_KEY
|
||||
from .models import AdditionalGroup, Group, Shadow, SshPublicKey, User
|
||||
|
||||
|
||||
class AdditionalGroupInline(admin.TabularInline):
|
||||
|
@ -34,6 +22,7 @@ class AdditionalGroupInline(admin.TabularInline):
|
|||
Inline for :py:class:`osusers.models.AdditionalGroup` instances.
|
||||
|
||||
"""
|
||||
|
||||
model = AdditionalGroup
|
||||
|
||||
|
||||
|
@ -42,8 +31,9 @@ class ShadowInline(admin.TabularInline):
|
|||
Inline for :py:class:`osusers.models.ShadowInline` instances.
|
||||
|
||||
"""
|
||||
|
||||
model = Shadow
|
||||
readonly_fields = ['passwd']
|
||||
readonly_fields = ["passwd"]
|
||||
can_delete = False
|
||||
|
||||
|
||||
|
@ -53,18 +43,17 @@ class UserCreationForm(forms.ModelForm):
|
|||
<osusers.models.User>`.
|
||||
|
||||
"""
|
||||
|
||||
password1 = forms.CharField(
|
||||
label=_('Password'), widget=forms.PasswordInput,
|
||||
required=False,
|
||||
label=_("Password"), widget=forms.PasswordInput, required=False
|
||||
)
|
||||
password2 = forms.CharField(
|
||||
label=_('Password (again)'), widget=forms.PasswordInput,
|
||||
required=False,
|
||||
label=_("Password (again)"), widget=forms.PasswordInput, required=False
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ['customer']
|
||||
fields = ["customer"]
|
||||
|
||||
def clean_password2(self):
|
||||
"""
|
||||
|
@ -74,8 +63,8 @@ class UserCreationForm(forms.ModelForm):
|
|||
:rtype: str or None
|
||||
|
||||
"""
|
||||
password1 = self.cleaned_data.get('password1')
|
||||
password2 = self.cleaned_data.get('password2')
|
||||
password1 = self.cleaned_data.get("password1")
|
||||
password2 = self.cleaned_data.get("password2")
|
||||
if password1 and password2 and password1 != password2:
|
||||
raise forms.ValidationError(PASSWORD_MISMATCH_ERROR)
|
||||
return password2
|
||||
|
@ -90,8 +79,10 @@ class UserCreationForm(forms.ModelForm):
|
|||
|
||||
"""
|
||||
user = User.objects.create_user(
|
||||
customer=self.cleaned_data['customer'],
|
||||
password=self.cleaned_data['password1'], commit=commit)
|
||||
customer=self.cleaned_data["customer"],
|
||||
password=self.cleaned_data["password1"],
|
||||
commit=commit,
|
||||
)
|
||||
return user
|
||||
|
||||
def save_m2m(self):
|
||||
|
@ -108,14 +99,16 @@ class UserAdmin(admin.ModelAdmin):
|
|||
<osusers.models.User>`.
|
||||
|
||||
"""
|
||||
actions = ['perform_delete_selected']
|
||||
|
||||
actions = ["perform_delete_selected"]
|
||||
add_form = UserCreationForm
|
||||
inlines = [AdditionalGroupInline, ShadowInline]
|
||||
|
||||
add_fieldsets = (
|
||||
(None, {
|
||||
'classes': ('wide',),
|
||||
'fields': ('customer', 'password1', 'password2')}),
|
||||
(
|
||||
None,
|
||||
{"classes": ("wide",), "fields": ("customer", "password1", "password2")},
|
||||
),
|
||||
)
|
||||
|
||||
def get_form(self, request, obj=None, **kwargs):
|
||||
|
@ -132,10 +125,12 @@ class UserAdmin(admin.ModelAdmin):
|
|||
"""
|
||||
defaults = {}
|
||||
if obj is None:
|
||||
defaults.update({
|
||||
'form': self.add_form,
|
||||
'fields': admin.options.flatten_fieldsets(self.add_fieldsets),
|
||||
})
|
||||
defaults.update(
|
||||
{
|
||||
"form": self.add_form,
|
||||
"fields": admin.options.flatten_fieldsets(self.add_fieldsets),
|
||||
}
|
||||
)
|
||||
defaults.update(kwargs)
|
||||
return super(UserAdmin, self).get_form(request, obj, **defaults)
|
||||
|
||||
|
@ -151,7 +146,7 @@ class UserAdmin(admin.ModelAdmin):
|
|||
|
||||
"""
|
||||
if obj:
|
||||
return ['uid']
|
||||
return ["uid"]
|
||||
return []
|
||||
|
||||
def perform_delete_selected(self, request, queryset):
|
||||
|
@ -167,7 +162,8 @@ class UserAdmin(admin.ModelAdmin):
|
|||
"""
|
||||
for user in queryset.all():
|
||||
user.delete()
|
||||
perform_delete_selected.short_description = _('Delete selected users')
|
||||
|
||||
perform_delete_selected.short_description = _("Delete selected users")
|
||||
|
||||
def get_actions(self, request):
|
||||
"""
|
||||
|
@ -182,8 +178,8 @@ class UserAdmin(admin.ModelAdmin):
|
|||
|
||||
"""
|
||||
actions = super(UserAdmin, self).get_actions(request)
|
||||
if 'delete_selected' in actions: # pragma: no cover
|
||||
del actions['delete_selected']
|
||||
if "delete_selected" in actions: # pragma: no cover
|
||||
del actions["delete_selected"]
|
||||
return actions
|
||||
|
||||
|
||||
|
@ -193,7 +189,8 @@ class GroupAdmin(admin.ModelAdmin):
|
|||
<osusers.models.Group>`.
|
||||
|
||||
"""
|
||||
actions = ['perform_delete_selected']
|
||||
|
||||
actions = ["perform_delete_selected"]
|
||||
|
||||
def perform_delete_selected(self, request, queryset):
|
||||
"""
|
||||
|
@ -208,7 +205,8 @@ class GroupAdmin(admin.ModelAdmin):
|
|||
"""
|
||||
for group in queryset.all():
|
||||
group.delete()
|
||||
perform_delete_selected.short_description = _('Delete selected groups')
|
||||
|
||||
perform_delete_selected.short_description = _("Delete selected groups")
|
||||
|
||||
def get_actions(self, request):
|
||||
"""
|
||||
|
@ -223,8 +221,8 @@ class GroupAdmin(admin.ModelAdmin):
|
|||
|
||||
"""
|
||||
actions = super(GroupAdmin, self).get_actions(request)
|
||||
if 'delete_selected' in actions: # pragma: no cover
|
||||
del actions['delete_selected']
|
||||
if "delete_selected" in actions: # pragma: no cover
|
||||
del actions["delete_selected"]
|
||||
return actions
|
||||
|
||||
|
||||
|
@ -234,33 +232,37 @@ class SshPublicKeyCreationForm(forms.ModelForm):
|
|||
<osusers.models.SshPublicKey>`.
|
||||
|
||||
"""
|
||||
|
||||
publickeytext = forms.CharField(
|
||||
label=_('Key text'), widget=forms.Textarea,
|
||||
help_text=_('A SSH public key in either OpenSSH or RFC 4716 format'))
|
||||
label=_("Key text"),
|
||||
widget=forms.Textarea,
|
||||
help_text=_("A SSH public key in either OpenSSH or RFC 4716 format"),
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = SshPublicKey
|
||||
fields = ['user']
|
||||
fields = ["user"]
|
||||
|
||||
def clean_publickeytext(self):
|
||||
keytext = self.cleaned_data.get('publickeytext')
|
||||
keytext = self.cleaned_data.get("publickeytext")
|
||||
try:
|
||||
SshPublicKey.objects.parse_keytext(keytext)
|
||||
SshPublicKey.objects.parse_key_text(keytext)
|
||||
except:
|
||||
raise forms.ValidationError(INVALID_SSH_PUBLIC_KEY)
|
||||
return keytext
|
||||
|
||||
def clean(self):
|
||||
user = self.cleaned_data.get('user')
|
||||
keytext = self.cleaned_data.get('publickeytext')
|
||||
user = self.cleaned_data.get("user")
|
||||
keytext = self.cleaned_data.get("publickeytext")
|
||||
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(
|
||||
user=user, algorithm=alg, data=data
|
||||
).exists():
|
||||
self.add_error(
|
||||
'publickeytext',
|
||||
forms.ValidationError(DUPLICATE_SSH_PUBLIC_KEY_FOR_USER))
|
||||
"publickeytext",
|
||||
forms.ValidationError(DUPLICATE_SSH_PUBLIC_KEY_FOR_USER),
|
||||
)
|
||||
super(SshPublicKeyCreationForm, self).clean()
|
||||
|
||||
def save(self, commit=True):
|
||||
|
@ -272,8 +274,9 @@ class SshPublicKeyCreationForm(forms.ModelForm):
|
|||
:rtype: :py:class:`osusers.models.SshPublicKey`
|
||||
|
||||
"""
|
||||
algorithm, keydata, comment = SshPublicKey.objects.parse_keytext(
|
||||
self.cleaned_data.get('publickeytext'))
|
||||
algorithm, keydata, comment = SshPublicKey.objects.parse_key_text(
|
||||
self.cleaned_data.get("publickeytext")
|
||||
)
|
||||
self.instance.algorithm = algorithm
|
||||
self.instance.data = keydata
|
||||
self.instance.comment = comment
|
||||
|
@ -286,14 +289,13 @@ class SshPublicKeyAdmin(admin.ModelAdmin):
|
|||
<osusers.models.SshPublicKey>`.
|
||||
|
||||
"""
|
||||
actions = ['perform_delete_selected']
|
||||
|
||||
actions = ["perform_delete_selected"]
|
||||
add_form = SshPublicKeyCreationForm
|
||||
list_display = ['user', 'algorithm', 'comment']
|
||||
list_display = ["user", "algorithm", "comment"]
|
||||
|
||||
add_fieldsets = (
|
||||
(None, {
|
||||
'classes': ('wide',),
|
||||
'fields': ('user', 'publickeytext')}),
|
||||
(None, {"classes": ("wide",), "fields": ("user", "publickeytext")}),
|
||||
)
|
||||
|
||||
def get_form(self, request, obj=None, **kwargs):
|
||||
|
@ -311,13 +313,14 @@ class SshPublicKeyAdmin(admin.ModelAdmin):
|
|||
"""
|
||||
defaults = {}
|
||||
if obj is None:
|
||||
defaults.update({
|
||||
'form': self.add_form,
|
||||
'fields': admin.options.flatten_fieldsets(self.add_fieldsets),
|
||||
})
|
||||
defaults.update(
|
||||
{
|
||||
"form": self.add_form,
|
||||
"fields": admin.options.flatten_fieldsets(self.add_fieldsets),
|
||||
}
|
||||
)
|
||||
defaults.update(kwargs)
|
||||
return super(SshPublicKeyAdmin, self).get_form(
|
||||
request, obj, **defaults)
|
||||
return super(SshPublicKeyAdmin, self).get_form(request, obj, **defaults)
|
||||
|
||||
def get_readonly_fields(self, request, obj=None):
|
||||
"""
|
||||
|
@ -332,7 +335,7 @@ class SshPublicKeyAdmin(admin.ModelAdmin):
|
|||
|
||||
"""
|
||||
if obj:
|
||||
return ['algorithm', 'data']
|
||||
return ["algorithm", "data"]
|
||||
return []
|
||||
|
||||
def perform_delete_selected(self, request, queryset):
|
||||
|
@ -370,23 +373,19 @@ class SshPublicKeyAdmin(admin.ModelAdmin):
|
|||
}
|
||||
|
||||
"""
|
||||
users = set([
|
||||
item['user'] for item in
|
||||
queryset.values('user').distinct()
|
||||
])
|
||||
users = set([item["user"] for item in queryset.values("user").distinct()])
|
||||
queryset.delete()
|
||||
for user in users:
|
||||
# TODO: move to model/signal
|
||||
TaskResult.objects.create_task_result(
|
||||
'perform_delete_selected',
|
||||
"perform_delete_selected",
|
||||
set_file_ssh_authorized_keys.s(
|
||||
User.objects.get(uid=user).username,
|
||||
[str(key) for key in SshPublicKey.objects.filter(
|
||||
user_id=user)]
|
||||
[str(key) for key in SshPublicKey.objects.filter(user_id=user)],
|
||||
),
|
||||
)
|
||||
)
|
||||
perform_delete_selected.short_description = _(
|
||||
'Delete selected SSH public keys')
|
||||
|
||||
perform_delete_selected.short_description = _("Delete selected SSH public keys")
|
||||
|
||||
def get_actions(self, request):
|
||||
"""
|
||||
|
@ -401,8 +400,8 @@ class SshPublicKeyAdmin(admin.ModelAdmin):
|
|||
|
||||
"""
|
||||
actions = super(SshPublicKeyAdmin, self).get_actions(request)
|
||||
if 'delete_selected' in actions: # pragma: no cover
|
||||
del actions['delete_selected']
|
||||
if "delete_selected" in actions: # pragma: no cover
|
||||
del actions["delete_selected"]
|
||||
return actions
|
||||
|
||||
|
||||
|
|
|
@ -13,14 +13,12 @@ from crispy_forms.layout import Submit
|
|||
|
||||
from gvawebcore.forms import PasswordModelFormMixin
|
||||
|
||||
from .models import (
|
||||
SshPublicKey,
|
||||
User,
|
||||
)
|
||||
from .models import 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 = _(
|
||||
'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):
|
||||
|
@ -28,6 +26,7 @@ class ChangeOsUserPasswordForm(PasswordModelFormMixin, forms.ModelForm):
|
|||
A form for setting an OS user's password.
|
||||
|
||||
"""
|
||||
|
||||
class Meta:
|
||||
model = User
|
||||
fields = []
|
||||
|
@ -36,8 +35,9 @@ class ChangeOsUserPasswordForm(PasswordModelFormMixin, forms.ModelForm):
|
|||
self.helper = FormHelper()
|
||||
super(ChangeOsUserPasswordForm, self).__init__(*args, **kwargs)
|
||||
self.helper.form_action = reverse(
|
||||
'set_osuser_password', kwargs={'slug': self.instance.username})
|
||||
self.helper.add_input(Submit('submit', _('Set password')))
|
||||
"set_osuser_password", kwargs={"slug": self.instance.username}
|
||||
)
|
||||
self.helper.add_input(Submit("submit", _("Set password")))
|
||||
|
||||
def save(self, commit=True):
|
||||
"""
|
||||
|
@ -48,7 +48,7 @@ class ChangeOsUserPasswordForm(PasswordModelFormMixin, forms.ModelForm):
|
|||
: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)
|
||||
|
||||
|
||||
|
@ -58,41 +58,45 @@ class AddSshPublicKeyForm(forms.ModelForm):
|
|||
<osusers.models.SshPublicKey>`.
|
||||
|
||||
"""
|
||||
|
||||
publickeytext = forms.CharField(
|
||||
label=_('Key text'), widget=forms.Textarea,
|
||||
help_text=_('A SSH public key in either OpenSSH or RFC 4716 format'))
|
||||
label=_("Key text"),
|
||||
widget=forms.Textarea,
|
||||
help_text=_("A SSH public key in either OpenSSH or RFC 4716 format"),
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = SshPublicKey
|
||||
fields = []
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
hosting_package = kwargs.pop('hostingpackage')
|
||||
hosting_package = kwargs.pop("hostingpackage")
|
||||
self.osuser = hosting_package.osuser
|
||||
super(AddSshPublicKeyForm, self).__init__(*args, **kwargs)
|
||||
self.helper = FormHelper()
|
||||
self.helper.form_action = reverse(
|
||||
'add_ssh_key', kwargs={'package': hosting_package.id})
|
||||
self.helper.add_input(Submit('submit', _('Add SSH public key')))
|
||||
"add_ssh_key", kwargs={"package": hosting_package.id}
|
||||
)
|
||||
self.helper.add_input(Submit("submit", _("Add SSH public key")))
|
||||
|
||||
def clean_publickeytext(self):
|
||||
keytext = self.cleaned_data.get('publickeytext')
|
||||
keytext = self.cleaned_data.get("publickeytext")
|
||||
try:
|
||||
SshPublicKey.objects.parse_keytext(keytext)
|
||||
SshPublicKey.objects.parse_key_text(keytext)
|
||||
except ValueError:
|
||||
raise forms.ValidationError(INVALID_SSH_PUBLIC_KEY)
|
||||
return keytext
|
||||
|
||||
def clean(self):
|
||||
keytext = self.cleaned_data.get('publickeytext')
|
||||
keytext = self.cleaned_data.get("publickeytext")
|
||||
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(
|
||||
user=self.osuser, algorithm=alg, data=data
|
||||
).exists():
|
||||
self.add_error(
|
||||
'publickeytext',
|
||||
forms.ValidationError(DUPLICATE_SSH_PUBLIC_KEY_FOR_USER)
|
||||
"publickeytext",
|
||||
forms.ValidationError(DUPLICATE_SSH_PUBLIC_KEY_FOR_USER),
|
||||
)
|
||||
|
||||
def save(self, commit=True):
|
||||
|
@ -104,8 +108,9 @@ class AddSshPublicKeyForm(forms.ModelForm):
|
|||
:rtype: :py:class:`osusers.models.SshPublicKey`
|
||||
|
||||
"""
|
||||
algorithm, keydata, comment = SshPublicKey.objects.parse_keytext(
|
||||
self.cleaned_data.get('publickeytext'))
|
||||
algorithm, keydata, comment = SshPublicKey.objects.parse_key_text(
|
||||
self.cleaned_data.get("publickeytext")
|
||||
)
|
||||
self.instance.user = self.osuser
|
||||
self.instance.algorithm = algorithm
|
||||
self.instance.data = keydata
|
||||
|
@ -119,17 +124,19 @@ class EditSshPublicKeyCommentForm(forms.ModelForm):
|
|||
<osusers.models.SshPublicKey>` comment fields.
|
||||
|
||||
"""
|
||||
|
||||
class Meta:
|
||||
model = SshPublicKey
|
||||
fields = ['comment']
|
||||
fields = ["comment"]
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
hosting_package = kwargs.pop('hostingpackage')
|
||||
hosting_package = kwargs.pop("hostingpackage")
|
||||
self.osuser = hosting_package.osuser
|
||||
super(EditSshPublicKeyCommentForm, self).__init__(*args, **kwargs)
|
||||
self.fields['comment'].widget = forms.TextInput()
|
||||
self.fields["comment"].widget = forms.TextInput()
|
||||
self.helper = FormHelper()
|
||||
self.helper.form_action = reverse(
|
||||
'edit_ssh_key_comment',
|
||||
kwargs={'package': hosting_package.id, 'pk': self.instance.id})
|
||||
self.helper.add_input(Submit('submit', _('Change Comment')))
|
||||
"edit_ssh_key_comment",
|
||||
kwargs={"package": hosting_package.id, "pk": self.instance.id},
|
||||
)
|
||||
self.helper.add_input(Submit("submit", _("Change Comment")))
|
||||
|
|
|
@ -2,20 +2,16 @@
|
|||
This module defines the database models of operating system users.
|
||||
|
||||
"""
|
||||
from __future__ import unicode_literals
|
||||
|
||||
import base64
|
||||
from datetime import date
|
||||
import logging
|
||||
import os
|
||||
import six
|
||||
|
||||
from django.db import models, transaction
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.dispatch import Signal
|
||||
from django.utils import timezone
|
||||
from django.utils.encoding import python_2_unicode_compatible
|
||||
from django.utils.translation import ugettext as _
|
||||
|
||||
from model_utils.models import TimeStampedModel
|
||||
|
@ -27,11 +23,10 @@ from passlib.utils import generate_password
|
|||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
password_set = Signal(providing_args=['instance', 'password'])
|
||||
password_set = Signal(providing_args=["instance", "password"])
|
||||
|
||||
|
||||
CANNOT_USE_PRIMARY_GROUP_AS_ADDITIONAL = _(
|
||||
"You can not use a user's primary group.")
|
||||
CANNOT_USE_PRIMARY_GROUP_AS_ADDITIONAL = _("You can not use a user's primary group.")
|
||||
|
||||
|
||||
class GroupManager(models.Manager):
|
||||
|
@ -48,34 +43,31 @@ class GroupManager(models.Manager):
|
|||
:rtype: int
|
||||
|
||||
"""
|
||||
q = self.aggregate(models.Max('gid'))
|
||||
if q['gid__max'] is None:
|
||||
q = self.aggregate(models.Max("gid"))
|
||||
if q["gid__max"] is None:
|
||||
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):
|
||||
"""
|
||||
This entity class corresponds to an operating system group.
|
||||
|
||||
"""
|
||||
groupname = models.CharField(
|
||||
_('Group name'), max_length=16, unique=True)
|
||||
gid = models.PositiveSmallIntegerField(
|
||||
_('Group ID'), unique=True, primary_key=True)
|
||||
descr = models.TextField(_('Description'), blank=True)
|
||||
passwd = models.CharField(
|
||||
_('Group password'), max_length=128, blank=True)
|
||||
|
||||
groupname = models.CharField(_("Group name"), max_length=16, unique=True)
|
||||
gid = models.PositiveSmallIntegerField(_("Group ID"), unique=True, primary_key=True)
|
||||
descr = models.TextField(_("Description"), blank=True)
|
||||
passwd = models.CharField(_("Group password"), max_length=128, blank=True)
|
||||
|
||||
objects = GroupManager()
|
||||
|
||||
class Meta:
|
||||
verbose_name = _('Group')
|
||||
verbose_name_plural = _('Groups')
|
||||
verbose_name = _("Group")
|
||||
verbose_name_plural = _("Groups")
|
||||
|
||||
def __str__(self):
|
||||
return '{0} ({1})'.format(self.groupname, self.gid)
|
||||
return "{0} ({1})".format(self.groupname, self.gid)
|
||||
|
||||
@transaction.atomic
|
||||
def save(self, *args, **kwargs):
|
||||
|
@ -122,10 +114,10 @@ class UserManager(models.Manager):
|
|||
:rtype: int
|
||||
|
||||
"""
|
||||
q = self.aggregate(models.Max('uid'))
|
||||
if q['uid__max'] is None:
|
||||
q = self.aggregate(models.Max("uid"))
|
||||
if q["uid__max"] is None:
|
||||
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):
|
||||
"""
|
||||
|
@ -137,23 +129,21 @@ class UserManager(models.Manager):
|
|||
"""
|
||||
count = 1
|
||||
usernameformat = "{0}{1:02d}"
|
||||
nextuser = usernameformat.format(settings.OSUSER_USERNAME_PREFIX,
|
||||
count)
|
||||
for user in self.values('username').filter(
|
||||
username__startswith=settings.OSUSER_USERNAME_PREFIX
|
||||
).order_by('username'):
|
||||
if user['username'] == nextuser:
|
||||
nextuser = usernameformat.format(settings.OSUSER_USERNAME_PREFIX, count)
|
||||
for user in (
|
||||
self.values("username")
|
||||
.filter(username__startswith=settings.OSUSER_USERNAME_PREFIX)
|
||||
.order_by("username")
|
||||
):
|
||||
if user["username"] == nextuser:
|
||||
count += 1
|
||||
nextuser = usernameformat.format(
|
||||
settings.OSUSER_USERNAME_PREFIX, count)
|
||||
nextuser = usernameformat.format(settings.OSUSER_USERNAME_PREFIX, count)
|
||||
else:
|
||||
break
|
||||
return nextuser
|
||||
|
||||
@transaction.atomic
|
||||
def create_user(
|
||||
self, customer, username=None, password=None, commit=False
|
||||
):
|
||||
def create_user(self, customer, username=None, password=None, commit=False):
|
||||
"""
|
||||
Create a new user with a primary group named the same as the user and
|
||||
an initial password.
|
||||
|
@ -179,41 +169,42 @@ class UserManager(models.Manager):
|
|||
password = generate_password()
|
||||
homedir = os.path.join(settings.OSUSER_HOME_BASEPATH, username)
|
||||
group = Group.objects.create(groupname=username, gid=gid)
|
||||
user = self.create(username=username, group=group, uid=uid,
|
||||
homedir=homedir, customer=customer,
|
||||
shell=settings.OSUSER_DEFAULT_SHELL)
|
||||
user = self.create(
|
||||
username=username,
|
||||
group=group,
|
||||
uid=uid,
|
||||
homedir=homedir,
|
||||
customer=customer,
|
||||
shell=settings.OSUSER_DEFAULT_SHELL,
|
||||
)
|
||||
user.set_password(password)
|
||||
if commit:
|
||||
user.save()
|
||||
return user
|
||||
|
||||
|
||||
@python_2_unicode_compatible
|
||||
class User(TimeStampedModel, models.Model):
|
||||
"""
|
||||
This entity class corresponds to an operating system user.
|
||||
|
||||
"""
|
||||
username = models.CharField(
|
||||
_('User name'), max_length=64, unique=True)
|
||||
uid = models.PositiveSmallIntegerField(
|
||||
_('User ID'), unique=True, primary_key=True)
|
||||
group = models.ForeignKey(
|
||||
Group, verbose_name=_('Group'), on_delete=models.CASCADE)
|
||||
gecos = models.CharField(_('Gecos field'), max_length=128, blank=True)
|
||||
homedir = models.CharField(_('Home directory'), max_length=256)
|
||||
shell = models.CharField(_('Login shell'), max_length=64)
|
||||
customer = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
|
||||
|
||||
username = models.CharField(_("User name"), max_length=64, unique=True)
|
||||
uid = models.PositiveSmallIntegerField(_("User ID"), unique=True, primary_key=True)
|
||||
group = models.ForeignKey(Group, verbose_name=_("Group"), on_delete=models.CASCADE)
|
||||
gecos = models.CharField(_("Gecos field"), max_length=128, blank=True)
|
||||
homedir = models.CharField(_("Home directory"), max_length=256)
|
||||
shell = models.CharField(_("Login shell"), max_length=64)
|
||||
customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
|
||||
|
||||
objects = UserManager()
|
||||
|
||||
class Meta:
|
||||
verbose_name = _('User')
|
||||
verbose_name_plural = _('Users')
|
||||
verbose_name = _("User")
|
||||
verbose_name_plural = _("Users")
|
||||
|
||||
def __str__(self):
|
||||
return '{0} ({1})'.format(self.username, self.uid)
|
||||
return "{0} ({1})".format(self.username, self.uid)
|
||||
|
||||
@transaction.atomic
|
||||
def set_password(self, password):
|
||||
|
@ -226,17 +217,15 @@ class User(TimeStampedModel, models.Model):
|
|||
:param str password: the new password
|
||||
|
||||
"""
|
||||
if hasattr(self, 'shadow'):
|
||||
if hasattr(self, "shadow"):
|
||||
self.shadow.set_password(password)
|
||||
else:
|
||||
self.shadow = Shadow.objects.create_shadow(
|
||||
user=self, password=password
|
||||
)
|
||||
password_set.send(
|
||||
sender=self.__class__, password=password, instance=self)
|
||||
self.shadow = Shadow.objects.create_shadow(user=self, password=password)
|
||||
password_set.send(sender=self.__class__, password=password, instance=self)
|
||||
return True
|
||||
|
||||
def is_sftp_user(self):
|
||||
# noinspection PyUnresolvedReferences
|
||||
return self.additionalgroup_set.filter(
|
||||
group__groupname=settings.OSUSER_SFTP_GROUP
|
||||
).exists()
|
||||
|
@ -269,6 +258,7 @@ class User(TimeStampedModel, models.Model):
|
|||
:py:meth:`django.db.Model.delete`
|
||||
|
||||
"""
|
||||
# noinspection PyUnresolvedReferences
|
||||
self.group.delete()
|
||||
super(User, self).delete(*args, **kwargs)
|
||||
|
||||
|
@ -293,64 +283,84 @@ class ShadowManager(models.Manager):
|
|||
"""
|
||||
changedays = (timezone.now().date() - date(1970, 1, 1)).days
|
||||
shadow = self.create(
|
||||
user=user, changedays=changedays,
|
||||
minage=0, maxage=None, gracedays=7,
|
||||
inactdays=30, expiredays=None
|
||||
user=user,
|
||||
changedays=changedays,
|
||||
minage=0,
|
||||
maxage=None,
|
||||
gracedays=7,
|
||||
inactdays=30,
|
||||
expiredays=None,
|
||||
)
|
||||
shadow.set_password(password)
|
||||
shadow.save()
|
||||
return shadow
|
||||
|
||||
|
||||
@python_2_unicode_compatible
|
||||
class Shadow(TimeStampedModel, models.Model):
|
||||
"""
|
||||
This entity class corresponds to an operating system user's shadow file
|
||||
entry.
|
||||
|
||||
"""
|
||||
|
||||
user = models.OneToOneField(
|
||||
User, primary_key=True, verbose_name=_('User'),
|
||||
on_delete=models.CASCADE)
|
||||
passwd = models.CharField(_('Encrypted password'), max_length=128)
|
||||
User, primary_key=True, verbose_name=_("User"), on_delete=models.CASCADE
|
||||
)
|
||||
passwd = models.CharField(_("Encrypted password"), max_length=128)
|
||||
changedays = models.PositiveSmallIntegerField(
|
||||
_('Date of last change'),
|
||||
help_text=_('This is expressed in days since Jan 1, 1970'),
|
||||
blank=True, null=True)
|
||||
_("Date of last change"),
|
||||
help_text=_("This is expressed in days since Jan 1, 1970"),
|
||||
blank=True,
|
||||
null=True,
|
||||
)
|
||||
minage = models.PositiveSmallIntegerField(
|
||||
_('Minimum age'),
|
||||
help_text=_('Minimum number of days before the password can be'
|
||||
' changed'),
|
||||
blank=True, null=True)
|
||||
_("Minimum age"),
|
||||
help_text=_("Minimum number of days before the password can be" " changed"),
|
||||
blank=True,
|
||||
null=True,
|
||||
)
|
||||
maxage = models.PositiveSmallIntegerField(
|
||||
_('Maximum age'),
|
||||
help_text=_('Maximum number of days after which the password has to'
|
||||
' be changed'),
|
||||
blank=True, null=True)
|
||||
_("Maximum age"),
|
||||
help_text=_(
|
||||
"Maximum number of days after which the password has to" " be changed"
|
||||
),
|
||||
blank=True,
|
||||
null=True,
|
||||
)
|
||||
gracedays = models.PositiveSmallIntegerField(
|
||||
_('Grace period'),
|
||||
help_text=_('The number of days before the password is going to'
|
||||
' expire'),
|
||||
blank=True, null=True)
|
||||
_("Grace period"),
|
||||
help_text=_("The number of days before the password is going to" " expire"),
|
||||
blank=True,
|
||||
null=True,
|
||||
)
|
||||
inactdays = models.PositiveSmallIntegerField(
|
||||
_('Inactivity period'),
|
||||
help_text=_('The number of days after the password has expired during'
|
||||
' which the password should still be accepted'),
|
||||
blank=True, null=True)
|
||||
_("Inactivity period"),
|
||||
help_text=_(
|
||||
"The number of days after the password has expired during"
|
||||
" which the password should still be accepted"
|
||||
),
|
||||
blank=True,
|
||||
null=True,
|
||||
)
|
||||
expiredays = models.PositiveSmallIntegerField(
|
||||
_('Account expiration date'),
|
||||
help_text=_('The date of expiration of the account, expressed as'
|
||||
' number of days since Jan 1, 1970'),
|
||||
blank=True, null=True, default=None)
|
||||
_("Account expiration date"),
|
||||
help_text=_(
|
||||
"The date of expiration of the account, expressed as"
|
||||
" number of days since Jan 1, 1970"
|
||||
),
|
||||
blank=True,
|
||||
null=True,
|
||||
default=None,
|
||||
)
|
||||
|
||||
objects = ShadowManager()
|
||||
|
||||
class Meta:
|
||||
verbose_name = _('Shadow password')
|
||||
verbose_name_plural = _('Shadow passwords')
|
||||
verbose_name = _("Shadow password")
|
||||
verbose_name_plural = _("Shadow passwords")
|
||||
|
||||
def __str__(self):
|
||||
return 'for user {0}'.format(self.user)
|
||||
return "for user {0}".format(self.user)
|
||||
|
||||
def set_password(self, password):
|
||||
"""
|
||||
|
@ -361,23 +371,23 @@ class Shadow(TimeStampedModel, models.Model):
|
|||
self.passwd = sha512_crypt.encrypt(password)
|
||||
|
||||
|
||||
@python_2_unicode_compatible
|
||||
class AdditionalGroup(TimeStampedModel, models.Model):
|
||||
"""
|
||||
This entity class corresponds to additional group assignments for an
|
||||
:py:class:`operating system user <osusers.models.User>`.
|
||||
|
||||
"""
|
||||
|
||||
user = models.ForeignKey(User, on_delete=models.CASCADE)
|
||||
group = models.ForeignKey(Group, on_delete=models.CASCADE)
|
||||
|
||||
class Meta:
|
||||
unique_together = ('user', 'group')
|
||||
verbose_name = _('Additional group')
|
||||
verbose_name_plural = _('Additional groups')
|
||||
unique_together = ("user", "group")
|
||||
verbose_name = _("Additional group")
|
||||
verbose_name_plural = _("Additional groups")
|
||||
|
||||
def __str__(self):
|
||||
return '{0} in {1}'.format(self.user, self.group)
|
||||
return "{0} in {1}".format(self.user, self.group)
|
||||
|
||||
def clean(self):
|
||||
"""
|
||||
|
@ -385,6 +395,7 @@ class AdditionalGroup(TimeStampedModel, models.Model):
|
|||
group.
|
||||
|
||||
"""
|
||||
# noinspection PyUnresolvedReferences
|
||||
if self.user.group == self.group:
|
||||
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
|
||||
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
|
||||
:rtype: triple of str
|
||||
|
||||
"""
|
||||
if keytext.startswith('---- BEGIN SSH2 PUBLIC KEY ----'):
|
||||
comment = ''
|
||||
data = ''
|
||||
continued = ''
|
||||
if key_text.startswith("---- BEGIN SSH2 PUBLIC KEY ----"):
|
||||
comment = ""
|
||||
data = ""
|
||||
continued = ""
|
||||
headers = {}
|
||||
for line in keytext.splitlines():
|
||||
if line == '---- BEGIN SSH2 PUBLIC KEY ----':
|
||||
header_tag = None
|
||||
for line in key_text.splitlines():
|
||||
if line == "---- BEGIN SSH2 PUBLIC KEY ----":
|
||||
continue
|
||||
elif ':' in line: # a header line
|
||||
elif ":" in line: # a header line
|
||||
header_tag, header_value = [
|
||||
item.strip() for item in line.split(':', 1)]
|
||||
if header_value.endswith('\\'):
|
||||
item.strip() for item in line.split(":", 1)
|
||||
]
|
||||
if header_value.endswith("\\"):
|
||||
continued = header_value[:-1]
|
||||
else:
|
||||
headers[header_tag.lower()] = header_value
|
||||
elif continued:
|
||||
if line.endswith('\\'):
|
||||
if line.endswith("\\"):
|
||||
continued += line[:-1]
|
||||
continue
|
||||
header_value = continued + line
|
||||
headers[header_tag.lower()] = header_value
|
||||
continued = ''
|
||||
elif line == '---- END SSH2 PUBLIC KEY ----':
|
||||
continued = ""
|
||||
elif line == "---- END SSH2 PUBLIC KEY ----":
|
||||
break
|
||||
elif line: # ignore empty lines
|
||||
data += line
|
||||
if 'comment' in headers:
|
||||
comment = headers['comment']
|
||||
if "comment" in headers:
|
||||
comment = headers["comment"]
|
||||
else:
|
||||
parts = keytext.split(None, 2)
|
||||
parts = key_text.split(None, 2)
|
||||
if len(parts) < 2:
|
||||
raise ValueError('invalid SSH public key')
|
||||
raise ValueError("invalid SSH public key")
|
||||
data = parts[1]
|
||||
comment = len(parts) == 3 and parts[2] or ""
|
||||
try:
|
||||
keybytes = base64.b64decode(data)
|
||||
except TypeError:
|
||||
raise ValueError('invalid SSH public key')
|
||||
parts = keybytes.split(b'\x00' * 3)
|
||||
raise ValueError("invalid SSH public key")
|
||||
parts = keybytes.split(b"\x00" * 3)
|
||||
if len(parts) < 2:
|
||||
raise ValueError('invalid SSH public key')
|
||||
alglength = six.byte2int(parts[1])
|
||||
algname = parts[1][1:1+alglength]
|
||||
return algname, data, comment
|
||||
raise ValueError("invalid SSH public key")
|
||||
key_length = int.from_bytes(parts[1], byteorder="big")
|
||||
key_algorithm = parts[1][1 : 1 + key_length].decode("utf-8")
|
||||
return key_algorithm, data, comment
|
||||
|
||||
def create_ssh_public_key(self, user, keytext):
|
||||
"""
|
||||
|
@ -490,31 +503,28 @@ class SshPublicKeyManager(models.Manager):
|
|||
:retype: :py:class:`osusers.models.SshPublicKey`
|
||||
|
||||
"""
|
||||
algorithm, data, comment = self.parse_keytext(keytext)
|
||||
return self.create(
|
||||
user=user, algorithm=algorithm, data=data, comment=comment)
|
||||
algorithm, data, comment = self.parse_key_text(keytext)
|
||||
return self.create(user=user, algorithm=algorithm, data=data, comment=comment)
|
||||
|
||||
|
||||
@python_2_unicode_compatible
|
||||
class SshPublicKey(TimeStampedModel):
|
||||
"""
|
||||
This entity class represents single SSH keys for an :py:class:`operating
|
||||
system user <osusers.models.User>`.
|
||||
|
||||
"""
|
||||
user = models.ForeignKey(
|
||||
User, verbose_name=_('User'), on_delete=models.CASCADE)
|
||||
algorithm = models.CharField(_('Algorithm'), max_length=20)
|
||||
data = models.TextField(_('Key bytes'),
|
||||
help_text=_('Base64 encoded key bytes'))
|
||||
comment = models.TextField(_('Comment'), blank=True)
|
||||
|
||||
user = models.ForeignKey(User, verbose_name=_("User"), on_delete=models.CASCADE)
|
||||
algorithm = models.CharField(_("Algorithm"), max_length=20)
|
||||
data = models.TextField(_("Key bytes"), help_text=_("Base64 encoded key bytes"))
|
||||
comment = models.TextField(_("Comment"), blank=True)
|
||||
|
||||
objects = SshPublicKeyManager()
|
||||
|
||||
class Meta:
|
||||
verbose_name = _('SSH public key')
|
||||
verbose_name_plural = _('SSH public keys')
|
||||
unique_together = [('user', 'algorithm', 'data')]
|
||||
verbose_name = _("SSH public key")
|
||||
verbose_name_plural = _("SSH public keys")
|
||||
unique_together = [("user", "algorithm", "data")]
|
||||
|
||||
def __str__(self):
|
||||
return "{algorithm} {data} {comment}".format(
|
||||
|
|
|
@ -5,17 +5,10 @@ from django.test.utils import override_settings
|
|||
|
||||
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 (
|
||||
INVALID_SSH_PUBLIC_KEY,
|
||||
DUPLICATE_SSH_PUBLIC_KEY_FOR_USER,
|
||||
)
|
||||
from osusers.models import (
|
||||
Group,
|
||||
SshPublicKey,
|
||||
User,
|
||||
)
|
||||
from osusers.forms import INVALID_SSH_PUBLIC_KEY, DUPLICATE_SSH_PUBLIC_KEY_FOR_USER
|
||||
from osusers.models import Group, SshPublicKey, User
|
||||
from osusers.admin import (
|
||||
GroupAdmin,
|
||||
PASSWORD_MISMATCH_ERROR,
|
||||
|
@ -30,20 +23,19 @@ Customer = get_user_model()
|
|||
|
||||
class CustomerTestCase(TestCase):
|
||||
def setUp(self):
|
||||
self.customer = Customer.objects.create_user('test')
|
||||
self.customer = Customer.objects.create_user("test")
|
||||
super(CustomerTestCase, self).setUp()
|
||||
|
||||
|
||||
class UserCreationFormTest(CustomerTestCase):
|
||||
|
||||
def test_clean_password2_same(self):
|
||||
form = UserCreationForm()
|
||||
form.cleaned_data = {
|
||||
'customer': self.customer,
|
||||
'password1': 'secret',
|
||||
'password2': 'secret'
|
||||
"customer": self.customer,
|
||||
"password1": "secret",
|
||||
"password2": "secret",
|
||||
}
|
||||
self.assertEqual(form.clean_password2(), 'secret')
|
||||
self.assertEqual(form.clean_password2(), "secret")
|
||||
|
||||
def test_clean_password2_empty(self):
|
||||
form = UserCreationForm()
|
||||
|
@ -53,25 +45,23 @@ class UserCreationFormTest(CustomerTestCase):
|
|||
def test_clean_password2_mismatch(self):
|
||||
form = UserCreationForm()
|
||||
form.cleaned_data = {
|
||||
'customer': self.customer,
|
||||
'password1': 'secretx',
|
||||
'password2': 'secrety'
|
||||
"customer": self.customer,
|
||||
"password1": "secretx",
|
||||
"password2": "secrety",
|
||||
}
|
||||
with self.assertRaises(forms.ValidationError) as cm:
|
||||
form.clean_password2()
|
||||
self.assertEqual(cm.exception.message, PASSWORD_MISMATCH_ERROR)
|
||||
|
||||
@override_settings(
|
||||
CELERY_ALWAYS_EAGER=True,
|
||||
CELERY_CACHE_BACKEND='memory',
|
||||
BROKER_BACKEND='memory'
|
||||
CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
|
||||
)
|
||||
def test_save_commit(self):
|
||||
form = UserCreationForm()
|
||||
form.cleaned_data = {
|
||||
'customer': self.customer,
|
||||
'password1': 'secret',
|
||||
'password2': 'secret'
|
||||
"customer": self.customer,
|
||||
"password1": "secret",
|
||||
"password2": "secret",
|
||||
}
|
||||
user = form.save()
|
||||
self.assertIsNotNone(user)
|
||||
|
@ -89,121 +79,99 @@ class UserAdminTest(CustomerTestCase):
|
|||
super(UserAdminTest, self).setUp()
|
||||
|
||||
def test_get_form_without_object(self):
|
||||
form = self.uadmin.get_form(Mock(name='request'))
|
||||
self.assertEqual(
|
||||
form.Meta.fields,
|
||||
['customer', 'password1', 'password2']
|
||||
)
|
||||
form = self.uadmin.get_form(Mock(name="request"))
|
||||
self.assertEqual(form.Meta.fields, ["customer", "password1", "password2"])
|
||||
|
||||
@override_settings(
|
||||
CELERY_ALWAYS_EAGER=True,
|
||||
CELERY_CACHE_BACKEND='memory',
|
||||
BROKER_BACKEND='memory'
|
||||
CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
|
||||
)
|
||||
def test_get_form_with_object(self):
|
||||
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(
|
||||
form.Meta.fields,
|
||||
['username', 'group', 'gecos', 'homedir', 'shell', 'customer',
|
||||
'uid']
|
||||
["username", "group", "gecos", "homedir", "shell", "customer", "uid"],
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
@override_settings(
|
||||
CELERY_ALWAYS_EAGER=True,
|
||||
CELERY_CACHE_BACKEND='memory',
|
||||
BROKER_BACKEND='memory'
|
||||
CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
|
||||
)
|
||||
def test_get_inline_instances_with_object(self):
|
||||
user = User.objects.create_user(customer=self.customer)
|
||||
inlines = self.uadmin.get_inline_instances(
|
||||
Mock(name='request'), user)
|
||||
inlines = self.uadmin.get_inline_instances(Mock(name="request"), user)
|
||||
self.assertEqual(len(inlines), len(UserAdmin.inlines))
|
||||
for index in range(len(inlines)):
|
||||
self.assertIsInstance(inlines[index], UserAdmin.inlines[index])
|
||||
|
||||
@override_settings(
|
||||
CELERY_ALWAYS_EAGER=True,
|
||||
CELERY_CACHE_BACKEND='memory',
|
||||
BROKER_BACKEND='memory'
|
||||
CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
|
||||
)
|
||||
def test_perform_delete_selected(self):
|
||||
user = User.objects.create_user(customer=self.customer)
|
||||
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)
|
||||
|
||||
def test_get_actions(self):
|
||||
requestmock = MagicMock(name='request')
|
||||
self.assertNotIn(
|
||||
'delete_selected',
|
||||
self.uadmin.get_actions(requestmock))
|
||||
self.assertIn(
|
||||
'perform_delete_selected',
|
||||
self.uadmin.get_actions(requestmock))
|
||||
requestmock = MagicMock(name="request")
|
||||
self.assertNotIn("delete_selected", self.uadmin.get_actions(requestmock))
|
||||
self.assertIn("perform_delete_selected", self.uadmin.get_actions(requestmock))
|
||||
|
||||
|
||||
class GroupAdminTest(TestCase):
|
||||
|
||||
def setUp(self):
|
||||
site = AdminSite()
|
||||
self.gadmin = GroupAdmin(Group, site)
|
||||
super(GroupAdminTest, self).setUp()
|
||||
|
||||
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, [])
|
||||
|
||||
@override_settings(
|
||||
CELERY_ALWAYS_EAGER=True,
|
||||
CELERY_CACHE_BACKEND='memory',
|
||||
BROKER_BACKEND='memory'
|
||||
CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
|
||||
)
|
||||
def test_get_inline_instances_with_object(self):
|
||||
group = Group.objects.create(gid=1000, groupname='test')
|
||||
inlines = self.gadmin.get_inline_instances(
|
||||
Mock(name='request'), group)
|
||||
group = Group.objects.create(gid=1000, groupname="test")
|
||||
inlines = self.gadmin.get_inline_instances(Mock(name="request"), group)
|
||||
self.assertEqual(len(inlines), len(GroupAdmin.inlines))
|
||||
for index in range(len(inlines)):
|
||||
self.assertIsInstance(inlines[index], GroupAdmin.inlines[index])
|
||||
|
||||
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(
|
||||
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)
|
||||
|
||||
def test_get_actions(self):
|
||||
requestmock = MagicMock(name='request')
|
||||
self.assertNotIn(
|
||||
'delete_selected',
|
||||
self.gadmin.get_actions(requestmock))
|
||||
self.assertIn(
|
||||
'perform_delete_selected',
|
||||
self.gadmin.get_actions(requestmock))
|
||||
requestmock = MagicMock(name="request")
|
||||
self.assertNotIn("delete_selected", self.gadmin.get_actions(requestmock))
|
||||
self.assertIn("perform_delete_selected", self.gadmin.get_actions(requestmock))
|
||||
|
||||
|
||||
class SshPublicKeyCreationFormTest(CustomerTestCase):
|
||||
|
||||
@patch('osusers.admin.SshPublicKey.objects')
|
||||
@patch("osusers.admin.SshPublicKey.objects")
|
||||
def test_clean_publickeytext_valid_key(self, sshpkmanager):
|
||||
form = SshPublicKeyCreationForm()
|
||||
sshpkmanager.parse_keytext = MagicMock(side_effect=ValueError)
|
||||
form.cleaned_data = {'publickeytext': 'wrongkey'}
|
||||
sshpkmanager.parse_key_text = MagicMock(side_effect=ValueError)
|
||||
form.cleaned_data = {"publickeytext": "wrongkey"}
|
||||
with self.assertRaises(forms.ValidationError) as ve:
|
||||
form.clean_publickeytext()
|
||||
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):
|
||||
form = SshPublicKeyCreationForm()
|
||||
sshpkmanager.parse_keytext = MagicMock(return_value='goodkey')
|
||||
form.cleaned_data = {'publickeytext': 'goodkey'}
|
||||
self.assertEqual(form.clean_publickeytext(), 'goodkey')
|
||||
sshpkmanager.parse_key_text = MagicMock(return_value="goodkey")
|
||||
form.cleaned_data = {"publickeytext": "goodkey"}
|
||||
self.assertEqual(form.clean_publickeytext(), "goodkey")
|
||||
|
||||
def test_clean_missing_data(self):
|
||||
form = SshPublicKeyCreationForm()
|
||||
|
@ -211,95 +179,83 @@ class SshPublicKeyCreationFormTest(CustomerTestCase):
|
|||
form.clean()
|
||||
self.assertEqual(len(form.errors), 0)
|
||||
|
||||
@patch('osusers.admin.SshPublicKey.objects.parse_keytext')
|
||||
def test_clean_once(self, parse_keytext):
|
||||
parse_keytext.return_value = ('good', 'key', 'comment')
|
||||
@patch("osusers.admin.SshPublicKey.objects.parse_key_text")
|
||||
def test_clean_once(self, parse_key_text):
|
||||
parse_key_text.return_value = ("good", "key", "comment")
|
||||
user = User.objects.create_user(customer=self.customer)
|
||||
form = SshPublicKeyCreationForm()
|
||||
form.cleaned_data = {
|
||||
'user': user,
|
||||
'publickeytext': 'good key comment'
|
||||
}
|
||||
form.cleaned_data = {"user": user, "publickeytext": "good key comment"}
|
||||
form.clean()
|
||||
self.assertEqual(len(form.errors), 0)
|
||||
|
||||
@patch('osusers.admin.SshPublicKey.objects.parse_keytext')
|
||||
def test_clean_again(self, parse_keytext):
|
||||
parse_keytext.return_value = ('good', 'key', 'comment')
|
||||
@patch("osusers.admin.SshPublicKey.objects.parse_key_text")
|
||||
def test_clean_again(self, parse_key_text):
|
||||
parse_key_text.return_value = ("good", "key", "comment")
|
||||
user = User.objects.create_user(customer=self.customer)
|
||||
SshPublicKey.objects.create(
|
||||
user=user, algorithm='good', data='key', comment='comment')
|
||||
user=user, algorithm="good", data="key", comment="comment"
|
||||
)
|
||||
form = SshPublicKeyCreationForm()
|
||||
form.cleaned_data = {
|
||||
'user': user,
|
||||
'publickeytext': 'good key comment'
|
||||
}
|
||||
form.cleaned_data = {"user": user, "publickeytext": "good key comment"}
|
||||
form.clean()
|
||||
self.assertIn('publickeytext', form.errors)
|
||||
self.assertIn("publickeytext", form.errors)
|
||||
self.assertEqual(
|
||||
form.errors['publickeytext'],
|
||||
[DUPLICATE_SSH_PUBLIC_KEY_FOR_USER])
|
||||
form.errors["publickeytext"], [DUPLICATE_SSH_PUBLIC_KEY_FOR_USER]
|
||||
)
|
||||
|
||||
@patch('osusers.admin.SshPublicKey.objects.parse_keytext')
|
||||
def test_save(self, parse_keytext):
|
||||
parse_keytext.return_value = ('good', 'key', 'comment')
|
||||
@patch("osusers.admin.SshPublicKey.objects.parse_key_text")
|
||||
def test_save(self, parse_key_text):
|
||||
parse_key_text.return_value = ("good", "key", "comment")
|
||||
user = User.objects.create_user(customer=self.customer)
|
||||
form = SshPublicKeyCreationForm()
|
||||
form.cleaned_data = {
|
||||
'user': user,
|
||||
'publickeytext': 'good key comment'
|
||||
}
|
||||
form.cleaned_data = {"user": user, "publickeytext": "good key comment"}
|
||||
form.instance.user = user
|
||||
form.save()
|
||||
self.assertTrue(
|
||||
SshPublicKey.objects.filter(
|
||||
user=user, algorithm='good', data='key'))
|
||||
SshPublicKey.objects.filter(user=user, algorithm="good", data="key")
|
||||
)
|
||||
|
||||
|
||||
class SshPublicKeyAdminTest(CustomerTestCase):
|
||||
|
||||
def setUp(self):
|
||||
site = AdminSite()
|
||||
self.sadmin = SshPublicKeyAdmin(SshPublicKey, site)
|
||||
super(SshPublicKeyAdminTest, self).setUp()
|
||||
|
||||
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)
|
||||
|
||||
def test_get_form_with_instance(self):
|
||||
user = User.objects.create_user(customer=self.customer)
|
||||
key = SshPublicKey.objects.create(
|
||||
user=user, algorithm='good', data='key', comment='comment')
|
||||
form = self.sadmin.get_form(request=Mock(name='request'), obj=key)
|
||||
user=user, algorithm="good", data="key", comment="comment"
|
||||
)
|
||||
form = self.sadmin.get_form(request=Mock(name="request"), obj=key)
|
||||
self.assertEqual(form.Meta.model, SshPublicKey)
|
||||
self.assertEqual(
|
||||
form.Meta.fields,
|
||||
['user', 'comment', 'algorithm', 'data'])
|
||||
self.assertEqual(form.Meta.fields, ["user", "comment", "algorithm", "data"])
|
||||
|
||||
def test_get_readonly_fields_no_instance(self):
|
||||
readonly_fields = self.sadmin.get_readonly_fields(
|
||||
request=Mock(name='request'))
|
||||
readonly_fields = self.sadmin.get_readonly_fields(request=Mock(name="request"))
|
||||
self.assertEqual(readonly_fields, [])
|
||||
|
||||
def test_get_readonly_fields_with_instance(self):
|
||||
readonly_fields = self.sadmin.get_readonly_fields(
|
||||
request=Mock(name='request'), obj=Mock())
|
||||
self.assertEqual(readonly_fields, ['algorithm', 'data'])
|
||||
request=Mock(name="request"), obj=Mock()
|
||||
)
|
||||
self.assertEqual(readonly_fields, ["algorithm", "data"])
|
||||
|
||||
def test_perform_delete_selected(self):
|
||||
user = User.objects.create_user(customer=self.customer)
|
||||
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(
|
||||
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())
|
||||
|
||||
def test_get_actions(self):
|
||||
requestmock = MagicMock(name='request')
|
||||
self.assertNotIn(
|
||||
'delete_selected',
|
||||
self.sadmin.get_actions(requestmock))
|
||||
self.assertIn(
|
||||
'perform_delete_selected',
|
||||
self.sadmin.get_actions(requestmock))
|
||||
requestmock = MagicMock(name="request")
|
||||
self.assertNotIn("delete_selected", self.sadmin.get_actions(requestmock))
|
||||
self.assertIn("perform_delete_selected", self.sadmin.get_actions(requestmock))
|
||||
|
|
|
@ -2,15 +2,13 @@
|
|||
This module provides tests for :py:mod:`osusers.forms`.
|
||||
|
||||
"""
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
from mock import MagicMock, Mock, patch
|
||||
from unittest.mock import MagicMock, Mock, patch
|
||||
|
||||
from django import forms
|
||||
from django.core.urlresolvers import reverse
|
||||
from django.test import TestCase
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.urls import reverse
|
||||
|
||||
from passlib.hash import sha512_crypt
|
||||
|
||||
|
@ -34,7 +32,7 @@ class AddSshPublicKeyFormTest(TestCase):
|
|||
"""
|
||||
|
||||
def _setup_hostingpackage(self):
|
||||
customer = Customer.objects.create_user('test')
|
||||
customer = Customer.objects.create_user("test")
|
||||
user = User.objects.create_user(customer=customer)
|
||||
self.hostingpackage = Mock(id=42, osuser=user)
|
||||
|
||||
|
@ -42,97 +40,92 @@ class AddSshPublicKeyFormTest(TestCase):
|
|||
instance = MagicMock()
|
||||
with self.assertRaises(KeyError) as ke:
|
||||
AddSshPublicKeyForm(instance)
|
||||
self.assertEqual(ke.exception.args[0], 'hostingpackage')
|
||||
self.assertEqual(ke.exception.args[0], "hostingpackage")
|
||||
|
||||
def test_constructor(self):
|
||||
self._setup_hostingpackage()
|
||||
instance = MagicMock()
|
||||
form = AddSshPublicKeyForm(
|
||||
instance, hostingpackage=self.hostingpackage)
|
||||
self.assertTrue(hasattr(form, 'osuser'))
|
||||
form = AddSshPublicKeyForm(instance, hostingpackage=self.hostingpackage)
|
||||
self.assertTrue(hasattr(form, "osuser"))
|
||||
self.assertEqual(form.osuser, self.hostingpackage.osuser)
|
||||
self.assertTrue(hasattr(form, 'helper'))
|
||||
self.assertEqual(form.helper.form_action, reverse(
|
||||
'add_ssh_key', kwargs={'package': self.hostingpackage.id}))
|
||||
self.assertIn('publickeytext', form.fields)
|
||||
self.assertEqual(form.helper.inputs[0].name, 'submit')
|
||||
self.assertTrue(hasattr(form, "helper"))
|
||||
self.assertEqual(
|
||||
form.helper.form_action,
|
||||
reverse("add_ssh_key", kwargs={"package": self.hostingpackage.id}),
|
||||
)
|
||||
self.assertIn("publickeytext", form.fields)
|
||||
self.assertEqual(form.helper.inputs[0].name, "submit")
|
||||
|
||||
@patch('osusers.forms.SshPublicKey.objects.parse_keytext')
|
||||
def test_clean_publickeytext_invalid(self, parse_keytext):
|
||||
@patch("osusers.forms.SshPublicKey.objects.parse_key_text")
|
||||
def test_clean_publickeytext_invalid(self, parse_key_text):
|
||||
self._setup_hostingpackage()
|
||||
instance = MagicMock()
|
||||
form = AddSshPublicKeyForm(
|
||||
instance, hostingpackage=self.hostingpackage)
|
||||
form.cleaned_data = {'publickeytext': 'a bad key'}
|
||||
parse_keytext.side_effect = ValueError
|
||||
form = AddSshPublicKeyForm(instance, hostingpackage=self.hostingpackage)
|
||||
form.cleaned_data = {"publickeytext": "a bad key"}
|
||||
parse_key_text.side_effect = ValueError
|
||||
with self.assertRaises(forms.ValidationError) as ve:
|
||||
form.clean_publickeytext()
|
||||
self.assertEqual(ve.exception.message, INVALID_SSH_PUBLIC_KEY)
|
||||
|
||||
@patch('osusers.forms.SshPublicKey.objects.parse_keytext')
|
||||
def test_clean_publickeytext_valid(self, parse_keytext):
|
||||
@patch("osusers.forms.SshPublicKey.objects.parse_key_text")
|
||||
def test_clean_publickeytext_valid(self, _):
|
||||
self._setup_hostingpackage()
|
||||
instance = MagicMock()
|
||||
form = AddSshPublicKeyForm(
|
||||
instance, hostingpackage=self.hostingpackage)
|
||||
form.cleaned_data = {'publickeytext': 'good key comment'}
|
||||
form = AddSshPublicKeyForm(instance, hostingpackage=self.hostingpackage)
|
||||
form.cleaned_data = {"publickeytext": "good key comment"}
|
||||
retval = form.clean_publickeytext()
|
||||
self.assertEqual(retval, 'good key comment')
|
||||
self.assertEqual(retval, "good key comment")
|
||||
|
||||
def test_clean_none(self):
|
||||
self._setup_hostingpackage()
|
||||
instance = MagicMock()
|
||||
form = AddSshPublicKeyForm(
|
||||
instance, hostingpackage=self.hostingpackage)
|
||||
form.cleaned_data = {'publickeytext': None}
|
||||
form = AddSshPublicKeyForm(instance, hostingpackage=self.hostingpackage)
|
||||
form.cleaned_data = {"publickeytext": None}
|
||||
form.clean()
|
||||
self.assertIsNone(form.cleaned_data['publickeytext'])
|
||||
self.assertIsNone(form.cleaned_data["publickeytext"])
|
||||
|
||||
@patch('osusers.forms.SshPublicKey.objects.parse_keytext')
|
||||
def test_clean_fresh(self, parse_keytext):
|
||||
@patch("osusers.forms.SshPublicKey.objects.parse_key_text")
|
||||
def test_clean_fresh(self, parse_key_text):
|
||||
self._setup_hostingpackage()
|
||||
instance = MagicMock()
|
||||
form = AddSshPublicKeyForm(
|
||||
instance, hostingpackage=self.hostingpackage)
|
||||
sshpubkey = 'good key comment'
|
||||
form.cleaned_data = {'publickeytext': sshpubkey}
|
||||
parse_keytext.return_value = sshpubkey.split(' ')
|
||||
form = AddSshPublicKeyForm(instance, hostingpackage=self.hostingpackage)
|
||||
sshpubkey = "good key comment"
|
||||
form.cleaned_data = {"publickeytext": sshpubkey}
|
||||
parse_key_text.return_value = sshpubkey.split(" ")
|
||||
form.clean()
|
||||
self.assertEqual(
|
||||
form.cleaned_data['publickeytext'], 'good key comment')
|
||||
self.assertEqual(form.cleaned_data["publickeytext"], "good key comment")
|
||||
|
||||
@patch('osusers.forms.SshPublicKey.objects.parse_keytext')
|
||||
def test_clean_duplicate(self, parse_keytext):
|
||||
@patch("osusers.forms.SshPublicKey.objects.parse_key_text")
|
||||
def test_clean_duplicate(self, parse_key_text):
|
||||
self._setup_hostingpackage()
|
||||
instance = MagicMock()
|
||||
form = AddSshPublicKeyForm(
|
||||
instance, hostingpackage=self.hostingpackage)
|
||||
form = AddSshPublicKeyForm(instance, hostingpackage=self.hostingpackage)
|
||||
SshPublicKey.objects.create(
|
||||
user=self.hostingpackage.osuser, algorithm='good', data='key',
|
||||
comment='comment')
|
||||
sshpubkey = 'good key comment'
|
||||
form.cleaned_data = {'publickeytext': sshpubkey}
|
||||
parse_keytext.return_value = sshpubkey.split(' ')
|
||||
user=self.hostingpackage.osuser,
|
||||
algorithm="good",
|
||||
data="key",
|
||||
comment="comment",
|
||||
)
|
||||
sshpubkey = "good key comment"
|
||||
form.cleaned_data = {"publickeytext": sshpubkey}
|
||||
parse_key_text.return_value = sshpubkey.split(" ")
|
||||
form.clean()
|
||||
self.assertIn('publickeytext', form.errors)
|
||||
self.assertIn(
|
||||
DUPLICATE_SSH_PUBLIC_KEY_FOR_USER,
|
||||
form.errors['publickeytext'])
|
||||
self.assertIn("publickeytext", form.errors)
|
||||
self.assertIn(DUPLICATE_SSH_PUBLIC_KEY_FOR_USER, form.errors["publickeytext"])
|
||||
|
||||
@patch('osusers.admin.SshPublicKey.objects.parse_keytext')
|
||||
def test_save(self, parse_keytext):
|
||||
@patch("osusers.admin.SshPublicKey.objects.parse_key_text")
|
||||
def test_save(self, parse_key_text):
|
||||
self._setup_hostingpackage()
|
||||
instance = MagicMock()
|
||||
form = AddSshPublicKeyForm(
|
||||
instance, hostingpackage=self.hostingpackage)
|
||||
sshpubkey = 'good key comment'
|
||||
form.cleaned_data = {'publickeytext': sshpubkey}
|
||||
parse_keytext.return_value = sshpubkey.split(' ')
|
||||
form = AddSshPublicKeyForm(instance, hostingpackage=self.hostingpackage)
|
||||
sshpubkey = "good key comment"
|
||||
form.cleaned_data = {"publickeytext": sshpubkey}
|
||||
parse_key_text.return_value = sshpubkey.split(" ")
|
||||
retval = form.save()
|
||||
self.assertTrue(isinstance(retval, SshPublicKey))
|
||||
self.assertEqual(retval.algorithm, 'good')
|
||||
self.assertEqual(retval.data, 'key')
|
||||
self.assertEqual(retval.comment, 'comment')
|
||||
self.assertEqual(retval.algorithm, "good")
|
||||
self.assertEqual(retval.data, "key")
|
||||
self.assertEqual(retval.comment, "comment")
|
||||
|
||||
|
||||
class ChangeOsUserPasswordFormTest(TestCase):
|
||||
|
@ -142,25 +135,27 @@ class ChangeOsUserPasswordFormTest(TestCase):
|
|||
"""
|
||||
|
||||
def _setup_user(self):
|
||||
customer = Customer.objects.create_user('test')
|
||||
customer = Customer.objects.create_user("test")
|
||||
self.user = User.objects.create_user(customer=customer)
|
||||
|
||||
def test_constructor(self):
|
||||
self._setup_user()
|
||||
form = ChangeOsUserPasswordForm(instance=self.user)
|
||||
self.assertTrue(hasattr(form, 'instance'))
|
||||
self.assertTrue(hasattr(form, "instance"))
|
||||
self.assertEqual(form.instance, self.user)
|
||||
self.assertTrue(hasattr(form, 'helper'))
|
||||
self.assertEqual(form.helper.form_action, reverse(
|
||||
'set_osuser_password', kwargs={'slug': self.user.username}))
|
||||
self.assertEqual(form.helper.inputs[0].name, 'submit')
|
||||
self.assertTrue(hasattr(form, "helper"))
|
||||
self.assertEqual(
|
||||
form.helper.form_action,
|
||||
reverse("set_osuser_password", kwargs={"slug": self.user.username}),
|
||||
)
|
||||
self.assertEqual(form.helper.inputs[0].name, "submit")
|
||||
|
||||
def test_save(self):
|
||||
self._setup_user()
|
||||
form = ChangeOsUserPasswordForm(instance=self.user)
|
||||
form.cleaned_data = {'password1': 'test'}
|
||||
form.cleaned_data = {"password1": "test"}
|
||||
user = form.save()
|
||||
self.assertTrue(sha512_crypt.verify('test', user.shadow.passwd))
|
||||
self.assertTrue(sha512_crypt.verify("test", user.shadow.passwd))
|
||||
|
||||
|
||||
class EditSshPublicKeyCommentFormTest(TestCase):
|
||||
|
@ -170,7 +165,7 @@ class EditSshPublicKeyCommentFormTest(TestCase):
|
|||
"""
|
||||
|
||||
def _setup_hostingpackage(self):
|
||||
customer = Customer.objects.create_user('test')
|
||||
customer = Customer.objects.create_user("test")
|
||||
user = User.objects.create_user(customer=customer)
|
||||
self.hostingpackage = Mock(id=42, osuser=user)
|
||||
|
||||
|
@ -178,18 +173,23 @@ class EditSshPublicKeyCommentFormTest(TestCase):
|
|||
instance = MagicMock()
|
||||
with self.assertRaises(KeyError) as ke:
|
||||
EditSshPublicKeyCommentForm(instance)
|
||||
self.assertEqual(ke.exception.args[0], 'hostingpackage')
|
||||
self.assertEqual(ke.exception.args[0], "hostingpackage")
|
||||
|
||||
def test_constructor(self):
|
||||
self._setup_hostingpackage()
|
||||
instance = MagicMock(id=1)
|
||||
form = EditSshPublicKeyCommentForm(
|
||||
instance=instance, hostingpackage=self.hostingpackage)
|
||||
self.assertTrue(hasattr(form, 'osuser'))
|
||||
instance=instance, hostingpackage=self.hostingpackage
|
||||
)
|
||||
self.assertTrue(hasattr(form, "osuser"))
|
||||
self.assertEqual(form.osuser, self.hostingpackage.osuser)
|
||||
self.assertIn('comment', form.fields)
|
||||
self.assertTrue(hasattr(form, 'helper'))
|
||||
self.assertEqual(form.helper.form_action, reverse(
|
||||
'edit_ssh_key_comment',
|
||||
kwargs={'package': self.hostingpackage.id, 'pk': instance.id}))
|
||||
self.assertEqual(form.helper.inputs[0].name, 'submit')
|
||||
self.assertIn("comment", form.fields)
|
||||
self.assertTrue(hasattr(form, "helper"))
|
||||
self.assertEqual(
|
||||
form.helper.form_action,
|
||||
reverse(
|
||||
"edit_ssh_key_comment",
|
||||
kwargs={"package": self.hostingpackage.id, "pk": instance.id},
|
||||
),
|
||||
)
|
||||
self.assertEqual(form.helper.inputs[0].name, "submit")
|
||||
|
|
|
@ -1,19 +1,17 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
from datetime import date
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.test import TestCase
|
||||
from django.test.utils import override_settings
|
||||
from django.utils import timezone
|
||||
from django.contrib.auth import get_user_model
|
||||
|
||||
from passlib.hash import sha512_crypt
|
||||
|
||||
from osusers.models import (
|
||||
CANNOT_USE_PRIMARY_GROUP_AS_ADDITIONAL,
|
||||
AdditionalGroup,
|
||||
CANNOT_USE_PRIMARY_GROUP_AS_ADDITIONAL,
|
||||
Group,
|
||||
Shadow,
|
||||
SshPublicKey,
|
||||
|
@ -21,7 +19,6 @@ from osusers.models import (
|
|||
)
|
||||
from taskresults.models import TaskResult
|
||||
|
||||
|
||||
EXAMPLE_KEY_1_RFC4716 = """---- BEGIN SSH2 PUBLIC KEY ----
|
||||
Comment: "1024-bit RSA, converted from OpenSSH by me@example.com"
|
||||
x-command: /home/me/bin/lock-in-guest.sh
|
||||
|
@ -57,12 +54,14 @@ n24VYtYtsMu74qXviYjziVucWKjjKEb11juqnF0GDlB3VVmxHLmxnAz643WK42Z7dLM5
|
|||
sY29ouezv4Xz2PuMch5VGPP+CDqzCM4loWgV
|
||||
---- END SSH2 PUBLIC KEY ----"""
|
||||
|
||||
EXAMPLE_KEY_4_OPENSSH = "".join((
|
||||
EXAMPLE_KEY_4_OPENSSH = "".join(
|
||||
(
|
||||
"ssh-rsa ",
|
||||
"AAAAB3NzaC1yc2EAAAABIwAAAIEA1on8gxCGJJWSRT4uOrR13mUaUk0hRf4RzxSZ1zRb",
|
||||
"YYFw8pfGesIFoEuVth4HKyF8k1y4mRUnYHP1XNMNMJl1JcEArC2asV8sHf6zSPVffozZ",
|
||||
"5TT4SfsUu/iKy9lUcCfXzwre4WWZSXXcPff+EHtWshahu3WzBdnGxm5Xoi89zcE="
|
||||
))
|
||||
"5TT4SfsUu/iKy9lUcCfXzwre4WWZSXXcPff+EHtWshahu3WzBdnGxm5Xoi89zcE=",
|
||||
)
|
||||
)
|
||||
|
||||
EXAMPLE_KEY_5_RFC4716_MULTILINE = """---- BEGIN SSH2 PUBLIC KEY ----
|
||||
Comment: DSA Public Key \\
|
||||
|
@ -99,10 +98,7 @@ YYFw8pfGesIFoEuVth4HKyF8k1y4mRUnYHP1XNMNMJl1JcEArC2asV8sHf6zSPVffozZ
|
|||
5TT4SfsUu/iKy9lUcCfXzwre4WWZSXXcPff+EHtWshahu3WzBdnGxm5Xoi89zcE=
|
||||
---- END SSH2 PUBLIC KEY ----"""
|
||||
|
||||
EXAMPLE_KEY_8_OPENSSH_BROKEN = "".join((
|
||||
"ssh-rsa ",
|
||||
"AschrÖdderöd"
|
||||
))
|
||||
EXAMPLE_KEY_8_OPENSSH_BROKEN = "".join(("ssh-rsa ", "AschrÖdderöd"))
|
||||
|
||||
EXAMPLE_KEY_9_RFC4716_ONLY_HEADER = "---- BEGIN SSH2 PUBLIC KEY ----"
|
||||
|
||||
|
@ -110,9 +106,7 @@ Customer = get_user_model()
|
|||
|
||||
|
||||
@override_settings(
|
||||
CELERY_ALWAYS_EAGER=True,
|
||||
CELERY_CACHE_BACKEND='memory',
|
||||
BROKER_BACKEND='memory'
|
||||
CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
|
||||
)
|
||||
class TestCaseWithCeleryTasks(TestCase):
|
||||
pass
|
||||
|
@ -120,38 +114,44 @@ class TestCaseWithCeleryTasks(TestCase):
|
|||
|
||||
class AdditionalGroupTest(TestCaseWithCeleryTasks):
|
||||
def setUp(self):
|
||||
customer = Customer.objects.create(username='test')
|
||||
self.group1 = Group.objects.create(groupname='test1', gid=1000)
|
||||
customer = Customer.objects.create(username="test")
|
||||
self.group1 = Group.objects.create(groupname="test1", gid=1000)
|
||||
self.user = User.objects.create(
|
||||
customer=customer, username='test', uid=1000, group=self.group1,
|
||||
homedir='/home/test', shell='/bin/bash')
|
||||
customer=customer,
|
||||
username="test",
|
||||
uid=1000,
|
||||
group=self.group1,
|
||||
homedir="/home/test",
|
||||
shell="/bin/bash",
|
||||
)
|
||||
|
||||
def test_clean_primary_group(self):
|
||||
testsubj = AdditionalGroup(user=self.user, group=self.group1)
|
||||
with self.assertRaises(ValidationError) as cm:
|
||||
testsubj.clean()
|
||||
self.assertEqual(
|
||||
cm.exception.message, CANNOT_USE_PRIMARY_GROUP_AS_ADDITIONAL)
|
||||
self.assertEqual(cm.exception.message, CANNOT_USE_PRIMARY_GROUP_AS_ADDITIONAL)
|
||||
|
||||
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.clean()
|
||||
|
||||
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.save()
|
||||
taskres = TaskResult.objects.all()
|
||||
self.assertTrue(len(taskres), 4)
|
||||
creators = [r.creator for r in taskres]
|
||||
for tcount, tcreator in [
|
||||
(2, 'handle_group_created'), (1, 'handle_user_created'),
|
||||
(1, 'handle_user_added_to_group')]:
|
||||
(2, "handle_group_created"),
|
||||
(1, "handle_user_created"),
|
||||
(1, "handle_user_added_to_group"),
|
||||
]:
|
||||
self.assertEqual(creators.count(tcreator), tcount)
|
||||
|
||||
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()
|
||||
addgroup = AdditionalGroup(user=self.user, group=group2)
|
||||
addgroup.save()
|
||||
|
@ -161,15 +161,18 @@ class AdditionalGroupTest(TestCaseWithCeleryTasks):
|
|||
self.assertEqual(len(taskres), 0)
|
||||
|
||||
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.delete()
|
||||
# noinspection PyUnresolvedReferences
|
||||
self.assertEqual(len(AdditionalGroup.objects.all()), 0)
|
||||
|
||||
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)
|
||||
self.assertEqual(str(addgroup), 'test (1000) in test2 (1001)')
|
||||
self.assertEqual(str(addgroup), "test (1000) in test2 (1001)")
|
||||
|
||||
|
||||
@override_settings(OSUSER_MINGID=10000)
|
||||
|
@ -178,56 +181,61 @@ class GroupManagerTest(TestCaseWithCeleryTasks):
|
|||
self.assertEqual(Group.objects.get_next_gid(), 10000)
|
||||
|
||||
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)
|
||||
|
||||
|
||||
class GroupTest(TestCaseWithCeleryTasks):
|
||||
def test___str__(self):
|
||||
group = Group.objects.create(gid=10000, groupname='test')
|
||||
self.assertEqual(str(group), 'test (10000)')
|
||||
group = Group.objects.create(gid=10000, groupname="test")
|
||||
self.assertEqual(str(group), "test (10000)")
|
||||
|
||||
def test_save(self):
|
||||
group = Group(gid=10000, groupname='test')
|
||||
group = Group(gid=10000, groupname="test")
|
||||
self.assertIs(group.save(), group)
|
||||
taskres = TaskResult.objects.all()
|
||||
self.assertTrue(len(taskres), 1)
|
||||
creators = [r.creator for r in taskres]
|
||||
for tcount, tcreator in [
|
||||
(1, 'handle_group_created')]:
|
||||
for tcount, tcreator in [(1, "handle_group_created")]:
|
||||
self.assertEqual(creators.count(tcreator), tcount)
|
||||
|
||||
def test_save_again(self):
|
||||
group = Group.objects.create(gid=10000, groupname='test')
|
||||
taskres = TaskResult.objects.all().delete()
|
||||
group = Group.objects.create(gid=10000, groupname="test")
|
||||
TaskResult.objects.all().delete()
|
||||
group.save()
|
||||
taskres = TaskResult.objects.all()
|
||||
self.assertEqual(len(taskres), 0)
|
||||
|
||||
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)
|
||||
group.delete()
|
||||
self.assertEqual(len(Group.objects.all()), 0)
|
||||
self.assertEqual(len(TaskResult.objects.all()), 2)
|
||||
tr = TaskResult.objects.first()
|
||||
self.assertEqual(tr.creator, 'handle_group_created')
|
||||
self.assertEqual(tr.creator, "handle_group_created")
|
||||
|
||||
|
||||
class ShadowManagerTest(TestCaseWithCeleryTasks):
|
||||
def setUp(self):
|
||||
self.customer = Customer.objects.create(username='test')
|
||||
self.customer = Customer.objects.create(username="test")
|
||||
super(ShadowManagerTest, self).setUp()
|
||||
|
||||
def test_create_shadow(self):
|
||||
user = User(
|
||||
customer=self.customer, username='test', uid=1000,
|
||||
group=Group(gid=1000, groupname='test'), homedir='/home/test',
|
||||
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)
|
||||
group = Group.objects.create(gid=1000, groupname="test")
|
||||
user = User.objects.create(
|
||||
customer=self.customer,
|
||||
username="test",
|
||||
uid=1000,
|
||||
group=group,
|
||||
homedir="/home/test",
|
||||
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.minage, 0)
|
||||
self.assertIsNone(shadow.maxage)
|
||||
|
@ -238,39 +246,50 @@ class ShadowManagerTest(TestCaseWithCeleryTasks):
|
|||
|
||||
class ShadowTest(TestCaseWithCeleryTasks):
|
||||
def setUp(self):
|
||||
self.customer = Customer.objects.create(username='test')
|
||||
self.customer = Customer.objects.create(username="test")
|
||||
super(ShadowTest, self).setUp()
|
||||
|
||||
def test___str__(self):
|
||||
group = Group.objects.create(
|
||||
groupname='test', gid=1000)
|
||||
group = Group.objects.create(groupname="test", gid=1000)
|
||||
user = User.objects.create(
|
||||
customer=self.customer, username='test', uid=1000, group=group,
|
||||
homedir='/home/test', shell='/bin/bash')
|
||||
customer=self.customer,
|
||||
username="test",
|
||||
uid=1000,
|
||||
group=group,
|
||||
homedir="/home/test",
|
||||
shell="/bin/bash",
|
||||
)
|
||||
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):
|
||||
group = Group.objects.create(
|
||||
groupname='test', gid=1000)
|
||||
group = Group.objects.create(groupname="test", gid=1000)
|
||||
user = User.objects.create(
|
||||
customer=self.customer, username='test', uid=1000, group=group,
|
||||
homedir='/home/test', shell='/bin/bash')
|
||||
customer=self.customer,
|
||||
username="test",
|
||||
uid=1000,
|
||||
group=group,
|
||||
homedir="/home/test",
|
||||
shell="/bin/bash",
|
||||
)
|
||||
shadow = Shadow(user=user)
|
||||
shadow.set_password('test')
|
||||
self.assertTrue(sha512_crypt.verify('test', shadow.passwd))
|
||||
shadow.set_password("test")
|
||||
self.assertTrue(sha512_crypt.verify("test", shadow.passwd))
|
||||
|
||||
|
||||
@override_settings(
|
||||
OSUSER_MINUID=10000, OSUSER_MINGID=10000, OSUSER_USERNAME_PREFIX='test',
|
||||
OSUSER_HOME_BASEPATH='/home', OSUSER_DEFAULT_SHELL='/bin/fooshell'
|
||||
OSUSER_MINUID=10000,
|
||||
OSUSER_MINGID=10000,
|
||||
OSUSER_USERNAME_PREFIX="test",
|
||||
OSUSER_HOME_BASEPATH="/home",
|
||||
OSUSER_DEFAULT_SHELL="/bin/fooshell",
|
||||
)
|
||||
class UserManagerTest(TestCaseWithCeleryTasks):
|
||||
def _create_group(self):
|
||||
return Group.objects.create(gid=10000, groupname='foo')
|
||||
return Group.objects.create(gid=10000, groupname="foo")
|
||||
|
||||
def setUp(self):
|
||||
self.customer = Customer.objects.create(username='test')
|
||||
self.customer = Customer.objects.create(username="test")
|
||||
super(UserManagerTest, self).setUp()
|
||||
|
||||
def test_get_next_uid_first(self):
|
||||
|
@ -278,40 +297,58 @@ class UserManagerTest(TestCaseWithCeleryTasks):
|
|||
|
||||
def test_get_next_uid_second(self):
|
||||
User.objects.create(
|
||||
customer=self.customer, uid=10010, username='foo',
|
||||
group=self._create_group(), homedir='/home/foo',
|
||||
shell='/bin/fooshell')
|
||||
customer=self.customer,
|
||||
uid=10010,
|
||||
username="foo",
|
||||
group=self._create_group(),
|
||||
homedir="/home/foo",
|
||||
shell="/bin/fooshell",
|
||||
)
|
||||
self.assertEqual(User.objects.get_next_uid(), 10011)
|
||||
|
||||
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):
|
||||
User.objects.create(
|
||||
customer=self.customer, uid=10000, username='test01',
|
||||
group=self._create_group(), homedir='/home/foo',
|
||||
shell='/bin/fooshell')
|
||||
self.assertEqual(User.objects.get_next_username(), 'test02')
|
||||
customer=self.customer,
|
||||
uid=10000,
|
||||
username="test01",
|
||||
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):
|
||||
group = self._create_group()
|
||||
User.objects.create(
|
||||
customer=self.customer, uid=10000, username='test01', group=group,
|
||||
homedir='/home/foo', shell='/bin/fooshell')
|
||||
customer=self.customer,
|
||||
uid=10000,
|
||||
username="test01",
|
||||
group=group,
|
||||
homedir="/home/foo",
|
||||
shell="/bin/fooshell",
|
||||
)
|
||||
User.objects.create(
|
||||
customer=self.customer, uid=10002, username='test03', group=group,
|
||||
homedir='/home/foo', shell='/bin/fooshell')
|
||||
self.assertEqual(User.objects.get_next_username(), 'test02')
|
||||
customer=self.customer,
|
||||
uid=10002,
|
||||
username="test03",
|
||||
group=group,
|
||||
homedir="/home/foo",
|
||||
shell="/bin/fooshell",
|
||||
)
|
||||
self.assertEqual(User.objects.get_next_username(), "test02")
|
||||
|
||||
def test_create_user_first(self):
|
||||
user = User.objects.create_user(customer=self.customer)
|
||||
self.assertIsInstance(user, User)
|
||||
self.assertEqual(user.uid, 10000)
|
||||
self.assertEqual(user.group.gid, 10000)
|
||||
self.assertEqual(user.group.groupname, 'test01')
|
||||
self.assertEqual(user.username, 'test01')
|
||||
self.assertEqual(user.homedir, '/home/test01')
|
||||
self.assertEqual(user.shell, '/bin/fooshell')
|
||||
self.assertEqual(user.group.groupname, "test01")
|
||||
self.assertEqual(user.username, "test01")
|
||||
self.assertEqual(user.homedir, "/home/test01")
|
||||
self.assertEqual(user.shell, "/bin/fooshell")
|
||||
self.assertIsNotNone(user.shadow)
|
||||
|
||||
def test_create_user_tasks(self):
|
||||
|
@ -320,8 +357,10 @@ class UserManagerTest(TestCaseWithCeleryTasks):
|
|||
self.assertEqual(len(taskres), 3)
|
||||
creators = [r.creator for r in taskres]
|
||||
for creator in [
|
||||
'handle_group_created', 'handle_user_created',
|
||||
'handle_user_password_set']:
|
||||
"handle_group_created",
|
||||
"handle_user_created",
|
||||
"handle_user_password_set",
|
||||
]:
|
||||
self.assertIn(creator, creators)
|
||||
|
||||
def test_create_user_second(self):
|
||||
|
@ -330,36 +369,34 @@ class UserManagerTest(TestCaseWithCeleryTasks):
|
|||
self.assertIsInstance(user, User)
|
||||
self.assertEqual(user.uid, 10001)
|
||||
self.assertEqual(user.group.gid, 10001)
|
||||
self.assertEqual(user.group.groupname, 'test02')
|
||||
self.assertEqual(user.username, 'test02')
|
||||
self.assertEqual(user.homedir, '/home/test02')
|
||||
self.assertEqual(user.shell, '/bin/fooshell')
|
||||
self.assertEqual(user.group.groupname, "test02")
|
||||
self.assertEqual(user.username, "test02")
|
||||
self.assertEqual(user.homedir, "/home/test02")
|
||||
self.assertEqual(user.shell, "/bin/fooshell")
|
||||
self.assertIsNotNone(user.shadow)
|
||||
self.assertEqual(len(User.objects.all()), 2)
|
||||
|
||||
def test_create_user_known_password(self):
|
||||
user = User.objects.create_user(
|
||||
customer=self.customer, password='foobar')
|
||||
user = User.objects.create_user(customer=self.customer, password="foobar")
|
||||
self.assertIsInstance(user, User)
|
||||
self.assertEqual(user.uid, 10000)
|
||||
self.assertEqual(user.group.gid, 10000)
|
||||
self.assertEqual(user.group.groupname, 'test01')
|
||||
self.assertEqual(user.username, 'test01')
|
||||
self.assertEqual(user.homedir, '/home/test01')
|
||||
self.assertEqual(user.shell, '/bin/fooshell')
|
||||
self.assertEqual(user.group.groupname, "test01")
|
||||
self.assertEqual(user.username, "test01")
|
||||
self.assertEqual(user.homedir, "/home/test01")
|
||||
self.assertEqual(user.shell, "/bin/fooshell")
|
||||
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):
|
||||
user = User.objects.create_user(
|
||||
customer=self.customer, username='tester')
|
||||
user = User.objects.create_user(customer=self.customer, username="tester")
|
||||
self.assertIsInstance(user, User)
|
||||
self.assertEqual(user.uid, 10000)
|
||||
self.assertEqual(user.group.gid, 10000)
|
||||
self.assertEqual(user.group.groupname, 'tester')
|
||||
self.assertEqual(user.username, 'tester')
|
||||
self.assertEqual(user.homedir, '/home/tester')
|
||||
self.assertEqual(user.shell, '/bin/fooshell')
|
||||
self.assertEqual(user.group.groupname, "tester")
|
||||
self.assertEqual(user.username, "tester")
|
||||
self.assertEqual(user.homedir, "/home/tester")
|
||||
self.assertEqual(user.shell, "/bin/fooshell")
|
||||
self.assertIsNotNone(user.shadow)
|
||||
|
||||
def test_create_user_commit(self):
|
||||
|
@ -367,31 +404,34 @@ class UserManagerTest(TestCaseWithCeleryTasks):
|
|||
self.assertIsInstance(user, User)
|
||||
self.assertEqual(user.uid, 10000)
|
||||
self.assertEqual(user.group.gid, 10000)
|
||||
self.assertEqual(user.group.groupname, 'test01')
|
||||
self.assertEqual(user.username, 'test01')
|
||||
self.assertEqual(user.homedir, '/home/test01')
|
||||
self.assertEqual(user.shell, '/bin/fooshell')
|
||||
self.assertEqual(user.group.groupname, "test01")
|
||||
self.assertEqual(user.username, "test01")
|
||||
self.assertEqual(user.homedir, "/home/test01")
|
||||
self.assertEqual(user.shell, "/bin/fooshell")
|
||||
self.assertIsNotNone(user.shadow)
|
||||
|
||||
|
||||
@override_settings(
|
||||
OSUSER_MINUID=10000, OSUSER_MINGID=10000, OSUSER_USERNAME_PREFIX='test',
|
||||
OSUSER_HOME_BASEPATH='/home', OSUSER_DEFAULT_SHELL='/bin/fooshell'
|
||||
OSUSER_MINUID=10000,
|
||||
OSUSER_MINGID=10000,
|
||||
OSUSER_USERNAME_PREFIX="test",
|
||||
OSUSER_HOME_BASEPATH="/home",
|
||||
OSUSER_DEFAULT_SHELL="/bin/fooshell",
|
||||
)
|
||||
class UserTest(TestCaseWithCeleryTasks):
|
||||
def setUp(self):
|
||||
self.customer = Customer.objects.create_user('test')
|
||||
self.customer = Customer.objects.create_user("test")
|
||||
super(UserTest, self).setUp()
|
||||
|
||||
def test___str__(self):
|
||||
user = User.objects.create_user(self.customer)
|
||||
self.assertEqual(str(user), 'test01 (10000)')
|
||||
self.assertEqual(str(user), "test01 (10000)")
|
||||
|
||||
def test_set_password(self):
|
||||
user = User.objects.create_user(self.customer)
|
||||
self.assertFalse(sha512_crypt.verify('test', user.shadow.passwd))
|
||||
user.set_password('test')
|
||||
self.assertTrue(sha512_crypt.verify('test', user.shadow.passwd))
|
||||
self.assertFalse(sha512_crypt.verify("test", user.shadow.passwd))
|
||||
user.set_password("test")
|
||||
self.assertTrue(sha512_crypt.verify("test", user.shadow.passwd))
|
||||
|
||||
def test_save(self):
|
||||
user = User.objects.create_user(self.customer)
|
||||
|
@ -400,8 +440,10 @@ class UserTest(TestCaseWithCeleryTasks):
|
|||
self.assertEqual(len(taskres), 3)
|
||||
creators = [r.creator for r in taskres]
|
||||
for task in [
|
||||
'handle_group_created', 'handle_user_created',
|
||||
'handle_user_password_set']:
|
||||
"handle_group_created",
|
||||
"handle_user_created",
|
||||
"handle_user_password_set",
|
||||
]:
|
||||
self.assertIn(task, creators)
|
||||
|
||||
def test_delete_only_user(self):
|
||||
|
@ -411,30 +453,38 @@ class UserTest(TestCaseWithCeleryTasks):
|
|||
self.assertEqual(len(taskres), 6)
|
||||
creators = [r.creator for r in taskres]
|
||||
for task in [
|
||||
'handle_group_created', 'handle_user_created',
|
||||
'handle_user_password_set', 'handle_user_deleted',
|
||||
'handle_group_deleted', 'handle_user_deleted']:
|
||||
"handle_group_created",
|
||||
"handle_user_created",
|
||||
"handle_user_password_set",
|
||||
"handle_user_deleted",
|
||||
"handle_group_deleted",
|
||||
"handle_user_deleted",
|
||||
]:
|
||||
self.assertIn(task, creators)
|
||||
self.assertEqual(len(User.objects.all()), 0)
|
||||
|
||||
def test_delete_additional_groups(self):
|
||||
group1 = Group.objects.create(gid=2000, groupname='group1')
|
||||
group2 = Group.objects.create(gid=2001, groupname='group2')
|
||||
group1 = Group.objects.create(gid=2000, groupname="group1")
|
||||
group2 = Group.objects.create(gid=2001, groupname="group2")
|
||||
user = User.objects.create_user(self.customer)
|
||||
for group in [group1, group2]:
|
||||
# noinspection PyUnresolvedReferences
|
||||
user.additionalgroup_set.add(
|
||||
AdditionalGroup.objects.create(user=user, group=group))
|
||||
AdditionalGroup.objects.create(user=user, group=group)
|
||||
)
|
||||
TaskResult.objects.all().delete()
|
||||
user.delete()
|
||||
taskres = TaskResult.objects.all()
|
||||
self.assertEqual(len(taskres), 5)
|
||||
creators = [t.creator for t in taskres]
|
||||
for tcount, tcreator in [
|
||||
(2, 'handle_user_removed_from_group'),
|
||||
(2, 'handle_user_deleted'),
|
||||
(1, 'handle_group_deleted')]:
|
||||
(2, "handle_user_removed_from_group"),
|
||||
(2, "handle_user_deleted"),
|
||||
(1, "handle_group_deleted"),
|
||||
]:
|
||||
self.assertEqual(creators.count(tcreator), tcount)
|
||||
self.assertEqual(len(User.objects.all()), 0)
|
||||
# noinspection PyUnresolvedReferences
|
||||
self.assertEqual(len(AdditionalGroup.objects.all()), 0)
|
||||
|
||||
def test_is_sftp_user(self):
|
||||
|
@ -442,138 +492,140 @@ class UserTest(TestCaseWithCeleryTasks):
|
|||
self.assertFalse(user.is_sftp_user())
|
||||
|
||||
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(
|
||||
AdditionalGroup.objects.create(user=user, group=sftp_group))
|
||||
AdditionalGroup.objects.create(user=user, group=sftp_group)
|
||||
)
|
||||
self.assertTrue(user.is_sftp_user())
|
||||
|
||||
|
||||
class SshPublicKeyManagerTest(TestCaseWithCeleryTasks):
|
||||
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.assertGreater(len(res[1]), 40)
|
||||
self.assertEqual(res[0], 'ssh-rsa')
|
||||
self.assertEqual(res[0], "ssh-rsa")
|
||||
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):
|
||||
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(res[0], 'ssh-dss')
|
||||
self.assertEqual(res[0], "ssh-dss")
|
||||
self.assertGreater(len(res[1]), 40)
|
||||
self.assertEqual(
|
||||
res[2],
|
||||
"This is my public key for use on servers which I don't like.")
|
||||
res[2], "This is my public key for use on servers which I don't like."
|
||||
)
|
||||
|
||||
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(res[0], 'ssh-dss')
|
||||
self.assertEqual(res[0], "ssh-dss")
|
||||
self.assertGreater(len(res[1]), 40)
|
||||
self.assertEqual(res[2], "DSA Public Key for use with MyIsp")
|
||||
|
||||
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.assertEqual(res[0], 'ssh-rsa')
|
||||
self.assertEqual(res[0], "ssh-rsa")
|
||||
self.assertGreater(len(res[1]), 40)
|
||||
self.assertEqual(res[2], '')
|
||||
self.assertEqual(res[2], "")
|
||||
|
||||
def test_parse_keytext_invalid_multiline(self):
|
||||
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):
|
||||
res = SshPublicKey.objects.parse_keytext(
|
||||
EXAMPLE_KEY_6_RFC4716_EMPTY_LINE)
|
||||
res = SshPublicKey.objects.parse_key_text(EXAMPLE_KEY_6_RFC4716_EMPTY_LINE)
|
||||
self.assertEqual(len(res), 3)
|
||||
self.assertEqual(res[0], 'ssh-dss')
|
||||
self.assertEqual(res[0], "ssh-dss")
|
||||
self.assertGreater(len(res[1]), 40)
|
||||
self.assertEqual(res[2], "DSA Public Key for use with MyIsp")
|
||||
|
||||
def test_parse_keytext_invalid_empty_rfc4716_header(self):
|
||||
with self.assertRaises(ValueError):
|
||||
SshPublicKey.objects.parse_keytext(
|
||||
EXAMPLE_KEY_9_RFC4716_ONLY_HEADER)
|
||||
SshPublicKey.objects.parse_key_text(EXAMPLE_KEY_9_RFC4716_ONLY_HEADER)
|
||||
|
||||
def test_parse_keytext_no_comment(self):
|
||||
res = SshPublicKey.objects.parse_keytext(
|
||||
EXAMPLE_KEY_7_NO_COMMENT)
|
||||
res = SshPublicKey.objects.parse_key_text(EXAMPLE_KEY_7_NO_COMMENT)
|
||||
self.assertEqual(len(res), 3)
|
||||
self.assertEqual(res[0], 'ssh-rsa')
|
||||
self.assertEqual(res[0], "ssh-rsa")
|
||||
self.assertGreater(len(res[1]), 40)
|
||||
self.assertEqual(res[2], '')
|
||||
self.assertEqual(res[2], "")
|
||||
|
||||
def test_parse_keytext_multiline_comment(self):
|
||||
res = SshPublicKey.objects.parse_keytext(
|
||||
EXAMPLE_KEY_5_RFC4716_MULTILINE)
|
||||
res = SshPublicKey.objects.parse_key_text(EXAMPLE_KEY_5_RFC4716_MULTILINE)
|
||||
self.assertEqual(len(res), 3)
|
||||
self.assertEqual(res[0], 'ssh-dss')
|
||||
self.assertEqual(res[0], "ssh-dss")
|
||||
self.assertGreater(len(res[1]), 40)
|
||||
self.assertEqual(res[2], "DSA Public Key for use with MyIsp")
|
||||
|
||||
def test_parse_keytext_invalid(self):
|
||||
with self.assertRaises(ValueError):
|
||||
SshPublicKey.objects.parse_keytext('invalid')
|
||||
SshPublicKey.objects.parse_key_text("invalid")
|
||||
|
||||
def test_parse_keytext_invalid_openssh(self):
|
||||
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):
|
||||
customer = Customer.objects.create_user('test')
|
||||
customer = Customer.objects.create_user("test")
|
||||
user = User.objects.create_user(customer)
|
||||
key = SshPublicKey.objects.create_ssh_public_key(
|
||||
user, EXAMPLE_KEY_4_OPENSSH)
|
||||
key = SshPublicKey.objects.create_ssh_public_key(user, EXAMPLE_KEY_4_OPENSSH)
|
||||
self.assertIsInstance(key, SshPublicKey)
|
||||
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.comment, '')
|
||||
self.assertEqual(key.comment, "")
|
||||
|
||||
|
||||
class SshPublicKeyTest(TestCaseWithCeleryTasks):
|
||||
def setUp(self):
|
||||
super(SshPublicKeyTest, self).setUp()
|
||||
customer = Customer.objects.create_user('test')
|
||||
customer = Customer.objects.create_user("test")
|
||||
self.user = User.objects.create_user(customer)
|
||||
TaskResult.objects.all().delete()
|
||||
|
||||
def test__str__rfc4716(self):
|
||||
res = SshPublicKey.objects.create_ssh_public_key(
|
||||
self.user, EXAMPLE_KEY_3_RFC4716)
|
||||
self.user, EXAMPLE_KEY_3_RFC4716
|
||||
)
|
||||
self.maxDiff = None
|
||||
self.assertEqual(
|
||||
str(res), 'ssh-dss AAAAB3NzaC1kc3MAAACBAPY8ZOHY2yFSJA6XYC9HRwNHxae'
|
||||
'hvx5wOJ0rzZdzoSOXxbETW6ToHv8D1UJ/z+zHo9Fiko5XybZnDIaBDHtblQ+Yp7St'
|
||||
'xyltHnXF1YLfKD1G4T6JYrdHYI14Om1eg9e4NnCRleaqoZPF3UGfZia6bXrGTQf3g'
|
||||
'Jq2e7Yisk/gF+1VAAAAFQDb8D5cvwHWTZDPfX0D2s9Rd7NBvQAAAIEAlN92+Bb7D4'
|
||||
'KLYk3IwRbXblwXdkPggA4pfdtW9vGfJ0/RHd+NjB4eo1D+0dix6tXwYGN7PKS5R/F'
|
||||
'XPNwxHPapcj9uL1Jn2AWQ2dsknf+i/FAAvioUPkmdMc0zuWoSOEsSNhVDtX3WdvVc'
|
||||
'GcBq9cetzrtOKWOocJmJ80qadxTRHtUAAACBAN7CY+KKv1gHpRzFwdQm7HK9bb1LA'
|
||||
'o2KwaoXnadFgeptNBQeSXG1vO+JsvphVMBJc9HSn24VYtYtsMu74qXviYjziVucWK'
|
||||
'jjKEb11juqnF0GDlB3VVmxHLmxnAz643WK42Z7dLM5sY29ouezv4Xz2PuMch5VGPP'
|
||||
'+CDqzCM4loWgV DSA Public Key for use with MyIsp')
|
||||
str(res),
|
||||
"ssh-dss AAAAB3NzaC1kc3MAAACBAPY8ZOHY2yFSJA6XYC9HRwNHxae"
|
||||
"hvx5wOJ0rzZdzoSOXxbETW6ToHv8D1UJ/z+zHo9Fiko5XybZnDIaBDHtblQ+Yp7St"
|
||||
"xyltHnXF1YLfKD1G4T6JYrdHYI14Om1eg9e4NnCRleaqoZPF3UGfZia6bXrGTQf3g"
|
||||
"Jq2e7Yisk/gF+1VAAAAFQDb8D5cvwHWTZDPfX0D2s9Rd7NBvQAAAIEAlN92+Bb7D4"
|
||||
"KLYk3IwRbXblwXdkPggA4pfdtW9vGfJ0/RHd+NjB4eo1D+0dix6tXwYGN7PKS5R/F"
|
||||
"XPNwxHPapcj9uL1Jn2AWQ2dsknf+i/FAAvioUPkmdMc0zuWoSOEsSNhVDtX3WdvVc"
|
||||
"GcBq9cetzrtOKWOocJmJ80qadxTRHtUAAACBAN7CY+KKv1gHpRzFwdQm7HK9bb1LA"
|
||||
"o2KwaoXnadFgeptNBQeSXG1vO+JsvphVMBJc9HSn24VYtYtsMu74qXviYjziVucWK"
|
||||
"jjKEb11juqnF0GDlB3VVmxHLmxnAz643WK42Z7dLM5sY29ouezv4Xz2PuMch5VGPP"
|
||||
"+CDqzCM4loWgV DSA Public Key for use with MyIsp",
|
||||
)
|
||||
|
||||
def test__str__openssh(self):
|
||||
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)
|
||||
|
||||
def test_call_tasks_on_save(self):
|
||||
SshPublicKey.objects.create_ssh_public_key(
|
||||
self.user, EXAMPLE_KEY_4_OPENSSH)
|
||||
SshPublicKey.objects.create_ssh_public_key(self.user, EXAMPLE_KEY_4_OPENSSH)
|
||||
taskresults = TaskResult.objects.all()
|
||||
self.assertEqual(len(taskresults), 1)
|
||||
self.assertEqual(
|
||||
taskresults[0].creator, 'handle_ssh_keys_changed')
|
||||
self.assertEqual(taskresults[0].creator, "handle_ssh_keys_changed")
|
||||
|
||||
def test_call_tasks_on_delete(self):
|
||||
key = SshPublicKey.objects.create_ssh_public_key(
|
||||
self.user, EXAMPLE_KEY_4_OPENSSH)
|
||||
self.user, EXAMPLE_KEY_4_OPENSSH
|
||||
)
|
||||
TaskResult.objects.all().delete()
|
||||
key.delete()
|
||||
taskresults = TaskResult.objects.all()
|
||||
self.assertEqual(len(taskresults), 1)
|
||||
self.assertEqual(
|
||||
taskresults[0].creator, 'handle_ssh_keys_changed')
|
||||
self.assertEqual(taskresults[0].creator, "handle_ssh_keys_changed")
|
||||
|
|
|
@ -2,66 +2,59 @@
|
|||
This module provides tests for :py:mod:`osusers.views`.
|
||||
|
||||
"""
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
try:
|
||||
from unittest.mock import patch, MagicMock
|
||||
except ImportError:
|
||||
from mock import patch, MagicMock
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
from django.core.urlresolvers import reverse
|
||||
from django.test import TestCase, TransactionTestCase
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.urls import reverse
|
||||
|
||||
from hostingpackages.models import (
|
||||
CustomerHostingPackage,
|
||||
HostingPackageTemplate,
|
||||
)
|
||||
from hostingpackages.models import CustomerHostingPackage, HostingPackageTemplate
|
||||
|
||||
from osusers.models import SshPublicKey
|
||||
from osusers.views import (
|
||||
AddSshPublicKey,
|
||||
DeleteSshPublicKey,
|
||||
EditSshPublicKeyComment,
|
||||
)
|
||||
from osusers.views import AddSshPublicKey, DeleteSshPublicKey, EditSshPublicKeyComment
|
||||
|
||||
|
||||
User = get_user_model()
|
||||
|
||||
TEST_USER = 'test'
|
||||
TEST_PASSWORD = 'secret'
|
||||
TEST_EMAIL = 'test@example.org'
|
||||
EXAMPLE_KEY = "".join((
|
||||
TEST_USER = "test"
|
||||
TEST_PASSWORD = "secret"
|
||||
TEST_EMAIL = "test@example.org"
|
||||
EXAMPLE_KEY = "".join(
|
||||
(
|
||||
"ssh-rsa ",
|
||||
"AAAAB3NzaC1yc2EAAAABIwAAAIEA1on8gxCGJJWSRT4uOrR13mUaUk0hRf4RzxSZ1zRb",
|
||||
"YYFw8pfGesIFoEuVth4HKyF8k1y4mRUnYHP1XNMNMJl1JcEArC2asV8sHf6zSPVffozZ",
|
||||
"5TT4SfsUu/iKy9lUcCfXzwre4WWZSXXcPff+EHtWshahu3WzBdnGxm5Xoi89zcE="
|
||||
))
|
||||
"5TT4SfsUu/iKy9lUcCfXzwre4WWZSXXcPff+EHtWshahu3WzBdnGxm5Xoi89zcE=",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class HostingPackageAwareTestMixin(object):
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def _setup_hosting_package(self, customer):
|
||||
template = HostingPackageTemplate.objects.create(
|
||||
name='testpackagetemplate', mailboxcount=10, diskspace=1,
|
||||
diskspace_unit=0)
|
||||
name="testpackagetemplate", mailboxcount=10, diskspace=1, diskspace_unit=0
|
||||
)
|
||||
package = CustomerHostingPackage.objects.create_from_template(
|
||||
customer, template, 'testpackage')
|
||||
with patch('hostingpackages.models.settings') as hmsettings:
|
||||
customer, template, "testpackage"
|
||||
)
|
||||
with patch("hostingpackages.models.settings") as hmsettings:
|
||||
hmsettings.OSUSER_DEFAULT_GROUPS = []
|
||||
package.save()
|
||||
return package
|
||||
|
||||
|
||||
class AddSshPublicKeyTest(HostingPackageAwareTestMixin, TestCase):
|
||||
|
||||
def setUp(self):
|
||||
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)
|
||||
|
||||
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):
|
||||
response = self.client.get(self._get_url())
|
||||
|
@ -73,77 +66,75 @@ class AddSshPublicKeyTest(HostingPackageAwareTestMixin, TestCase):
|
|||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_get_other_regular_user(self):
|
||||
User.objects.create_user(
|
||||
'test2', password=TEST_PASSWORD)
|
||||
self.client.login(username='test2', password=TEST_PASSWORD)
|
||||
User.objects.create_user("test2", password=TEST_PASSWORD)
|
||||
self.client.login(username="test2", password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url())
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_get_staff_user(self):
|
||||
User.objects.create_superuser(
|
||||
'admin', email=TEST_EMAIL, password=TEST_PASSWORD)
|
||||
self.client.login(username='admin', password=TEST_PASSWORD)
|
||||
User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
|
||||
self.client.login(username="admin", password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_get_template(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
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):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
view = AddSshPublicKey(
|
||||
request=MagicMock(), kwargs={'package': str(self.package.pk)})
|
||||
request=MagicMock(), kwargs={"package": str(self.package.pk)}
|
||||
)
|
||||
the_kwargs = view.get_form_kwargs()
|
||||
self.assertIn('hostingpackage', the_kwargs)
|
||||
self.assertEqual(the_kwargs['hostingpackage'], self.package)
|
||||
self.assertIn("hostingpackage", the_kwargs)
|
||||
self.assertEqual(the_kwargs["hostingpackage"], self.package)
|
||||
|
||||
def test_get_context_data(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url())
|
||||
self.assertIn('customer', response.context)
|
||||
self.assertEqual(response.context['customer'], self.customer)
|
||||
self.assertIn('osuser', response.context)
|
||||
self.assertEqual(
|
||||
response.context['osuser'], self.package.osuser.username)
|
||||
self.assertIn("customer", response.context)
|
||||
self.assertEqual(response.context["customer"], self.customer)
|
||||
self.assertIn("osuser", response.context)
|
||||
self.assertEqual(response.context["osuser"], self.package.osuser.username)
|
||||
|
||||
def test_form_valid_redirect(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.post(
|
||||
self._get_url(),
|
||||
data={'publickeytext': EXAMPLE_KEY})
|
||||
self._get_url(), data={"publickeytext": EXAMPLE_KEY}
|
||||
)
|
||||
self.assertRedirects(response, self.package.get_absolute_url())
|
||||
|
||||
def test_form_valid_message(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.post(
|
||||
self._get_url(), follow=True,
|
||||
data={'publickeytext': EXAMPLE_KEY})
|
||||
messages = list(response.context['messages'])
|
||||
self._get_url(), follow=True, data={"publickeytext": EXAMPLE_KEY}
|
||||
)
|
||||
messages = list(response.context["messages"])
|
||||
self.assertEqual(len(messages), 1)
|
||||
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
|
||||
), str(messages[0]))
|
||||
),
|
||||
str(messages[0]),
|
||||
)
|
||||
|
||||
|
||||
class DeleteSshPublicKeyTest(HostingPackageAwareTestMixin, TestCase):
|
||||
|
||||
def setUp(self):
|
||||
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.sshkey = SshPublicKey.objects.create(
|
||||
user=self.package.osuser, algorithm='good', data='key',
|
||||
comment='comment')
|
||||
user=self.package.osuser, algorithm="good", data="key", comment="comment"
|
||||
)
|
||||
|
||||
def _get_url(self):
|
||||
return reverse(
|
||||
'delete_ssh_key', kwargs={
|
||||
'package': self.package.id,
|
||||
'pk': self.sshkey.id
|
||||
})
|
||||
"delete_ssh_key", kwargs={"package": self.package.id, "pk": self.sshkey.id}
|
||||
)
|
||||
|
||||
def test_get_anonymous(self):
|
||||
response = self.client.get(self._get_url())
|
||||
|
@ -155,71 +146,63 @@ class DeleteSshPublicKeyTest(HostingPackageAwareTestMixin, TestCase):
|
|||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_get_other_regular_user(self):
|
||||
User.objects.create_user(
|
||||
'test2', password=TEST_PASSWORD)
|
||||
self.client.login(username='test2', password=TEST_PASSWORD)
|
||||
User.objects.create_user("test2", password=TEST_PASSWORD)
|
||||
self.client.login(username="test2", password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url())
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_get_staff_user(self):
|
||||
User.objects.create_superuser(
|
||||
'admin', email=TEST_EMAIL, password=TEST_PASSWORD)
|
||||
self.client.login(username='admin', password=TEST_PASSWORD)
|
||||
User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
|
||||
self.client.login(username="admin", password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_get_template(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url())
|
||||
self.assertTemplateUsed(
|
||||
response, 'osusers/sshpublickey_confirm_delete.html')
|
||||
self.assertTemplateUsed(response, "osusers/sshpublickey_confirm_delete.html")
|
||||
|
||||
def test_get_queryset(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
view = DeleteSshPublicKey(
|
||||
request=MagicMock(), kwargs={
|
||||
'package': str(self.package.pk),
|
||||
'pk': str(self.sshkey.pk)
|
||||
})
|
||||
request=MagicMock(),
|
||||
kwargs={"package": str(self.package.pk), "pk": str(self.sshkey.pk)},
|
||||
)
|
||||
queryset = view.get_queryset()
|
||||
self.assertQuerysetEqual(queryset, [repr(self.sshkey)])
|
||||
|
||||
def test_get_context_data(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
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.assertEqual(response.context['hostingpackage'], self.package)
|
||||
self.assertEqual(response.context['customer'], self.customer)
|
||||
self.assertEqual(
|
||||
response.context['osuser'], self.package.osuser.username)
|
||||
self.assertEqual(response.context["hostingpackage"], self.package)
|
||||
self.assertEqual(response.context["customer"], self.customer)
|
||||
self.assertEqual(response.context["osuser"], self.package.osuser.username)
|
||||
|
||||
def test_get_success_url(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.post(
|
||||
self._get_url(),
|
||||
data={'comment': 'new comment'})
|
||||
self.assertRedirects(response, reverse('list_ssh_keys', kwargs={
|
||||
'package': self.package.id}))
|
||||
response = self.client.post(self._get_url(), data={"comment": "new comment"})
|
||||
self.assertRedirects(
|
||||
response, reverse("list_ssh_keys", kwargs={"package": self.package.id})
|
||||
)
|
||||
|
||||
|
||||
class EditSshPublicKeyCommentTest(
|
||||
HostingPackageAwareTestMixin, TransactionTestCase):
|
||||
|
||||
class EditSshPublicKeyCommentTest(HostingPackageAwareTestMixin, TransactionTestCase):
|
||||
def setUp(self):
|
||||
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.sshkey = SshPublicKey.objects.create(
|
||||
user=self.package.osuser, algorithm='good', data='key',
|
||||
comment='comment')
|
||||
user=self.package.osuser, algorithm="good", data="key", comment="comment"
|
||||
)
|
||||
|
||||
def _get_url(self):
|
||||
return reverse(
|
||||
'edit_ssh_key_comment', kwargs={
|
||||
'package': self.package.id,
|
||||
'pk': self.sshkey.id
|
||||
})
|
||||
"edit_ssh_key_comment",
|
||||
kwargs={"package": self.package.id, "pk": self.sshkey.id},
|
||||
)
|
||||
|
||||
def test_get_anonymous(self):
|
||||
response = self.client.get(self._get_url())
|
||||
|
@ -231,74 +214,67 @@ class EditSshPublicKeyCommentTest(
|
|||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_get_other_regular_user(self):
|
||||
User.objects.create_user(
|
||||
'test2', password=TEST_PASSWORD)
|
||||
self.client.login(username='test2', password=TEST_PASSWORD)
|
||||
User.objects.create_user("test2", password=TEST_PASSWORD)
|
||||
self.client.login(username="test2", password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url())
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_get_staff_user(self):
|
||||
User.objects.create_superuser(
|
||||
'admin', email=TEST_EMAIL, password=TEST_PASSWORD)
|
||||
self.client.login(username='admin', password=TEST_PASSWORD)
|
||||
User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
|
||||
self.client.login(username="admin", password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_get_template(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url())
|
||||
self.assertTemplateUsed(
|
||||
response, 'osusers/sshpublickey_edit_comment.html')
|
||||
self.assertTemplateUsed(response, "osusers/sshpublickey_edit_comment.html")
|
||||
|
||||
def test_get_queryset(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
view = EditSshPublicKeyComment(
|
||||
request=MagicMock(), kwargs={
|
||||
'package': str(self.package.pk),
|
||||
'pk': str(self.sshkey.pk)
|
||||
})
|
||||
request=MagicMock(),
|
||||
kwargs={"package": str(self.package.pk), "pk": str(self.sshkey.pk)},
|
||||
)
|
||||
queryset = view.get_queryset()
|
||||
self.assertQuerysetEqual(queryset, [repr(self.sshkey)])
|
||||
|
||||
def test_get_form_kwargs(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
view = EditSshPublicKeyComment(
|
||||
request=MagicMock(), kwargs={
|
||||
'package': str(self.package.pk),
|
||||
'pk': str(self.sshkey.pk)
|
||||
})
|
||||
request=MagicMock(),
|
||||
kwargs={"package": str(self.package.pk), "pk": str(self.sshkey.pk)},
|
||||
)
|
||||
the_kwargs = view.get_form_kwargs()
|
||||
self.assertIn('hostingpackage', the_kwargs)
|
||||
self.assertEqual(the_kwargs['hostingpackage'], self.package)
|
||||
self.assertIn("hostingpackage", the_kwargs)
|
||||
self.assertEqual(the_kwargs["hostingpackage"], self.package)
|
||||
|
||||
def test_get_context_data(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
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.assertEqual(response.context['hostingpackage'], self.package)
|
||||
self.assertEqual(response.context['customer'], self.customer)
|
||||
self.assertEqual(
|
||||
response.context['osuser'], self.package.osuser.username)
|
||||
self.assertEqual(response.context["hostingpackage"], self.package)
|
||||
self.assertEqual(response.context["customer"], self.customer)
|
||||
self.assertEqual(response.context["osuser"], self.package.osuser.username)
|
||||
|
||||
def test_get_success_url(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.post(
|
||||
self._get_url(),
|
||||
data={'comment': 'new comment'})
|
||||
self.assertRedirects(response, reverse('list_ssh_keys', kwargs={
|
||||
'package': self.package.id}))
|
||||
response = self.client.post(self._get_url(), data={"comment": "new comment"})
|
||||
self.assertRedirects(
|
||||
response, reverse("list_ssh_keys", kwargs={"package": self.package.id})
|
||||
)
|
||||
|
||||
|
||||
class ListSshPublicKeysTest(HostingPackageAwareTestMixin, TestCase):
|
||||
|
||||
def setUp(self):
|
||||
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)
|
||||
|
||||
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):
|
||||
response = self.client.get(self._get_url())
|
||||
|
@ -310,45 +286,43 @@ class ListSshPublicKeysTest(HostingPackageAwareTestMixin, TestCase):
|
|||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_get_other_regular_user(self):
|
||||
User.objects.create_user(
|
||||
'test2', password=TEST_PASSWORD)
|
||||
self.client.login(username='test2', password=TEST_PASSWORD)
|
||||
User.objects.create_user("test2", password=TEST_PASSWORD)
|
||||
self.client.login(username="test2", password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url())
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_get_staff_user(self):
|
||||
User.objects.create_superuser(
|
||||
'admin', email=TEST_EMAIL, password=TEST_PASSWORD)
|
||||
self.client.login(username='admin', password=TEST_PASSWORD)
|
||||
User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
|
||||
self.client.login(username="admin", password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_get_template(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
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):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
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.assertEqual(response.context['hostingpackage'], self.package)
|
||||
self.assertEqual(response.context['customer'], self.customer)
|
||||
self.assertEqual(
|
||||
response.context['osuser'], self.package.osuser.username)
|
||||
self.assertEqual(response.context["hostingpackage"], self.package)
|
||||
self.assertEqual(response.context["customer"], self.customer)
|
||||
self.assertEqual(response.context["osuser"], self.package.osuser.username)
|
||||
|
||||
|
||||
class SetOsUserPasswordTest(HostingPackageAwareTestMixin, TestCase):
|
||||
|
||||
def setUp(self):
|
||||
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)
|
||||
|
||||
def _get_url(self):
|
||||
return reverse('set_osuser_password', kwargs={
|
||||
'slug': self.package.osuser.username})
|
||||
return reverse(
|
||||
"set_osuser_password", kwargs={"slug": self.package.osuser.username}
|
||||
)
|
||||
|
||||
def test_get_anonymous(self):
|
||||
response = self.client.get(self._get_url())
|
||||
|
@ -360,45 +334,48 @@ class SetOsUserPasswordTest(HostingPackageAwareTestMixin, TestCase):
|
|||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_get_other_regular_user(self):
|
||||
User.objects.create_user(
|
||||
'test2', password=TEST_PASSWORD)
|
||||
self.client.login(username='test2', password=TEST_PASSWORD)
|
||||
User.objects.create_user("test2", password=TEST_PASSWORD)
|
||||
self.client.login(username="test2", password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url())
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_get_staff_user(self):
|
||||
User.objects.create_superuser(
|
||||
'admin', email=TEST_EMAIL, password=TEST_PASSWORD)
|
||||
self.client.login(username='admin', password=TEST_PASSWORD)
|
||||
User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
|
||||
self.client.login(username="admin", password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_get_template(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
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):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url())
|
||||
self.assertIn('customer', response.context)
|
||||
self.assertEqual(response.context['customer'], self.customer)
|
||||
self.assertIn("customer", response.context)
|
||||
self.assertEqual(response.context["customer"], self.customer)
|
||||
|
||||
def test_form_valid_redirect(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.post(
|
||||
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())
|
||||
|
||||
def test_form_valid_message(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.post(
|
||||
self._get_url(), follow=True,
|
||||
data={'password1': TEST_PASSWORD, 'password2': TEST_PASSWORD})
|
||||
messages = list(response.context['messages'])
|
||||
self._get_url(),
|
||||
follow=True,
|
||||
data={"password1": TEST_PASSWORD, "password2": TEST_PASSWORD},
|
||||
)
|
||||
messages = list(response.context["messages"])
|
||||
self.assertEqual(len(messages), 1)
|
||||
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
|
||||
), str(messages[0]))
|
||||
),
|
||||
str(messages[0]),
|
||||
)
|
||||
|
|
|
@ -4,39 +4,32 @@ This module provides tests for the
|
|||
command.
|
||||
|
||||
"""
|
||||
from __future__ import unicode_literals
|
||||
|
||||
try:
|
||||
from unittest.mock import patch, MagicMock
|
||||
except ImportError:
|
||||
from mock import patch, MagicMock
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from django.test import TestCase
|
||||
|
||||
from taskresults.management.commands.fetch_taskresults import Command
|
||||
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'
|
||||
TEST_TASK_NAME = 'test.task'
|
||||
TEST_TASK_RESULT = '4ll y0ur b453 4r3 b3l0ng t0 u5'
|
||||
|
||||
|
||||
@patch('taskresults.models.app.AsyncResult')
|
||||
@patch("taskresults.models.app.AsyncResult")
|
||||
class FetchTaskResultsCommandTest(TestCase):
|
||||
|
||||
def test_handle_unfinished(self, asyncresult):
|
||||
resultmock = MagicMock(task_id=TEST_TASK_UUID)
|
||||
sigmock = MagicMock()
|
||||
sigmock.apply_async.return_value = resultmock
|
||||
tr = TaskResult.objects.create_task_result(TEST_TASK_NAME, sigmock)
|
||||
self.assertFalse(tr.finished)
|
||||
self.assertEqual(tr.result, '')
|
||||
self.assertEqual(tr.state, '')
|
||||
self.assertEqual(tr.result, "")
|
||||
self.assertEqual(tr.state, "")
|
||||
|
||||
aresult = asyncresult.return_value
|
||||
aresult.state = 'PENDING'
|
||||
aresult.state = "PENDING"
|
||||
aresult.ready.return_value = False
|
||||
|
||||
Command().handle()
|
||||
|
@ -45,8 +38,8 @@ class FetchTaskResultsCommandTest(TestCase):
|
|||
self.assertTrue(asyncresult.called_with(TEST_TASK_UUID))
|
||||
self.assertTrue(aresult.ready.called_with())
|
||||
self.assertFalse(tr.finished)
|
||||
self.assertEqual(tr.result, '')
|
||||
self.assertEqual(tr.state, 'PENDING')
|
||||
self.assertEqual(tr.result, "")
|
||||
self.assertEqual(tr.state, "PENDING")
|
||||
|
||||
def test_handle_finished(self, asyncresult):
|
||||
resultmock = MagicMock(task_id=TEST_TASK_UUID)
|
||||
|
@ -54,11 +47,11 @@ class FetchTaskResultsCommandTest(TestCase):
|
|||
sigmock.apply_async.return_value = resultmock
|
||||
tr = TaskResult.objects.create_task_result(TEST_TASK_NAME, sigmock)
|
||||
self.assertFalse(tr.finished)
|
||||
self.assertEqual(tr.result, '')
|
||||
self.assertEqual(tr.state, '')
|
||||
self.assertEqual(tr.result, "")
|
||||
self.assertEqual(tr.state, "")
|
||||
|
||||
aresult = asyncresult.return_value
|
||||
aresult.state = 'SUCCESS'
|
||||
aresult.state = "SUCCESS"
|
||||
aresult.ready.return_value = True
|
||||
aresult.get.return_value = TEST_TASK_RESULT
|
||||
|
||||
|
@ -70,4 +63,4 @@ class FetchTaskResultsCommandTest(TestCase):
|
|||
self.assertTrue(aresult.get.called_with())
|
||||
self.assertTrue(tr.finished)
|
||||
self.assertEqual(tr.result, TEST_TASK_RESULT)
|
||||
self.assertEqual(tr.state, 'SUCCESS')
|
||||
self.assertEqual(tr.state, "SUCCESS")
|
||||
|
|
|
@ -2,25 +2,19 @@
|
|||
This module provides tests for :py:mod:`taskresults.models`.
|
||||
|
||||
"""
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
try:
|
||||
from unittest.mock import patch, MagicMock
|
||||
except ImportError:
|
||||
from mock import patch, MagicMock
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from django.test import TestCase
|
||||
|
||||
from taskresults.models import TaskResult
|
||||
|
||||
|
||||
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"
|
||||
TEST_TASK_NAME = "test.task"
|
||||
TEST_TASK_RESULT = "4ll y0ur b453 4r3 b3l0ng t0 u5"
|
||||
|
||||
|
||||
class TaskResultTest(TestCase):
|
||||
@patch('taskresults.models.app.AsyncResult')
|
||||
@patch("taskresults.models.app.AsyncResult")
|
||||
def test_update_taskstatus_unfinished(self, asyncresult):
|
||||
resultmock = MagicMock(task_id=TEST_TASK_UUID)
|
||||
sigmock = MagicMock()
|
||||
|
@ -28,13 +22,13 @@ class TaskResultTest(TestCase):
|
|||
tr = TaskResult.objects.create_task_result(TEST_TASK_NAME, sigmock)
|
||||
self.assertFalse(tr.finished)
|
||||
mymock = asyncresult.return_value
|
||||
mymock.state = 'PENDING'
|
||||
mymock.state = "PENDING"
|
||||
mymock.ready.return_value = False
|
||||
tr.fetch_result()
|
||||
mymock.get.assert_not_called()
|
||||
self.assertFalse(tr.finished)
|
||||
|
||||
@patch('taskresults.models.app.AsyncResult')
|
||||
@patch("taskresults.models.app.AsyncResult")
|
||||
def test_update_taskstatus_finished(self, asyncresult):
|
||||
resultmock = MagicMock(task_id=TEST_TASK_UUID)
|
||||
sigmock = MagicMock()
|
||||
|
@ -43,7 +37,7 @@ class TaskResultTest(TestCase):
|
|||
tr = TaskResult.objects.create_task_result(TEST_TASK_NAME, sigmock)
|
||||
self.assertFalse(tr.finished)
|
||||
aresult = asyncresult.return_value
|
||||
aresult.state = 'SUCCESS'
|
||||
aresult.state = "SUCCESS"
|
||||
aresult.ready.return_value = True
|
||||
aresult.get.return_value = TEST_TASK_RESULT
|
||||
tr.fetch_result()
|
||||
|
@ -61,11 +55,15 @@ class TaskResultTest(TestCase):
|
|||
sigmock = MagicMock()
|
||||
sigmock.apply_async.return_value = resultmock
|
||||
tr = TaskResult.objects.create_task_result(TEST_TASK_NAME, sigmock)
|
||||
self.assertEqual(str(tr), "{name} ({taskid}): no".format(
|
||||
name=TEST_TASK_NAME, taskid=TEST_TASK_UUID))
|
||||
self.assertEqual(
|
||||
str(tr),
|
||||
"{name} ({taskid}): no".format(name=TEST_TASK_NAME, taskid=TEST_TASK_UUID),
|
||||
)
|
||||
tr.finished = True
|
||||
self.assertEqual(str(tr), "{name} ({taskid}): yes".format(
|
||||
name=TEST_TASK_NAME, taskid=TEST_TASK_UUID))
|
||||
self.assertEqual(
|
||||
str(tr),
|
||||
"{name} ({taskid}): yes".format(name=TEST_TASK_NAME, taskid=TEST_TASK_UUID),
|
||||
)
|
||||
|
||||
|
||||
TEST_RESULT = MagicMock()
|
||||
|
|
|
@ -2,35 +2,33 @@
|
|||
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.test import TestCase
|
||||
|
||||
from userdbs.admin import (DatabaseUserAdmin, DatabaseUserCreationForm,
|
||||
UserDatabaseAdmin, UserDatabaseCreationForm)
|
||||
from userdbs.admin import (
|
||||
DatabaseUserAdmin,
|
||||
DatabaseUserCreationForm,
|
||||
UserDatabaseAdmin,
|
||||
UserDatabaseCreationForm,
|
||||
)
|
||||
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):
|
||||
|
||||
@patch('userdbs.admin.DatabaseUser.objects.create_database_user')
|
||||
@patch("userdbs.admin.DatabaseUser.objects.create_database_user")
|
||||
def test_save(self, create_database_user):
|
||||
create_database_user.return_value = Mock()
|
||||
form = DatabaseUserCreationForm()
|
||||
mockuser = Mock(name='osuser')
|
||||
form.cleaned_data = {
|
||||
'osuser': mockuser,
|
||||
'db_type': DB_TYPES.pgsql
|
||||
}
|
||||
mockuser = Mock(name="osuser")
|
||||
form.cleaned_data = {"osuser": mockuser, "db_type": DB_TYPES.pgsql}
|
||||
retval = form.save()
|
||||
self.assertTrue(create_database_user.called_with(
|
||||
osuser=mockuser, db_type=DB_TYPES.pgsql, commit=True))
|
||||
self.assertTrue(
|
||||
create_database_user.called_with(
|
||||
osuser=mockuser, db_type=DB_TYPES.pgsql, commit=True
|
||||
)
|
||||
)
|
||||
self.assertEqual(retval, create_database_user.return_value)
|
||||
|
||||
def test_save_m2m_returns_none(self):
|
||||
|
@ -39,16 +37,14 @@ class DatabaseUserCreationFormTest(TestCase):
|
|||
|
||||
|
||||
class UserDatabaseCreationFormTest(TestCase):
|
||||
|
||||
@patch('userdbs.admin.UserDatabase.objects.create_userdatabase')
|
||||
@patch("userdbs.admin.UserDatabase.objects.create_userdatabase")
|
||||
def test_save(self, create_userdatabase):
|
||||
create_userdatabase.return_value = Mock()
|
||||
form = UserDatabaseCreationForm()
|
||||
mockuser = Mock(name='mockuser')
|
||||
form.cleaned_data = {'db_user': mockuser}
|
||||
mockuser = Mock(name="mockuser")
|
||||
form.cleaned_data = {"db_user": mockuser}
|
||||
retval = form.save()
|
||||
self.assertTrue(create_userdatabase.called_with(
|
||||
db_user=mockuser, commit=True))
|
||||
self.assertTrue(create_userdatabase.called_with(db_user=mockuser, commit=True))
|
||||
self.assertEqual(retval, create_userdatabase.return_value)
|
||||
|
||||
def test_save_m2m_returns_none(self):
|
||||
|
@ -57,116 +53,96 @@ class UserDatabaseCreationFormTest(TestCase):
|
|||
|
||||
|
||||
class DatabaseUserAdminTest(TestCase):
|
||||
|
||||
def setUp(self):
|
||||
site = AdminSite()
|
||||
self.dbuadmin = DatabaseUserAdmin(DatabaseUser, site)
|
||||
super(DatabaseUserAdminTest, self).setUp()
|
||||
|
||||
def test_get_form_with_instance(self):
|
||||
form = self.dbuadmin.get_form(
|
||||
Mock(name='request'), obj=Mock(name='dbuser'))
|
||||
self.assertEqual(
|
||||
form.Meta.fields,
|
||||
['osuser', 'name', 'db_type']
|
||||
)
|
||||
form = self.dbuadmin.get_form(Mock(name="request"), obj=Mock(name="dbuser"))
|
||||
self.assertEqual(form.Meta.fields, ["osuser", "name", "db_type"])
|
||||
|
||||
def test_get_form_without_instance(self):
|
||||
form = self.dbuadmin.get_form(Mock(name='request'))
|
||||
self.assertEqual(
|
||||
form.Meta.fields,
|
||||
['osuser', 'db_type']
|
||||
)
|
||||
form = self.dbuadmin.get_form(Mock(name="request"))
|
||||
self.assertEqual(form.Meta.fields, ["osuser", "db_type"])
|
||||
|
||||
def test_get_readonly_fields_with_instance(self):
|
||||
fields = self.dbuadmin.get_readonly_fields(
|
||||
Mock(name='request'), obj=Mock(name='dbuser'))
|
||||
self.assertEqual(
|
||||
fields, ['osuser', 'name', 'db_type'])
|
||||
Mock(name="request"), obj=Mock(name="dbuser")
|
||||
)
|
||||
self.assertEqual(fields, ["osuser", "name", "db_type"])
|
||||
|
||||
def test_get_readonly_fields_without_instance(self):
|
||||
fields = self.dbuadmin.get_readonly_fields(
|
||||
Mock(name='request'))
|
||||
fields = self.dbuadmin.get_readonly_fields(Mock(name="request"))
|
||||
self.assertEqual(fields, [])
|
||||
|
||||
def test_save_model_change(self):
|
||||
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())
|
||||
|
||||
def test_save_model_no_change(self):
|
||||
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())
|
||||
|
||||
def test_perform_delete_selected(self):
|
||||
usermock = Mock()
|
||||
selected = Mock()
|
||||
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(usermock.delete.called_with())
|
||||
|
||||
def test_get_actions(self):
|
||||
requestmock = MagicMock(name='request')
|
||||
self.assertNotIn(
|
||||
'delete_selected',
|
||||
self.dbuadmin.get_actions(requestmock))
|
||||
self.assertIn(
|
||||
'perform_delete_selected',
|
||||
self.dbuadmin.get_actions(requestmock))
|
||||
requestmock = MagicMock(name="request")
|
||||
self.assertNotIn("delete_selected", self.dbuadmin.get_actions(requestmock))
|
||||
self.assertIn("perform_delete_selected", self.dbuadmin.get_actions(requestmock))
|
||||
|
||||
|
||||
class UserDatabaseAdminTest(TestCase):
|
||||
|
||||
def setUp(self):
|
||||
site = AdminSite()
|
||||
self.udbadmin = UserDatabaseAdmin(UserDatabase, site)
|
||||
super(UserDatabaseAdminTest, self).setUp()
|
||||
|
||||
def test_get_form_with_instance(self):
|
||||
form = self.udbadmin.get_form(
|
||||
Mock(name='request'), obj=Mock(name='userdb'))
|
||||
self.assertEqual(form.Meta.fields, ['db_name', 'db_user'])
|
||||
form = self.udbadmin.get_form(Mock(name="request"), obj=Mock(name="userdb"))
|
||||
self.assertEqual(form.Meta.fields, ["db_name", "db_user"])
|
||||
|
||||
def test_get_form_without_instance(self):
|
||||
form = self.udbadmin.get_form(Mock(name='request'))
|
||||
self.assertEqual(form.Meta.fields, ['db_user'])
|
||||
form = self.udbadmin.get_form(Mock(name="request"))
|
||||
self.assertEqual(form.Meta.fields, ["db_user"])
|
||||
|
||||
def test_get_readonly_fields_with_instance(self):
|
||||
fields = self.udbadmin.get_readonly_fields(
|
||||
Mock(name='request'), obj=Mock(name='userdb'))
|
||||
self.assertEqual(
|
||||
fields, ['db_name', 'db_user'])
|
||||
Mock(name="request"), obj=Mock(name="userdb")
|
||||
)
|
||||
self.assertEqual(fields, ["db_name", "db_user"])
|
||||
|
||||
def test_get_readonly_fields_without_instance(self):
|
||||
fields = self.udbadmin.get_readonly_fields(
|
||||
Mock(name='request'))
|
||||
fields = self.udbadmin.get_readonly_fields(Mock(name="request"))
|
||||
self.assertEqual(fields, [])
|
||||
|
||||
def test_save_model_change(self):
|
||||
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())
|
||||
|
||||
def test_save_model_no_change(self):
|
||||
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())
|
||||
|
||||
def test_perform_delete_selected(self):
|
||||
userdbmock = Mock()
|
||||
selected = Mock()
|
||||
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(userdbmock.delete.called_with())
|
||||
|
||||
def test_get_actions(self):
|
||||
requestmock = MagicMock(name='request')
|
||||
self.assertNotIn(
|
||||
'delete_selected',
|
||||
self.udbadmin.get_actions(requestmock))
|
||||
self.assertIn(
|
||||
'perform_delete_selected',
|
||||
self.udbadmin.get_actions(requestmock))
|
||||
requestmock = MagicMock(name="request")
|
||||
self.assertNotIn("delete_selected", self.udbadmin.get_actions(requestmock))
|
||||
self.assertIn("perform_delete_selected", self.udbadmin.get_actions(requestmock))
|
||||
|
|
|
@ -2,20 +2,15 @@
|
|||
This module provides tests for :py:mod:`userdbs.forms`.
|
||||
|
||||
"""
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django import forms
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.urlresolvers import reverse
|
||||
from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from userdbs.forms import AddUserDatabaseForm, ChangeDatabaseUserPasswordForm
|
||||
from userdbs.models import DB_TYPES
|
||||
|
||||
try:
|
||||
from unittest.mock import MagicMock, Mock, patch
|
||||
except ImportError:
|
||||
from mock import MagicMock, Mock, patch
|
||||
from unittest.mock import MagicMock, Mock, patch
|
||||
|
||||
|
||||
Customer = get_user_model()
|
||||
|
@ -33,66 +28,68 @@ class AddUserDatabaseFormTest(TestCase):
|
|||
def test_constructor_needs_hostingpackage(self):
|
||||
with self.assertRaises(KeyError) as ke:
|
||||
AddUserDatabaseForm(instance=Mock())
|
||||
self.assertEqual(ke.exception.args[0], 'hostingpackage')
|
||||
self.assertEqual(ke.exception.args[0], "hostingpackage")
|
||||
|
||||
def test_constructor_needs_dbtypes(self):
|
||||
with self.assertRaises(KeyError) as ke:
|
||||
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):
|
||||
self._setup_hostingpackage()
|
||||
dbtypes = [(DB_TYPES.pgsql, DB_TYPES[DB_TYPES.pgsql])]
|
||||
form = AddUserDatabaseForm(
|
||||
instance=MagicMock(), hostingpackage=self.hostingpackage,
|
||||
dbtypes=dbtypes)
|
||||
self.assertIn('db_type', form.fields)
|
||||
self.assertEqual(form.fields['db_type'].choices, dbtypes)
|
||||
self.assertTrue(isinstance(
|
||||
form.fields['db_type'].widget,
|
||||
forms.HiddenInput))
|
||||
self.assertTrue(hasattr(form, 'helper'))
|
||||
self.assertEqual(form.helper.form_action, reverse(
|
||||
'add_userdatabase', kwargs={'package': self.hostingpackage.id}))
|
||||
self.assertEqual(form.helper.inputs[0].name, 'submit')
|
||||
instance=MagicMock(), hostingpackage=self.hostingpackage, dbtypes=dbtypes
|
||||
)
|
||||
self.assertIn("db_type", form.fields)
|
||||
self.assertEqual(form.fields["db_type"].choices, dbtypes)
|
||||
self.assertTrue(isinstance(form.fields["db_type"].widget, forms.HiddenInput))
|
||||
self.assertTrue(hasattr(form, "helper"))
|
||||
self.assertEqual(
|
||||
form.helper.form_action,
|
||||
reverse("add_userdatabase", kwargs={"package": self.hostingpackage.id}),
|
||||
)
|
||||
self.assertEqual(form.helper.inputs[0].name, "submit")
|
||||
|
||||
def test_constructor_multiple_dbtypes(self):
|
||||
self._setup_hostingpackage()
|
||||
dbtypes = [
|
||||
(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(
|
||||
instance=MagicMock(), hostingpackage=self.hostingpackage,
|
||||
dbtypes=dbtypes)
|
||||
self.assertIn('db_type', form.fields)
|
||||
self.assertEqual(form.fields['db_type'].choices, dbtypes)
|
||||
self.assertTrue(isinstance(
|
||||
form.fields['db_type'].widget,
|
||||
forms.RadioSelect))
|
||||
self.assertTrue(hasattr(form, 'helper'))
|
||||
self.assertEqual(form.helper.form_action, reverse(
|
||||
'add_userdatabase', kwargs={'package': self.hostingpackage.id}))
|
||||
self.assertEqual(form.helper.inputs[0].name, 'submit')
|
||||
instance=MagicMock(), hostingpackage=self.hostingpackage, dbtypes=dbtypes
|
||||
)
|
||||
self.assertIn("db_type", form.fields)
|
||||
self.assertEqual(form.fields["db_type"].choices, dbtypes)
|
||||
self.assertTrue(isinstance(form.fields["db_type"].widget, forms.RadioSelect))
|
||||
self.assertTrue(hasattr(form, "helper"))
|
||||
self.assertEqual(
|
||||
form.helper.form_action,
|
||||
reverse("add_userdatabase", kwargs={"package": self.hostingpackage.id}),
|
||||
)
|
||||
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):
|
||||
self._setup_hostingpackage()
|
||||
dbtypes = [
|
||||
(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(
|
||||
instance=MagicMock(), hostingpackage=self.hostingpackage,
|
||||
dbtypes=dbtypes)
|
||||
form.cleaned_data = {
|
||||
'db_type': DB_TYPES.pgsql,
|
||||
'password1': 'secret',
|
||||
}
|
||||
instance=MagicMock(), hostingpackage=self.hostingpackage, dbtypes=dbtypes
|
||||
)
|
||||
form.cleaned_data = {"db_type": DB_TYPES.pgsql, "password1": "secret"}
|
||||
form.save()
|
||||
self.assertTrue(create_userdatabase_with_user.called_with(
|
||||
DB_TYPES.pgsql, self.hostingpackage.osuser,
|
||||
password='secret', commit=True))
|
||||
self.assertTrue(
|
||||
create_userdatabase_with_user.called_with(
|
||||
DB_TYPES.pgsql,
|
||||
self.hostingpackage.osuser,
|
||||
password="secret",
|
||||
commit=True,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class ChangeDatabaseUserPasswordFormTest(TestCase):
|
||||
|
@ -107,29 +104,31 @@ class ChangeDatabaseUserPasswordFormTest(TestCase):
|
|||
def test_constructor_needs_hostingpackage(self):
|
||||
with self.assertRaises(KeyError) as ke:
|
||||
ChangeDatabaseUserPasswordForm(instance=Mock())
|
||||
self.assertEqual(ke.exception.args[0], 'hostingpackage')
|
||||
self.assertEqual(ke.exception.args[0], "hostingpackage")
|
||||
|
||||
def test_constructor(self):
|
||||
self._setup_hostingpackage()
|
||||
instance = MagicMock()
|
||||
instance.name = 'test'
|
||||
instance.name = "test"
|
||||
form = ChangeDatabaseUserPasswordForm(
|
||||
instance=instance, hostingpackage=self.hostingpackage)
|
||||
self.assertIn('password1', form.fields)
|
||||
self.assertIn('password2', form.fields)
|
||||
self.assertTrue(hasattr(form, 'helper'))
|
||||
self.assertEqual(form.helper.form_action, reverse(
|
||||
'change_dbuser_password', kwargs={
|
||||
'slug': 'test', 'package': 42
|
||||
}))
|
||||
self.assertEqual(form.helper.inputs[0].name, 'submit')
|
||||
instance=instance, hostingpackage=self.hostingpackage
|
||||
)
|
||||
self.assertIn("password1", form.fields)
|
||||
self.assertIn("password2", form.fields)
|
||||
self.assertTrue(hasattr(form, "helper"))
|
||||
self.assertEqual(
|
||||
form.helper.form_action,
|
||||
reverse("change_dbuser_password", kwargs={"slug": "test", "package": 42}),
|
||||
)
|
||||
self.assertEqual(form.helper.inputs[0].name, "submit")
|
||||
|
||||
def test_save(self):
|
||||
instance = MagicMock()
|
||||
instance.name = 'test'
|
||||
instance.name = "test"
|
||||
self._setup_hostingpackage()
|
||||
form = ChangeDatabaseUserPasswordForm(
|
||||
instance=instance, hostingpackage=self.hostingpackage)
|
||||
form.cleaned_data = {'password1': 'secret'}
|
||||
instance=instance, hostingpackage=self.hostingpackage
|
||||
)
|
||||
form.cleaned_data = {"password1": "secret"}
|
||||
form.save()
|
||||
self.assertTrue(instance.set_password.called_with('secret'))
|
||||
self.assertTrue(instance.set_password.called_with("secret"))
|
||||
|
|
|
@ -2,8 +2,6 @@
|
|||
This module provides tests for :py:mod:`userdbs.models`.
|
||||
|
||||
"""
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import TestCase
|
||||
from django.test.utils import override_settings
|
||||
|
@ -16,9 +14,7 @@ Customer = get_user_model()
|
|||
|
||||
|
||||
@override_settings(
|
||||
CELERY_ALWAYS_EAGER=True,
|
||||
CELERY_CACHE_BACKEND='memory',
|
||||
BROKER_BACKEND='memory'
|
||||
CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
|
||||
)
|
||||
class TestCaseWithCeleryTasks(TestCase):
|
||||
pass
|
||||
|
@ -29,93 +25,85 @@ class DatabaseUserManagerTest(TestCaseWithCeleryTasks):
|
|||
Test case for :py:class:`userdbs.models.DatabaseUserManager`.
|
||||
|
||||
"""
|
||||
|
||||
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)
|
||||
TaskResult.objects.all().delete()
|
||||
|
||||
def test_create_database_user_with_name(self):
|
||||
dbu = DatabaseUser.objects.create_database_user(
|
||||
self.osuser, DB_TYPES.pgsql, 'testname', 'secret')
|
||||
self.assertEqual(dbu.name, 'testname')
|
||||
self.osuser, DB_TYPES.pgsql, "testname", "secret"
|
||||
)
|
||||
self.assertEqual(dbu.name, "testname")
|
||||
self.assertEqual(dbu.osuser, self.osuser)
|
||||
self.assertEqual(dbu.db_type, DB_TYPES.pgsql)
|
||||
taskres = TaskResult.objects.all()
|
||||
self.assertEqual(len(taskres), 1)
|
||||
self.assertEqual(taskres[0].creator, 'handle_dbuser_created')
|
||||
self.assertEqual(taskres[0].notes, 'pgsql user creation')
|
||||
self.assertEqual(taskres[0].creator, "handle_dbuser_created")
|
||||
self.assertEqual(taskres[0].notes, "pgsql user creation")
|
||||
|
||||
def test_create_database_user_with_name_no_commit(self):
|
||||
dbu = DatabaseUser.objects.create_database_user(
|
||||
self.osuser, DB_TYPES.pgsql, 'testname', 'secret', False)
|
||||
self.assertEqual(dbu.name, 'testname')
|
||||
self.osuser, DB_TYPES.pgsql, "testname", "secret", False
|
||||
)
|
||||
self.assertEqual(dbu.name, "testname")
|
||||
self.assertEqual(dbu.osuser, self.osuser)
|
||||
self.assertEqual(dbu.db_type, DB_TYPES.pgsql)
|
||||
self.assertFalse(TaskResult.objects.exists())
|
||||
|
||||
def test_create_database_user_generate_name(self):
|
||||
dbu = DatabaseUser.objects.create_database_user(
|
||||
self.osuser, DB_TYPES.pgsql)
|
||||
self.assertEqual(dbu.name, '{user}db01'.format(
|
||||
user=self.osuser.username))
|
||||
dbu = DatabaseUser.objects.create_database_user(self.osuser, DB_TYPES.pgsql)
|
||||
self.assertEqual(dbu.name, "{user}db01".format(user=self.osuser.username))
|
||||
self.assertEqual(dbu.osuser, self.osuser)
|
||||
self.assertEqual(dbu.db_type, DB_TYPES.pgsql)
|
||||
taskres = TaskResult.objects.all()
|
||||
self.assertEqual(len(taskres), 1)
|
||||
self.assertEqual(taskres[0].creator, 'handle_dbuser_created')
|
||||
self.assertEqual(taskres[0].notes, 'pgsql user creation')
|
||||
self.assertEqual(taskres[0].creator, "handle_dbuser_created")
|
||||
self.assertEqual(taskres[0].notes, "pgsql user creation")
|
||||
|
||||
def test_create_database_user_multiple_generate_name(self):
|
||||
dbu = DatabaseUser.objects.create_database_user(
|
||||
self.osuser, DB_TYPES.mysql)
|
||||
self.assertEqual(dbu.name, '{user}db01'.format(
|
||||
user=self.osuser.username))
|
||||
dbu = DatabaseUser.objects.create_database_user(self.osuser, DB_TYPES.mysql)
|
||||
self.assertEqual(dbu.name, "{user}db01".format(user=self.osuser.username))
|
||||
self.assertEqual(dbu.osuser, self.osuser)
|
||||
self.assertEqual(dbu.db_type, DB_TYPES.mysql)
|
||||
dbu = DatabaseUser.objects.create_database_user(
|
||||
self.osuser, DB_TYPES.mysql)
|
||||
self.assertEqual(dbu.name, '{user}db02'.format(
|
||||
user=self.osuser.username))
|
||||
dbu = DatabaseUser.objects.create_database_user(self.osuser, DB_TYPES.mysql)
|
||||
self.assertEqual(dbu.name, "{user}db02".format(user=self.osuser.username))
|
||||
self.assertEqual(dbu.osuser, self.osuser)
|
||||
self.assertEqual(dbu.db_type, DB_TYPES.mysql)
|
||||
taskres = TaskResult.objects.all()
|
||||
self.assertEqual(len(taskres), 2)
|
||||
self.assertEqual(taskres[0].creator, 'handle_dbuser_created')
|
||||
self.assertEqual(taskres[0].notes, 'mysql user creation')
|
||||
self.assertEqual(taskres[1].creator, 'handle_dbuser_created')
|
||||
self.assertEqual(taskres[1].notes, 'mysql user creation')
|
||||
self.assertEqual(taskres[0].creator, "handle_dbuser_created")
|
||||
self.assertEqual(taskres[0].notes, "mysql user creation")
|
||||
self.assertEqual(taskres[1].creator, "handle_dbuser_created")
|
||||
self.assertEqual(taskres[1].notes, "mysql user creation")
|
||||
|
||||
def test_create_database_user_multiple_gap_generate_name(self):
|
||||
dbu = DatabaseUser.objects.create_database_user(
|
||||
self.osuser, DB_TYPES.mysql)
|
||||
self.assertEqual(dbu.name, '{user}db01'.format(
|
||||
user=self.osuser.username))
|
||||
dbu = DatabaseUser.objects.create_database_user(self.osuser, DB_TYPES.mysql)
|
||||
self.assertEqual(dbu.name, "{user}db01".format(user=self.osuser.username))
|
||||
self.assertEqual(dbu.osuser, self.osuser)
|
||||
self.assertEqual(dbu.db_type, DB_TYPES.mysql)
|
||||
dbu = DatabaseUser.objects.create_database_user(
|
||||
self.osuser, DB_TYPES.mysql)
|
||||
self.assertEqual(dbu.name, '{user}db02'.format(
|
||||
user=self.osuser.username))
|
||||
dbu = DatabaseUser.objects.create_database_user(self.osuser, DB_TYPES.mysql)
|
||||
self.assertEqual(dbu.name, "{user}db02".format(user=self.osuser.username))
|
||||
self.assertEqual(dbu.osuser, self.osuser)
|
||||
self.assertEqual(dbu.db_type, DB_TYPES.mysql)
|
||||
DatabaseUser.objects.get(
|
||||
name='{user}db01'.format(user=self.osuser.username)).delete()
|
||||
dbu = DatabaseUser.objects.create_database_user(
|
||||
self.osuser, DB_TYPES.mysql)
|
||||
self.assertEqual(dbu.name, '{user}db01'.format(
|
||||
user=self.osuser.username))
|
||||
name="{user}db01".format(user=self.osuser.username)
|
||||
).delete()
|
||||
dbu = DatabaseUser.objects.create_database_user(self.osuser, DB_TYPES.mysql)
|
||||
self.assertEqual(dbu.name, "{user}db01".format(user=self.osuser.username))
|
||||
self.assertEqual(dbu.osuser, self.osuser)
|
||||
self.assertEqual(dbu.db_type, DB_TYPES.mysql)
|
||||
taskres = TaskResult.objects.all()
|
||||
self.assertEqual(len(taskres), 4)
|
||||
self.assertEqual(taskres[0].creator, 'handle_dbuser_created')
|
||||
self.assertEqual(taskres[0].notes, 'mysql user creation')
|
||||
self.assertEqual(taskres[1].creator, 'handle_dbuser_created')
|
||||
self.assertEqual(taskres[1].notes, 'mysql user creation')
|
||||
self.assertEqual(taskres[2].creator, 'handle_dbuser_deleted')
|
||||
self.assertEqual(taskres[2].notes, 'mysql user deletion')
|
||||
self.assertEqual(taskres[3].creator, 'handle_dbuser_created')
|
||||
self.assertEqual(taskres[3].notes, 'mysql user creation')
|
||||
self.assertEqual(taskres[0].creator, "handle_dbuser_created")
|
||||
self.assertEqual(taskres[0].notes, "mysql user creation")
|
||||
self.assertEqual(taskres[1].creator, "handle_dbuser_created")
|
||||
self.assertEqual(taskres[1].notes, "mysql user creation")
|
||||
self.assertEqual(taskres[2].creator, "handle_dbuser_deleted")
|
||||
self.assertEqual(taskres[2].notes, "mysql user deletion")
|
||||
self.assertEqual(taskres[3].creator, "handle_dbuser_created")
|
||||
self.assertEqual(taskres[3].notes, "mysql user creation")
|
||||
|
||||
|
||||
class DatabaseUserTest(TestCaseWithCeleryTasks):
|
||||
|
@ -123,41 +111,43 @@ class DatabaseUserTest(TestCaseWithCeleryTasks):
|
|||
Test case for :py:class:`userdbs.models.DatabaseUser`.
|
||||
|
||||
"""
|
||||
|
||||
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.dbu = DatabaseUser.objects.create_database_user(
|
||||
self.osuser, DB_TYPES.pgsql)
|
||||
self.osuser, DB_TYPES.pgsql
|
||||
)
|
||||
TaskResult.objects.all().delete()
|
||||
|
||||
def test___str__(self):
|
||||
self.assertEqual(
|
||||
str(self.dbu),
|
||||
'{user}db01 (PostgreSQL for {user})'.format(
|
||||
user=self.osuser.username))
|
||||
"{user}db01 (PostgreSQL for {user})".format(user=self.osuser.username),
|
||||
)
|
||||
|
||||
def test_set_password_pgsql(self):
|
||||
self.dbu.set_password('secret')
|
||||
self.dbu.set_password("secret")
|
||||
taskres = TaskResult.objects.all()
|
||||
self.assertEqual(len(taskres), 1)
|
||||
self.assertEqual(taskres[0].creator, 'handle_dbuser_password_set')
|
||||
self.assertEqual(taskres[0].notes, 'pgsql password change')
|
||||
self.assertEqual(taskres[0].creator, "handle_dbuser_password_set")
|
||||
self.assertEqual(taskres[0].notes, "pgsql password change")
|
||||
|
||||
def test_set_password_mysql(self):
|
||||
self.dbu.db_type = DB_TYPES.mysql
|
||||
self.dbu.save()
|
||||
self.dbu.set_password('secret')
|
||||
self.dbu.set_password("secret")
|
||||
taskres = TaskResult.objects.all()
|
||||
self.assertEqual(len(taskres), 1)
|
||||
self.assertEqual(taskres[0].creator, 'handle_dbuser_password_set')
|
||||
self.assertEqual(taskres[0].notes, 'mysql password change')
|
||||
self.assertEqual(taskres[0].creator, "handle_dbuser_password_set")
|
||||
self.assertEqual(taskres[0].notes, "mysql password change")
|
||||
|
||||
def test_delete_no_dbs(self):
|
||||
self.dbu.delete()
|
||||
taskres = TaskResult.objects.all()
|
||||
self.assertEqual(len(taskres), 1)
|
||||
self.assertEqual(taskres[0].creator, 'handle_dbuser_deleted')
|
||||
self.assertEqual(taskres[0].notes, 'pgsql user deletion')
|
||||
self.assertEqual(taskres[0].creator, "handle_dbuser_deleted")
|
||||
self.assertEqual(taskres[0].notes, "pgsql user deletion")
|
||||
|
||||
def test_delete_with_dbs(self):
|
||||
db = UserDatabase.objects.create_userdatabase(self.dbu)
|
||||
|
@ -166,12 +156,12 @@ class DatabaseUserTest(TestCaseWithCeleryTasks):
|
|||
self.assertFalse(UserDatabase.objects.filter(id=dbid).exists())
|
||||
taskres = TaskResult.objects.all()
|
||||
self.assertEqual(len(taskres), 3)
|
||||
self.assertEqual(taskres[0].creator, 'handle_userdb_created')
|
||||
self.assertEqual(taskres[0].notes, 'pgsql database creation')
|
||||
self.assertEqual(taskres[1].creator, 'handle_userdb_deleted')
|
||||
self.assertEqual(taskres[1].notes, 'pgsql database deletion')
|
||||
self.assertEqual(taskres[2].creator, 'handle_dbuser_deleted')
|
||||
self.assertEqual(taskres[2].notes, 'pgsql user deletion')
|
||||
self.assertEqual(taskres[0].creator, "handle_userdb_created")
|
||||
self.assertEqual(taskres[0].notes, "pgsql database creation")
|
||||
self.assertEqual(taskres[1].creator, "handle_userdb_deleted")
|
||||
self.assertEqual(taskres[1].notes, "pgsql database deletion")
|
||||
self.assertEqual(taskres[2].creator, "handle_dbuser_deleted")
|
||||
self.assertEqual(taskres[2].notes, "pgsql user deletion")
|
||||
|
||||
|
||||
class UserDatabaseManagerTest(TestCaseWithCeleryTasks):
|
||||
|
@ -179,50 +169,52 @@ class UserDatabaseManagerTest(TestCaseWithCeleryTasks):
|
|||
Test case for :py:class:`userdbs.models.UserDatabaseManager`.
|
||||
|
||||
"""
|
||||
|
||||
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)
|
||||
TaskResult.objects.all().delete()
|
||||
|
||||
def _create_database_user(self, dbtype):
|
||||
self.dbu = DatabaseUser.objects.create_database_user(
|
||||
self.osuser, dbtype)
|
||||
self.dbu = DatabaseUser.objects.create_database_user(self.osuser, dbtype)
|
||||
TaskResult.objects.all().delete()
|
||||
|
||||
def test_create_userdatabase_with_user_mysql(self):
|
||||
db = UserDatabase.objects.create_userdatabase_with_user(
|
||||
DB_TYPES.mysql, self.osuser)
|
||||
self.assertEqual(db.db_name, '{user}db01'.format(
|
||||
user=self.osuser.username))
|
||||
self.assertEqual(db.db_user.name, '{user}db01'.format(
|
||||
user=self.osuser.username))
|
||||
DB_TYPES.mysql, self.osuser
|
||||
)
|
||||
self.assertEqual(db.db_name, "{user}db01".format(user=self.osuser.username))
|
||||
self.assertEqual(
|
||||
db.db_user.name, "{user}db01".format(user=self.osuser.username)
|
||||
)
|
||||
taskres = TaskResult.objects.all()
|
||||
self.assertEqual(len(taskres), 2)
|
||||
self.assertEqual(taskres[0].creator, 'handle_dbuser_created')
|
||||
self.assertEqual(taskres[0].notes, 'mysql user creation')
|
||||
self.assertEqual(taskres[1].creator, 'handle_userdb_created')
|
||||
self.assertEqual(taskres[1].notes, 'mysql database creation')
|
||||
self.assertEqual(taskres[0].creator, "handle_dbuser_created")
|
||||
self.assertEqual(taskres[0].notes, "mysql user creation")
|
||||
self.assertEqual(taskres[1].creator, "handle_userdb_created")
|
||||
self.assertEqual(taskres[1].notes, "mysql database creation")
|
||||
|
||||
def test_create_userdatabase_with_user_pgsql(self):
|
||||
db = UserDatabase.objects.create_userdatabase_with_user(
|
||||
DB_TYPES.pgsql, self.osuser)
|
||||
self.assertEqual(db.db_name, '{user}db01'.format(
|
||||
user=self.osuser.username))
|
||||
self.assertEqual(db.db_user.name, '{user}db01'.format(
|
||||
user=self.osuser.username))
|
||||
DB_TYPES.pgsql, self.osuser
|
||||
)
|
||||
self.assertEqual(db.db_name, "{user}db01".format(user=self.osuser.username))
|
||||
self.assertEqual(
|
||||
db.db_user.name, "{user}db01".format(user=self.osuser.username)
|
||||
)
|
||||
taskres = TaskResult.objects.all()
|
||||
self.assertEqual(len(taskres), 2)
|
||||
self.assertEqual(taskres[0].creator, 'handle_dbuser_created')
|
||||
self.assertEqual(taskres[0].notes, 'pgsql user creation')
|
||||
self.assertEqual(taskres[1].creator, 'handle_userdb_created')
|
||||
self.assertEqual(taskres[1].notes, 'pgsql database creation')
|
||||
self.assertEqual(taskres[0].creator, "handle_dbuser_created")
|
||||
self.assertEqual(taskres[0].notes, "pgsql user creation")
|
||||
self.assertEqual(taskres[1].creator, "handle_userdb_created")
|
||||
self.assertEqual(taskres[1].notes, "pgsql database creation")
|
||||
|
||||
def test_create_userdatabase_given_name_no_new_write(self):
|
||||
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()
|
||||
self.assertEqual(len(taskres), 1)
|
||||
self.assertEqual(db.db_name, 'test')
|
||||
self.assertEqual(db.db_name, "test")
|
||||
TaskResult.objects.all().delete()
|
||||
db.save()
|
||||
taskres = TaskResult.objects.all()
|
||||
|
@ -230,11 +222,11 @@ class UserDatabaseManagerTest(TestCaseWithCeleryTasks):
|
|||
|
||||
def test_create_userdatabase_given_name(self):
|
||||
self._create_database_user(DB_TYPES.pgsql)
|
||||
db = UserDatabase.objects.create_userdatabase(self.dbu, db_name='test')
|
||||
self.assertEqual(db.db_name, 'test')
|
||||
db = UserDatabase.objects.create_userdatabase(self.dbu, db_name="test")
|
||||
self.assertEqual(db.db_name, "test")
|
||||
taskres = TaskResult.objects.all()
|
||||
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):
|
||||
self._create_database_user(DB_TYPES.pgsql)
|
||||
|
@ -252,19 +244,19 @@ class UserDatabaseManagerTest(TestCaseWithCeleryTasks):
|
|||
db = UserDatabase.objects.create_userdatabase(self.dbu)
|
||||
self.assertEqual(db.db_name, self.dbu.name)
|
||||
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):
|
||||
self._create_database_user(DB_TYPES.pgsql)
|
||||
db = UserDatabase.objects.create_userdatabase(self.dbu)
|
||||
self.assertEqual(db.db_name, self.dbu.name)
|
||||
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)
|
||||
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()
|
||||
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):
|
||||
|
@ -272,24 +264,23 @@ class UserDatabaseTest(TestCaseWithCeleryTasks):
|
|||
Test case for :py:class:`userdbs.models.UserDabase`.
|
||||
|
||||
"""
|
||||
|
||||
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)
|
||||
db = UserDatabase.objects.create_userdatabase_with_user(
|
||||
DB_TYPES.pgsql, osuser)
|
||||
db = UserDatabase.objects.create_userdatabase_with_user(DB_TYPES.pgsql, osuser)
|
||||
self.assertEqual(
|
||||
str(db),
|
||||
'{user}db01 ({dbuser})'.format(
|
||||
user=osuser.username, dbuser=db.db_user))
|
||||
"{user}db01 ({dbuser})".format(user=osuser.username, dbuser=db.db_user),
|
||||
)
|
||||
|
||||
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)
|
||||
TaskResult.objects.all().delete()
|
||||
db = UserDatabase.objects.create_userdatabase_with_user(
|
||||
DB_TYPES.mysql, osuser)
|
||||
db = UserDatabase.objects.create_userdatabase_with_user(DB_TYPES.mysql, osuser)
|
||||
db.delete()
|
||||
taskres = TaskResult.objects.all()
|
||||
self.assertEqual(len(taskres), 3)
|
||||
self.assertEqual(taskres[2].creator, 'handle_userdb_deleted')
|
||||
self.assertEqual(taskres[2].notes, 'mysql database deletion')
|
||||
self.assertEqual(taskres[2].creator, "handle_userdb_deleted")
|
||||
self.assertEqual(taskres[2].notes, "mysql database deletion")
|
||||
|
|
|
@ -4,63 +4,60 @@ This module contains explicit tests for corner cases in
|
|||
:py:mod:`userdbs.tests.test_models`.
|
||||
|
||||
"""
|
||||
from __future__ import unicode_literals
|
||||
from unittest.mock import Mock
|
||||
|
||||
from django.test import TestCase
|
||||
from django.test.utils import override_settings
|
||||
|
||||
from taskresults.models import TaskResult
|
||||
from userdbs.signals import (handle_dbuser_created, handle_dbuser_deleted,
|
||||
handle_dbuser_password_set, handle_userdb_created,
|
||||
handle_userdb_deleted)
|
||||
|
||||
try:
|
||||
from unittest.mock import Mock
|
||||
except ImportError:
|
||||
from mock import Mock
|
||||
from userdbs.signals import (
|
||||
handle_dbuser_created,
|
||||
handle_dbuser_deleted,
|
||||
handle_dbuser_password_set,
|
||||
handle_userdb_created,
|
||||
handle_userdb_deleted,
|
||||
)
|
||||
|
||||
|
||||
@override_settings(
|
||||
CELERY_ALWAYS_EAGER=True,
|
||||
CELERY_CACHE_BACKEND='memory',
|
||||
BROKER_BACKEND='memory'
|
||||
CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", BROKER_BACKEND="memory"
|
||||
)
|
||||
class TestCaseWithCeleryTasks(TestCase):
|
||||
pass
|
||||
|
||||
|
||||
class TestWithUnknownDBType(TestCaseWithCeleryTasks):
|
||||
|
||||
def test_handle_dbuser_password_set_unknown(self):
|
||||
instance = Mock(data={'name': 'test', 'db_type': -1})
|
||||
handle_dbuser_password_set(Mock(name='sender'), instance, 'secret')
|
||||
instance = Mock(data={"name": "test", "db_type": -1})
|
||||
handle_dbuser_password_set(Mock(name="sender"), instance, "secret")
|
||||
self.assertFalse(TaskResult.objects.exists())
|
||||
|
||||
def test_handle_dbuser_create_unknown(self):
|
||||
instance = Mock(data={'name': 'test', 'db_type': -1})
|
||||
handle_dbuser_created(
|
||||
Mock(name='sender'), instance, True, password='secret')
|
||||
instance = Mock(data={"name": "test", "db_type": -1})
|
||||
handle_dbuser_created(Mock(name="sender"), instance, True, password="secret")
|
||||
self.assertFalse(TaskResult.objects.exists())
|
||||
|
||||
def test_handle_dbuser_deleted_unknown(self):
|
||||
instance = Mock(data={'name': 'test', 'db_type': -1})
|
||||
handle_dbuser_deleted(Mock(name='sender'), instance)
|
||||
instance = Mock(data={"name": "test", "db_type": -1})
|
||||
handle_dbuser_deleted(Mock(name="sender"), instance)
|
||||
self.assertFalse(TaskResult.objects.exists())
|
||||
|
||||
def test_handle_userdb_created_unknown(self):
|
||||
instance = Mock(
|
||||
data={
|
||||
'db_name': 'test',
|
||||
'db_user': Mock(data={'name': 'test', 'db_type': -1, })
|
||||
})
|
||||
handle_userdb_created(Mock(name='sender'), instance, True)
|
||||
"db_name": "test",
|
||||
"db_user": Mock(data={"name": "test", "db_type": -1}),
|
||||
}
|
||||
)
|
||||
handle_userdb_created(Mock(name="sender"), instance, True)
|
||||
self.assertFalse(TaskResult.objects.exists())
|
||||
|
||||
def test_handle_userdb_deleted_unknown(self):
|
||||
instance = Mock(
|
||||
data={
|
||||
'db_name': 'test',
|
||||
'db_user': Mock(data={'name': 'test', 'db_type': -1, })
|
||||
})
|
||||
handle_userdb_deleted(Mock(name='sender'), instance)
|
||||
"db_name": "test",
|
||||
"db_user": Mock(data={"name": "test", "db_type": -1}),
|
||||
}
|
||||
)
|
||||
handle_userdb_deleted(Mock(name="sender"), instance)
|
||||
self.assertFalse(TaskResult.objects.exists())
|
||||
|
|
|
@ -2,16 +2,11 @@
|
|||
This module provides tests for :py:mod:`userdbs.views`.
|
||||
|
||||
"""
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
try:
|
||||
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.contrib.auth import get_user_model
|
||||
from django.urls import reverse
|
||||
|
||||
from hostingpackages.models import (
|
||||
CustomerHostingPackage,
|
||||
|
@ -26,58 +21,61 @@ from userdbs.views import AddUserDatabase, ChangeDatabaseUserPassword
|
|||
|
||||
User = get_user_model()
|
||||
|
||||
TEST_USER = 'test'
|
||||
TEST_PASSWORD = 'secret'
|
||||
TEST_EMAIL = 'test@example.org'
|
||||
TEST_USER = "test"
|
||||
TEST_PASSWORD = "secret"
|
||||
TEST_EMAIL = "test@example.org"
|
||||
|
||||
|
||||
class HostingPackageAwareTestMixin(object):
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def _setup_hosting_package(self, customer):
|
||||
template = HostingPackageTemplate.objects.create(
|
||||
name='testpackagetemplate', mailboxcount=10, diskspace=1,
|
||||
diskspace_unit=0)
|
||||
name="testpackagetemplate", mailboxcount=10, diskspace=1, diskspace_unit=0
|
||||
)
|
||||
package = CustomerHostingPackage.objects.create_from_template(
|
||||
customer, template, 'testpackage')
|
||||
with patch('hostingpackages.models.settings') as hmsettings:
|
||||
customer, template, "testpackage"
|
||||
)
|
||||
with patch("hostingpackages.models.settings") as hmsettings:
|
||||
hmsettings.OSUSER_DEFAULT_GROUPS = []
|
||||
package.save()
|
||||
return package
|
||||
|
||||
|
||||
class CustomerUserDatabaseOptionAwareTestMixin(object):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(CustomerUserDatabaseOptionAwareTestMixin, self).__init__(
|
||||
*args, **kwargs)
|
||||
super(CustomerUserDatabaseOptionAwareTestMixin, self).__init__(*args, **kwargs)
|
||||
self._templates = {}
|
||||
|
||||
def _setup_userdatabaseoption(self, number, dbtype):
|
||||
key = "{}_{}".format(dbtype, number)
|
||||
if key not in self._templates:
|
||||
self._templates[key] = UserDatabaseOption.objects.create(
|
||||
number=number, db_type=dbtype)
|
||||
number=number, db_type=dbtype
|
||||
)
|
||||
return self._templates[key]
|
||||
|
||||
def _create_userdatabase_option(self, number=1, dbtype=DB_TYPES.pgsql):
|
||||
# noinspection PyUnresolvedReferences
|
||||
return CustomerUserDatabaseOption.objects.create(
|
||||
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(
|
||||
HostingPackageAwareTestMixin, CustomerUserDatabaseOptionAwareTestMixin,
|
||||
TestCase
|
||||
HostingPackageAwareTestMixin, CustomerUserDatabaseOptionAwareTestMixin, TestCase
|
||||
):
|
||||
|
||||
def setUp(self):
|
||||
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)
|
||||
|
||||
def _get_url(self):
|
||||
return reverse(
|
||||
'add_userdatabase', kwargs={'package': self.package.id})
|
||||
return reverse("add_userdatabase", kwargs={"package": self.package.id})
|
||||
|
||||
def test_get_anonymous(self):
|
||||
response = self.client.get(self._get_url())
|
||||
|
@ -95,31 +93,29 @@ class AddUserDatabaseTest(
|
|||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_get_other_regular_user(self):
|
||||
User.objects.create_user(
|
||||
'test2', password=TEST_PASSWORD)
|
||||
self.client.login(username='test2', password=TEST_PASSWORD)
|
||||
User.objects.create_user("test2", password=TEST_PASSWORD)
|
||||
self.client.login(username="test2", password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url())
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_get_staff_user_nodboption(self):
|
||||
User.objects.create_superuser(
|
||||
'admin', email=TEST_EMAIL, password=TEST_PASSWORD)
|
||||
self.client.login(username='admin', password=TEST_PASSWORD)
|
||||
User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
|
||||
self.client.login(username="admin", password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url())
|
||||
self.assertEqual(response.status_code, 400)
|
||||
|
||||
def test_get_staff_user(self):
|
||||
self._create_userdatabase_option()
|
||||
User.objects.create_superuser(
|
||||
'admin', email=TEST_EMAIL, password=TEST_PASSWORD)
|
||||
self.client.login(username='admin', password=TEST_PASSWORD)
|
||||
User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
|
||||
self.client.login(username="admin", password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_get_regular_user_nofree_db(self):
|
||||
db_option = self._create_userdatabase_option()
|
||||
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)
|
||||
response = self.client.get(self._get_url())
|
||||
self.assertEqual(response.status_code, 400)
|
||||
|
@ -128,21 +124,21 @@ class AddUserDatabaseTest(
|
|||
db_option = self._create_userdatabase_option()
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
view = AddUserDatabase(
|
||||
request=MagicMock(), kwargs={'package': str(self.package.pk)})
|
||||
request=MagicMock(), kwargs={"package": str(self.package.pk)}
|
||||
)
|
||||
the_kwargs = view.get_form_kwargs()
|
||||
self.assertIn('hostingpackage', the_kwargs)
|
||||
self.assertEqual(the_kwargs['hostingpackage'], self.package)
|
||||
self.assertIn('dbtypes', the_kwargs)
|
||||
self.assertIn("hostingpackage", the_kwargs)
|
||||
self.assertEqual(the_kwargs["hostingpackage"], self.package)
|
||||
self.assertIn("dbtypes", the_kwargs)
|
||||
self.assertEqual(
|
||||
the_kwargs['dbtypes'],
|
||||
[(db_option.db_type, DB_TYPES[db_option.db_type])],
|
||||
the_kwargs["dbtypes"], [(db_option.db_type, DB_TYPES[db_option.db_type])]
|
||||
)
|
||||
|
||||
def test_get_template(self):
|
||||
self._create_userdatabase_option()
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
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):
|
||||
db_option = self._create_userdatabase_option()
|
||||
|
@ -150,48 +146,55 @@ class AddUserDatabaseTest(
|
|||
response = self.client.post(
|
||||
self._get_url(),
|
||||
data={
|
||||
'db_type': db_option.db_type, 'password1': TEST_PASSWORD,
|
||||
'password2': TEST_PASSWORD})
|
||||
"db_type": db_option.db_type,
|
||||
"password1": TEST_PASSWORD,
|
||||
"password2": TEST_PASSWORD,
|
||||
},
|
||||
)
|
||||
self.assertRedirects(response, self.package.get_absolute_url())
|
||||
|
||||
def test_form_valid_message(self):
|
||||
db_option = self._create_userdatabase_option()
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.post(
|
||||
self._get_url(), follow=True,
|
||||
self._get_url(),
|
||||
follow=True,
|
||||
data={
|
||||
'db_type': db_option.db_type, 'password1': TEST_PASSWORD,
|
||||
'password2': TEST_PASSWORD})
|
||||
db = UserDatabase.objects.filter(
|
||||
db_user__osuser=self.package.osuser).get()
|
||||
messages = list(response.context['messages'])
|
||||
"db_type": db_option.db_type,
|
||||
"password1": TEST_PASSWORD,
|
||||
"password2": TEST_PASSWORD,
|
||||
},
|
||||
)
|
||||
db = UserDatabase.objects.filter(db_user__osuser=self.package.osuser).get()
|
||||
messages = list(response.context["messages"])
|
||||
self.assertEqual(len(messages), 1)
|
||||
self.assertEqual(
|
||||
str(messages[0]), (
|
||||
'Successfully create new {type} database {dbname} for user '
|
||||
'{dbuser}.').format(
|
||||
type=db.db_user.db_type, dbname=db.db_name,
|
||||
dbuser=db.db_user))
|
||||
str(messages[0]),
|
||||
(
|
||||
"Successfully create new {type} database {dbname} for user " "{dbuser}."
|
||||
).format(type=db.db_user.db_type, dbname=db.db_name, dbuser=db.db_user),
|
||||
)
|
||||
|
||||
|
||||
class ChangeDatabaseUserPasswordTest(
|
||||
HostingPackageAwareTestMixin, CustomerUserDatabaseOptionAwareTestMixin,
|
||||
TestCase
|
||||
HostingPackageAwareTestMixin, CustomerUserDatabaseOptionAwareTestMixin, TestCase
|
||||
):
|
||||
|
||||
def setUp(self):
|
||||
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)
|
||||
template = self._create_userdatabase_option()
|
||||
database = UserDatabase.objects.create_userdatabase_with_user(
|
||||
template.db_type, self.package.osuser)
|
||||
template.db_type, self.package.osuser
|
||||
)
|
||||
self.dbuser = database.db_user
|
||||
|
||||
def _get_url(self, dbuser):
|
||||
return reverse(
|
||||
'change_dbuser_password', kwargs={
|
||||
'package': self.package.id, 'slug': dbuser.name})
|
||||
"change_dbuser_password",
|
||||
kwargs={"package": self.package.id, "slug": dbuser.name},
|
||||
)
|
||||
|
||||
def test_get_anonymous(self):
|
||||
response = self.client.get(self._get_url(self.dbuser))
|
||||
|
@ -203,80 +206,85 @@ class ChangeDatabaseUserPasswordTest(
|
|||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_get_other_regular_user(self):
|
||||
User.objects.create_user(
|
||||
'test2', password=TEST_PASSWORD)
|
||||
self.client.login(username='test2', password=TEST_PASSWORD)
|
||||
User.objects.create_user("test2", password=TEST_PASSWORD)
|
||||
self.client.login(username="test2", password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url(self.dbuser))
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_get_staff_user(self):
|
||||
User.objects.create_superuser(
|
||||
'admin', email=TEST_EMAIL, password=TEST_PASSWORD)
|
||||
self.client.login(username='admin', password=TEST_PASSWORD)
|
||||
User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
|
||||
self.client.login(username="admin", password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url(self.dbuser))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_get_template(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url(self.dbuser))
|
||||
self.assertTemplateUsed(
|
||||
response, 'userdbs/databaseuser_setpassword.html')
|
||||
self.assertTemplateUsed(response, "userdbs/databaseuser_setpassword.html")
|
||||
|
||||
def test_get_form_kwargs(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
view = ChangeDatabaseUserPassword(request=MagicMock(), kwargs={
|
||||
'package': str(self.package.pk), 'slug': self.dbuser.name})
|
||||
view = ChangeDatabaseUserPassword(
|
||||
request=MagicMock(),
|
||||
kwargs={"package": str(self.package.pk), "slug": self.dbuser.name},
|
||||
)
|
||||
the_kwargs = view.get_form_kwargs()
|
||||
self.assertIn('hostingpackage', the_kwargs)
|
||||
self.assertEqual(the_kwargs['hostingpackage'], self.package)
|
||||
self.assertIn("hostingpackage", the_kwargs)
|
||||
self.assertEqual(the_kwargs["hostingpackage"], self.package)
|
||||
|
||||
def test_get_context_data(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url(self.dbuser))
|
||||
self.assertIn('dbuser', response.context)
|
||||
self.assertEqual(response.context['dbuser'], self.dbuser)
|
||||
self.assertIn('hostingpackage', response.context)
|
||||
self.assertEqual(response.context['hostingpackage'], self.package)
|
||||
self.assertIn('customer', response.context)
|
||||
self.assertEqual(response.context['customer'], self.customer)
|
||||
self.assertIn("dbuser", response.context)
|
||||
self.assertEqual(response.context["dbuser"], self.dbuser)
|
||||
self.assertIn("hostingpackage", response.context)
|
||||
self.assertEqual(response.context["hostingpackage"], self.package)
|
||||
self.assertIn("customer", response.context)
|
||||
self.assertEqual(response.context["customer"], self.customer)
|
||||
|
||||
def test_form_valid_redirect(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.post(self._get_url(self.dbuser), data={
|
||||
'password1': TEST_PASSWORD, 'password2': TEST_PASSWORD})
|
||||
response = self.client.post(
|
||||
self._get_url(self.dbuser),
|
||||
data={"password1": TEST_PASSWORD, "password2": TEST_PASSWORD},
|
||||
)
|
||||
self.assertRedirects(response, self.package.get_absolute_url())
|
||||
|
||||
def test_form_valid_message(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.post(
|
||||
self._get_url(self.dbuser), follow=True, data={
|
||||
'password1': TEST_PASSWORD, 'password2': TEST_PASSWORD})
|
||||
messages = list(response.context['messages'])
|
||||
self._get_url(self.dbuser),
|
||||
follow=True,
|
||||
data={"password1": TEST_PASSWORD, "password2": TEST_PASSWORD},
|
||||
)
|
||||
messages = list(response.context["messages"])
|
||||
self.assertEqual(len(messages), 1)
|
||||
self.assertEqual(
|
||||
str(messages[0]),
|
||||
'Successfully changed password of database user {dbuser}.'.format(
|
||||
dbuser=self.dbuser.name))
|
||||
"Successfully changed password of database user {dbuser}.".format(
|
||||
dbuser=self.dbuser.name
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class DeleteUserDatabaseTest(
|
||||
HostingPackageAwareTestMixin, CustomerUserDatabaseOptionAwareTestMixin,
|
||||
TestCase
|
||||
HostingPackageAwareTestMixin, CustomerUserDatabaseOptionAwareTestMixin, TestCase
|
||||
):
|
||||
|
||||
def setUp(self):
|
||||
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)
|
||||
template = self._create_userdatabase_option()
|
||||
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):
|
||||
return reverse(
|
||||
'delete_userdatabase', kwargs={
|
||||
'package': self.package.id,
|
||||
'slug': userdatabase.db_name})
|
||||
"delete_userdatabase",
|
||||
kwargs={"package": self.package.id, "slug": userdatabase.db_name},
|
||||
)
|
||||
|
||||
def test_get_anonymous(self):
|
||||
response = self.client.get(self._get_url(self.database))
|
||||
|
@ -288,34 +296,31 @@ class DeleteUserDatabaseTest(
|
|||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_get_other_regular_user(self):
|
||||
User.objects.create_user(
|
||||
'test2', password=TEST_PASSWORD)
|
||||
self.client.login(username='test2', password=TEST_PASSWORD)
|
||||
User.objects.create_user("test2", password=TEST_PASSWORD)
|
||||
self.client.login(username="test2", password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url(self.database))
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_get_staff_user(self):
|
||||
User.objects.create_superuser(
|
||||
'admin', email=TEST_EMAIL, password=TEST_PASSWORD)
|
||||
self.client.login(username='admin', password=TEST_PASSWORD)
|
||||
User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
|
||||
self.client.login(username="admin", password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url(self.database))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_get_template(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url(self.database))
|
||||
self.assertTemplateUsed(
|
||||
response, 'userdbs/userdatabase_confirm_delete.html')
|
||||
self.assertTemplateUsed(response, "userdbs/userdatabase_confirm_delete.html")
|
||||
|
||||
def test_get_context_data(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
response = self.client.get(self._get_url(self.database))
|
||||
self.assertIn('database', response.context)
|
||||
self.assertEqual(response.context['database'], self.database)
|
||||
self.assertIn('hostingpackage', response.context)
|
||||
self.assertEqual(response.context['hostingpackage'], self.package)
|
||||
self.assertIn('customer', response.context)
|
||||
self.assertEqual(response.context['customer'], self.customer)
|
||||
self.assertIn("database", response.context)
|
||||
self.assertEqual(response.context["database"], self.database)
|
||||
self.assertIn("hostingpackage", response.context)
|
||||
self.assertEqual(response.context["hostingpackage"], self.package)
|
||||
self.assertIn("customer", response.context)
|
||||
self.assertEqual(response.context["customer"], self.customer)
|
||||
|
||||
def test_form_valid_redirect(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
|
@ -325,6 +330,6 @@ class DeleteUserDatabaseTest(
|
|||
def test_form_valid_message(self):
|
||||
self.client.login(username=TEST_USER, password=TEST_PASSWORD)
|
||||
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(str(messages[0]), "Database deleted.")
|
||||
|
|
Loading…
Reference in a new issue