| 1 |
from django.conf import settings |
| 2 |
from django.contrib.sites.managers import CurrentSiteManager |
| 3 |
from django.contrib.sites.models import Site |
| 4 |
from django.core import checks |
| 5 |
from django.db import models |
| 6 |
from django.test import SimpleTestCase, TestCase |
| 7 |
from django.test.utils import isolate_apps |
| 8 |
|
| 9 |
from .models import CustomArticle, ExclusiveArticle, SyndicatedArticle |
| 10 |
|
| 11 |
|
| 12 |
class SitesFrameworkTestCase(TestCase): |
| 13 |
@classmethod |
| 14 |
def setUpTestData(cls): |
| 15 |
Site.objects.get_or_create( |
| 16 |
id=settings.SITE_ID, domain="example.com", name="example.com" |
| 17 |
) |
| 18 |
Site.objects.create( |
| 19 |
id=settings.SITE_ID + 1, domain="example2.com", name="example2.com" |
| 20 |
) |
| 21 |
|
| 22 |
def test_site_fk(self): |
| 23 |
article = ExclusiveArticle.objects.create( |
| 24 |
title="Breaking News!", site_id=settings.SITE_ID |
| 25 |
) |
| 26 |
self.assertEqual(ExclusiveArticle.on_site.get(), article) |
| 27 |
|
| 28 |
def test_sites_m2m(self): |
| 29 |
article = SyndicatedArticle.objects.create(title="Fresh News!") |
| 30 |
article.sites.add(Site.objects.get(id=settings.SITE_ID)) |
| 31 |
article.sites.add(Site.objects.get(id=settings.SITE_ID + 1)) |
| 32 |
article2 = SyndicatedArticle.objects.create(title="More News!") |
| 33 |
article2.sites.add(Site.objects.get(id=settings.SITE_ID + 1)) |
| 34 |
self.assertEqual(SyndicatedArticle.on_site.get(), article) |
| 35 |
|
| 36 |
def test_custom_named_field(self): |
| 37 |
article = CustomArticle.objects.create( |
| 38 |
title="Tantalizing News!", |
| 39 |
places_this_article_should_appear_id=settings.SITE_ID, |
| 40 |
) |
| 41 |
self.assertEqual(CustomArticle.on_site.get(), article) |
| 42 |
|
| 43 |
|
| 44 |
@isolate_apps("sites_framework") |
| 45 |
class CurrentSiteManagerChecksTests(SimpleTestCase): |
| 46 |
def test_invalid_name(self): |
| 47 |
class InvalidArticle(models.Model): |
| 48 |
on_site = CurrentSiteManager("places_this_article_should_appear") |
| 49 |
|
| 50 |
errors = InvalidArticle.check() |
| 51 |
expected = [ |
| 52 |
checks.Error( |
| 53 |
"CurrentSiteManager could not find a field named " |
| 54 |
"'places_this_article_should_appear'.", |
| 55 |
obj=InvalidArticle.on_site, |
| 56 |
id="sites.E001", |
| 57 |
) |
| 58 |
] |
| 59 |
self.assertEqual(errors, expected) |
| 60 |
|
| 61 |
def test_invalid_field_type(self): |
| 62 |
class ConfusedArticle(models.Model): |
| 63 |
site = models.IntegerField() |
| 64 |
on_site = CurrentSiteManager() |
| 65 |
|
| 66 |
errors = ConfusedArticle.check() |
| 67 |
expected = [ |
| 68 |
checks.Error( |
| 69 |
"CurrentSiteManager cannot use 'ConfusedArticle.site' as it is " |
| 70 |
"not a foreign key or a many-to-many field.", |
| 71 |
obj=ConfusedArticle.on_site, |
| 72 |
id="sites.E002", |
| 73 |
) |
| 74 |
] |
| 75 |
self.assertEqual(errors, expected) |