Revert to old method of sample data gen

bulk_create is super quick, but no autoincrement on sqlite is killer when trying to run tests.
This commit is contained in:
2021-02-07 14:40:15 +00:00
parent 788fb3efe6
commit ef1d9868da
15 changed files with 324 additions and 339 deletions

View File

@@ -5,15 +5,18 @@ from django.urls.exceptions import NoReverseMatch
from RIGS.models import Event from RIGS.models import Event
from assets.models import Asset from assets.models import Asset
from django.db import connection
@pytest.mark.parametrize("command", ['generateSampleAssetsData', 'generateSampleRIGSData', 'generateSampleUserData', 'deleteSampleData']) @pytest.mark.parametrize("command", ['generateSampleAssetsData', 'generateSampleRIGSData', 'generateSampleUserData',
'deleteSampleData'])
def test_production_exception(command): def test_production_exception(command):
from django.core.management.base import CommandError from django.core.management.base import CommandError
with pytest.raises(CommandError, match=".*production"): with pytest.raises(CommandError, match=".*production"):
call_command(command) call_command(command)
@pytest.mark.django_db
def test_sample_data(settings): def test_sample_data(settings):
settings.DEBUG = True settings.DEBUG = True
call_command('generateSampleData') call_command('generateSampleData')
@@ -22,6 +25,3 @@ def test_sample_data(settings):
call_command('deleteSampleData') call_command('deleteSampleData')
assert Asset.objects.all().count() == 0 assert Asset.objects.all().count() == 0
assert Event.objects.all().count() == 0 assert Event.objects.all().count() == 0
# Cleanup
call_command('flush', '--noinput')
call_command('migrate')

View File

@@ -10,6 +10,7 @@ from pytest_django.asserts import assertTemplateUsed, assertInHTML
from PyRIGS import urls from PyRIGS import urls
from RIGS.models import Event from RIGS.models import Event
from assets.models import Asset from assets.models import Asset
from django.db import connection
def find_urls_recursive(patterns): def find_urls_recursive(patterns):
@@ -46,11 +47,9 @@ def sample_data(django_db_blocker):
assert Asset.objects.all().count() > 50 assert Asset.objects.all().count() > 50
assert Event.objects.all().count() > 100 assert Event.objects.all().count() > 100
settings.DEBUG = False settings.DEBUG = False
yield
call_command('flush', '--noinput')
call_command('migrate')
@pytest.mark.django_db
def test_unauthenticated(client): # Nothing should be available to the unauthenticated def test_unauthenticated(client): # Nothing should be available to the unauthenticated
for url in find_urls_recursive(urls.urlpatterns): for url in find_urls_recursive(urls.urlpatterns):
request_url = get_request_url(url) request_url = get_request_url(url)
@@ -67,6 +66,7 @@ def test_unauthenticated(client): # Nothing should be available to the unauthen
assertRedirects(response, expected_url) assertRedirects(response, expected_url)
@pytest.mark.django_db
def test_page_titles(admin_client): def test_page_titles(admin_client):
for url in filter((lambda u: "embed" not in u.name), find_urls_recursive(urls.urlpatterns)): for url in filter((lambda u: "embed" not in u.name), find_urls_recursive(urls.urlpatterns)):
request_url = get_request_url(url) request_url = get_request_url(url)
@@ -81,6 +81,7 @@ def test_page_titles(admin_client):
# print(response.content.decode(), file=open('output.html', 'w')) # print(response.content.decode(), file=open('output.html', 'w'))
@pytest.mark.django_db
def test_basic_access(client): def test_basic_access(client):
client.logout() client.logout()
assert client.login(username="basic", password="basic") assert client.login(username="basic", password="basic")
@@ -92,14 +93,14 @@ def test_basic_access(client):
assertNotContains(response, assertNotContains(response,
'Duplicate') # If this line is randomly failing, check the debug toolbar HTML hasn't crept in 'Duplicate') # If this line is randomly failing, check the debug toolbar HTML hasn't crept in
url = reverse('asset_detail', kwargs={'pk': 1}) url = reverse('asset_detail', kwargs={'pk': Asset.objects.first().pk})
response = client.get(url) response = client.get(url)
assertNotContains(response, 'Purchase Details') assertNotContains(response, 'Purchase Details')
assertNotContains(response, 'View Revision History') assertNotContains(response, 'View Revision History')
urlz = {'asset_history', 'asset_update', 'asset_duplicate'} urlz = {'asset_history', 'asset_update', 'asset_duplicate'}
for url_name in urlz: for url_name in urlz:
request_url = reverse(url_name, kwargs={'pk': 1}) request_url = reverse(url_name, kwargs={'pk': Asset.objects.first().pk})
response = client.get(request_url, follow=True) response = client.get(request_url, follow=True)
assert response.status_code == 403 assert response.status_code == 403
@@ -113,6 +114,7 @@ def test_basic_access(client):
client.logout() client.logout()
@pytest.mark.django_db
def test_keyholder_access(client): def test_keyholder_access(client):
client.logout() client.logout()
assert client.login(username="keyholder", password="keyholder") assert client.login(username="keyholder", password="keyholder")
@@ -123,7 +125,7 @@ def test_keyholder_access(client):
assertContains(response, 'Edit') assertContains(response, 'Edit')
assertContains(response, 'Duplicate') assertContains(response, 'Duplicate')
url = reverse('asset_detail', kwargs={'pk': 1}) url = reverse('asset_detail', kwargs={'pk': Asset.objects.first().pk})
response = client.get(url) response = client.get(url)
assertContains(response, 'Purchase Details') assertContains(response, 'Purchase Details')
assertContains(response, 'View Revision History') assertContains(response, 'View Revision History')

View File

@@ -12,4 +12,3 @@ class Command(BaseCommand):
call_command('generateSampleUserData') call_command('generateSampleUserData')
call_command('generateSampleRIGSData') call_command('generateSampleRIGSData')
call_command('generateSampleAssetsData') call_command('generateSampleAssetsData')
call_command('createinitialrevisions')

View File

@@ -18,11 +18,7 @@ class Command(BaseCommand):
organisations = [] organisations = []
venues = [] venues = []
events = [] events = []
event_items = [] profiles = models.Profile.objects.all()
invoices = []
payments = []
ras = []
checklists = []
def handle(self, *args, **options): def handle(self, *args, **options):
from django.conf import settings from django.conf import settings
@@ -36,21 +32,12 @@ class Command(BaseCommand):
with transaction.atomic(): with transaction.atomic():
models.VatRate.objects.create(start_at='2014-03-05', rate=0.20, comment='test1') models.VatRate.objects.create(start_at='2014-03-05', rate=0.20, comment='test1')
self.setupPeople() self.setup_people()
models.Person.objects.bulk_create(self.people) self.setup_organisations()
self.setupOrganisations() self.setup_venues()
models.Organisation.objects.bulk_create(self.organisations) self.setup_events()
self.setupVenues()
models.Venue.objects.bulk_create(self.venues)
self.setupEvents()
models.Event.objects.bulk_create(self.events)
models.EventItem.objects.bulk_create(self.event_items)
models.Invoice.objects.bulk_create(self.invoices)
models.Payment.objects.bulk_create(self.payments)
models.RiskAssessment.objects.bulk_create(self.ras)
models.EventChecklist.objects.bulk_create(self.checklists)
def setupPeople(self): def setup_people(self):
names = ["Regulus Black", "Sirius Black", "Lavender Brown", "Cho Chang", "Vincent Crabbe", "Vincent Crabbe", names = ["Regulus Black", "Sirius Black", "Lavender Brown", "Cho Chang", "Vincent Crabbe", "Vincent Crabbe",
"Bartemius Crouch", "Fleur Delacour", "Cedric Diggory", "Alberforth Dumbledore", "Albus Dumbledore", "Bartemius Crouch", "Fleur Delacour", "Cedric Diggory", "Alberforth Dumbledore", "Albus Dumbledore",
"Dudley Dursley", "Petunia Dursley", "Vernon Dursley", "Argus Filch", "Seamus Finnigan", "Dudley Dursley", "Petunia Dursley", "Vernon Dursley", "Argus Filch", "Seamus Finnigan",
@@ -64,24 +51,26 @@ class Command(BaseCommand):
"Charlie Weasley", "Fred Weasley", "George Weasley", "Ginny Weasley", "Molly Weasley", "Percy Weasley", "Charlie Weasley", "Fred Weasley", "George Weasley", "Ginny Weasley", "Molly Weasley", "Percy Weasley",
"Ron Weasley", "Dobby", "Fluffy", "Hedwig", "Moaning Myrtle", "Aragog", "Grawp"] # noqa "Ron Weasley", "Dobby", "Fluffy", "Hedwig", "Moaning Myrtle", "Aragog", "Grawp"] # noqa
for i, name in enumerate(names): for i, name in enumerate(names):
pk = i + 1 with reversion.create_revision():
person = models.Person(pk=pk, name=name) reversion.set_user(random.choice(models.Profile.objects.all()))
person = models.Person.objects.create(name=name)
if i % 3 == 0: if i % 3 == 0:
person.email = "address@person.com" person.email = "address@person.com"
if i % 5 == 0: if i % 5 == 0:
person.notes = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua" person.notes = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"
if i % 7 == 0: if i % 7 == 0:
person.address = "1 Person Test Street \n Demoton \n United States of TEC \n RMRF 567" person.address = "1 Person Test Street \n Demoton \n United States of TEC \n RMRF 567"
if i % 9 == 0: if i % 9 == 0:
person.phone = "01234 567894" person.phone = "01234 567894"
self.people.append(person) person.save()
self.people.append(person)
def setupOrganisations(self): def setup_organisations(self):
names = ["Acme, inc.", "Widget Corp", "123 Warehousing", "Demo Company", "Smith and Co.", "Foo Bars", names = ["Acme, inc.", "Widget Corp", "123 Warehousing", "Demo Company", "Smith and Co.", "Foo Bars",
"ABC Telecom", "Fake Brothers", "QWERTY Logistics", "Demo, inc.", "Sample Company", "Sample, inc", "ABC Telecom", "Fake Brothers", "QWERTY Logistics", "Demo, inc.", "Sample Company", "Sample, inc",
"Acme Corp", "Allied Biscuit", "Ankh-Sto Associates", "Extensive Enterprise", "Galaxy Corp", "Acme Corp", "Allied Biscuit", "Ankh-Sto Associates", "Extensive Enterprise", "Galaxy Corp",
@@ -109,27 +98,29 @@ class Command(BaseCommand):
"Klimpys", "The Krusty Krab", "Monks Diner", "Milliways", "Minuteman Cafe", "Taco Grande", "Klimpys", "The Krusty Krab", "Monks Diner", "Milliways", "Minuteman Cafe", "Taco Grande",
"Tip Top Cafe", "Moes Tavern", "Central Perk", "Chasers"] # noqa "Tip Top Cafe", "Moes Tavern", "Central Perk", "Chasers"] # noqa
for i, name in enumerate(names): for i, name in enumerate(names):
pk = i + 1 with reversion.create_revision():
newOrganisation = models.Organisation(pk=pk, name=name) reversion.set_user(random.choice(models.Profile.objects.all()))
new_organisation = models.Organisation.objects.create(name=name)
if i % 2 == 0: if i % 2 == 0:
newOrganisation.has_su_account = True new_organisation.has_su_account = True
if i % 3 == 0: if i % 3 == 0:
newOrganisation.email = "address@organisation.com" new_organisation.email = "address@organisation.com"
if i % 5 == 0: if i % 5 == 0:
newOrganisation.notes = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua" new_organisation.notes = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"
if i % 7 == 0: if i % 7 == 0:
newOrganisation.address = "1 Organisation Test Street \n Demoton \n United States of TEC \n RMRF 567" new_organisation.address = "1 Organisation Test Street \n Demoton \n United States of TEC \n RMRF 567"
if i % 9 == 0: if i % 9 == 0:
newOrganisation.phone = "01234 567894" new_organisation.phone = "01234 567894"
self.organisations.append(newOrganisation) new_organisation.save()
self.organisations.append(new_organisation)
def setupVenues(self): def setup_venues(self):
names = ["Bear Island", "Crossroads Inn", "Deepwood Motte", "The Dreadfort", "The Eyrie", "Greywater Watch", names = ["Bear Island", "Crossroads Inn", "Deepwood Motte", "The Dreadfort", "The Eyrie", "Greywater Watch",
"The Iron Islands", "Karhold", "Moat Cailin", "Oldstones", "Raventree Hall", "Riverlands", "The Iron Islands", "Karhold", "Moat Cailin", "Oldstones", "Raventree Hall", "Riverlands",
"The Ruby Ford", "Saltpans", "Seagard", "Torrhen's Square", "The Trident", "The Twins", "The Ruby Ford", "Saltpans", "Seagard", "Torrhen's Square", "The Trident", "The Twins",
@@ -143,27 +134,29 @@ class Command(BaseCommand):
"Qohor", "The Red Waste", "Tyrosh", "Vaes Dothrak", "Valyria", "Village of the Lhazareen", "Volantis", "Qohor", "The Red Waste", "Tyrosh", "Vaes Dothrak", "Valyria", "Village of the Lhazareen", "Volantis",
"Yunkai"] # noqa "Yunkai"] # noqa
for i, name in enumerate(names): for i, name in enumerate(names):
pk = i + 1 with reversion.create_revision():
newVenue = models.Venue(pk=pk, name=name) reversion.set_user(random.choice(self.profiles))
new_venue = models.Venue.objects.create(name=name)
if i % 2 == 0: if i % 2 == 0:
newVenue.three_phase_available = True new_venue.three_phase_available = True
if i % 3 == 0: if i % 3 == 0:
newVenue.email = "address@venue.com" new_venue.email = "address@venue.com"
if i % 5 == 0: if i % 5 == 0:
newVenue.notes = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua" new_venue.notes = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"
if i % 7 == 0: if i % 7 == 0:
newVenue.address = "1 Venue Test Street \n Demoton \n United States of TEC \n RMRF 567" new_venue.address = "1 Venue Test Street \n Demoton \n United States of TEC \n RMRF 567"
if i % 9 == 0: if i % 9 == 0:
newVenue.phone = "01234 567894" new_venue.phone = "01234 567894"
self.venues.append(newVenue) new_venue.save()
self.venues.append(new_venue)
def setupEvents(self): def setup_events(self):
names = ["Outdoor Concert", "Hall Open Mic Night", "Festival", "Weekend Event", "Magic Show", "Society Ball", names = ["Outdoor Concert", "Hall Open Mic Night", "Festival", "Weekend Event", "Magic Show", "Society Ball",
"Evening Show", "Talent Show", "Acoustic Evening", "Hire of Things", "SU Event", "Evening Show", "Talent Show", "Acoustic Evening", "Hire of Things", "SU Event",
"End of Term Show", "Theatre Show", "Outdoor Fun Day", "Summer Carnival", "Open Days", "Magic Show", "End of Term Show", "Theatre Show", "Outdoor Fun Day", "Summer Carnival", "Open Days", "Magic Show",
@@ -174,7 +167,7 @@ class Command(BaseCommand):
notes = ["The client came into the office at some point", "Who knows if this will happen", notes = ["The client came into the office at some point", "Who knows if this will happen",
"Probably should check this event", "Maybe not happening", "Run away!"] "Probably should check this event", "Maybe not happening", "Run away!"]
itemOptions = [ item_options = [
{'name': 'Speakers', 'description': 'Some really really big speakers \n these are very loud', 'quantity': 2, {'name': 'Speakers', 'description': 'Some really really big speakers \n these are very loud', 'quantity': 2,
'cost': 200.00}, 'cost': 200.00},
{'name': 'Projector', {'name': 'Projector',
@@ -191,107 +184,108 @@ class Command(BaseCommand):
{'name': 'Crew', 'description': 'Costs nothing, because reasons', 'quantity': 1, 'cost': 0.00}, {'name': 'Crew', 'description': 'Costs nothing, because reasons', 'quantity': 1, 'cost': 0.00},
{'name': 'Loyalty Discount', 'description': 'Have some negative moneys', 'quantity': 1, 'cost': -50.00}] {'name': 'Loyalty Discount', 'description': 'Have some negative moneys', 'quantity': 1, 'cost': -50.00}]
dayDelta = -120 # start adding events from 4 months ago day_delta = -120 # start adding events from 4 months ago
item_pk = 0
for i in range(150): # Let's add 100 events for i in range(150): # Let's add 100 events
pk = i + 1 with reversion.create_revision():
name = names[i % len(names)] reversion.set_user(random.choice(self.profiles))
startDate = datetime.date.today() + datetime.timedelta(days=dayDelta) name = names[i % len(names)]
dayDelta = dayDelta + random.randint(0, 3)
newEvent = models.Event(pk=pk, name=name, start_date=startDate) start_date = datetime.date.today() + datetime.timedelta(days=day_delta)
day_delta = day_delta + random.randint(0, 3)
if random.randint(0, 2) > 1: # 1 in 3 have a start time new_event = models.Event.objects.create(name=name, start_date=start_date)
newEvent.start_time = datetime.time(random.randint(15, 20))
if random.randint(0, 2) > 1: # of those, 1 in 3 have an end time on the same day
newEvent.end_time = datetime.time(random.randint(21, 23))
elif random.randint(0, 1) > 0: # half of the others finish early the next day
newEvent.end_date = newEvent.start_date + datetime.timedelta(days=1)
newEvent.end_time = datetime.time(random.randint(0, 5))
elif random.randint(0, 2) > 1: # 1 in 3 of the others finish a few days ahead
newEvent.end_date = newEvent.start_date + datetime.timedelta(days=random.randint(1, 4))
if random.randint(0, 6) > 0: # 5 in 6 have MIC if random.randint(0, 2) > 1: # 1 in 3 have a start time
newEvent.mic = random.choice(models.Profile.objects.all()) new_event.start_time = datetime.time(random.randint(15, 20))
if random.randint(0, 2) > 1: # of those, 1 in 3 have an end time on the same day
new_event.end_time = datetime.time(random.randint(21, 23))
elif random.randint(0, 1) > 0: # half of the others finish early the next day
new_event.end_date = new_event.start_date + datetime.timedelta(days=1)
new_event.end_time = datetime.time(random.randint(0, 5))
elif random.randint(0, 2) > 1: # 1 in 3 of the others finish a few days ahead
new_event.end_date = new_event.start_date + datetime.timedelta(days=random.randint(1, 4))
if random.randint(0, 6) > 0: # 5 in 6 have organisation if random.randint(0, 6) > 0: # 5 in 6 have MIC
newEvent.organisation = random.choice(self.organisations) new_event.mic = random.choice(self.profiles)
if random.randint(0, 6) > 0: # 5 in 6 have person if random.randint(0, 6) > 0: # 5 in 6 have organisation
newEvent.person = random.choice(self.people) new_event.organisation = random.choice(self.organisations)
if random.randint(0, 6) > 0: # 5 in 6 have venue if random.randint(0, 6) > 0: # 5 in 6 have person
newEvent.venue = random.choice(self.venues) new_event.person = random.choice(self.people)
# Could have any status, equally weighted if random.randint(0, 6) > 0: # 5 in 6 have venue
newEvent.status = random.choice( new_event.venue = random.choice(self.venues)
[models.Event.BOOKED, models.Event.CONFIRMED, models.Event.PROVISIONAL, models.Event.CANCELLED])
newEvent.dry_hire = (random.randint(0, 7) == 0) # 1 in 7 are dry hire # Could have any status, equally weighted
new_event.status = random.choice(
[models.Event.BOOKED, models.Event.CONFIRMED, models.Event.PROVISIONAL, models.Event.CANCELLED])
if random.randint(0, 1) > 0: # 1 in 2 have description new_event.dry_hire = (random.randint(0, 7) == 0) # 1 in 7 are dry hire
newEvent.description = random.choice(descriptions)
if random.randint(0, 1) > 0: # 1 in 2 have notes if random.randint(0, 1) > 0: # 1 in 2 have description
newEvent.notes = random.choice(notes) new_event.description = random.choice(descriptions)
self.events.append(newEvent) if random.randint(0, 1) > 0: # 1 in 2 have notes
new_event.notes = random.choice(notes)
# Now add some items new_event.save()
for j in range(random.randint(1, 5)):
itemData = itemOptions[random.randint(0, len(itemOptions) - 1)]
newItem = models.EventItem(pk=item_pk, event=newEvent, order=j, **itemData)
item_pk += 1
self.event_items.append(newItem)
# while newEvent.sum_total < 0: # Now add some items
# itemData = itemOptions[random.randint(0, len(itemOptions) - 1)] for j in range(random.randint(1, 5)):
# newItem = models.EventItem(pk=pk + j + 150, event=newEvent, order=j, **itemData) item_data = item_options[random.randint(0, len(item_options) - 1)]
# self.event_items.append(newItem) new_item = models.EventItem.objects.create(event=new_event, order=j, **item_data)
new_item.save()
if newEvent.start_date < datetime.date.today(): # think about adding an invoice while new_event.sum_total < 0:
if random.randint(0, 2) > 0: # 2 in 3 have had paperwork sent to treasury item_data = item_options[random.randint(0, len(item_options) - 1)]
newInvoice = models.Invoice(pk=pk, event=newEvent) new_item = models.EventItem.objects.create(event=new_event, order=j, **item_data)
if newEvent.status is models.Event.CANCELLED: # void cancelled events new_item.save()
newInvoice.void = True
elif random.randint(0, 2) > 1: # 1 in 3 have been paid with reversion.create_revision():
self.payments.append(models.Payment(pk=pk, invoice=newInvoice, amount=newInvoice.balance, reversion.set_user(random.choice(self.profiles))
date=datetime.date.today())) if new_event.start_date < datetime.date.today(): # think about adding an invoice
self.invoices.append(newInvoice) if random.randint(0, 2) > 0: # 2 in 3 have had paperwork sent to treasury
new_invoice = models.Invoice.objects.create(event=new_event)
if new_event.status is models.Event.CANCELLED: # void cancelled events
new_invoice.void = True
elif random.randint(0, 2) > 1: # 1 in 3 have been paid
models.Payment.objects.create(invoice=new_invoice, amount=new_invoice.balance,
date=datetime.date.today())
if i == 1 or random.randint(0, 5) > 0: # Event 1 and 1 in 5 have a RA if i == 1 or random.randint(0, 5) > 0: # Event 1 and 1 in 5 have a RA
self.ras.append( models.RiskAssessment.objects.create(event=new_event, supervisor_consulted=bool(random.getrandbits(1)),
models.RiskAssessment(pk=pk, event=newEvent, supervisor_consulted=bool(random.getrandbits(1)), nonstandard_equipment=bool(random.getrandbits(1)),
nonstandard_equipment=bool(random.getrandbits(1)), nonstandard_use=bool(random.getrandbits(1)),
nonstandard_use=bool(random.getrandbits(1)), contractors=bool(random.getrandbits(1)),
contractors=bool(random.getrandbits(1)), other_companies=bool(random.getrandbits(1)),
other_companies=bool(random.getrandbits(1)), crew_fatigue=bool(random.getrandbits(1)),
crew_fatigue=bool(random.getrandbits(1)), big_power=bool(random.getrandbits(1)),
big_power=bool(random.getrandbits(1)), generators=bool(random.getrandbits(1)),
generators=bool(random.getrandbits(1)), other_companies_power=bool(random.getrandbits(1)),
other_companies_power=bool(random.getrandbits(1)), nonstandard_equipment_power=bool(random.getrandbits(1)),
nonstandard_equipment_power=bool(random.getrandbits(1)), multiple_electrical_environments=bool(random.getrandbits(1)),
multiple_electrical_environments=bool(random.getrandbits(1)), noise_monitoring=bool(random.getrandbits(1)),
noise_monitoring=bool(random.getrandbits(1)), known_venue=bool(random.getrandbits(1)),
known_venue=bool(random.getrandbits(1)), safe_loading=bool(random.getrandbits(1)),
safe_loading=bool(random.getrandbits(1)), safe_storage=bool(random.getrandbits(1)),
safe_storage=bool(random.getrandbits(1)), area_outside_of_control=bool(random.getrandbits(1)),
area_outside_of_control=bool(random.getrandbits(1)), barrier_required=bool(random.getrandbits(1)),
barrier_required=bool(random.getrandbits(1)), nonstandard_emergency_procedure=bool(random.getrandbits(1)),
nonstandard_emergency_procedure=bool(random.getrandbits(1)), special_structures=bool(random.getrandbits(1)),
special_structures=bool(random.getrandbits(1)), suspended_structures=bool(random.getrandbits(1)),
suspended_structures=bool(random.getrandbits(1)), outside=bool(random.getrandbits(1)))
outside=bool(random.getrandbits(1))))
if i == 0 or random.randint(0, 1) > 0: # Event 1 and 1 in 10 have a Checklist if i == 0 or random.randint(0, 1) > 0: # Event 1 and 1 in 10 have a Checklist
self.checklists.append( models.EventChecklist.objects.create(event=new_event, power_mic=random.choice(self.profiles),
models.EventChecklist(pk=pk, event=newEvent, power_mic=random.choice(models.Profile.objects.all()), safe_parking=bool(random.getrandbits(1)),
safe_parking=bool(random.getrandbits(1)), safe_packing=bool(random.getrandbits(1)),
safe_packing=bool(random.getrandbits(1)), exits=bool(random.getrandbits(1)),
exits=bool(random.getrandbits(1)), trip_hazard=bool(random.getrandbits(1)),
trip_hazard=bool(random.getrandbits(1)), warning_signs=bool(random.getrandbits(1)),
warning_signs=bool(random.getrandbits(1)), ear_plugs=bool(random.getrandbits(1)),
ear_plugs=bool(random.getrandbits(1)), hs_location="Locked away safely", hs_location="Locked away safely",
extinguishers_location="Somewhere, I forgot", extinguishers_location="Somewhere, I forgot",
earthing=bool(random.getrandbits(1)), pat=bool(random.getrandbits(1)), earthing=bool(random.getrandbits(1)),
date=timezone.now(), venue=random.choice(self.venues))) pat=bool(random.getrandbits(1)),
date=timezone.now(), venue=random.choice(self.venues))

View File

@@ -13,17 +13,18 @@ def basic_event(db):
@pytest.fixture @pytest.fixture
def ra(basic_event, admin_user): def ra(basic_event, admin_user):
ra = models.RiskAssessment.objects.create(event=basic_event, nonstandard_equipment=False, nonstandard_use=False, ra = models.RiskAssessment.objects.create(event=basic_event, nonstandard_equipment=False, nonstandard_use=False,
contractors=False, other_companies=False, crew_fatigue=False, contractors=False, other_companies=False, crew_fatigue=False,
big_power=False, power_mic=admin_user, generators=False, big_power=False, power_mic=admin_user, generators=False,
other_companies_power=False, nonstandard_equipment_power=False, other_companies_power=False, nonstandard_equipment_power=False,
multiple_electrical_environments=False, noise_monitoring=False, multiple_electrical_environments=False, noise_monitoring=False,
known_venue=True, safe_loading=True, safe_storage=True, known_venue=True, safe_loading=True, safe_storage=True,
area_outside_of_control=True, barrier_required=True, area_outside_of_control=True, barrier_required=True,
nonstandard_emergency_procedure=True, special_structures=False, nonstandard_emergency_procedure=True, special_structures=False,
suspended_structures=False, outside=False) suspended_structures=False, outside=False)
yield ra yield ra
ra.delete() ra.delete()
@pytest.fixture @pytest.fixture
def venue(db): def venue(db):
venue = models.Venue.objects.create(name="Venue 1") venue = models.Venue.objects.create(name="Venue 1")
@@ -34,10 +35,10 @@ def venue(db):
@pytest.fixture # TODO parameterise with Event sizes @pytest.fixture # TODO parameterise with Event sizes
def checklist(basic_event, venue, admin_user): def checklist(basic_event, venue, admin_user):
checklist = models.EventChecklist.objects.create(event=basic_event, power_mic=admin_user, safe_parking=False, checklist = models.EventChecklist.objects.create(event=basic_event, power_mic=admin_user, safe_parking=False,
safe_packing=False, exits=False, trip_hazard=False, warning_signs=False, safe_packing=False, exits=False, trip_hazard=False, warning_signs=False,
ear_plugs=False, hs_location="Locked away safely", ear_plugs=False, hs_location="Locked away safely",
extinguishers_location="Somewhere, I forgot", earthing=False, pat=False, extinguishers_location="Somewhere, I forgot", earthing=False, pat=False,
date=timezone.now(), venue=venue) date=timezone.now(), venue=venue)
yield checklist yield checklist
checklist.delete() checklist.delete()
@@ -45,54 +46,54 @@ def checklist(basic_event, venue, admin_user):
@pytest.fixture @pytest.fixture
def many_events(db, scope="class"): def many_events(db, scope="class"):
many_events = { many_events = {
# produce 7 normal events - 5 current # produce 7 normal events - 5 current
1: models.Event.objects.create(name="TE E1", start_date=date.today() + timedelta(days=6), 1: models.Event.objects.create(name="TE E1", start_date=date.today() + timedelta(days=6),
description="start future no end"), description="start future no end"),
2: models.Event.objects.create(name="TE E2", start_date=date.today(), description="start today no end"), 2: models.Event.objects.create(name="TE E2", start_date=date.today(), description="start today no end"),
3: models.Event.objects.create(name="TE E3", start_date=date.today(), end_date=date.today(), 3: models.Event.objects.create(name="TE E3", start_date=date.today(), end_date=date.today(),
description="start today with end today"), description="start today with end today"),
4: models.Event.objects.create(name="TE E4", start_date='2014-03-20', description="start past no end"), 4: models.Event.objects.create(name="TE E4", start_date='2014-03-20', description="start past no end"),
5: models.Event.objects.create(name="TE E5", start_date='2014-03-20', end_date='2014-03-21', 5: models.Event.objects.create(name="TE E5", start_date='2014-03-20', end_date='2014-03-21',
description="start past with end past"), description="start past with end past"),
6: models.Event.objects.create(name="TE E6", start_date=date.today() - timedelta(days=2), 6: models.Event.objects.create(name="TE E6", start_date=date.today() - timedelta(days=2),
end_date=date.today() + timedelta(days=2), end_date=date.today() + timedelta(days=2),
description="start past, end future"), description="start past, end future"),
7: models.Event.objects.create(name="TE E7", start_date=date.today() + timedelta(days=2), 7: models.Event.objects.create(name="TE E7", start_date=date.today() + timedelta(days=2),
end_date=date.today() + timedelta(days=2), end_date=date.today() + timedelta(days=2),
description="start + end in future"), description="start + end in future"),
# 2 cancelled - 1 current # 2 cancelled - 1 current
8: models.Event.objects.create(name="TE E8", start_date=date.today() + timedelta(days=2), 8: models.Event.objects.create(name="TE E8", start_date=date.today() + timedelta(days=2),
end_date=date.today() + timedelta(days=2), status=models.Event.CANCELLED, end_date=date.today() + timedelta(days=2), status=models.Event.CANCELLED,
description="cancelled in future"), description="cancelled in future"),
9: models.Event.objects.create(name="TE E9", start_date=date.today() - timedelta(days=1), 9: models.Event.objects.create(name="TE E9", start_date=date.today() - timedelta(days=1),
end_date=date.today() + timedelta(days=2), status=models.Event.CANCELLED, end_date=date.today() + timedelta(days=2), status=models.Event.CANCELLED,
description="cancelled and started"), description="cancelled and started"),
# 5 dry hire - 3 current # 5 dry hire - 3 current
10: models.Event.objects.create(name="TE E10", start_date=date.today(), dry_hire=True, 10: models.Event.objects.create(name="TE E10", start_date=date.today(), dry_hire=True,
description="dryhire today"), description="dryhire today"),
11: models.Event.objects.create(name="TE E11", start_date=date.today(), dry_hire=True, 11: models.Event.objects.create(name="TE E11", start_date=date.today(), dry_hire=True,
checked_in_by=cls.profile, checked_in_by=cls.profile,
description="dryhire today, checked in"), description="dryhire today, checked in"),
12: models.Event.objects.create(name="TE E12", start_date=date.today() - timedelta(days=1), dry_hire=True, 12: models.Event.objects.create(name="TE E12", start_date=date.today() - timedelta(days=1), dry_hire=True,
status=models.Event.BOOKED, description="dryhire past"), status=models.Event.BOOKED, description="dryhire past"),
13: models.Event.objects.create(name="TE E13", start_date=date.today() - timedelta(days=2), dry_hire=True, 13: models.Event.objects.create(name="TE E13", start_date=date.today() - timedelta(days=2), dry_hire=True,
checked_in_by=cls.profile, description="dryhire past checked in"), checked_in_by=cls.profile, description="dryhire past checked in"),
14: models.Event.objects.create(name="TE E14", start_date=date.today(), dry_hire=True, 14: models.Event.objects.create(name="TE E14", start_date=date.today(), dry_hire=True,
status=models.Event.CANCELLED, description="dryhire today cancelled"), status=models.Event.CANCELLED, description="dryhire today cancelled"),
# 4 non rig - 3 current # 4 non rig - 3 current
15: models.Event.objects.create(name="TE E15", start_date=date.today(), is_rig=False, 15: models.Event.objects.create(name="TE E15", start_date=date.today(), is_rig=False,
description="non rig today"), description="non rig today"),
16: models.Event.objects.create(name="TE E16", start_date=date.today() + timedelta(days=1), is_rig=False, 16: models.Event.objects.create(name="TE E16", start_date=date.today() + timedelta(days=1), is_rig=False,
description="non rig tomorrow"), description="non rig tomorrow"),
17: models.Event.objects.create(name="TE E17", start_date=date.today() - timedelta(days=1), is_rig=False, 17: models.Event.objects.create(name="TE E17", start_date=date.today() - timedelta(days=1), is_rig=False,
description="non rig yesterday"), description="non rig yesterday"),
18: models.Event.objects.create(name="TE E18", start_date=date.today(), is_rig=False, 18: models.Event.objects.create(name="TE E18", start_date=date.today(), is_rig=False,
status=models.Event.CANCELLED, status=models.Event.CANCELLED,
description="non rig today cancelled"), description="non rig today cancelled"),
} }
yield many_events yield many_events
for event in many_events: for event in many_events:
event.delete() event.delete()

View File

@@ -854,7 +854,6 @@ class TestHealthAndSafety(BaseRigboardTest):
self.page.submit() self.page.submit()
self.assertTrue(self.page.success) self.assertTrue(self.page.success)
def test_ec_create_extras(self): def test_ec_create_extras(self):
eid = self.testEvent2.pk eid = self.testEvent2.pk
self.page = pages.CreateEventChecklist(self.driver, self.live_server_url, event_id=eid).open() self.page = pages.CreateEventChecklist(self.driver, self.live_server_url, event_id=eid).open()

View File

@@ -35,7 +35,7 @@ def test_percent_correct(vat_rate):
def test_related_vatrate(basic_event, vat_rate): def test_related_vatrate(basic_event, vat_rate):
assert vat_rate.pk == basic_event.vat_rate.pk assert_decimal_equality(vat_rate.rate, basic_event.vat_rate.rate)
class EventTest(): class EventTest():
@@ -43,12 +43,10 @@ class EventTest():
# Sanity check we have the expected events created # Sanity check we have the expected events created
assert models.Event.objects.count() == 18 assert models.Event.objects.count() == 18
def test_rig_count(many_events): def test_rig_count(many_events):
# Changed to not include unreturned dry hires in rig count # Changed to not include unreturned dry hires in rig count
assert models.Event.objects.rig_count() == 7 assert models.Event.objects.rig_count() == 7
def test_current_events(many_events): def test_current_events(many_events):
all_events = set(range(1, 18)) all_events = set(range(1, 18))
current_events = (1, 2, 3, 6, 7, 8, 10, 11, 12, 14, 15, 16, 18) current_events = (1, 2, 3, 6, 7, 8, 10, 11, 12, 14, 15, 16, 18)
@@ -61,7 +59,6 @@ class EventTest():
for eid in not_current_events: for eid in not_current_events:
assert models.Event.objects.get(name="TE E%d" % eid) not in current_events assert models.Event.objects.get(name="TE E%d" % eid) not in current_events
def test_related(many_events): def test_related(many_events):
v1 = models.Venue.objects.create(name="TE V1") v1 = models.Venue.objects.create(name="TE V1")
v2 = models.Venue.objects.create(name="TE V2") v2 = models.Venue.objects.create(name="TE V2")
@@ -83,7 +80,6 @@ class EventTest():
v1.delete() v1.delete()
v2.delete() v2.delete()
def test_related_person(many_events): def test_related_person(many_events):
p1 = models.Person.objects.create(name="TE P1") p1 = models.Person.objects.create(name="TE P1")
p2 = models.Person.objects.create(name="TE P2") p2 = models.Person.objects.create(name="TE P2")
@@ -105,7 +101,6 @@ class EventTest():
p1.delete() p1.delete()
p2.delete() p2.delete()
def test_related_organisation(many_events): def test_related_organisation(many_events):
o1 = models.Organisation.objects.create(name="TE O1") o1 = models.Organisation.objects.create(name="TE O1")
o2 = models.Organisation.objects.create(name="TE O2") o2 = models.Organisation.objects.create(name="TE O2")
@@ -205,6 +200,7 @@ def test_earliest_time():
event.start_date = date(2015, 12, 0o3) event.start_date = date(2015, 12, 0o3)
assert event.earliest_time == create_datetime(2015, 12, 0o3, 9, 00) assert event.earliest_time == create_datetime(2015, 12, 0o3, 9, 00)
def test_latest_time(): def test_latest_time():
event = models.Event(name="TE LT", start_date=date(2016, 0o1, 0o1)) event = models.Event(name="TE LT", start_date=date(2016, 0o1, 0o1))
@@ -219,6 +215,7 @@ def test_latest_time():
event.end_time = time(23, 00) event.end_time = time(23, 00)
assert event.latest_time == create_datetime(2016, 1, 2, 23, 00) assert event.latest_time == create_datetime(2016, 1, 2, 23, 00)
def test_in_bounds(): def test_in_bounds():
manager = models.Event.objects manager = models.Event.objects
events = [ events = [

View File

@@ -299,7 +299,6 @@ def test_oembed(client, basic_event):
assert_oembed(alt_event_embed_url, alt_oembed_url, client, event_embed_url, event_url, oembed_url) assert_oembed(alt_event_embed_url, alt_oembed_url, client, event_embed_url, event_url, oembed_url)
def search(client, url, found, notfound, arguments): def search(client, url, found, notfound, arguments):
for argument in arguments: for argument in arguments:
query = getattr(found, argument) query = getattr(found, argument)

View File

@@ -1,13 +1,12 @@
import random import random
from django.core.management.base import BaseCommand, CommandError from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from django.db import transaction from django.db import transaction
from django.utils import timezone
from reversion import revisions as reversion from reversion import revisions as reversion
from RIGS import models as rigsmodels from RIGS import models as rigsmodels
from assets import models from assets import models
from assets.signals import split_asset_id
class Command(BaseCommand): class Command(BaseCommand):
@@ -17,7 +16,6 @@ class Command(BaseCommand):
statuses = [] statuses = []
suppliers = [] suppliers = []
connectors = [] connectors = []
cable_types = []
assets = [] assets = []
def handle(self, *args, **kwargs): def handle(self, *args, **kwargs):
@@ -28,100 +26,53 @@ class Command(BaseCommand):
random.seed('Some object to see the random number generator') random.seed('Some object to see the random number generator')
# with transaction.atomic(): This is redundant since its all bulk create with transaction.atomic():
self.create_categories() self.create_categories()
models.AssetCategory.objects.bulk_create(self.categories) self.create_statuses()
self.create_statuses() self.create_suppliers()
models.AssetStatus.objects.bulk_create(self.statuses) self.create_assets()
self.create_suppliers() self.create_connectors()
models.Supplier.objects.bulk_create(self.suppliers) self.create_cables()
self.create_assets()
self.create_connectors()
models.Connector.objects.bulk_create(self.connectors)
self.create_cable_types()
models.CableType.objects.bulk_create(self.cable_types)
self.create_cables()
models.Asset.objects.bulk_create(self.assets)
def create_statuses(self): def create_statuses(self):
choices = [('In Service', True, 'success'), ('Lost', False, 'warning'), ('Binned', False, 'danger'), ('Sold', False, 'danger'), ('Broken', False, 'warning')] choices = [('In Service', True, 'success'), ('Lost', False, 'warning'), ('Binned', False, 'danger'), ('Sold', False, 'danger'), ('Broken', False, 'warning')]
pk = 1
for stat in choices: for stat in choices:
self.statuses.append(models.AssetStatus(pk=pk, name=stat[0], should_show=stat[1], display_class=stat[2])) self.statuses.append(models.AssetStatus.objects.create(name=stat[0], should_show=stat[1], display_class=stat[2]))
pk += 1
def create_suppliers(self): def create_suppliers(self):
choices = ["Acme, inc.", "Widget Corp", "123 Warehousing", "Demo Company", "Smith and Co.", "Foo Bars", "ABC Telecom", "Fake Brothers", "QWERTY Logistics", "Demo, inc.", "Sample Company", "Sample, inc", "Acme Corp", "Allied Biscuit", "Ankh-Sto Associates", "Extensive Enterprise", "Galaxy Corp", "Globo-Chem", "Mr. Sparkle", "Globex Corporation", "LexCorp", "LuthorCorp", "North Central Positronics", "Omni Consimer Products", "Praxis Corporation", "Sombra Corporation", "Sto Plains Holdings", "Tessier-Ashpool", "Wayne Enterprises", "Wentworth Industries", "ZiffCorp", "Bluth Company", "Strickland Propane", "Thatherton Fuels", "Three Waters", "Water and Power", "Western Gas & Electric", "Mammoth Pictures", "Mooby Corp", "Gringotts", "Thrift Bank", "Flowers By Irene", "The Legitimate Businessmens Club", "Osato Chemicals", "Transworld Consortium", "Universal Export", "United Fried Chicken", "Virtucon", "Kumatsu Motors", "Keedsler Motors", "Powell Motors", "Industrial Automation", "Sirius Cybernetics Corporation", "U.S. Robotics and Mechanical Men", "Colonial Movers", "Corellian Engineering Corporation", "Incom Corporation", "General Products", "Leeding Engines Ltd.", "Blammo", # noqa choices = ["Acme, inc.", "Widget Corp", "123 Warehousing", "Demo Company", "Smith and Co.", "Foo Bars", "ABC Telecom", "Fake Brothers", "QWERTY Logistics", "Demo, inc.", "Sample Company", "Sample, inc", "Acme Corp", "Allied Biscuit", "Ankh-Sto Associates", "Extensive Enterprise", "Galaxy Corp", "Globo-Chem", "Mr. Sparkle", "Globex Corporation", "LexCorp", "LuthorCorp", "North Central Positronics", "Omni Consimer Products", "Praxis Corporation", "Sombra Corporation", "Sto Plains Holdings", "Tessier-Ashpool", "Wayne Enterprises", "Wentworth Industries", "ZiffCorp", "Bluth Company", "Strickland Propane", "Thatherton Fuels", "Three Waters", "Water and Power", "Western Gas & Electric", "Mammoth Pictures", "Mooby Corp", "Gringotts", "Thrift Bank", "Flowers By Irene", "The Legitimate Businessmens Club", "Osato Chemicals", "Transworld Consortium", "Universal Export", "United Fried Chicken", "Virtucon", "Kumatsu Motors", "Keedsler Motors", "Powell Motors", "Industrial Automation", "Sirius Cybernetics Corporation", "U.S. Robotics and Mechanical Men", "Colonial Movers", "Corellian Engineering Corporation", "Incom Corporation", "General Products", "Leeding Engines Ltd.", "Blammo", # noqa
"Input, Inc.", "Mainway Toys", "Videlectrix", "Zevo Toys", "Ajax", "Axis Chemical Co.", "Barrytron", "Carrys Candles", "Cogswell Cogs", "Spacely Sprockets", "General Forge and Foundry", "Duff Brewing Company", "Dunder Mifflin", "General Services Corporation", "Monarch Playing Card Co.", "Krustyco", "Initech", "Roboto Industries", "Primatech", "Sonky Rubber Goods", "St. Anky Beer", "Stay Puft Corporation", "Vandelay Industries", "Wernham Hogg", "Gadgetron", "Burleigh and Stronginthearm", "BLAND Corporation", "Nordyne Defense Dynamics", "Petrox Oil Company", "Roxxon", "McMahon and Tate", "Sixty Second Avenue", "Charles Townsend Agency", "Spade and Archer", "Megadodo Publications", "Rouster and Sideways", "C.H. Lavatory and Sons", "Globo Gym American Corp", "The New Firm", "SpringShield", "Compuglobalhypermeganet", "Data Systems", "Gizmonic Institute", "Initrode", "Taggart Transcontinental", "Atlantic Northern", "Niagular", "Plow King", "Big Kahuna Burger", "Big T Burgers and Fries", "Chez Quis", "Chotchkies", "The Frying Dutchman", "Klimpys", "The Krusty Krab", "Monks Diner", "Milliways", "Minuteman Cafe", "Taco Grande", "Tip Top Cafe", "Moes Tavern", "Central Perk", "Chasers"] # noqa "Input, Inc.", "Mainway Toys", "Videlectrix", "Zevo Toys", "Ajax", "Axis Chemical Co.", "Barrytron", "Carrys Candles", "Cogswell Cogs", "Spacely Sprockets", "General Forge and Foundry", "Duff Brewing Company", "Dunder Mifflin", "General Services Corporation", "Monarch Playing Card Co.", "Krustyco", "Initech", "Roboto Industries", "Primatech", "Sonky Rubber Goods", "St. Anky Beer", "Stay Puft Corporation", "Vandelay Industries", "Wernham Hogg", "Gadgetron", "Burleigh and Stronginthearm", "BLAND Corporation", "Nordyne Defense Dynamics", "Petrox Oil Company", "Roxxon", "McMahon and Tate", "Sixty Second Avenue", "Charles Townsend Agency", "Spade and Archer", "Megadodo Publications", "Rouster and Sideways", "C.H. Lavatory and Sons", "Globo Gym American Corp", "The New Firm", "SpringShield", "Compuglobalhypermeganet", "Data Systems", "Gizmonic Institute", "Initrode", "Taggart Transcontinental", "Atlantic Northern", "Niagular", "Plow King", "Big Kahuna Burger", "Big T Burgers and Fries", "Chez Quis", "Chotchkies", "The Frying Dutchman", "Klimpys", "The Krusty Krab", "Monks Diner", "Milliways", "Minuteman Cafe", "Taco Grande", "Tip Top Cafe", "Moes Tavern", "Central Perk", "Chasers"] # noqa
pk = 1 pk = 1
for supplier in choices: for supplier in choices:
self.suppliers.append(models.Supplier(pk=pk, name=supplier)) self.suppliers.append(models.Supplier.objects.create(name=supplier))
pk += 1 pk += 1
def create_categories(self): def create_categories(self):
choices = ['Case', 'Video', 'General', 'Sound', 'Lighting', 'Rigging'] choices = ['Case', 'Video', 'General', 'Sound', 'Lighting', 'Rigging']
pk = models.AssetCategory.objects.count() + 10
for cat in choices: for cat in choices:
self.categories.append(models.AssetCategory(pk=pk, name=cat)) self.categories.append(models.AssetCategory.objects.create(name=cat))
pk += 1
def create_assets(self): def create_assets(self):
asset_description = ['Large cable', 'Shiny thing', 'New lights', 'Really expensive microphone', 'Box of fuse flaps', 'Expensive tool we didn\'t agree to buy', 'Cable drums', 'Boring amount of tape', 'Video stuff no one knows how to use', 'More amplifiers', 'Heatshrink'] asset_description = ['Large cable', 'Shiny thing', 'New lights', 'Really expensive microphone', 'Box of fuse flaps', 'Expensive tool we didn\'t agree to buy', 'Cable drums', 'Boring amount of tape', 'Video stuff no one knows how to use', 'More amplifiers', 'Heatshrink']
pk = 1
for i in range(100):
asset_search = split_asset_id(str(pk))
asset = models.Asset(
pk=pk,
asset_id=str(pk),
asset_id_prefix = asset_search.group(1),
asset_id_number = int(asset_search.group(2)),
description=random.choice(asset_description),
category=random.choice(self.categories),
status=random.choice(self.statuses),
date_acquired=timezone.now().date()
)
if i % 4 == 0 and self.assets: with reversion.create_revision():
asset.parent = random.choice(self.assets) for i in range(100):
reversion.set_user(random.choice(rigsmodels.Profile.objects.all()))
asset = models.Asset(
asset_id='{}'.format(get_available_asset_id()),
description=random.choice(asset_description),
category=random.choice(self.categories),
status=random.choice(self.statuses),
date_acquired=timezone.now().date()
)
if i % 3 == 0: if i % 4 == 0:
asset.purchased_from = random.choice(self.suppliers) asset.parent = models.Asset.objects.order_by('?').first()
self.assets.append(asset)
pk += 1
def create_cables(self): if i % 3 == 0:
asset_description = ['The worm', 'Harting without a cap', 'Heavy cable', 'Extension lead', 'IEC cable that we should remember to prep'] asset.purchased_from = random.choice(suppliers)
asset_prefixes = ["C", "C4P", "CBNC", "CDMX", "CDV", "CRCD", "CSOCA", "CXLR"] asset.clean()
asset.save()
csas = [0.75, 1.00, 1.25, 2.5, 4]
lengths = [1, 2, 5, 10, 15, 20, 25, 30, 50, 100]
pk = 9000 # Offset to avoid other asset IDs
for i in range(100):
asset_id = random.choice(asset_prefixes) + str(pk)
asset_search = split_asset_id(asset_id)
asset = models.Asset(
pk=pk,
asset_id=asset_id,
asset_id_prefix = asset_search.group(1),
asset_id_number = int(asset_search.group(2)),
description=random.choice(asset_description),
category=random.choice(self.categories),
status=random.choice(self.statuses),
date_acquired=timezone.now().date(),
is_cable=True,
cable_type=random.choice(self.cable_types),
csa=random.choice(csas),
length=random.choice(lengths),
)
if i % 4 == 0 and self.assets:
asset.parent = random.choice(self.assets)
if i % 3 == 0:
asset.purchased_from = random.choice(self.suppliers)
self.assets.append(asset)
pk += 1
def create_connectors(self): def create_connectors(self):
connectors = [ connectors = [
@@ -130,15 +81,47 @@ class Command(BaseCommand):
{"description": "32/3", "current_rating": 32, "voltage_rating": 400, "num_pins": 5}, {"description": "32/3", "current_rating": 32, "voltage_rating": 400, "num_pins": 5},
{"description": "Socapex", "current_rating": 23, "voltage_rating": 600, "num_pins": 19}, {"description": "Socapex", "current_rating": 23, "voltage_rating": 600, "num_pins": 19},
] ]
pk = 1
for connector in connectors: for connector in connectors:
self.connectors.append(models.Connector(pk=pk, **connector)) conn = models.Connector.objects.create(** connector)
pk += 1 conn.save()
self.connectors.append(conn)
def create_cable_types(self): def create_cables(self):
asset_description = ['The worm', 'Harting without a cap', 'Heavy cable', 'Extension lead', 'IEC cable that we should remember to prep']
asset_prefixes = ["C", "C4P", "CBNC", "CDMX", "CDV", "CRCD", "CSOCA", "CXLR"]
csas = [0.75, 1.00, 1.25, 2.5, 4]
lengths = [1, 2, 5, 10, 15, 20, 25, 30, 50, 100]
cores = [3, 5] cores = [3, 5]
circuits = [1, 2, 3, 6] circuits = [1, 2, 3, 6]
pk = 1 types = []
for i in range(10):
self.cable_types.append(models.CableType(pk=pk, plug=random.choice(self.connectors), socket=random.choice(self.connectors), circuits=random.choice(circuits), cores=random.choice(cores))) for i in range(len(connectors)):
pk += 1 types.append(models.CableType.objects.create(plug=random.choice(self.connectors), socket=random.choice(self.connectors), circuits=random.choice(circuits), cores=random.choice(cores)))
for i in range(100):
asset = models.Asset(
asset_id='{}'.format(get_available_asset_id()),
description=random.choice(asset_description),
category=random.choice(self.categories),
status=random.choice(self.statuses),
date_acquired=timezone.now().date(),
is_cable=True,
cable_type=random.choice(types),
csa=random.choice(csas),
length=random.choice(lengths),
)
if i % 5 == 0:
prefix = random.choice(asset_prefixes)
asset.asset_id = prefix + str(get_available_asset_id(wanted_prefix=prefix))
if i % 4 == 0:
asset.parent = models.Asset.objects.order_by('?').first()
if i % 3 == 0:
asset.purchased_from = random.choice(suppliers)
asset.clean()
asset.save()

View File

@@ -84,6 +84,24 @@ class CableType(models.Model):
return "Unknown" return "Unknown"
def get_available_asset_id(wanted_prefix=""):
sql = """
SELECT a.asset_id_number+1
FROM assets_asset a
LEFT OUTER JOIN assets_asset b ON
(a.asset_id_number + 1 = b.asset_id_number AND
a.asset_id_prefix = b.asset_id_prefix)
WHERE b.asset_id IS NULL AND a.asset_id_number >= %s AND a.asset_id_prefix = %s;
"""
with connection.cursor() as cursor:
cursor.execute(sql, [9000, wanted_prefix])
row = cursor.fetchone()
if row is None or row[0] is None:
return 9000
else:
return row[0]
@reversion.register @reversion.register
class Asset(models.Model, RevisionMixin): class Asset(models.Model, RevisionMixin):
class Meta: class Meta:
@@ -125,23 +143,6 @@ class Asset(models.Model, RevisionMixin):
reversion_perm = 'assets.asset_finance' reversion_perm = 'assets.asset_finance'
def get_available_asset_id(wanted_prefix=""):
sql = """
SELECT a.asset_id_number+1
FROM assets_asset a
LEFT OUTER JOIN assets_asset b ON
(a.asset_id_number + 1 = b.asset_id_number AND
a.asset_id_prefix = b.asset_id_prefix)
WHERE b.asset_id IS NULL AND a.asset_id_number >= %s AND a.asset_id_prefix = %s;
"""
with connection.cursor() as cursor:
cursor.execute(sql, [9000, wanted_prefix])
row = cursor.fetchone()
if row is None or row[0] is None:
return 9000
else:
return row[0]
def get_absolute_url(self): def get_absolute_url(self):
return reverse('asset_detail', kwargs={'pk': self.asset_id}) return reverse('asset_detail', kwargs={'pk': self.asset_id})

View File

@@ -4,17 +4,12 @@ from django.dispatch.dispatcher import receiver
from .models import Asset from .models import Asset
def split_asset_id(asset_id):
"""Automatically fills in hidden members on database access"""
asset_search = re.search("^([a-zA-Z0-9]*?[a-zA-Z]?)([0-9]+)$", asset_id)
return asset_search
@receiver(pre_save, sender=Asset) @receiver(pre_save, sender=Asset)
def pre_save_asset(sender, instance, **kwargs): def pre_save_asset(sender, instance, **kwargs):
asset_search = split_asset_id(instance.asset_id) """Automatically fills in hidden members on database access"""
asset_search = re.search("^([a-zA-Z0-9]*?[a-zA-Z]?)([0-9]+)$", instance.asset_id)
if asset_search is None: if asset_search is None:
instance.asset_id += "1" instance.asset_id += "1"
asset_search = split_asset_id(instance.asset_id) asset_search = re.search("^([a-zA-Z0-9]*?[a-zA-Z]?)([0-9]+)$", instance.asset_id)
instance.asset_id_prefix = asset_search.group(1) instance.asset_id_prefix = asset_search.group(1)
instance.asset_id_number = int(asset_search.group(2)) instance.asset_id_number = int(asset_search.group(2))

View File

@@ -13,6 +13,7 @@ from django.views.decorators.csrf import csrf_exempt
from PyRIGS.views import GenericListView, GenericDetailView, GenericUpdateView, GenericCreateView, ModalURLMixin, \ from PyRIGS.views import GenericListView, GenericDetailView, GenericUpdateView, GenericCreateView, ModalURLMixin, \
is_ajax, OEmbedView is_ajax, OEmbedView
from assets import forms, models from assets import forms, models
from assets.models import get_available_asset_id
class AssetList(LoginRequiredMixin, generic.ListView): class AssetList(LoginRequiredMixin, generic.ListView):
@@ -139,7 +140,7 @@ class AssetCreate(LoginRequiredMixin, generic.CreateView):
def get_initial(self, *args, **kwargs): def get_initial(self, *args, **kwargs):
initial = super().get_initial(*args, **kwargs) initial = super().get_initial(*args, **kwargs)
initial["asset_id"] = models.Asset.get_available_asset_id() initial["asset_id"] = get_available_asset_id()
return initial return initial
def get_success_url(self): def get_success_url(self):

View File

@@ -30,3 +30,14 @@ def vat_rate(db):
vat_rate = VatRate.objects.create(start_at='2014-03-05', rate=0.20, comment='test1') vat_rate = VatRate.objects.create(start_at='2014-03-05', rate=0.20, comment='test1')
yield vat_rate yield vat_rate
vat_rate.delete() vat_rate.delete()
def _has_transactional_marker(item):
db_marker = item.get_closest_marker("django_db")
if db_marker and db_marker.kwargs.get("transaction"):
return 1
return 0
def pytest_collection_modifyitems(items):
items.sort(key=_has_transactional_marker)

0
users/__init__.py Normal file
View File

View File

@@ -66,20 +66,23 @@ class Command(BaseCommand):
for permId in hs_perms: for permId in hs_perms:
self.hs_group.permissions.add(Permission.objects.get(codename=permId)) self.hs_group.permissions.add(Permission.objects.get(codename=permId))
self.keyholder_group.save()
self.finance_group.save()
self.hs_group.save()
def setup_generic_profiles(self): def setup_generic_profiles(self):
names = ["Clara Oswin Oswald", "Rory Williams", "Amy Pond", "River Song", "Martha Jones", "Donna Noble", names = ["Clara Oswin Oswald", "Rory Williams", "Amy Pond", "River Song", "Martha Jones", "Donna Noble",
"Jack Harkness", "Mickey Smith", "Rose Tyler"] "Jack Harkness", "Mickey Smith", "Rose Tyler"]
for i, name in enumerate(names): for i, name in enumerate(names):
newProfile = models.Profile.objects.create(username=name.replace(" ", ""), first_name=name.split(" ")[0], new_profile = models.Profile.objects.create(username=name.replace(" ", ""), first_name=name.split(" ")[0],
last_name=name.split(" ")[-1], last_name=name.split(" ")[-1],
email=name.replace(" ", "") + "@example.com", email=name.replace(" ", "") + "@example.com",
initials="".join([j[0].upper() for j in name.split()])) initials="".join([j[0].upper() for j in name.split()]))
if i % 2 == 0: if i % 2 == 0:
newProfile.phone = "01234 567894" new_profile.phone = "01234 567894"
newProfile.save() new_profile.save()
self.profiles.append(newProfile) self.profiles.append(new_profile)
def setup_useful_profiles(self): def setup_useful_profiles(self):
super_user = models.Profile.objects.create(username="superuser", first_name="Super", last_name="User", super_user = models.Profile.objects.create(username="superuser", first_name="Super", last_name="User",