Browse Source

tests et corrections des commandes

Élie Bouttier 8 years ago
parent
commit
c9bc2af239

+ 12 - 12
adhesions/management/commands/adherents.py

@@ -2,7 +2,7 @@ from django.core.management.base import BaseCommand, CommandParser, CommandError
 from django.contrib.contenttypes.models import ContentType
 
 from django.contrib.auth.models import User
-from adhesions.models import Adherent, Corporation
+from adhesions.models import Adhesion, Corporation
 
 
 class Command(BaseCommand):
@@ -43,20 +43,20 @@ class Command(BaseCommand):
         getattr(self, 'handle_{cmd}'.format(cmd=cmd))(*args, **options)
 
     def handle_list(self, *args, **options):
-        adherents = Adherent.objects.all()
+        adhesions = Adhesion.objects.all()
         if options['physique']:
-            adherents = adherents.filter(adherent_type=ContentType.objects.get(app_label='auth', model='user'))
+            adhesions = adhesions.filter(adherent_type=ContentType.objects.get(app_label='auth', model='user'))
         if options['morale']:
-            adherents = adherents.filter(adherent_type=ContentType.objects.get(app_label='adhesions', model='corporation'))
-        for adh in adherents:
-            print("#{id:<8}{name:<30}{type:<20}".format(**{
+            adhesions = adhesions.filter(adherent_type=ContentType.objects.get(app_label='adhesions', model='corporation'))
+        for adh in adhesions:
+            self.stdout.write("#{id:<8}{name:<30}{type:<20}".format(**{
                 'id': adh.id,
-                'name': adh.get_name(),
+                'name': adh.get_adherent_name(),
                 'type': adh.type,
             }))
 
     def handle_create(self, *args, **options):
-        if options['id'] and Adherent.objects.filter(id=options['id']).exists():
+        if options['id'] and Adhesion.objects.filter(id=options['id']).exists():
             raise CommandError('Le numéro d’adherent "%d" est déjà attribué' % options['id'])
         getattr(self, 'handle_create_personne_{type}'.format(**{
             'type': options.pop('type'),
@@ -66,13 +66,13 @@ class Command(BaseCommand):
         if User.objects.filter(username=options['username']).exists():
             raise CommandError('Le nom d’utilisateur "%s" est déjà utilisé' % options['username'])
         user = User.objects.create_user(**{key: options[key] for key in ['username', 'email', 'first_name', 'last_name']})
-        adherent = Adherent.objects.create(id=options['id'], adherent=user)
-        self.stdout.write(self.style.SUCCESS('Adhérent #%d créé avec succès' % adherent.id))
+        adhesion = Adhesion.objects.create(id=options['id'], adherent=user)
+        self.stdout.write(self.style.SUCCESS('Adhérent #%d créé avec succès' % adhesion.id))
 
     def handle_create_personne_morale(self, *args, **options):
         if Corporation.objects.filter(social_reason=options['social_reason']).exists():
             raise CommandError('La raison sociale "%s" est déjà utilisé' % options['social_reason'])
         corporation = Corporation.objects.create(**{key: options[key] for key in ['social_reason', 'description']})
-        adherent = Adherent.objects.create(id=options['id'], adherent=corporation)
-        self.stdout.write(self.style.SUCCESS('Adhérent #%d créé avec succès' % adherent.id))
+        adhesion = Adhesion.objects.create(id=options['id'], adherent=corporation)
+        self.stdout.write(self.style.SUCCESS('Adhérent #%d créé avec succès' % adhesion.id))
         

+ 61 - 1
adhesions/tests.py

@@ -2,11 +2,16 @@ from django.test import TestCase
 from django.contrib.auth.models import User
 from django.contrib.contenttypes.models import ContentType
 from django.core.urlresolvers import reverse
+from django.core.management import call_command
+from django.core.management.base import CommandError
+
+from io import StringIO
+from os import devnull
 
 from .models import Corporation, Adhesion
 
 
-class AdhesionsTests(TestCase):
+class AdhesionsMixin:
     def setUp(self):
         admin = User.objects.create_user('admin', email='admin@example.net', password='admin', is_superuser=True)
         user = User.objects.create_user('user', first_name='first', last_name='last', email='user@example.net', password='user')
@@ -16,6 +21,8 @@ class AdhesionsTests(TestCase):
         corp2 = Corporation.objects.create(social_reason='EvilCorp')
         adh2 = Adhesion.objects.create(adherent_type=ContentType.objects.get_for_model(Corporation), adherent_id=corp1.pk)
 
+
+class ViewsTestCase(AdhesionsMixin, TestCase):
     def test_adhesion_backend(self):
         user = User.objects.get(username='user')
         adhesion = user.profile.adhesion
@@ -138,3 +145,56 @@ class AdhesionsTests(TestCase):
         self.client.login(username='admin', password='admin')
         response = self.client.get(url)
         self.assertEqual(response.status_code, 200)
+
+
+class CommandsTestCase(AdhesionsMixin, TestCase):
+    def test_list(self):
+        out = StringIO()
+        call_command("adherents", "list", stdout=out)
+        result = out.getvalue()
+        self.assertNotRegex(result, "admin") # non adhérent
+        self.assertRegex(result, "first last")
+        self.assertRegex(result, "GoodCorp")
+        self.assertNotRegex(result, "EvilCorp") # non adhérent
+
+        out = StringIO()
+        call_command("adherents", "list", "--physique", stdout=out)
+        result = out.getvalue()
+        self.assertRegex(result, "first last")
+        self.assertNotRegex(result, "GoodCorp")
+
+        out = StringIO()
+        call_command("adherents", "list", "--morale", stdout=out)
+        result = out.getvalue()
+        self.assertNotRegex(result, "first last")
+        self.assertRegex(result, "GoodCorp")
+
+    def test_create_personne_physique(self):
+        user = User.objects.first()
+        adh = Adhesion.objects.first()
+        args = ["adherents", "create", "--id", "%d" % adh.pk, "physique", "--login", "user2", "--firstname", "first2", "--lastname", "last2"]
+        kwargs = {'stdout': open(devnull, 'w')}
+        self.assertRaisesRegex(CommandError, "numéro .* déjà attribué", call_command, *args, **kwargs)
+        args[args.index("--id") + 1] = "1000"
+        args[args.index("--login") + 1] = user.username
+        self.assertRaisesRegex(CommandError, "nom d’utilisateur .* déjà utilisé", call_command, *args, **kwargs)
+        args[args.index("--login") + 1] = "user2"
+        call_command(*args, **kwargs)
+        user = User.objects.get(username='user2')
+        adh = Adhesion.objects.get(adherent_type=ContentType.objects.get_for_model(User), adherent_id=user.pk)
+        self.assertEquals(adh.id, 1000)
+
+    def test_create_personne_morale(self):
+        corp = Corporation.objects.first()
+        adh = Adhesion.objects.first()
+        args = ["adherents", "create", "--id", "%d" % adh.pk, "morale", "--name", "NewCorp"]
+        kwargs = {'stdout': open(devnull, 'w')}
+        self.assertRaisesRegex(CommandError, "numéro .* déjà attribué", call_command, *args, **kwargs)
+        args[args.index("--id") + 1] = "1000"
+        args[args.index("--name") + 1] = corp.social_reason
+        self.assertRaisesRegex(CommandError, "raison sociale .* déjà utilisé", call_command, *args, **kwargs)
+        args[args.index("--name") + 1] = "NewCorp"
+        call_command(*args, **kwargs)
+        corp = Corporation.objects.get(social_reason='NewCorp')
+        adh = Adhesion.objects.get(adherent_type=ContentType.objects.get_for_model(Corporation), adherent_id=corp.pk)
+        self.assertEquals(adh.id, 1000)

+ 11 - 11
services/management/commands/services.py

@@ -8,7 +8,7 @@ import argparse
 from decimal import Decimal
 
 from djadhere.utils import get_active_filter
-from adhesions.models import Adherent
+from adhesions.models import Adhesion
 from services.models import Service, ServiceType, IPResource, ResourceAllocation
 
 
@@ -86,14 +86,14 @@ class Command(BaseCommand):
         getattr(self, 'handle_{cmd}'.format(cmd=cmd))(*args, **options)
 
     def handle_stats(self, *args, **options):
-        # TODO: move this code in utils.py or some file like that
+        # TODO: move this code in utils.py or some place like that
         as_float_template = '%(function)s(%(expressions)s AS FLOAT)'
         total_income = Decimal(0.0)
         lines = []
         for service_type in ServiceType.objects.all():
             services = service_type.services.filter(active=True)
             ntotal = services.count()
-            services = services.exclude(adherent=None)
+            #services = services.exclude(adherent=None) # TODO: remove infra services here
             nadh = services.count()
             ninf = ntotal - nadh
             services = services.exclude(
@@ -124,17 +124,17 @@ class Command(BaseCommand):
             st = ServiceType.objects.get(name=options['type'])
             services = services.filter(service_type=st)
         if options['active']:
-            services = services.filter(get_active_filter())
+            services = services.filter(active=True)
         if options['inactive']:
-            services = services.exclude(get_active_filter())
+            services = services.filter(active=False)
 
-        fmt = '{:<8}{:<20}{:<20}{:<10}{:<40}'
-        print(fmt.format('ID', 'Type', 'Adhérent', 'Actif', 'IPs'))
+        fmt = '{:<8}{:<20}{:<20}{:<20}{:<10}{:<40}'
+        self.stdout.write(fmt.format('ID', 'Type', 'Label', 'Adhérent', 'Actif', 'IPs'))
         for service in services:
-            adh = service.adherent.get_name()
+            adh = service.adhesion.get_adherent_name()
             ips = ', '.join(map(lambda a: str(a.resource), service.active_allocations.all())) or '-'
             active = '✔' if service.active else '✘'
-            print(fmt.format(service.pk, str(service.service_type), adh, active, ips))
+            self.stdout.write(fmt.format(service.pk, str(service.service_type), service.label, adh, active, ips))
 
     def handle_show(self, *args, **options):
         try:
@@ -161,8 +161,8 @@ class Command(BaseCommand):
                 pass
         st = ServiceType.objects.get(name=options['type'])
         try:
-            adherent = Adherent.objects.get(pk=options['adherent'])
-        except Adherent.DoesNotExist:
+            adherent = Adhesion.objects.get(pk=options['adherent'])
+        except Adhesion.DoesNotExist:
             raise CommandError("L’adhérent %d n’existe pas." % options['adherent'])
         if Service.objects.filter(service_type=st, label=options['label']).exists():
             raise CommandError("Un service du même type et portant le même label existe déjà.")

+ 2 - 2
services/management/commands/servicetypes.py

@@ -35,7 +35,7 @@ class Command(BaseCommand):
 
     def handle_list(self, *args, **options):
         for st in ServiceType.objects.all():
-            print('{:<30} {:4d} services'.format(st.name, st.services.count()))
+            self.stdout.write('{:<30} {:4d} services'.format(st.name, st.services.count()))
 
     def handle_add(self, *args, **options):
         if ServiceType.objects.filter(name=options['name']).exists():
@@ -49,7 +49,7 @@ class Command(BaseCommand):
         except ServiceType.DoesNotExist:
             raise CommandError('Le type de service "%s" n’existe pas' % options['old_name'])
         if ServiceType.objects.filter(name=options['new_name']).exists():
-            raise CommandError('Le type de service "%s" existe déjà' % options['name'])
+            raise CommandError('Le type de service "%s" existe déjà' % options['new_name'])
         st.name = options['new_name']
         st.save()
         self.stdout.write(self.style.SUCCESS('Type de service renommé en "%s"' % options['new_name']))

+ 94 - 6
services/tests.py

@@ -3,12 +3,16 @@ from django.core.urlresolvers import reverse
 from django.test import TestCase
 from django.contrib.contenttypes.models import ContentType
 from django.utils import timezone
+from django.core.management import call_command
+from django.core.management.base import CommandError
+
+from io import StringIO
 
 from adhesions.models import Adhesion, Corporation
 from .models import Service, ServiceType, IPResource, ResourceAllocation
 
 
-class ServicesTests(TestCase):
+class ServicesMixin:
     def setUp(self):
         user_ct = ContentType.objects.get_for_model(User)
         corp_ct = ContentType.objects.get_for_model(Corporation)
@@ -22,16 +26,20 @@ class ServicesTests(TestCase):
         corp2 = Corporation.objects.create(social_reason='Corp 2')
         corp2.members.add(user2)
         adh_c2 = Adhesion.objects.create(adherent_type=corp_ct, adherent_id=corp2.pk)
-        stype = ServiceType.objects.create(name='VM')
-        s1 = Service.objects.create(adhesion=adh_u1, service_type=stype, label='Service 1')
-        s2 = Service.objects.create(adhesion=adh_u2, service_type=stype, label='Service 2')
-        s3 = Service.objects.create(adhesion=adh_c1, service_type=stype, label='Service 3')
-        s4 = Service.objects.create(adhesion=adh_c2, service_type=stype, label='Service 4')
+        stype1 = ServiceType.objects.create(name='VM')
+        stype2 = ServiceType.objects.create(name='Abo Toulouse')
+        stype3 = ServiceType.objects.create(name='Abo Castre')
+        s1 = Service.objects.create(adhesion=adh_u1, service_type=stype1, label='Service 1')
+        s2 = Service.objects.create(adhesion=adh_u2, service_type=stype1, label='Service 2')
+        s3 = Service.objects.create(adhesion=adh_c1, service_type=stype2, label='Service 3')
+        s4 = Service.objects.create(adhesion=adh_c2, service_type=stype1, label='Service 4', active=False)
         ip1 = IPResource.objects.create(ip='91.224.148.1')
         ResourceAllocation.objects.create(resource=ip1, service=s1, start=timezone.now())
         ip2 = IPResource.objects.create(ip='91.224.148.2')
         ip3 = IPResource.objects.create(ip='91.224.148.3', mask=32)
 
+
+class ViewsTestCase(ServicesMixin, TestCase):
     def test_home_service_list(self):
         self.client.login(username='user1', password='user1')
         response = self.client.get(reverse('user'))
@@ -125,3 +133,83 @@ class ServicesTests(TestCase):
         self.assertFalse(allocation.active)
         response = self.client.post(url)
         self.assertEqual(response.status_code, 403)
+
+
+class ServicesCommandTestCase(ServicesMixin, TestCase):
+    def test_stats(self):
+        out = StringIO()
+        call_command("services", "stats", stdout=out)
+        result = out.getvalue()
+        self.assertRegex(result, "VM")
+        self.assertRegex(result, "Abo Toulouse")
+
+    def test_list(self):
+        out = StringIO()
+        call_command("services", "list", stdout=out)
+        result = out.getvalue()
+        self.assertRegex(result, "Service 1")
+        self.assertRegex(result, "Service 4")
+
+        out = StringIO()
+        call_command("services", "list", "--active", stdout=out)
+        result = out.getvalue()
+        self.assertRegex(result, "Service 1")
+        self.assertNotRegex(result, "Service 4")
+
+        out = StringIO()
+        call_command("services", "list", "--inactive", stdout=out)
+        result = out.getvalue()
+        self.assertNotRegex(result, "Service 1")
+        self.assertRegex(result, "Service 4")
+
+        out = StringIO()
+        call_command("services", "list", "--type", "VM", stdout=out)
+        result = out.getvalue()
+        self.assertRegex(result, "Service 1")
+        self.assertNotRegex(result, "Service 3")
+
+    def test_show(self):
+        pass
+
+    def test_add(self):
+        pass
+
+    def test_delete(self):
+        pass
+
+
+class ServiceTypesCommandTestCase(ServicesMixin, TestCase):
+    def test_list(self):
+        out = StringIO()
+        call_command("servicetypes", "list", stdout=out)
+        result = out.getvalue()
+        self.assertRegex(result, "VM")
+
+    def test_add(self):
+        self.assertRaisesRegex(CommandError, "type de service .* existe déjà", call_command, "servicetypes", "add", "VM", stdout=None)
+        out = StringIO()
+        call_command("servicetypes", "add", "Abo Muret", stdout=out)
+        result = out.getvalue()
+        self.assertRegex(result, "succès")
+        st = ServiceType.objects.get(name="Abo Muret")
+
+    def test_change(self):
+        st_old = ServiceType.objects.get(name="Abo Toulouse")
+        self.assertRaisesRegex(CommandError, "type de service .* existe déjà", call_command, "servicetypes", "change", "Abo Toulouse", "VM", stdout=None)
+        self.assertRaisesRegex(CommandError, "type de service .* n’existe pas", call_command, "servicetypes", "change", "Abo Muret", "Abo Auch", stdout=None)
+        out = StringIO()
+        call_command("servicetypes", "change", "Abo Toulouse", "Abo Muret", stdout=out)
+        result = out.getvalue()
+        self.assertRegex(result, "renommé")
+        st_new = ServiceType.objects.get(name="Abo Muret")
+        self.assertEquals(st_old.pk, st_new.pk)
+
+    def test_delete(self):
+        self.assertRaisesRegex(CommandError, "suppression refusé", call_command, "servicetypes", "delete", "VM", stdout=None)
+        self.assertRaisesRegex(CommandError, "type de service .* n’existe pas", call_command, "servicetypes", "delete", "Abo Paris", stdout=None)
+        out = StringIO()
+        call_command("servicetypes", "delete", "Abo Castre", stdout=out)
+        result = out.getvalue()
+        self.assertRegex(result, "supprimé")
+        ServiceType.objects.get(name="VM")
+        self.assertRaises(ServiceType.DoesNotExist, ServiceType.objects.get, name="Abo Castre")