Fakultas Ilmu Komputer UI

Commit 01bf3008 authored by Nabila Febri Viola's avatar Nabila Febri Viola
Browse files

[CHORES] Fix conflicts

parents d19b0218 f685381c
Pipeline #48921 passed with stages
in 2 minutes and 34 seconds
.data
\ No newline at end of file
...@@ -22,7 +22,7 @@ DRF Unit Tests: ...@@ -22,7 +22,7 @@ DRF Unit Tests:
- export DEBUG=True - export DEBUG=True
- pip install -r requirements-dev.txt - pip install -r requirements-dev.txt
script: script:
- coverage run --include='main/*,stok_darah/*,donor/*,rest_framework_authlib/*,acara_donor/*' manage.py test - coverage run --include='main/*,stok_darah/*,donor/*,rest_framework_authlib/*,acara_donor/*,edukasi/*' manage.py test
- coverage report --show-missing - coverage report --show-missing
- coverage xml - coverage xml
artifacts: artifacts:
......
...@@ -10,3 +10,4 @@ db.sqlite3 ...@@ -10,3 +10,4 @@ db.sqlite3
.coverage .coverage
coverage.xml coverage.xml
.idea/ .idea/
media/
\ No newline at end of file
...@@ -47,7 +47,7 @@ PS C:\Users\Giovan\Projects\mantan-aab-d-blood\drf> Set-ExecutionPolicy -Scope C ...@@ -47,7 +47,7 @@ PS C:\Users\Giovan\Projects\mantan-aab-d-blood\drf> Set-ExecutionPolicy -Scope C
5. Run unit tests and measure coverage 5. Run unit tests and measure coverage
``` ```
(venv) PS C:\Users\Giovan\Projects\mantan-aab-d-blood\drf> coverage run --include='main/*,stok_darah/*,donor/*,rest_framework_authlib/*' manage.py test (venv) PS C:\Users\Giovan\Projects\mantan-aab-d-blood\drf> coverage run --include='main/*,stok_darah/*,donor/*,rest_framework_authlib/*,acara_donor/*,edukasi/*' manage.py test
(venv) PS C:\Users\Giovan\Projects\mantan-aab-d-blood\drf> coverage report --show-missing (venv) PS C:\Users\Giovan\Projects\mantan-aab-d-blood\drf> coverage report --show-missing
``` ```
......
from django.http import HttpResponse
from django.contrib import admin from django.contrib import admin
from acara_donor.models import AcaraDonor from acara_donor.models import AcaraDonor
from acara_donor.filters import AcaraDonorFilter from acara_donor.filters import AcaraDonorFilter
def download_acara_donor(modeladmin, request, queryset):
import pandas as pd
from django_pandas.io import read_frame
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = f'attachment; filename={modeladmin.model._meta}.xlsx'
df = read_frame(queryset)
df['waktu_donor'] = df['waktu_donor'].astype(str).str[:-6] # Strip tzinfo
writer = pd.ExcelWriter(response, engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
workbook = writer.book
# worksheet = writer.sheets['Sheet1']
workbook.close()
return response
download_acara_donor.short_description = 'Download Acara Donor as Excel Workbook'
@admin.register(AcaraDonor) @admin.register(AcaraDonor)
class AcaraDonorAdmin(admin.ModelAdmin): class AcaraDonorAdmin(admin.ModelAdmin):
list_filter = ('status', AcaraDonorFilter, 'kecamatan', 'kategori') list_filter = ('status', AcaraDonorFilter, 'kecamatan', 'kategori')
......
import datetime import datetime
from unittest.mock import patch from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.test import TestCase from django.test import TestCase
from django.urls import reverse
from django.utils import timezone from django.utils import timezone
from django.utils.timezone import localtime from django.utils.timezone import localtime
from rest_framework import status from rest_framework import status
...@@ -13,6 +15,9 @@ from acara_donor.admin import AcaraDonorAdmin ...@@ -13,6 +15,9 @@ from acara_donor.admin import AcaraDonorAdmin
from acara_donor.filters import AcaraDonorFilter from acara_donor.filters import AcaraDonorFilter
User = get_user_model()
class AcaraDonorTest(TestCase): class AcaraDonorTest(TestCase):
""" Test module for Acara Donor model""" """ Test module for Acara Donor model"""
......
...@@ -34,6 +34,7 @@ INSTALLED_APPS = [ ...@@ -34,6 +34,7 @@ INSTALLED_APPS = [
'anymail', 'anymail',
'corsheaders', 'corsheaders',
'donor', 'donor',
'edukasi',
'acara_donor' 'acara_donor'
] ]
......
import os
from .production import * from .production import *
SECRET_KEY = os.getenv('SECRET_KEY', '__super_secret_high_entropy_pseudo_random_bytes_a608e1fb__') SECRET_KEY = os.getenv('SECRET_KEY', '__super_secret_high_entropy_pseudo_random_bytes_a608e1fb__')
......
...@@ -22,6 +22,7 @@ urlpatterns = [ ...@@ -22,6 +22,7 @@ urlpatterns = [
path('admin/', admin.site.urls), path('admin/', admin.site.urls),
path('', include('main.urls')), path('', include('main.urls')),
path('donor/', include('donor.urls')), path('donor/', include('donor.urls')),
path('edukasi/', include('edukasi.urls')),
path('acara-donor/', include('acara_donor.urls')), path('acara-donor/', include('acara_donor.urls')),
path('stok-darah/', include('stok_darah.urls')) path('stok-darah/', include('stok_darah.urls'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.contrib import admin from django.contrib import admin
from django.http import HttpResponse
from donor.models import JadwalDonor, DaftarDonor from donor.models import JadwalDonor, DaftarDonor
def download_jadwaldonor(modeladmin, request, queryset):
import pandas as pd
from django_pandas.io import read_frame
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = f'attachment; filename={modeladmin.model._meta}.xlsx'
daftar_donor = DaftarDonor.download_query(queryset)
fieldnames = [
'id',
'jadwal_donor__time_start',
'user__profile__id_card_no',
'user__first_name',
'user__profile__address',
'user__profile__phone_no',
'user__profile__blood_type',
'user__profile__sex',
]
df = read_frame(daftar_donor, fieldnames=fieldnames)
df = df.rename(columns={
fieldnames[0]: "NoTrans",
fieldnames[1]: "Tanggal",
fieldnames[2]: "ID",
fieldnames[3]: "Nama Lengkap",
fieldnames[4]: "Alamat",
fieldnames[5]: "HP",
fieldnames[6]: "Gol (RH)",
fieldnames[7]: "JK",
})
if len(df):
df['Tanggal'] = df['Tanggal'].dt.tz_localize(None)
writer = pd.ExcelWriter(response, engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
workbook = writer.book
worksheet = writer.sheets['Sheet1']
def get_col_widths(dataframe):
# First we find the maximum length of the index column
idx_max = max([len(str(s)) for s in dataframe.index.values] + [len(str(dataframe.index.name))])
# Then, we concatenate this to the max of the lengths of column name
# and its values for each column, left to right
return [idx_max] + [max([len(str(s)) for s in dataframe[col].values] + [len(col)]) for col in dataframe.columns]
text_format = workbook.add_format({'text_wrap': True})
for i, width in enumerate(get_col_widths(df)):
worksheet.set_column(i, i, width, text_format)
workbook.close()
return response
download_jadwaldonor.short_description = 'Download Jadwal Donor as Excel Workbook'
@admin.register(JadwalDonor) @admin.register(JadwalDonor)
class JadwalDonorAdmin(admin.ModelAdmin): class JadwalDonorAdmin(admin.ModelAdmin):
list_filter = ('kecamatan', 'time_start', 'category') list_filter = ('kecamatan', 'time_start', 'category')
actions = [download_jadwaldonor]
@admin.register(DaftarDonor) @admin.register(DaftarDonor)
......
...@@ -97,10 +97,14 @@ class DaftarDonor(models.Model): ...@@ -97,10 +97,14 @@ class DaftarDonor(models.Model):
seks_dengan_orang_afrika = models.BooleanField() seks_dengan_orang_afrika = models.BooleanField()
tinggal_di_afrika = models.BooleanField() tinggal_di_afrika = models.BooleanField()
def __str__(self):
return str(self.user) + " - " + str(self.jadwal_donor)
@classmethod
def download_query(cls, jadwal_qs):
return cls.objects.filter(jadwal_donor__in=jadwal_qs, has_attended=True)
class Meta: class Meta:
constraints = [ constraints = [
models.UniqueConstraint(fields=['user', 'jadwal_donor'], name='unique__user-jadwal_donor') models.UniqueConstraint(fields=['user', 'jadwal_donor'], name='unique__user-jadwal_donor')
] ]
def __str__(self):
return str(self.user) + " - " + str(self.jadwal_donor)
from datetime import datetime, timedelta
from django.test import TestCase from django.test import TestCase
from django.utils import timezone
from django.core.exceptions import ValidationError
from main.factories import UserFactory from main.factories import UserFactory
from donor.models import JadwalDonor from donor.models import JadwalDonor, DaftarDonor
from donor.factories import JadwalDonorFactory, DaftarDonorFactory from donor.factories import JadwalDonorFactory, DaftarDonorFactory
from datetime import datetime
from django.core.exceptions import ValidationError
class JadwalDonorTest(TestCase): class JadwalDonorTest(TestCase):
...@@ -35,3 +37,17 @@ class DaftarDonorTest(TestCase): ...@@ -35,3 +37,17 @@ class DaftarDonorTest(TestCase):
jadwal_donor = JadwalDonorFactory() jadwal_donor = JadwalDonorFactory()
daftar_donor = DaftarDonorFactory(user=user, jadwal_donor=jadwal_donor) daftar_donor = DaftarDonorFactory(user=user, jadwal_donor=jadwal_donor)
self.assertEqual(str(daftar_donor), str(user) + ' - ' + str(jadwal_donor)) self.assertEqual(str(daftar_donor), str(user) + ' - ' + str(jadwal_donor))
def test_download_query(self):
user1 = UserFactory(email='donald@duckduckgo.org')
user1.save()
user2 = UserFactory(email='daisy@duckduckgo.org')
user2.save()
jadwal_donor = JadwalDonorFactory(time_start=timezone.localtime() - timedelta(hours=24),
time_end=timezone.localtime() - timedelta(hours=23))
DaftarDonorFactory(user=user1, jadwal_donor=jadwal_donor, has_attended=True)
DaftarDonorFactory(user=user2, jadwal_donor=jadwal_donor, has_attended=True)
qs = DaftarDonor.download_query(JadwalDonor.objects.filter(id=jadwal_donor.id))
self.assertEqual(len(qs), 2)
from datetime import timedelta
from django.urls import reverse
from django.utils import timezone
from django.utils.timezone import localtime
from django.test import TestCase
from rest_framework import status from rest_framework import status
from rest_framework.test import APITestCase from rest_framework.test import APITestCase
from django.utils import timezone
from donor.factories import JadwalDonorFactory, DaftarDonorFactory from donor.factories import JadwalDonorFactory, DaftarDonorFactory
from donor.models import JadwalDonor from donor.models import JadwalDonor
from main.factories import UserFactory from main.factories import UserFactory
from datetime import timedelta from main.models import User
from rest_framework_authlib.tokens import AccessToken from rest_framework_authlib.tokens import AccessToken
from django.utils.timezone import localtime
class JadwalDonorTests(APITestCase): class JadwalDonorTests(APITestCase):
...@@ -273,6 +276,28 @@ class RiwayatDonorTest(APITestCase): ...@@ -273,6 +276,28 @@ class RiwayatDonorTest(APITestCase):
}]) }])
class JadwalDonorAdminTest(TestCase):
def setUp(self):
username = 'admin@host'
password = 'secretsauce'
User.objects.create_superuser(username, password)
self.client.login(username=username, password=password)
def test_action_download_jadwaldonor(self):
user = UserFactory(email='donald@duckduckgo.org')
user.save()
jadwal_donor = JadwalDonorFactory(time_start=timezone.localtime() - timedelta(hours=24),
time_end=timezone.localtime() - timedelta(hours=23))
DaftarDonorFactory(user=user, jadwal_donor=jadwal_donor, has_attended=True)
endpoint = reverse('admin:donor_jadwaldonor_changelist')
data = {'action': 'download_jadwaldonor', '_selected_action': [jadwal_donor.id]}
response = self.client.post(endpoint, data=data)
self.assertEqual(response['content-type'], 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
class FormulirDaftarDonorTest(APITestCase): class FormulirDaftarDonorTest(APITestCase):
def setUp(self): def setUp(self):
self.user = UserFactory(email='fairuzi@dblood.com') self.user = UserFactory(email='fairuzi@dblood.com')
......
from django.contrib import admin
from edukasi.models import Artikel
@admin.register(Artikel)
class ArtikelAdmin(admin.ModelAdmin):
pass
from django.apps import AppConfig
class EdukasiConfig(AppConfig):
name = 'edukasi'
import os
import factory
from faker import Faker
from edukasi.models import Artikel
fake = Faker()
class ArtikelFactory(factory.DjangoModelFactory):
class Meta:
model = Artikel
title = fake.sentence()[:-1]
featured_image = os.path.join("edukasi", "placeholder.jpg")
content = "\n".join(fake.paragraphs())
import os
import random
from django.core.management import BaseCommand
from faker import Faker
from edukasi.models import Artikel
fake = Faker()
fake.seed_instance(10) # NOSONAR
class Command(BaseCommand):
help = 'Add dummy data artikel edukasi'
def handle(self, *args, **options):
for i in range(20):
content = []
for i in range(5):
content.append(" ".join(fake.paragraphs()))
Artikel.objects.create(
title=fake.sentence()[:-1],
featured_image=os.path.join("edukasi", random.choice([ # NOSONAR
"placeholder1.jpg", "placeholder2.jpg", "placeholder3.jpg"])),
content="\n".join(content)
)
self.stdout.write(self.style.SUCCESS("Successfully add dummy data artikel edukasi"))
# Generated by Django 3.0.5 on 2020-05-04 05:45
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Artikel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=32)),
('featured_image', models.ImageField(upload_to='')),
('content', models.TextField()),
],
),
]
# Generated by Django 3.0.5 on 2020-05-04 05:56
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('edukasi', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='artikel',
name='posted_at',
field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
]
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment