Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Linters #223

Merged
merged 10 commits into from
Jun 26, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ python:
# command to install dependencies
install:
- "pip install -r dependencies.txt"
- "pip install flake8"
- npm install -g casperjs
# create the database
- "cp Lagerregal/template_development.py Lagerregal/settings.py"
- "./manage.py migrate"
# command to run tests
script: "./manage.py test"
script:
- flake8 --config=setup.cfg
- "./manage.py test"
5 changes: 2 additions & 3 deletions Lagerregal/base_settings.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Django settings for Lagerregal project.
from __future__ import unicode_literals
import os
from django.contrib.messages import constants as messages


# Local time zone for this installation. Choices can be found here:
Expand Down Expand Up @@ -127,8 +126,8 @@
)

LANGUAGES = (
('de', 'German'),
('en', 'English'),
('de', 'German'),
('en', 'English'),
)

AUTH_USER_MODEL = 'users.Lageruser'
Expand Down
2 changes: 2 additions & 0 deletions Lagerregal/template_development.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import unicode_literals

from .base_settings import *

DEBUG = True
Expand Down
2 changes: 2 additions & 0 deletions Lagerregal/template_production.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import unicode_literals

from .base_settings import *

DEBUG = False
Expand Down
7 changes: 5 additions & 2 deletions Lagerregal/urls.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import unicode_literals

from django.conf.urls import include, url
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import logout
Expand All @@ -24,11 +26,12 @@
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
admin.autodiscover()
import permission; permission.autodiscover()
import permission
from permission.decorators import permission_required
from django.views.decorators.clickjacking import xframe_options_exempt

admin.autodiscover()
permission.autodiscover()

urlpatterns = [
url(r'^$', login_required(Home.as_view()), name="home"),
Expand Down
13 changes: 3 additions & 10 deletions Lagerregal/utils.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
from __future__ import unicode_literals
import csv
import codecs

import uuid
from datetime import date, timedelta

import six
from django.conf import settings
from django.test.runner import DiscoverRunner

try:
import io
except ImportError:
import cStringIO as io


class PaginationMixin():
def get_paginate_by(self, queryset):
Expand Down Expand Up @@ -50,15 +43,15 @@ def convert_ad_accountexpires(timestamp):
if timestamp is None or timestamp == 0:
return None
epoch_start = date(year=1601, month=1, day=1)
seconds_since_epoch = timestamp/10**7
seconds_since_epoch = timestamp / 10 ** 7
try:
# ad timestamp can be > than date.max, return None (==never expires)
new_date = epoch_start + timedelta(seconds=seconds_since_epoch)
return new_date
except OverflowError:
return None
except Exception:
print('Cannot convert expiration_date "{0}", falling back to None'.format(self.expiration_date))
print('Cannot convert expiration_date "{0}", falling back to None'.format(timestamp))


class DetectableTestRunner(DiscoverRunner):
Expand Down
2 changes: 2 additions & 0 deletions Lagerregal/wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
framework.

"""
from __future__ import unicode_literals

import os
import sys

Expand Down
3 changes: 2 additions & 1 deletion api/serializers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from __future__ import unicode_literals

from rest_framework import serializers
from django.contrib.auth.models import Group, Permission

from devices.models import Room, Building, Manufacturer, Device, Template, Lending, Picture
from django.contrib.auth.models import Group
from devicetypes.models import Type, TypeAttribute
from users.models import Lageruser, Department
from network.models import IpAddress
Expand Down
1 change: 1 addition & 0 deletions api/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

Replace this with more appropriate tests for your application.
"""
from __future__ import unicode_literals

from django.test import TestCase

Expand Down
1 change: 1 addition & 0 deletions api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,7 @@ class DeviceApiPicture(generics.RetrieveDestroyAPIView):
queryset = Picture.objects.all()
serializer_class = PictureSerializer


class DeviceApiPictureRotate(generics.RetrieveUpdateAPIView):
model = Picture
queryset = Picture.objects.all()
Expand Down
7 changes: 6 additions & 1 deletion devicegroups/models.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
from __future__ import unicode_literals

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse

import six
from reversion import revisions as reversion

from users.models import Department


@six.python_2_unicode_compatible
class Devicegroup(models.Model):
name = models.CharField(max_length=200)
department = models.ForeignKey(Department, null=True)

def __unicode__(self):
def __str__(self):
return self.name

class Meta:
Expand Down
10 changes: 7 additions & 3 deletions devicegroups/tests.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
from __future__ import unicode_literals

from django.test.client import Client
from django.test import TestCase
from model_mommy import mommy
from django.core.urlresolvers import reverse

import six
from model_mommy import mommy

from devicegroups.models import Devicegroup
from users.models import Lageruser


class DevicegroupTests(TestCase):
def setUp(self):
self.client = Client()
my_admin = Lageruser.objects.create_superuser("test", "[email protected]", "test")
Lageruser.objects.create_superuser("test", "[email protected]", "test")
self.client.login(username='test', password='test')

def test_devicegroup_creation(self):
devicegroup = mommy.make(Devicegroup)
self.assertEqual(devicegroup.__unicode__(), devicegroup.name)
self.assertEqual(six.text_type(devicegroup), devicegroup.name)
self.assertEqual(devicegroup.get_absolute_url(), reverse('devicegroup-detail', kwargs={'pk': devicegroup.pk}))
self.assertEqual(devicegroup.get_edit_url(), reverse('devicegroup-edit', kwargs={'pk': devicegroup.pk}))
3 changes: 2 additions & 1 deletion devices/admin.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from __future__ import unicode_literals

from django.contrib import admin

from devices.models import *
from reversion.models import Version, Revision


class DeviceAdmin(admin.ModelAdmin):
Expand Down
9 changes: 4 additions & 5 deletions devices/ajax.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json
import time
import csv
Expand Down Expand Up @@ -28,7 +29,6 @@
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ugettext
from django.utils.dateparse import parse_date
from django.contrib import messages

from devices.models import Device, Room, Building, Manufacturer, Lending
from users.models import Lageruser, Department
Expand Down Expand Up @@ -251,10 +251,10 @@ def post(self, request):
return HttpResponse("")
if invert:
data = [
{"value": "not " + str(object.pk) + "-" + object.__unicode__(), "label": "not " + object.__unicode__()}
{"value": "not " + str(object.pk) + "-" + six.text_type(object), "label": "not " + six.text_type(object)}
for object in items]
else:
data = [{"value": str(object.pk) + "-" + object.__unicode__(), "label": object.__unicode__()}
data = [{"value": str(object.pk) + "-" + six.text_type(object), "label": six.text_type(object)}
for object in items]
return HttpResponse(json.dumps(data), content_type='application/json')

Expand Down Expand Up @@ -443,7 +443,7 @@ def post(self, request):
return render(request, 'devices/searchresult.html', context)
except ValueError:
context = {
"wrong_id_format" : True
"wrong_id_format": True
}
return render(request, 'devices/searchempty.html', context)
except Device.DoesNotExist:
Expand Down Expand Up @@ -547,7 +547,6 @@ def post(self, request):
conn = httplib.HTTPSConnection(settings.PUPPETDB_SETTINGS['host'],
settings.PUPPETDB_SETTINGS['port'],
context=context)
req = settings.PUPPETDB_SETTINGS['req'] + params
conn.request("GET", settings.PUPPETDB_SETTINGS['req'] + params)
res = conn.getresponse()
if res.status != httplib.OK:
Expand Down
2 changes: 2 additions & 0 deletions devices/context_processors.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import unicode_literals

from django.conf import settings # import the settings file


Expand Down
11 changes: 5 additions & 6 deletions devices/forms.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from __future__ import unicode_literals

import re

from django import forms
Expand Down Expand Up @@ -66,14 +67,14 @@

def get_department_options():
try:
return DEPARTMENT_OPTIONS+list(Department.objects.all().values_list("id", "name"))
return DEPARTMENT_OPTIONS + list(Department.objects.all().values_list("id", "name"))
except OperationalError:
return []


def get_devicegroup_options():
try:
return [('all', _('All Groups')), ]+list(Devicegroup.objects.all().values_list("id", "name"))
return [('all', _('All Groups'))] + list(Devicegroup.objects.all().values_list("id", "name"))
except OperationalError:
return []

Expand Down Expand Up @@ -184,8 +185,8 @@ def __init__(self, pk=None, *args, **kwargs):
super(LendForm, self).__init__(*args, **kwargs)
device = None
try:
device = Device.objects.filter(pk = pk)[0]
except Exception as e:
device = Device.objects.filter(pk=pk)[0]
except:
pass
if device:
self.fields['owner'].initial = device.currentlending.owner
Expand All @@ -194,8 +195,6 @@ def __init__(self, pk=None, *args, **kwargs):
self.fields['device'].initial = device
print(self.fields['device'].initial)



def clean_device(self):
device = self.cleaned_data["device"]
return device
Expand Down
10 changes: 5 additions & 5 deletions devices/management/commands/ldapimport.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def paged_search_ext_s(self, base, scope, filterstr='(objectClass=*)', attrlist=
# Send first search request
msgid = self.search_ext(
*settings.LDAP_USER_SEARCH,
serverctrls=(serverctrls or [])+[req_ctrl]
serverctrls=(serverctrls or []) + [req_ctrl]
)

result_pages = 0
Expand All @@ -49,7 +49,7 @@ def paged_search_ext_s(self, base, scope, filterstr='(objectClass=*)', attrlist=
if pctrls[0].cookie:
# Copy cookie from response control to request control
req_ctrl.cookie = pctrls[0].cookie
msgid = self.search_ext(*settings.LDAP_USER_SEARCH, serverctrls=(serverctrls or [])+[req_ctrl])
msgid = self.search_ext(*settings.LDAP_USER_SEARCH, serverctrls=(serverctrls or []) + [req_ctrl])
else:
break
return result_pages, all_results
Expand Down Expand Up @@ -78,7 +78,7 @@ def handle(self, *args, **options):
user = Lageruser.objects.get(username=userdata["sAMAccountName"][0])
except TypeError:
continue
except Exception as e:
except:
saveuser = True
created = True
user = Lageruser(username=userdata["sAMAccountName"][0])
Expand All @@ -90,7 +90,7 @@ def handle(self, *args, **options):
try:
department_name = re.findall(settings.AUTH_LDAP_DEPARTMENT_REGEX, new_value)[-1]
new_value = Department.objects.get(name=department_name)
except Department.DoesNotExist as e:
except Department.DoesNotExist:
new_value = Department(name=department_name)
new_value.save()
except IndexError:
Expand Down Expand Up @@ -119,7 +119,7 @@ def handle(self, *args, **options):
saveuser = True
setattr(user, field, new_value)
changes[field] = (old_value, new_value)
except Exception as e:
except:
if attr == "accountExpires":
continue
if attr == "givenName" or attr == "sn":
Expand Down
Loading