Refactoring: fix most of the (many) 'flake8' complaints

This commit is contained in:
Michael Bideau 2019-08-22 16:02:06 +00:00
parent 9df996e5ad
commit a951f062f0
13 changed files with 401 additions and 390 deletions

2
.flake8 Normal file
View File

@ -0,0 +1,2 @@
[flake8]
max-line-length = 100

View File

@ -24,6 +24,7 @@ from django.forms import ModelForm
from .models import ForwardFile, Collectivite, Guichet from .models import ForwardFile, Collectivite, Guichet
class ForwardFileForm(ModelForm): class ForwardFileForm(ModelForm):
"""Form for the ForwardFile model.""" """Form for the ForwardFile model."""

View File

@ -26,24 +26,24 @@
JSON_SCHEMA_FILE = { JSON_SCHEMA_FILE = {
"description": "A file object", "description": "A file object",
"$id" : "#file", "$id": "#file",
"type": "object", "type": "object",
"properties": { "properties": {
"content" : {"type": "string"}, "content": {"type": "string"},
"content_type": {"type": ["string", "null"]}, "content_type": {"type": ["string", "null"]},
"filename" : {"type": "string"} "filename": {"type": "string"}
}, },
"required": ["content", "filename"] "required": ["content", "filename"]
} }
JSON_SCHEMA_FILE_B64 = { JSON_SCHEMA_FILE_B64 = {
"description": "A file object encoded in base64", "description": "A file object encoded in base64",
"$id" : "#file", "$id": "#file",
"type": "object", "type": "object",
"properties": { "properties": {
"b64_content" : {"type": "string"}, "b64_content": {"type": "string"},
"content_type": {"type": ["string", "null"]}, "content_type": {"type": ["string", "null"]},
"filename" : {"type": "string"} "filename": {"type": "string"}
}, },
"required": ["b64_content", "filename"] "required": ["b64_content", "filename"]
} }
@ -51,13 +51,13 @@ JSON_SCHEMA_FILE_B64 = {
JSON_SCHEMA_DATE_FRENCH = { JSON_SCHEMA_DATE_FRENCH = {
"type": "string", "type": "string",
# pylint: disable=anomalous-backslash-in-string # pylint: disable=anomalous-backslash-in-string
"pattern": "^(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/\d{4}$" "pattern": "^(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/\d{4}$" # noqa: W605
} }
JSON_SCHEMA_CHECK_STATUS_OUT = { JSON_SCHEMA_CHECK_STATUS_OUT = {
"$schema": "http://json-schema.org/draft-07/schema#", "$schema": "http://json-schema.org/draft-07/schema#",
"title" : "Response of an openADS 'connexion' test", "title": "Response of an openADS 'connexion' test",
"type" : "object", "type": "object",
"properties": { "properties": {
"response": {"type": "integer"} "response": {"type": "integer"}
}, },
@ -66,12 +66,12 @@ JSON_SCHEMA_CHECK_STATUS_OUT = {
JSON_SCHEMA_CREATE_DOSSIER_IN = { JSON_SCHEMA_CREATE_DOSSIER_IN = {
"$schema": "http://json-schema.org/draft-07/schema#", "$schema": "http://json-schema.org/draft-07/schema#",
"title" : "Incoming request to create a 'dossier' in openADS.API", "title": "Incoming request to create a 'dossier' in openADS.API",
"definitions": { "definitions": {
"refs-cadastrales": { "refs-cadastrales": {
"description": "The 3 items of a 'cadastrale' reference", "description": "The 3 items of a 'cadastrale' reference",
"$id" : "#refs-cadastrales", "$id": "#refs-cadastrales",
"type" : "array", "type": "array",
"items": { "items": {
"type": "string" "type": "string"
}, },
@ -99,11 +99,11 @@ JSON_SCHEMA_CREATE_DOSSIER_IN = {
"plan_cadastral_3": {"$ref": "#/definitions/file_plan_cadastral"}, "plan_cadastral_3": {"$ref": "#/definitions/file_plan_cadastral"},
"plan_cadastral_4": {"$ref": "#/definitions/file_plan_cadastral"}, "plan_cadastral_4": {"$ref": "#/definitions/file_plan_cadastral"},
"plan_cadastral_5": {"$ref": "#/definitions/file_plan_cadastral"}, "plan_cadastral_5": {"$ref": "#/definitions/file_plan_cadastral"},
"terrain_numero_voie" : {"type": "string"}, "terrain_numero_voie": {"type": "string"},
"terrain_nom_voie" : {"type": "string"}, "terrain_nom_voie": {"type": "string"},
"terrain_code_postal" : {"type": "string"}, "terrain_code_postal": {"type": "string"},
"terrain_localite" : {"type": "string"}, "terrain_localite": {"type": "string"},
"terrain_lieu_dit" : {"type": ["string", "null"]}, "terrain_lieu_dit": {"type": ["string", "null"]},
"reference_cadastrale": { "reference_cadastrale": {
"description": "A list of 'cadastrales' references", "description": "A list of 'cadastrales' references",
"type": "array", "type": "array",
@ -116,24 +116,24 @@ JSON_SCHEMA_CREATE_DOSSIER_IN = {
"description": "A list of 'cadastrales' references", "description": "A list of 'cadastrales' references",
# conditionaly required and typed below # conditionaly required and typed below
}, },
"proprietaire" : {"enum": ["Oui", "Non"]}, "proprietaire": {"enum": ["Oui", "Non"]},
"qualite" : {"type": "string"}, "qualite": {"type": "string"},
"denomination" : {}, # conditionaly required and typed below "denomination": {}, # conditionaly required and typed below
"raison_sociale" : {}, # conditionaly required and typed below "raison_sociale": {}, # conditionaly required and typed below
"nom" : {"type": "string"}, "nom": {"type": "string"},
"prenom" : {"type": "string"}, "prenom": {"type": "string"},
"numero_voie" : {"type": "string"}, "numero_voie": {"type": "string"},
"nom_voie" : {"type": "string"}, "nom_voie": {"type": "string"},
"code_postal" : {"type": "string"}, "code_postal": {"type": "string"},
"localite" : {"type": "string"}, "localite": {"type": "string"},
"lieu_dit" : {"type": ["string", "null"]}, "lieu_dit": {"type": ["string", "null"]},
"mandataire_nom" : {}, # conditionaly required and typed below "mandataire_nom": {}, # conditionaly required and typed below
"mandataire_prenom" : {}, # conditionaly required and typed below "mandataire_prenom": {}, # conditionaly required and typed below
"mandataire_numero_voie": {}, # conditionaly required and typed below "mandataire_numero_voie": {}, # conditionaly required and typed below
"mandataire_nom_voie" : {}, # conditionaly required and typed below "mandataire_nom_voie": {}, # conditionaly required and typed below
"mandataire_code_postal": {}, # conditionaly required and typed below "mandataire_code_postal": {}, # conditionaly required and typed below
"mandataire_localite" : {}, # conditionaly required and typed below "mandataire_localite": {}, # conditionaly required and typed below
"mandataire_lieu_dit" : {} # conditionaly required and typed below "mandataire_lieu_dit": {} # conditionaly required and typed below
}, },
# requirements # requirements
@ -166,7 +166,7 @@ JSON_SCHEMA_CREATE_DOSSIER_IN = {
{ {
"properties": { "properties": {
"qualite": {"const": "Un particulier"}, "qualite": {"const": "Un particulier"},
"denomination" : {"type": "null"}, "denomination": {"type": "null"},
"raison_sociale": {"type": "null"} "raison_sociale": {"type": "null"}
} }
}, },
@ -176,7 +176,7 @@ JSON_SCHEMA_CREATE_DOSSIER_IN = {
{ {
"properties": { "properties": {
"qualite": {"const": "Une personne morale"}, "qualite": {"const": "Une personne morale"},
"denomination" : {"type": "string"}, "denomination": {"type": "string"},
"raison_sociale": {"type": "string"} "raison_sociale": {"type": "string"}
}, },
"required": ["denomination", "raison_sociale"] "required": ["denomination", "raison_sociale"]
@ -193,13 +193,13 @@ JSON_SCHEMA_CREATE_DOSSIER_IN = {
{ {
"properties": { "properties": {
"proprietaire": {"const": "Oui"}, "proprietaire": {"const": "Oui"},
"mandataire_nom" : {"type": "null"}, "mandataire_nom": {"type": "null"},
"mandataire_prenom" : {"type": "null"}, "mandataire_prenom": {"type": "null"},
"mandataire_numero_voie": {"type": "null"}, "mandataire_numero_voie": {"type": "null"},
"mandataire_nom_voie" : {"type": "null"}, "mandataire_nom_voie": {"type": "null"},
"mandataire_code_postal": {"type": "null"}, "mandataire_code_postal": {"type": "null"},
"mandataire_localite" : {"type": "null"}, "mandataire_localite": {"type": "null"},
"mandataire_lieu_dit" : {"type": "null"} "mandataire_lieu_dit": {"type": "null"}
} }
}, },
@ -210,14 +210,14 @@ JSON_SCHEMA_CREATE_DOSSIER_IN = {
{ {
"properties": { "properties": {
"proprietaire": {"const": "Non"}, "proprietaire": {"const": "Non"},
"mandataire_nom" : {"type": "string"}, "mandataire_nom": {"type": "string"},
"mandataire_prenom" : {"type": "string"}, "mandataire_prenom": {"type": "string"},
"mandataire_numero_voie": {"type": "string"}, "mandataire_numero_voie": {"type": "string"},
"mandataire_nom_voie" : {"type": "string"}, "mandataire_nom_voie": {"type": "string"},
"mandataire_code_postal": {"type": "string"}, "mandataire_code_postal": {"type": "string"},
"mandataire_localite" : {"type": "string"}, "mandataire_localite": {"type": "string"},
"mandataire_qualite" : {"type": "string"}, "mandataire_qualite": {"type": "string"},
"mandataire_lieu_dit" : {"type": ["string", "null"]} "mandataire_lieu_dit": {"type": ["string", "null"]}
}, },
"required": [ "required": [
"mandataire_nom", "mandataire_nom",
@ -238,7 +238,7 @@ JSON_SCHEMA_CREATE_DOSSIER_IN = {
{ {
"properties": { "properties": {
"mandataire_qualite": {"const": "Un particulier"}, "mandataire_qualite": {"const": "Un particulier"},
"mandataire_denomination" : {"type": "null"}, "mandataire_denomination": {"type": "null"},
"mandataire_raison_sociale": {"type": "null"} "mandataire_raison_sociale": {"type": "null"}
} }
}, },
@ -248,7 +248,7 @@ JSON_SCHEMA_CREATE_DOSSIER_IN = {
{ {
"properties": { "properties": {
"mandataire_qualite": {"const": "Une personne morale"}, "mandataire_qualite": {"const": "Une personne morale"},
"mandataire_denomination" : {"type": "string"}, "mandataire_denomination": {"type": "string"},
"mandataire_raison_sociale": {"type": "string"} "mandataire_raison_sociale": {"type": "string"}
}, },
"required": [ "required": [
@ -296,8 +296,8 @@ JSON_SCHEMA_CREATE_DOSSIER_IN = {
JSON_SCHEMA_CREATE_DOSSIER_OUT = { JSON_SCHEMA_CREATE_DOSSIER_OUT = {
"$schema": "http://json-schema.org/draft-07/schema#", "$schema": "http://json-schema.org/draft-07/schema#",
"title" : "Response of a 'dossier' creation in openADS.API", "title": "Response of a 'dossier' creation in openADS.API",
"type" : "object", "type": "object",
"properties": { "properties": {
"numero_dossier": {"type": "string"}, "numero_dossier": {"type": "string"},
"recepisse": JSON_SCHEMA_FILE_B64 "recepisse": JSON_SCHEMA_FILE_B64
@ -307,14 +307,14 @@ JSON_SCHEMA_CREATE_DOSSIER_OUT = {
JSON_SCHEMA_GET_DOSSIER_OUT = { JSON_SCHEMA_GET_DOSSIER_OUT = {
"$schema": "http://json-schema.org/draft-07/schema#", "$schema": "http://json-schema.org/draft-07/schema#",
"title" : "Response of a 'dossier' creation in openADS.API", "title": "Response of a 'dossier' creation in openADS.API",
"type" : "object", "type": "object",
"properties": { "properties": {
"etat" : {"type": "string"}, "etat": {"type": "string"},
"date_depot" : JSON_SCHEMA_DATE_FRENCH, "date_depot": JSON_SCHEMA_DATE_FRENCH,
"date_decision": JSON_SCHEMA_DATE_FRENCH, "date_decision": JSON_SCHEMA_DATE_FRENCH,
"date_limite_instruction": JSON_SCHEMA_DATE_FRENCH, "date_limite_instruction": JSON_SCHEMA_DATE_FRENCH,
"decision" : {"type": "string"} "decision": {"type": "string"}
}, },
"required": [ "required": [
"etat", "etat",
@ -327,20 +327,20 @@ JSON_SCHEMA_GET_DOSSIER_OUT = {
JSON_SCHEMA_FORWARDFILE = { JSON_SCHEMA_FORWARDFILE = {
"description": "A ForwardFile object (PDF document that must be forwarded to openADS)", "description": "A ForwardFile object (PDF document that must be forwarded to openADS)",
"$id" : "#forwardfile", "$id": "#forwardfile",
"type": "object", "type": "object",
"properties": { "properties": {
"id" : {"type": "integer"}, "id": {"type": "integer"},
"numero_demande" : {"type": "string"}, "numero_demande": {"type": "string"},
"numero_dossier" : {"type": "string"}, "numero_dossier": {"type": "string"},
"type_fichier" : {"type": "string"}, "type_fichier": {"type": "string"},
"file_hash" : {"type": "string"}, "file_hash": {"type": "string"},
"orig_filename" : {"type": "string"}, "orig_filename": {"type": "string"},
"content_type" : {"type": "string"}, "content_type": {"type": "string"},
"upload_status" : {"type": "string"}, "upload_status": {"type": "string"},
"upload_attempt" : {"type": "integer"}, "upload_attempt": {"type": "integer"},
"upload_msg" : {"type": "string"}, "upload_msg": {"type": "string"},
"content_size" : {"type": "integer"}, "content_size": {"type": "integer"},
"last_update_datetime": {"type": "string", "format": "date-time"} "last_update_datetime": {"type": "string", "format": "date-time"}
}, },
"required": [ "required": [
@ -361,43 +361,43 @@ JSON_SCHEMA_FORWARDFILE = {
JSON_SCHEMA_GET_FWD_FILES_OUT = { JSON_SCHEMA_GET_FWD_FILES_OUT = {
"$schema": "http://json-schema.org/draft-07/schema#", "$schema": "http://json-schema.org/draft-07/schema#",
"title" : "Response of a request about the forwarding (detailled) of user files to openADS", "title": "Response of a request about the forwarding (detailled) of user files to openADS",
"type" : "array", "type": "array",
"items": {"$ref": "#/definitions/forwardfile"}, "items": {"$ref": "#/definitions/forwardfile"},
"definitions": { "definitions": {
"forwardfile" : JSON_SCHEMA_FORWARDFILE "forwardfile": JSON_SCHEMA_FORWARDFILE
} }
} }
JSON_SCHEMA_GET_FWD_FILE_STATUS = { JSON_SCHEMA_GET_FWD_FILE_STATUS = {
"description": "The status of a ForwardFile", "description": "The status of a ForwardFile",
"$id" : "#forwardfile-status", "$id": "#forwardfile-status",
"type": "string", "type": "string",
# pylint: disable=anomalous-backslash-in-string # pylint: disable=anomalous-backslash-in-string
"pattern": "^\[\w+\] .+ => .+$" "pattern": "^\[\w+\] .+ => .+$" # noqa: W605
} }
JSON_SCHEMA_GET_FWD_FILES_STATUS_OUT = { JSON_SCHEMA_GET_FWD_FILES_STATUS_OUT = {
"$schema": "http://json-schema.org/draft-07/schema#", "$schema": "http://json-schema.org/draft-07/schema#",
"title" : "Response of a request about the forwarding (summarized) of user files to openADS", "title": "Response of a request about the forwarding (summarized) of user files to openADS",
"type" : "object", "type": "object",
"properties": { "properties": {
"all_forwarded": {"type": "boolean"}, "all_forwarded": {"type": "boolean"},
"pending" : {"type": "array", "items": {"$ref": "#/definitions/forwardfile-status"}}, "pending": {"type": "array", "items": {"$ref": "#/definitions/forwardfile-status"}},
"uploading": {"type": "array", "items": {"$ref": "#/definitions/forwardfile-status"}}, "uploading": {"type": "array", "items": {"$ref": "#/definitions/forwardfile-status"}},
"success" : {"type": "array", "items": {"$ref": "#/definitions/forwardfile-status"}}, "success": {"type": "array", "items": {"$ref": "#/definitions/forwardfile-status"}},
"failed" : {"type": "array", "items": {"$ref": "#/definitions/forwardfile-status"}} "failed": {"type": "array", "items": {"$ref": "#/definitions/forwardfile-status"}}
}, },
"required": ["all_forwarded", "pending", "uploading", "success", "failed"], "required": ["all_forwarded", "pending", "uploading", "success", "failed"],
"definitions": { "definitions": {
"forwardfile-status" : JSON_SCHEMA_GET_FWD_FILE_STATUS "forwardfile-status": JSON_SCHEMA_GET_FWD_FILE_STATUS
} }
} }
JSON_SCHEMA_GET_COURRIER_OUT = { JSON_SCHEMA_GET_COURRIER_OUT = {
"$schema": "http://json-schema.org/draft-07/schema#", "$schema": "http://json-schema.org/draft-07/schema#",
"title" : "Response of a 'courrier' from an openADS 'dossier'", "title": "Response of a 'courrier' from an openADS 'dossier'",
"type" : "object", "type": "object",
"properties": { "properties": {
"courrier": JSON_SCHEMA_FILE_B64 "courrier": JSON_SCHEMA_FILE_B64
}, },

View File

@ -18,7 +18,7 @@
# You should have received a copy of the GNU Affero General Public License # You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Models for this connector module.""" # pylint: disable=too-many-lines """Models for this connector module.""" # pylint: disable=too-many-lines
import base64 import base64
import datetime import datetime
@ -41,12 +41,12 @@ from passerelle.utils.jsonresponse import APIError
from .json_schemas import ( from .json_schemas import (
JSON_SCHEMA_CREATE_DOSSIER_IN, JSON_SCHEMA_CREATE_DOSSIER_IN,
#JSON_SCHEMA_CHECK_STATUS_OUT, # JSON_SCHEMA_CHECK_STATUS_OUT,
#JSON_SCHEMA_CREATE_DOSSIER_OUT, # JSON_SCHEMA_CREATE_DOSSIER_OUT,
#JSON_SCHEMA_GET_DOSSIER_OUT, # JSON_SCHEMA_GET_DOSSIER_OUT,
#JSON_SCHEMA_GET_FWD_FILES_OUT, # JSON_SCHEMA_GET_FWD_FILES_OUT,
#JSON_SCHEMA_GET_FWD_FILES_STATUS_OUT, # JSON_SCHEMA_GET_FWD_FILES_STATUS_OUT,
#JSON_SCHEMA_GET_COURRIER_OUT # JSON_SCHEMA_GET_COURRIER_OUT
) )
from .utils import ( from .utils import (
@ -63,7 +63,7 @@ from .utils import (
) )
class ForwardFile(models.Model, BaseModel): # pylint: disable=too-many-instance-attributes class ForwardFile(models.Model, BaseModel): # pylint: disable=too-many-instance-attributes
"""Represent a file uploaded by a user, to be forwarded to openADS.API.""" """Represent a file uploaded by a user, to be forwarded to openADS.API."""
STATUSES = [ STATUSES = [
@ -124,7 +124,7 @@ class ForwardFile(models.Model, BaseModel): # pylint: disable=too-many-instance-
def __repr__(self): def __repr__(self):
return (u'ForwardFile(id=%s,connecteur=%s,collectivite=%s' return (u'ForwardFile(id=%s,connecteur=%s,collectivite=%s'
',demande=%s,dossier=%s,type=%s,filename=%s,status=%s)') % ( ',demande=%s,dossier=%s,type=%s,filename=%s,status=%s)') % (
self.id, # pylint: disable=no-member self.id, # pylint: disable=no-member
unicode(self.connecteur) if hasattr(self, 'connecteur') else None, unicode(self.connecteur) if hasattr(self, 'connecteur') else None,
unicode(self.collectivite) if hasattr(self, 'collectivite') else None, unicode(self.collectivite) if hasattr(self, 'collectivite') else None,
self.numero_demande, self.numero_dossier, self.numero_demande, self.numero_dossier,
@ -141,7 +141,7 @@ class ForwardFile(models.Model, BaseModel): # pylint: disable=too-many-instance-
def update_content_type(self, only_if_empty=False): def update_content_type(self, only_if_empty=False):
"""Update the content type from the content of the file.""" """Update the content type from the content of the file."""
if not self.content_type or not only_if_empty: if not self.content_type or not only_if_empty:
if self.upload_file and self.upload_file.size: # pylint: disable=no-member if self.upload_file and self.upload_file.size: # pylint: disable=no-member
# pylint: disable=no-member # pylint: disable=no-member
self.content_type = magic.from_buffer(self.upload_file.read(1024), mime=True) self.content_type = magic.from_buffer(self.upload_file.read(1024), mime=True)
else: else:
@ -150,7 +150,7 @@ class ForwardFile(models.Model, BaseModel): # pylint: disable=too-many-instance-
def update_file_hash(self, only_if_empty=False): def update_file_hash(self, only_if_empty=False):
"""Update the file_hash field from the content of the file.""" """Update the file_hash field from the content of the file."""
if not self.file_hash or not only_if_empty: if not self.file_hash or not only_if_empty:
if self.upload_file and self.upload_file.size: # pylint: disable=no-member if self.upload_file and self.upload_file.size: # pylint: disable=no-member
self.file_hash = get_file_digest(self.upload_file) self.file_hash = get_file_digest(self.upload_file)
else: else:
self.file_hash = '' self.file_hash = ''
@ -160,7 +160,7 @@ class ForwardFile(models.Model, BaseModel): # pylint: disable=too-many-instance-
# this will not be triggered when doing bulk actions like with QuerySet.update() # this will not be triggered when doing bulk actions like with QuerySet.update()
# @see: https://docs.djangoproject.com/en/2.2/topics/db/models/ # @see: https://docs.djangoproject.com/en/2.2/topics/db/models/
# The note entitled "Overridden model methods are not called on bulk operations" # The note entitled "Overridden model methods are not called on bulk operations"
def save(self, *args, **kwargs): # pylint: disable=arguments-differ def save(self, *args, **kwargs): # pylint: disable=arguments-differ
# delete file content (on success) # delete file content (on success)
if self.upload_status == 'success': if self.upload_status == 'success':
# pylint: disable=no-member # pylint: disable=no-member
@ -169,7 +169,7 @@ class ForwardFile(models.Model, BaseModel): # pylint: disable=too-many-instance-
self.upload_file.delete() self.upload_file.delete()
# else, update metadata # else, update metadata
else: else:
self.size = self.upload_file.size if self.upload_file else 0 # pylint: disable=no-member self.size = self.upload_file.size if self.upload_file else 0 # noqa: E501, pylint: disable=no-member
self.update_file_hash() self.update_file_hash()
self.update_content_type(only_if_empty=True) self.update_content_type(only_if_empty=True)
# validation (calling self.clean()) # validation (calling self.clean())
@ -179,7 +179,7 @@ class ForwardFile(models.Model, BaseModel): # pylint: disable=too-many-instance-
# check that one the following fields must not be blank/null: # check that one the following fields must not be blank/null:
# 'file_hash', 'orig_filename', 'upload_file' # 'file_hash', 'orig_filename', 'upload_file'
# because if they are all empty we dont have any usefull information about the upload # because if they are all empty we dont have any usefull information about the upload
def clean(self, *args, **kwargs): # pylint: disable=arguments-differ def clean(self, *args, **kwargs): # pylint: disable=arguments-differ
ret = super(ForwardFile, self).clean(*args, **kwargs) ret = super(ForwardFile, self).clean(*args, **kwargs)
if (not self.file_hash if (not self.file_hash
and not self.orig_filename and not self.orig_filename
@ -188,8 +188,7 @@ class ForwardFile(models.Model, BaseModel): # pylint: disable=too-many-instance-
raise ValidationError( raise ValidationError(
_("A %(object)s cannot have all the following fields empty: %(fields)s." % { _("A %(object)s cannot have all the following fields empty: %(fields)s." % {
'object': self.get_verbose_name(), 'object': self.get_verbose_name(),
'fields': ['file_hash', 'orig_filename', 'upload_file']} 'fields': ['file_hash', 'orig_filename', 'upload_file']})
)
) )
return ret return ret
@ -235,7 +234,7 @@ class Collectivite(models.Model, BaseModel):
@force_encoded_string_output @force_encoded_string_output
def __repr__(self): def __repr__(self):
return u'Collectivite(id=%s,name=%s,connecteur=%s,openADS_id=%s,guichet=%s)' % ( return u'Collectivite(id=%s,name=%s,connecteur=%s,openADS_id=%s,guichet=%s)' % (
self.id, unicode(self.name), # pylint: disable=no-member self.id, unicode(self.name), # pylint: disable=no-member
unicode(self.connecteur) if hasattr(self, 'connecteur') else None, unicode(self.connecteur) if hasattr(self, 'connecteur') else None,
self.openADS_id, self.openADS_id,
# pylint: disable=no-member # pylint: disable=no-member
@ -305,7 +304,7 @@ class Guichet(models.Model, BaseModel):
@force_encoded_string_output @force_encoded_string_output
def __repr__(self): def __repr__(self):
return u'Guichet(id=%s,collectivite=%s,%s)' % ( return u'Guichet(id=%s,collectivite=%s,%s)' % (
self.id, # pylint: disable=no-member self.id, # pylint: disable=no-member
unicode(self.collectivite) if hasattr(self, 'collectivite') else None, unicode(self.collectivite) if hasattr(self, 'collectivite') else None,
unicode(self)) unicode(self))
@ -354,8 +353,7 @@ class Guichet(models.Model, BaseModel):
or (day > self.ouverture_sem_d or (day > self.ouverture_sem_d
and day < self.fermeture_sem_d and day < self.fermeture_sem_d
and date_t > ouverture_jour_date_t and date_t > ouverture_jour_date_t
and date_t < fermeture_jour_date_t and date_t < fermeture_jour_date_t)
)
) )
return False return False
@ -392,10 +390,10 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
@force_encoded_string_output @force_encoded_string_output
def __repr__(self): def __repr__(self):
return u'AtrealOpenads(id=%s,openADS=%s,login=%s,collectivites=%s,default=%s)' % ( return u'AtrealOpenads(id=%s,openADS=%s,login=%s,collectivites=%s,default=%s)' % (
self.id, # pylint: disable=no-member self.id, # pylint: disable=no-member
unicode(self.openADS_API_url), unicode(self.openADS_API_url),
unicode(self.basic_auth_username), unicode(self.basic_auth_username),
self.collectivites.count(), # pylint: disable=no-member self.collectivites.count(), # pylint: disable=no-member
self.default_collectivite_openADS_id) self.default_collectivite_openADS_id)
def __unicode__(self): def __unicode__(self):
@ -452,7 +450,7 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
# return the files # return the files
return files return files
def check_file_dict(self, dict_file, title='payload', b64=True): # pylint: disable=no-self-use def check_file_dict(self, dict_file, title='payload', b64=True): # pylint: disable=no-self-use
"""Ensure a file dict has all its required items.""" """Ensure a file dict has all its required items."""
# key to get the content # key to get the content
@ -480,7 +478,6 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
u"Expecting '%s' value in JSON %s in file dict to be a %s (not a %s)" % u"Expecting '%s' value in JSON %s in file dict to be a %s (not a %s)" %
('file.filename', title, 'string', type(dict_file['filename']))) ('file.filename', title, 'string', type(dict_file['filename'])))
def get_first_file_from_payload(self, def get_first_file_from_payload(self,
payload, payload,
title='payload', title='payload',
@ -503,14 +500,14 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
@endpoint( @endpoint(
description=_("Test an openADS 'connexion'") description=_("Test an openADS 'connexion'")
#~ get={ # get={
#~ 'description': _("Test an openADS 'connexion'"), # 'description': _("Test an openADS 'connexion'"),
#~ 'response_body': { # 'response_body': {
#~ 'schema': { # 'schema': {
#~ 'application/json': JSON_SCHEMA_CHECK_STATUS_OUT # 'application/json': JSON_SCHEMA_CHECK_STATUS_OUT
#~ } # }
#~ } # }
#~ } # }
) )
# pylint: disable=unused-argument,arguments-differ,keyword-arg-before-vararg # pylint: disable=unused-argument,arguments-differ,keyword-arg-before-vararg
def check_status(self, request=None, *args, **kwargs): def check_status(self, request=None, *args, **kwargs):
@ -520,11 +517,10 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
response.raise_for_status() response.raise_for_status()
return {'response': response.status_code} return {'response': response.status_code}
@endpoint( @endpoint(
perm='can_access', perm='can_access',
methods=['post'], methods=['post'],
pattern='^(?P<type_dossier>\w+)/?$', # pylint: disable=anomalous-backslash-in-string pattern='^(?P<type_dossier>\w+)/?$', # noqa: W605,E501, pylint: disable=anomalous-backslash-in-string
example_pattern='{type_dossier}/', example_pattern='{type_dossier}/',
parameters={ parameters={
'type_dossier': {'description': _("Type of 'dossier'"), 'example_value': 'DIA'}, 'type_dossier': {'description': _("Type of 'dossier'"), 'example_value': 'DIA'},
@ -540,13 +536,13 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
'request_body': { 'request_body': {
'schema': { 'schema': {
'application/json': JSON_SCHEMA_CREATE_DOSSIER_IN 'application/json': JSON_SCHEMA_CREATE_DOSSIER_IN
} # pylint: disable=too-many-statements,too-many-branches,too-many-locals } # pylint: disable=too-many-statements,too-many-branches,too-many-locals
} }
#~ 'response_body': { # 'response_body': {
#~ 'schema': { # 'schema': {
#~ 'application/json': JSON_SCHEMA_CREATE_DOSSIER_OUT # 'application/json': JSON_SCHEMA_CREATE_DOSSIER_OUT
#~ } # }
#~ } # }
} }
) )
# pylint: disable=unused-argument,keyword-arg-before-vararg # pylint: disable=unused-argument,keyword-arg-before-vararg
@ -567,7 +563,7 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
collectivite = self.get_collectivite(collectivite_id) collectivite = self.get_collectivite(collectivite_id)
# no collectivite instance matching that ID # no collectivite instance matching that ID
except Collectivite.DoesNotExist: # pylint: disable=no-member except Collectivite.DoesNotExist: # pylint: disable=no-member
pass pass
# a collectivite instance was found # a collectivite instance was found
@ -599,9 +595,9 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
payload["terrain"] = { payload["terrain"] = {
"numero_voie": normalize(json_data['fields']['terrain_numero_voie']), "numero_voie": normalize(json_data['fields']['terrain_numero_voie']),
"nom_voie" : normalize(json_data['fields']['terrain_nom_voie']), "nom_voie": normalize(json_data['fields']['terrain_nom_voie']),
"code_postal": normalize(json_data['fields']['terrain_code_postal']), "code_postal": normalize(json_data['fields']['terrain_code_postal']),
"localite" : normalize(json_data['fields']['terrain_localite']), "localite": normalize(json_data['fields']['terrain_localite']),
"references_cadastrales": [] "references_cadastrales": []
} }
if 'terrain_lieu_dit' in json_data['fields'] and json_data['fields']['terrain_lieu_dit']: if 'terrain_lieu_dit' in json_data['fields'] and json_data['fields']['terrain_lieu_dit']:
@ -611,14 +607,14 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
payload["terrain"]["references_cadastrales"].append({ payload["terrain"]["references_cadastrales"].append({
"prefixe": normalize(ref[0]), "prefixe": normalize(ref[0]),
"section": normalize(ref[1]), "section": normalize(ref[1]),
"numero" : normalize(ref[2]) "numero": normalize(ref[2])
}) })
if json_data['fields']['autres_parcelles']: if json_data['fields']['autres_parcelles']:
for ref in json_data['fields']['references_cadastrales']: for ref in json_data['fields']['references_cadastrales']:
payload["terrain"]["references_cadastrales"].append({ payload["terrain"]["references_cadastrales"].append({
"prefixe": normalize(ref[0]), "prefixe": normalize(ref[0]),
"section": normalize(ref[1]), "section": normalize(ref[1]),
"numero" : normalize(ref[2]) "numero": normalize(ref[2])
}) })
# setup demandeur variable prefix # setup demandeur variable prefix
@ -638,14 +634,14 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
# get the demandeur informations # get the demandeur informations
demandeur = { demandeur = {
"type_personne": type_personne, "type_personne": type_personne,
"typologie" : 'petitionnaire' if key == 'demandeurs' else 'delegataire', "typologie": 'petitionnaire' if key == 'demandeurs' else 'delegataire',
"nom" : normalize(json_data['fields']['%snom' % prefix]), "nom": normalize(json_data['fields']['%snom' % prefix]),
"prenom" : normalize(json_data['fields']['%sprenom' % prefix]), "prenom": normalize(json_data['fields']['%sprenom' % prefix]),
"adresse": { "adresse": {
"numero_voie": normalize(json_data['fields']['%snumero_voie' % prefix]), "numero_voie": normalize(json_data['fields']['%snumero_voie' % prefix]),
"nom_voie" : normalize(json_data['fields']['%snom_voie' % prefix]), "nom_voie": normalize(json_data['fields']['%snom_voie' % prefix]),
"code_postal": normalize(json_data['fields']['%scode_postal' % prefix]), "code_postal": normalize(json_data['fields']['%scode_postal' % prefix]),
"localite" : normalize(json_data['fields']['%slocalite' % prefix]) "localite": normalize(json_data['fields']['%slocalite' % prefix])
}, },
"coordonnees": { "coordonnees": {
"email": normalize(json_data['fields']['%semail' % prefix]) "email": normalize(json_data['fields']['%semail' % prefix])
@ -736,11 +732,11 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
# append the file to the list # append the file to the list
files.append({ files.append({
'type_fichier' : type_fichier, 'type_fichier': type_fichier,
'orig_filename': filename, 'orig_filename': filename,
'content_type' : content_type, 'content_type': content_type,
'file_hash' : file_hash, 'file_hash': file_hash,
'upload_file' : upload_file 'upload_file': upload_file
}) })
# log files to be forwarded # log files to be forwarded
@ -822,11 +818,11 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
forwardfile.save() forwardfile.save()
self.logger.debug( self.logger.debug(
u"Created ForwardFile '%s' for file '%s' (%s)", u"Created ForwardFile '%s' for file '%s' (%s)",
forwardfile.id, # pylint: disable=no-member forwardfile.id, # pylint: disable=no-member
forwardfile.orig_filename, forwardfile.orig_filename,
forwardfile.upload_file.path # pylint: disable=no-member forwardfile.upload_file.path # pylint: disable=no-member
) )
file_ids.append(forwardfile.id) # pylint: disable=no-member file_ids.append(forwardfile.id) # pylint: disable=no-member
job = self.add_job('upload_user_files', job = self.add_job('upload_user_files',
natural_id=numero_dossier, natural_id=numero_dossier,
@ -835,7 +831,7 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
numero_dossier=numero_dossier, numero_dossier=numero_dossier,
file_ids=file_ids) file_ids=file_ids)
self.logger.debug(u"Added a job '%s' for dossier '%s' (%s) with file ids '%s'", self.logger.debug(u"Added a job '%s' for dossier '%s' (%s) with file ids '%s'",
job.id, # pylint: disable=no-member job.id, # pylint: disable=no-member
numero_dossier, numero_dossier,
type_dossier, type_dossier,
file_ids) file_ids)
@ -843,28 +839,28 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
# respond with the 'numero_dossier' and the recepisse file # respond with the 'numero_dossier' and the recepisse file
return { return {
'numero_dossier': numero_dossier, 'numero_dossier': numero_dossier,
'recepisse' : recepisse 'recepisse': recepisse
} }
@endpoint( @endpoint(
perm='can_access', perm='can_access',
description=_("Get informations about an openADS 'dossier'"), description=_("Get informations about an openADS 'dossier'"),
# pylint: disable=anomalous-backslash-in-string # pylint: disable=anomalous-backslash-in-string
pattern='^(?P<type_dossier>\w+)/(?P<numero_dossier>\w+)/?$', pattern='^(?P<type_dossier>\w+)/(?P<numero_dossier>\w+)/?$', # noqa: W605
example_pattern='{type_dossier}/{numero_dossier}', example_pattern='{type_dossier}/{numero_dossier}',
parameters={ parameters={
'type_dossier' : {'description': _("Type of 'dossier'"), 'example_value': 'DIA'}, 'type_dossier': {'description': _("Type of 'dossier'"), 'example_value': 'DIA'},
'numero_dossier': {'description': _("Identifier for 'dossier'"), 'numero_dossier': {'description': _("Identifier for 'dossier'"),
'example_value': 'DIA0130551900001'} 'example_value': 'DIA0130551900001'}
}, },
#~ get={ # get={
#~ 'description': _("Get informations about an openADS 'dossier'"), # 'description': _("Get informations about an openADS 'dossier'"),
#~ 'response_body': { # 'response_body': {
#~ 'schema': { # 'schema': {
#~ 'application/json': JSON_SCHEMA_GET_DOSSIER_OUT # 'application/json': JSON_SCHEMA_GET_DOSSIER_OUT
#~ } # }
#~ } # }
#~ } # }
) )
# pylint: disable=unused-argument,keyword-arg-before-vararg # pylint: disable=unused-argument,keyword-arg-before-vararg
def get_dossier(self, request, type_dossier, numero_dossier, *args, **kwargs): def get_dossier(self, request, type_dossier, numero_dossier, *args, **kwargs):
@ -896,22 +892,22 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
@endpoint( @endpoint(
perm='can_access', perm='can_access',
description=_("Get informations about the forwarding of user files to openADS"), description=_("Get informations about the forwarding of user files to openADS"),
pattern='^(?P<numero_dossier>\w+)/?$', # pylint: disable=anomalous-backslash-in-string pattern='^(?P<numero_dossier>\w+)/?$', # noqa: W605,E501, pylint: disable=anomalous-backslash-in-string
example_pattern='{numero_dossier}/', example_pattern='{numero_dossier}/',
parameters={ parameters={
'numero_dossier': {'description': _("Identifier for 'dossier'"), 'numero_dossier': {'description': _("Identifier for 'dossier'"),
'example_value': 'DIA0130551900001'}, 'example_value': 'DIA0130551900001'},
'fichier_id' : {'description': _("File identifier"), 'fichier_id': {'description': _("File identifier"),
'example_value': '78'} 'example_value': '78'}
}, },
#~ get={ # get={
#~ 'description': _("Get informations about the forwarding of user files to openADS"), # 'description': _("Get informations about the forwarding of user files to openADS"),
#~ 'response_body': { # 'response_body': {
#~ 'schema': { # 'schema': {
#~ 'application/json': JSON_SCHEMA_GET_FWD_FILES_OUT # 'application/json': JSON_SCHEMA_GET_FWD_FILES_OUT
#~ } # }
#~ } # }
#~ } # }
) )
# pylint: disable=unused-argument,keyword-arg-before-vararg,no-self-use # pylint: disable=unused-argument,keyword-arg-before-vararg,no-self-use
def get_fwd_files(self, request, numero_dossier, fichier_id=None, *args, **kwargs): def get_fwd_files(self, request, numero_dossier, fichier_id=None, *args, **kwargs):
@ -931,26 +927,26 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
except ValueError: except ValueError:
raise APIError('fichier_id must be an integer') raise APIError('fichier_id must be an integer')
try: try:
fwd_files = [ForwardFile.objects.get(id=fichier_id)] # pylint: disable=no-member fwd_files = [ForwardFile.objects.get(id=fichier_id)] # pylint: disable=no-member
except ForwardFile.DoesNotExist: # pylint: disable=no-member except ForwardFile.DoesNotExist: # pylint: disable=no-member
raise Http404(u"No file matches 'numero_dossier=%s' and 'id=%s'." % ( raise Http404(u"No file matches 'numero_dossier=%s' and 'id=%s'." % (
numero_dossier, fichier_id)) numero_dossier, fichier_id))
# append each file to the response payload # append each file to the response payload
for fwd_file in fwd_files: for fwd_file in fwd_files:
payload.append({ payload.append({
'id' : fwd_file.id, 'id': fwd_file.id,
'numero_demande': fwd_file.numero_demande, 'numero_demande': fwd_file.numero_demande,
'numero_dossier': fwd_file.numero_dossier, 'numero_dossier': fwd_file.numero_dossier,
'type_fichier' : fwd_file.type_fichier, 'type_fichier': fwd_file.type_fichier,
'file_hash' : fwd_file.file_hash, 'file_hash': fwd_file.file_hash,
'orig_filename' : fwd_file.orig_filename, 'orig_filename': fwd_file.orig_filename,
'content_type' : fwd_file.content_type, 'content_type': fwd_file.content_type,
'upload_status' : fwd_file.upload_status, 'upload_status': fwd_file.upload_status,
'upload_attempt': fwd_file.upload_attempt, 'upload_attempt': fwd_file.upload_attempt,
'upload_msg' : fwd_file.upload_msg, 'upload_msg': fwd_file.upload_msg,
'content_size' : fwd_file.upload_file.size if fwd_file.upload_file else 0, 'content_size': fwd_file.upload_file.size if fwd_file.upload_file else 0,
'last_update_datetime' : fwd_file.last_update_datetime 'last_update_datetime': fwd_file.last_update_datetime
}) })
# return the payload containing the list of files # return the payload containing the list of files
@ -959,22 +955,22 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
@endpoint( @endpoint(
perm='can_access', perm='can_access',
description=_("Get informations about the forwarding of a user file to openADS"), description=_("Get informations about the forwarding of a user file to openADS"),
pattern='^(?P<numero_dossier>\w+)/?$', # pylint: disable=anomalous-backslash-in-string pattern='^(?P<numero_dossier>\w+)/?$', # noqa: W605,E501, pylint: disable=anomalous-backslash-in-string
example_pattern='{numero_dossier}/', example_pattern='{numero_dossier}/',
parameters={ parameters={
'numero_dossier': {'description': _("Identifier for 'dossier'"), 'numero_dossier': {'description': _("Identifier for 'dossier'"),
'example_value': 'DIA0130551900001'}, 'example_value': 'DIA0130551900001'},
'fichier_id' : {'description': _("File identifier"), 'fichier_id': {'description': _("File identifier"),
'example_value': '78'} 'example_value': '78'}
}, },
#~ get={ # get={
#~ 'description': _("Get informations about the forwarding of a user file to openADS"), # 'description': _("Get informations about the forwarding of a user file to openADS"),
#~ 'response_body': { # 'response_body': {
#~ 'schema': { # 'schema': {
#~ 'application/json': JSON_SCHEMA_GET_FWD_FILES_STATUS_OUT # 'application/json': JSON_SCHEMA_GET_FWD_FILES_STATUS_OUT
#~ } # }
#~ } # }
#~ } # }
) )
# pylint: disable=unused-argument,keyword-arg-before-vararg # pylint: disable=unused-argument,keyword-arg-before-vararg
def get_fwd_files_status(self, request, numero_dossier, fichier_id=None, *args, **kwargs): def get_fwd_files_status(self, request, numero_dossier, fichier_id=None, *args, **kwargs):
@ -986,10 +982,10 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
# prepare the response payload # prepare the response payload
payload = { payload = {
'all_forwarded': True, 'all_forwarded': True,
'pending' : [], 'pending': [],
'uploading' : [], 'uploading': [],
'success' : [], 'success': [],
'failed' : [] 'failed': []
} }
# build a summary of all files statuses # build a summary of all files statuses
@ -1009,24 +1005,23 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
@endpoint( @endpoint(
perm='can_access', perm='can_access',
description=_("Get a 'courrier' from an openADS 'dossier'"), description=_("Get a 'courrier' from an openADS 'dossier'"),
# pylint: disable=anomalous-backslash-in-string pattern='^(?P<type_dossier>\w+)/(?P<numero_dossier>\w+)/(?P<lettre_type>\w+)/?$', # noqa: W605,E501, pylint: disable=anomalous-backslash-in-string
pattern='^(?P<type_dossier>\w+)/(?P<numero_dossier>\w+)/(?P<lettre_type>\w+)/?$',
example_pattern='{type_dossier}/{numero_dossier}/{lettre_type}', example_pattern='{type_dossier}/{numero_dossier}/{lettre_type}',
parameters={ parameters={
'type_dossier' : {'description': _("Type of 'dossier'"), 'example_value': 'DIA'}, 'type_dossier': {'description': _("Type of 'dossier'"), 'example_value': 'DIA'},
'numero_dossier': {'description': _("Identifier for 'dossier'"), 'numero_dossier': {'description': _("Identifier for 'dossier'"),
'example_value': 'DIA0130551900001'}, 'example_value': 'DIA0130551900001'},
'lettre_type' : {'description': _("Courrier ID to get"), 'lettre_type': {'description': _("Courrier ID to get"),
'example_value': 'dia_renonciation_preempter'} 'example_value': 'dia_renonciation_preempter'}
}, },
#~ get={ # get={
#~ 'description': _("Get a 'courrier' from an openADS 'dossier'"), # 'description': _("Get a 'courrier' from an openADS 'dossier'"),
#~ 'response_body': { # 'response_body': {
#~ 'schema': { # 'schema': {
#~ 'application/json': JSON_SCHEMA_GET_COURRIER_OUT # 'application/json': JSON_SCHEMA_GET_COURRIER_OUT
#~ } # }
#~ } # }
#~ } # }
) )
# pylint: disable=unused-argument,keyword-arg-before-vararg # pylint: disable=unused-argument,keyword-arg-before-vararg
def get_courrier(self, request, type_dossier, numero_dossier, lettre_type, *args, **kwargs): def get_courrier(self, request, type_dossier, numero_dossier, lettre_type, *args, **kwargs):
@ -1065,7 +1060,7 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
# return the 'courrier' file # return the 'courrier' file
return {'courrier': courrier} return {'courrier': courrier}
def get_response_error(self, response): # pylint: disable=no-self-use def get_response_error(self, response): # pylint: disable=no-self-use
"""Return a error string from an HTTP response.""" """Return a error string from an HTTP response."""
try: try:
# load the response as JSON # load the response as JSON
@ -1099,24 +1094,24 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
perm='can_access', perm='can_access',
description=_("Trigger the uploading of user's files to openADS"), description=_("Trigger the uploading of user's files to openADS"),
# pylint: disable=anomalous-backslash-in-string # pylint: disable=anomalous-backslash-in-string
pattern='^(?P<type_dossier>\w+)/(?P<numero_dossier>\w+)/?$', pattern='^(?P<type_dossier>\w+)/(?P<numero_dossier>\w+)/?$', # noqa: W605
example_pattern='{type_dossier}/{numero_dossier}', example_pattern='{type_dossier}/{numero_dossier}',
parameters={ parameters={
'type_dossier' : {'description': _("Type of 'dossier'"), 'example_value': 'DIA'}, 'type_dossier': {'description': _("Type of 'dossier'"), 'example_value': 'DIA'},
'numero_dossier': {'description': _("Identifier for 'dossier'"), 'numero_dossier': {'description': _("Identifier for 'dossier'"),
'example_value': 'DIA0130551900001'}, 'example_value': 'DIA0130551900001'},
'file_ids' : {'description': _(("List of ForwardFile IDs to upload " 'file_ids': {'description': _(("List of ForwardFile IDs to upload "
"(coma separated)")), "(coma separated)")),
'example_value': '12,18'} 'example_value': '12,18'}
}, # pylint: disable=too-many-statements,too-many-branches,too-many-locals }, # pylint: disable=too-many-statements,too-many-branches,too-many-locals
#~ get={ # get={
#~ 'description': _("Trigger the uploading of user's files to openADS"), # 'description': _("Trigger the uploading of user's files to openADS"),
#~ 'response_body': { # 'response_body': {
#~ 'schema': { # 'schema': {
#~ 'application/json': JSON_SCHEMA_UPLOAD_USER_FILES # 'application/json': JSON_SCHEMA_UPLOAD_USER_FILES
#~ } # }
#~ } # }
#~ } # }
) )
# @raise ForwareFile.DoesNotExist if not found # @raise ForwareFile.DoesNotExist if not found
# pylint: disable=unused-argument,keyword-arg-before-vararg # pylint: disable=unused-argument,keyword-arg-before-vararg
@ -1148,7 +1143,7 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
fwd_files_ids = set([ff.id for ff in fwd_files]) fwd_files_ids = set([ff.id for ff in fwd_files])
file_ids_diff = [item for item in file_ids if item not in fwd_files_ids] file_ids_diff = [item for item in file_ids if item not in fwd_files_ids]
if file_ids_diff: if file_ids_diff:
raise ForwardFile.DoesNotExist( # pylint: disable=no-member raise ForwardFile.DoesNotExist( # pylint: disable=no-member
"The following ForwardFile IDs were not found: %s." % file_ids_diff) "The following ForwardFile IDs were not found: %s." % file_ids_diff)
# filter out files not in status 'pending' # filter out files not in status 'pending'
@ -1165,7 +1160,7 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
else: else:
# process all ForwardFiles of the 'dossier' (in status 'pending') # process all ForwardFiles of the 'dossier' (in status 'pending')
fwd_files = ForwardFile.objects.filter( # pylint: disable=no-member fwd_files = ForwardFile.objects.filter( # pylint: disable=no-member
numero_dossier=numero_dossier, numero_dossier=numero_dossier,
upload_status='pending' upload_status='pending'
).all() ).all()
@ -1176,12 +1171,12 @@ class AtrealOpenads(BaseResource, HTTPResource, BaseModel):
# add the file content and data to the payload # add the file content and data to the payload
payload.append({ payload.append({
'filename' : '%s%s' % ( 'filename': '%s%s' % (
fwd_file.orig_filename, fwd_file.orig_filename,
'.pdf' if fwd_file.orig_filename[-4:] != '.pdf' else ''), '.pdf' if fwd_file.orig_filename[-4:] != '.pdf' else ''),
'content_type' : fwd_file.content_type, 'content_type': fwd_file.content_type,
'b64_content' : base64.b64encode(fwd_file.upload_file.read()), 'b64_content': base64.b64encode(fwd_file.upload_file.read()),
'file_type' : fwd_file.type_fichier 'file_type': fwd_file.type_fichier
}) })
self.logger.debug("upload_user_files() payload added") self.logger.debug("upload_user_files() payload added")

View File

@ -76,7 +76,7 @@ for view in [
regex_base = r'^(?P<connecteur>[\w,-]+)/' regex_base = r'^(?P<connecteur>[\w,-]+)/'
# pylint: disable=anomalous-backslash-in-string # pylint: disable=anomalous-backslash-in-string
regex_pkey = '/(?P<pk>[\w,-]+)' regex_pkey = '/(?P<pk>[\w,-]+)' # noqa: W605
url_name = url_prefix + view.model.get_class_name_dash_case() url_name = url_prefix + view.model.get_class_name_dash_case()
regex_url = '%s%s' % (url_prefix if view_action != 'view' else '', regex_url = '%s%s' % (url_prefix if view_action != 'view' else '',
@ -93,7 +93,7 @@ for view in [
# for 'guichet' prefix the regex by the collectivite # for 'guichet' prefix the regex by the collectivite
if view.model.get_class_name() == 'Guichet': if view.model.get_class_name() == 'Guichet':
regex_base += 'collectivite/(?P<collectivite>[\w,-]+)/' regex_base += 'collectivite/(?P<collectivite>[\w,-]+)/' # noqa: W605
# build the regex # build the regex
regex = regex_base + regex_url + regex_pkey + '$' regex = regex_base + regex_url + regex_pkey + '$'

View File

@ -56,8 +56,10 @@ class MLStripper(HTMLParser):
def __init__(self): def __init__(self):
self.reset() self.reset()
self.fed = [] self.fed = []
def handle_data(self, data): def handle_data(self, data):
self.fed.append(data) self.fed.append(data)
def get_data(self): def get_data(self):
"""Get the stripped data as a string.""" """Get the stripped data as a string."""
return ''.join(self.fed) return ''.join(self.fed)
@ -103,9 +105,11 @@ def get_file_digest(content, chunk_size=100000):
"""Return a hash for the content specified.""" """Return a hash for the content specified."""
digest = hashlib.sha256() digest = hashlib.sha256()
content.seek(0) content.seek(0)
def read_chunk(): def read_chunk():
"""Read 'chunk_size' amount of data from the content.""" """Read 'chunk_size' amount of data from the content."""
return content.read(chunk_size) return content.read(chunk_size)
for chunk in iter(read_chunk, ''): for chunk in iter(read_chunk, ''):
digest.update(chunk) digest.update(chunk)
return digest.hexdigest() return digest.hexdigest()
@ -145,7 +149,7 @@ def trunc_str_values(value, limit, visited=None, truncate_text=u'…'):
if visited is None: if visited is None:
visited = [] visited = []
if not value in visited: if value not in visited:
if isinstance(value, basestring) and len(value) > limit: if isinstance(value, basestring) and len(value) > limit:
value = value[:limit] + truncate_text value = value[:limit] + truncate_text
elif isinstance(value, (dict, list, tuple)): elif isinstance(value, (dict, list, tuple)):

View File

@ -23,13 +23,13 @@
from django.urls import reverse_lazy from django.urls import reverse_lazy
from django.views.generic.detail import DetailView from django.views.generic.detail import DetailView
from django.views.generic.list import ListView from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.views.generic.edit import CreateView, UpdateView, DeleteView
from passerelle.views import GenericConnectorView from passerelle.views import GenericConnectorView
from .models import ForwardFile, Collectivite, Guichet, AtrealOpenads from .models import ForwardFile, Collectivite, Guichet, AtrealOpenads
from .forms import ForwardFileForm, CollectiviteForm, GuichetForm from .forms import ForwardFileForm, CollectiviteForm, GuichetForm
def get_connecteur_from_request(view, key='connecteur'): def get_connecteur_from_request(view, key='connecteur'):
@ -93,7 +93,7 @@ class ForwardFileListView(ListView):
if order_by_field in fields_names: if order_by_field in fields_names:
order_by = order_by_param order_by = order_by_param
return qset.order_by(order_by) if order_by else qset # qset.order_by() return qset.order_by(order_by) if order_by else qset # qset.order_by()
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(ForwardFileListView, self).get_context_data(**kwargs) context = super(ForwardFileListView, self).get_context_data(**kwargs)
@ -161,7 +161,7 @@ class ForwardFileDeleteView(DeleteView):
}) })
return reverse_lazy('view-connector', kwargs={ return reverse_lazy('view-connector', kwargs={
'connector': 'atreal-openads', 'connector': 'atreal-openads',
'slug' : get_connecteur_from_request(self).slug 'slug': get_connecteur_from_request(self).slug
}) })
@ -176,10 +176,10 @@ class CollectiviteView(DetailView):
context = super(CollectiviteView, self).get_context_data(**kwargs) context = super(CollectiviteView, self).get_context_data(**kwargs)
context['connecteur'] = get_connecteur_from_request(self) context['connecteur'] = get_connecteur_from_request(self)
context['guichet_add_url'] = reverse_lazy('create-guichet', kwargs={ context['guichet_add_url'] = reverse_lazy('create-guichet', kwargs={
'connecteur' : context['connecteur'].slug, 'connecteur': context['connecteur'].slug,
'collectivite': self.get_object().id}) 'collectivite': self.get_object().id})
context['forward_files_list_url'] = reverse_lazy('col-list-forward-files', kwargs={ context['forward_files_list_url'] = reverse_lazy('col-list-forward-files', kwargs={
'connecteur' : context['connecteur'].slug, 'connecteur': context['connecteur'].slug,
'collectivite': self.get_object().id}) 'collectivite': self.get_object().id})
return context return context
@ -205,7 +205,7 @@ class CollectiviteListView(ListView):
if order_by_field in fields_names: if order_by_field in fields_names:
order_by = order_by_param order_by = order_by_param
return qset.order_by(order_by) if order_by else qset # qset.order_by() return qset.order_by(order_by) if order_by else qset # qset.order_by()
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(CollectiviteListView, self).get_context_data(**kwargs) context = super(CollectiviteListView, self).get_context_data(**kwargs)
@ -236,11 +236,11 @@ class CollectiviteCreateView(CreateView):
def get_success_url(self): def get_success_url(self):
if self.request.GET.get('back-to') == 'list-collectivites': if self.request.GET.get('back-to') == 'list-collectivites':
return reverse_lazy('list-collectivites', kwargs={ return reverse_lazy('list-collectivites', kwargs={
'connecteur' : get_connecteur_from_request(self).slug 'connecteur': get_connecteur_from_request(self).slug
}) })
return reverse_lazy('view-connector', kwargs={ return reverse_lazy('view-connector', kwargs={
'connector': 'atreal-openads', 'connector': 'atreal-openads',
'slug' : get_connecteur_from_request(self).slug 'slug': get_connecteur_from_request(self).slug
}) })
@ -260,7 +260,7 @@ class CollectiviteUpdateView(UpdateView):
def get_success_url(self): def get_success_url(self):
if self.request.GET.get('back-to') == 'list-collectivites': if self.request.GET.get('back-to') == 'list-collectivites':
return reverse_lazy('list-collectivites', kwargs={ return reverse_lazy('list-collectivites', kwargs={
'connecteur' : get_connecteur_from_request(self).slug 'connecteur': get_connecteur_from_request(self).slug
}) })
return self.get_object().get_absolute_url() return self.get_object().get_absolute_url()
@ -281,11 +281,11 @@ class CollectiviteDeleteView(DeleteView):
def get_success_url(self): def get_success_url(self):
if self.request.GET.get('back-to') == 'list-collectivites': if self.request.GET.get('back-to') == 'list-collectivites':
return reverse_lazy('list-collectivites', kwargs={ return reverse_lazy('list-collectivites', kwargs={
'connecteur' : get_connecteur_from_request(self).slug 'connecteur': get_connecteur_from_request(self).slug
}) })
return reverse_lazy('view-connector', kwargs={ return reverse_lazy('view-connector', kwargs={
'connector': 'atreal-openads', 'connector': 'atreal-openads',
'slug' : get_connecteur_from_request(self).slug 'slug': get_connecteur_from_request(self).slug
}) })
@ -325,7 +325,7 @@ class GuichetCreateView(CreateView):
def get_success_url(self): def get_success_url(self):
return reverse_lazy('view-collectivite', kwargs={ return reverse_lazy('view-collectivite', kwargs={
'connecteur': get_connecteur_from_request(self).slug, 'connecteur': get_connecteur_from_request(self).slug,
'pk' : get_collectivite_from_request(self).id 'pk': get_collectivite_from_request(self).id
}) })
@ -361,7 +361,7 @@ class GuichetDeleteView(DeleteView):
def get_success_url(self): def get_success_url(self):
return reverse_lazy('view-collectivite', kwargs={ return reverse_lazy('view-collectivite', kwargs={
'connecteur': get_connecteur_from_request(self).slug, 'connecteur': get_connecteur_from_request(self).slug,
'pk' : get_collectivite_from_request(self).id 'pk': get_collectivite_from_request(self).id
}) })

View File

@ -39,8 +39,8 @@ def media(settings, tmpdir):
def app(request): def app(request):
"""Return a Django WebTest application.""" """Return a Django WebTest application."""
wtm = django_webtest.WebTestMixin() wtm = django_webtest.WebTestMixin()
wtm._patch_settings() # pylint: disable=protected-access wtm._patch_settings() # pylint: disable=protected-access
request.addfinalizer(wtm._unpatch_settings) # pylint: disable=protected-access request.addfinalizer(wtm._unpatch_settings) # pylint: disable=protected-access
cache.clear() cache.clear()
return django_webtest.DjangoTestApp() return django_webtest.DjangoTestApp()
@ -55,7 +55,7 @@ def endpoint_dummy_cache(monkeypatch):
@urlmatch() @urlmatch()
def internal_server_error(url, request): # pylint: disable=unused-argument def internal_server_error(url, request): # pylint: disable=unused-argument
"""Return an HTTP 500 error.""" """Return an HTTP 500 error."""
return response(500, 'Internal server error') return response(500, 'Internal server error')

View File

@ -26,7 +26,7 @@ LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC' TIME_ZONE = 'UTC'
# include app # include app
INSTALLED_APPS += ( # pylint: disable=undefined-variable INSTALLED_APPS += ( # noqa: F821, pylint: disable=undefined-variable
'atreal_openads', 'atreal_openads',
) )

View File

@ -31,14 +31,14 @@ import magic
import mock import mock
import pytest import pytest
from requests import Response from requests import Response
from django.http import Http404 from django.http import Http404
from django.http.request import HttpRequest, QueryDict from django.http.request import HttpRequest, QueryDict
from django.http.response import JsonResponse from django.http.response import JsonResponse
from django.core.files import File from django.core.files import File
from django.core.files.base import ContentFile from django.core.files.base import ContentFile
#from django.db.models.query import QuerySet # from django.db.models.query import QuerySet
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from passerelle.utils.jsonresponse import APIError from passerelle.utils.jsonresponse import APIError
@ -86,26 +86,28 @@ def atreal_openads(db):
basic_auth_password=OPENADS_API_PASSWORD basic_auth_password=OPENADS_API_PASSWORD
) )
@pytest.fixture @pytest.fixture
# pylint: disable=unused-argument,redefined-outer-name,invalid-name # pylint: disable=unused-argument,redefined-outer-name,invalid-name
def collectivite_1(db, atreal_openads): def collectivite_1(db, atreal_openads):
"""Return an instance of a 'Collectivite'.""" """Return an instance of a 'Collectivite'."""
return Collectivite.objects.create( # pylint: disable=no-member return Collectivite.objects.create( # pylint: disable=no-member
name=u'Macollectivité', name=u'Macollectivité',
connecteur=atreal_openads, connecteur=atreal_openads,
openADS_id='3' openADS_id='3'
) )
@pytest.fixture @pytest.fixture
# pylint: disable=unused-argument,redefined-outer-name,invalid-name # pylint: disable=unused-argument,redefined-outer-name,invalid-name
def collectivite_1_guichet(db, atreal_openads, collectivite_1): def collectivite_1_guichet(db, atreal_openads, collectivite_1):
"""Return an instance of a 'Guichet'.""" """Return an instance of a 'Guichet'."""
return Guichet.objects.create( # pylint: disable=no-member return Guichet.objects.create( # pylint: disable=no-member
collectivite=collectivite_1, collectivite=collectivite_1,
ouverture_jour_h=datetime.time(9, 0), ouverture_jour_h=datetime.time(9, 0),
fermeture_jour_h=datetime.time(17, 0), fermeture_jour_h=datetime.time(17, 0),
ouverture_sem_d=1, # Lundi ouverture_sem_d=1, # Lundi
fermeture_sem_d=5, # Vendredi fermeture_sem_d=5, # Vendredi
ouverture_sem_h=datetime.time(8, 30), ouverture_sem_h=datetime.time(8, 30),
fermeture_sem_h=datetime.time(12, 15) fermeture_sem_h=datetime.time(12, 15)
) )
@ -152,7 +154,7 @@ def test_forward_file(atreal_openads):
assert repr(forwardfile) == ( assert repr(forwardfile) == (
u'ForwardFile(id=%s,connecteur=%s,collectivite=%s' u'ForwardFile(id=%s,connecteur=%s,collectivite=%s'
',demande=%s,dossier=%s,type=%s,filename=%s,status=%s)' % ( ',demande=%s,dossier=%s,type=%s,filename=%s,status=%s)' % (
forwardfile.id, unicode(forwardfile.connecteur), None, # pylint: disable=no-member forwardfile.id, unicode(forwardfile.connecteur), None, # pylint: disable=no-member
forwardfile.numero_demande, forwardfile.numero_dossier, forwardfile.numero_demande, forwardfile.numero_dossier,
forwardfile.type_fichier, forwardfile.orig_filename, forwardfile.upload_status forwardfile.type_fichier, forwardfile.orig_filename, forwardfile.upload_status
) )
@ -183,7 +185,7 @@ def test_forward_file(atreal_openads):
assert forwardfile.content_type == 'application/pdf' assert forwardfile.content_type == 'application/pdf'
with pytest.raises(ValueError) as exception: with pytest.raises(ValueError) as exception:
forwardfile.upload_file.size # pylint: disable=pointless-statement forwardfile.upload_file.size # pylint: disable=pointless-statement
assert unicode(exception.value) == "The 'upload_file' attribute has no file associated with it." assert unicode(exception.value) == "The 'upload_file' attribute has no file associated with it."
assert forwardfile.size > 0 assert forwardfile.size > 0
assert forwardfile.file_hash == ('811588016518eedeb4507f3e4c41be95' assert forwardfile.file_hash == ('811588016518eedeb4507f3e4c41be95'
@ -248,7 +250,7 @@ def test_collectivite(collectivite_1, collectivite_1_guichet):
assert instance_fields[2][1] is col.connecteur assert instance_fields[2][1] is col.connecteur
assert instance_fields[3][1] == col.openADS_id assert instance_fields[3][1] == col.openADS_id
assert instance_fields[4][1] is col.guichet assert instance_fields[4][1] is col.guichet
assert instance_fields[5][1] is None # shouldn't it be QuerySet? assert instance_fields[5][1] is None # shouldn't it be QuerySet?
params = col.get_url_params() params = col.get_url_params()
assert params['connecteur'] == col.connecteur.slug assert params['connecteur'] == col.connecteur.slug
@ -279,7 +281,7 @@ def test_guichet(collectivite_1_guichet):
# pylint: disable=unused-argument,redefined-outer-name # pylint: disable=unused-argument,redefined-outer-name
def test_guichet_is_open(collectivite_1_guichet): # pylint: disable=too-many-locals def test_guichet_is_open(collectivite_1_guichet): # pylint: disable=too-many-locals
"""Test the method Guichet.is_open().""" """Test the method Guichet.is_open()."""
guichet = collectivite_1_guichet guichet = collectivite_1_guichet
@ -333,7 +335,7 @@ def test_get_files_from_payload(atreal_openads):
title = 'payload' title = 'payload'
assert atreal_openads.get_files_from_payload({'files':[{'a':'file'}]}) == [{'a':'file'}] assert atreal_openads.get_files_from_payload({'files': [{'a': 'file'}]}) == [{'a': 'file'}]
with pytest.raises(APIError) as exception: with pytest.raises(APIError) as exception:
atreal_openads.get_files_from_payload({}) atreal_openads.get_files_from_payload({})
@ -345,7 +347,7 @@ def test_get_files_from_payload(atreal_openads):
'files', title, 'list', type('')) 'files', title, 'list', type(''))
with pytest.raises(APIError) as exception: with pytest.raises(APIError) as exception:
atreal_openads.get_files_from_payload({'files': {'i':'invalid'}}) atreal_openads.get_files_from_payload({'files': {'i': 'invalid'}})
assert unicode(exception.value) == u"Expecting '%s' value in JSON %s to be a %s (not a %s)" % ( assert unicode(exception.value) == u"Expecting '%s' value in JSON %s to be a %s (not a %s)" % (
'files', title, 'list', type({})) 'files', title, 'list', type({}))
@ -403,7 +405,7 @@ def test_check_file_dict(atreal_openads):
# pylint: disable=unused-argument,redefined-outer-name # pylint: disable=unused-argument,redefined-outer-name
def test_get_first_file_from_payload(atreal_openads): # pylint: disable=invalid-name def test_get_first_file_from_payload(atreal_openads): # pylint: disable=invalid-name
"""Test the method AtrealOpenads.get_first_file_from_payload().""" """Test the method AtrealOpenads.get_first_file_from_payload()."""
title = 'payload' title = 'payload'
@ -443,88 +445,88 @@ def test_create_dossier(atreal_openads, collectivite_1, collectivite_1_guichet):
"fields": { "fields": {
# proprietaire # proprietaire
"proprietaire" : "Non", "proprietaire": "Non",
"proprietaire_raw": "Non", "proprietaire_raw": "Non",
# mandataire # mandataire
"mandataire_prenom" : "John", "mandataire_prenom": "John",
"mandataire_nom" : "Man", "mandataire_nom": "Man",
"mandataire_email" : "mandataire_email@domain.example", "mandataire_email": "mandataire_email@domain.example",
"mandataire_qualite" : "Une personne morale", "mandataire_qualite": "Une personne morale",
"mandataire_qualite_raw" : "Une personne morale", "mandataire_qualite_raw": "Une personne morale",
"mandataire_denomination" : "SELARL", "mandataire_denomination": "SELARL",
"mandataire_raison_sociale" : "Super Juriste", "mandataire_raison_sociale": "Super Juriste",
"mandataire_numero_voie": "808", "mandataire_numero_voie": "808",
"mandataire_nom_voie" : "Avenue de l'argent", "mandataire_nom_voie": "Avenue de l'argent",
"mandataire_lieu_dit" : "geoisbour", "mandataire_lieu_dit": "geoisbour",
"mandataire_code_postal": "13004", "mandataire_code_postal": "13004",
"mandataire_localite" : "Marseille", "mandataire_localite": "Marseille",
# petitionnaire # petitionnaire
"prenom": "Toto", "prenom": "Toto",
"nom" : "Loulou", "nom": "Loulou",
"email" : "petitionnaire_email@domain.example", "email": "petitionnaire_email@domain.example",
"qualite" : "Un particulier", "qualite": "Un particulier",
"qualite_raw": "Un particulier", "qualite_raw": "Un particulier",
"numero_voie": "52", "numero_voie": "52",
"nom_voie" : "Avenue de la Blaque", "nom_voie": "Avenue de la Blaque",
"lieu_dit" : "tierquar", "lieu_dit": "tierquar",
"code_postal": "13004", "code_postal": "13004",
"localite" : "Marseille", "localite": "Marseille",
# terrain # terrain
"terrain_numero_voie": "23", "terrain_numero_voie": "23",
"terrain_nom_voie" : "Boulevard de la République", "terrain_nom_voie": "Boulevard de la République",
"terrain_lieu_dit" : "Leecorne", "terrain_lieu_dit": "Leecorne",
"terrain_code_postal": "13002", "terrain_code_postal": "13002",
"terrain_localite" : "Marseille", "terrain_localite": "Marseille",
# références cadastrales # références cadastrales
"reference_cadastrale" : [["999", "Z", "0010"]], "reference_cadastrale": [["999", "Z", "0010"]],
"autres_parcelles" : True, "autres_parcelles": True,
"references_cadastrales": [["123", "D", "9874"]], "references_cadastrales": [["123", "D", "9874"]],
# user attached files # user attached files
"cerfa": { "cerfa": {
"content" : get_file_data(TEST_FILE_CERFA_DIA), "content": get_file_data(TEST_FILE_CERFA_DIA),
"content_type": "invalid/content type", "content_type": "invalid/content type",
"field_id" : "50", "field_id": "50",
"filename" : os.path.basename(TEST_FILE_CERFA_DIA) "filename": os.path.basename(TEST_FILE_CERFA_DIA)
}, },
"plan_cadastral_1": { "plan_cadastral_1": {
"content" : get_file_data(TEST_FILE_PLAN_CADASTRAL), "content": get_file_data(TEST_FILE_PLAN_CADASTRAL),
"content_type": "application/pdf", "content_type": "application/pdf",
"filename" : os.path.basename(TEST_FILE_PLAN_CADASTRAL) "filename": os.path.basename(TEST_FILE_PLAN_CADASTRAL)
}, },
"plan_cadastral_2": { "plan_cadastral_2": {
"content" : get_file_data(TEST_FILE_PLAN_CADASTRAL), "content": get_file_data(TEST_FILE_PLAN_CADASTRAL),
"content_type": "application/pdf", "content_type": "application/pdf",
#"filename" : 'plan_cad' # "filename": 'plan_cad'
}, },
"pouvoir_mandat": { "pouvoir_mandat": {
"content" : get_file_data(TEST_FILE_CERFA_DIA), "content": get_file_data(TEST_FILE_CERFA_DIA),
"content_type": "application/pdf", "content_type": "application/pdf",
"filename" : 'mandat' "filename": 'mandat'
} }
} }
} }
req = HttpRequest() req = HttpRequest()
req._body = json.dumps(fake_req_json) # pylint: disable=protected-access req._body = json.dumps(fake_req_json) # pylint: disable=protected-access
req.path = '/test' req.path = '/test'
req.method = 'POST' req.method = 'POST'
req.encoding = 'utf-8' req.encoding = 'utf-8'
req.GET = QueryDict(mutable=True) # required because of encoding setter req.GET = QueryDict(mutable=True) # required because of encoding setter
req.POST = QueryDict(mutable=True) # required because of encoding setter req.POST = QueryDict(mutable=True) # required because of encoding setter
req.content_type = 'application/json' req.content_type = 'application/json'
req.content_params = None req.content_params = None
req.COOKIES = {} req.COOKIES = {}
req.META = {} req.META = {}
req._read_started = False # pylint: disable=protected-access req._read_started = False # pylint: disable=protected-access
fake_resp_bad = Response() fake_resp_bad = Response()
fake_resp_bad.status_code = 502 fake_resp_bad.status_code = 502
@ -537,8 +539,8 @@ def test_create_dossier(atreal_openads, collectivite_1, collectivite_1_guichet):
assert unicode(exception.value) == "invalid literal for int() with base 10: 'not an integer'" assert unicode(exception.value) == "invalid literal for int() with base 10: 'not an integer'"
# guichet is open from Monday/8:30 to Friday/12:15, between 9:00 and 17:00 # guichet is open from Monday/8:30 to Friday/12:15, between 9:00 and 17:00
now_open = datetime.datetime(2019, 8, 7, 14, 0, 0) # wednesday now_open = datetime.datetime(2019, 8, 7, 14, 0, 0) # wednesday
now_closed = datetime.datetime(2019, 8, 10, 16, 0, 0) # saturday now_closed = datetime.datetime(2019, 8, 10, 16, 0, 0) # saturday
with pytest.raises(APIError) as exception: with pytest.raises(APIError) as exception:
with mock.patch('passerelle.utils.Request.post') as requests_post: with mock.patch('passerelle.utils.Request.post') as requests_post:
@ -582,11 +584,11 @@ def test_create_dossier(atreal_openads, collectivite_1, collectivite_1_guichet):
"datetime or string formatted to '%s'" % now_str_fmt)) "datetime or string formatted to '%s'" % now_str_fmt))
fake_resp_json = { fake_resp_json = {
'numero_dossier' : FAKE_NUMERO_DOSSIER, 'numero_dossier': FAKE_NUMERO_DOSSIER,
'files': [{ 'files': [{
'b64_content' : get_file_data(TEST_FILE_CERFA_DIA), 'b64_content': get_file_data(TEST_FILE_CERFA_DIA),
'content_type' : 'text/plain', 'content_type': 'text/plain',
'filename' : 'recepisse_depot_%s.pdf' % FAKE_NUMERO_DOSSIER, 'filename': 'recepisse_depot_%s.pdf' % FAKE_NUMERO_DOSSIER,
}] }]
} }
fake_resp = Response() fake_resp = Response()
@ -594,7 +596,7 @@ def test_create_dossier(atreal_openads, collectivite_1, collectivite_1_guichet):
fake_resp.headers = {'Content-Type': 'application/json'} fake_resp.headers = {'Content-Type': 'application/json'}
fake_resp.encoding = 'utf-8' fake_resp.encoding = 'utf-8'
fake_resp.reason = 'OK' fake_resp.reason = 'OK'
fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access
with mock.patch('passerelle.utils.Request.post') as requests_post: with mock.patch('passerelle.utils.Request.post') as requests_post:
requests_post.return_value = fake_resp requests_post.return_value = fake_resp
@ -604,8 +606,8 @@ def test_create_dossier(atreal_openads, collectivite_1, collectivite_1_guichet):
assert jresp['recepisse']['content_type'] == 'application/pdf' assert jresp['recepisse']['content_type'] == 'application/pdf'
assert jresp['recepisse']['filename'] == fake_resp_json['files'][0]['filename'] assert jresp['recepisse']['filename'] == fake_resp_json['files'][0]['filename']
fake_resp_json['numero_dossier'] = {'a':'invalid type'} fake_resp_json['numero_dossier'] = {'a': 'invalid type'}
fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access
with pytest.raises(APIError) as exception: with pytest.raises(APIError) as exception:
with mock.patch('passerelle.utils.Request.post') as requests_post: with mock.patch('passerelle.utils.Request.post') as requests_post:
requests_post.return_value = fake_resp requests_post.return_value = fake_resp
@ -615,7 +617,7 @@ def test_create_dossier(atreal_openads, collectivite_1, collectivite_1_guichet):
'numero_dossier', 'string', type({}))) 'numero_dossier', 'string', type({})))
del fake_resp_json['numero_dossier'] del fake_resp_json['numero_dossier']
fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access
with pytest.raises(APIError) as exception: with pytest.raises(APIError) as exception:
with mock.patch('passerelle.utils.Request.post') as requests_post: with mock.patch('passerelle.utils.Request.post') as requests_post:
requests_post.return_value = fake_resp requests_post.return_value = fake_resp
@ -623,14 +625,14 @@ def test_create_dossier(atreal_openads, collectivite_1, collectivite_1_guichet):
assert unicode(exception.value) == u"Expecting 'numero_dossier' key in JSON response" assert unicode(exception.value) == u"Expecting 'numero_dossier' key in JSON response"
fake_resp_json['files'][0]['b64_content'] = 'invalid_;{[content}' fake_resp_json['files'][0]['b64_content'] = 'invalid_;{[content}'
fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access
with pytest.raises(APIError) as exception: with pytest.raises(APIError) as exception:
with mock.patch('passerelle.utils.Request.post') as requests_post: with mock.patch('passerelle.utils.Request.post') as requests_post:
requests_post.return_value = fake_resp requests_post.return_value = fake_resp
atreal_openads.create_dossier(req, 'DIA', collectivite_1.openADS_id, now=now_open) atreal_openads.create_dossier(req, 'DIA', collectivite_1.openADS_id, now=now_open)
assert unicode(exception.value) == u'Failed to decode recepisse content from base 64' assert unicode(exception.value) == u'Failed to decode recepisse content from base 64'
fake_resp._content = 'df[{gfd;g#vfd' # pylint: disable=protected-access fake_resp._content = 'df[{gfd;g#vfd' # pylint: disable=protected-access
with pytest.raises(APIError) as exception: with pytest.raises(APIError) as exception:
with mock.patch('passerelle.utils.Request.post') as requests_post: with mock.patch('passerelle.utils.Request.post') as requests_post:
requests_post.return_value = fake_resp requests_post.return_value = fake_resp
@ -638,7 +640,7 @@ def test_create_dossier(atreal_openads, collectivite_1, collectivite_1_guichet):
# pylint: disable=protected-access # pylint: disable=protected-access
assert unicode(exception.value) == u'No JSON content returned: %r' % fake_resp._content assert unicode(exception.value) == u'No JSON content returned: %r' % fake_resp._content
job = Job.objects.filter(natural_id=FAKE_NUMERO_DOSSIER).last() # pylint: disable=no-member job = Job.objects.filter(natural_id=FAKE_NUMERO_DOSSIER).last() # pylint: disable=no-member
assert job assert job
job_id = job.id job_id = job.id
assert job.status == 'registered' assert job.status == 'registered'
@ -650,7 +652,7 @@ def test_create_dossier(atreal_openads, collectivite_1, collectivite_1_guichet):
assert len(job.parameters['file_ids']) == 4 assert len(job.parameters['file_ids']) == 4
file_ids = job.parameters['file_ids'] file_ids = job.parameters['file_ids']
forwardfiles = ForwardFile.objects.filter(id__in=file_ids) # pylint: disable=no-member forwardfiles = ForwardFile.objects.filter(id__in=file_ids) # pylint: disable=no-member
for forwardfile in forwardfiles: for forwardfile in forwardfiles:
assert forwardfile.numero_demande assert forwardfile.numero_demande
assert forwardfile.numero_dossier == FAKE_NUMERO_DOSSIER assert forwardfile.numero_dossier == FAKE_NUMERO_DOSSIER
@ -668,10 +670,10 @@ def test_create_dossier(atreal_openads, collectivite_1, collectivite_1_guichet):
requests_post.return_value = fake_resp requests_post.return_value = fake_resp
atreal_openads.jobs() atreal_openads.jobs()
job = Job.objects.get(id=job_id) # pylint: disable=no-member job = Job.objects.get(id=job_id) # pylint: disable=no-member
assert job.status == 'completed' assert job.status == 'completed'
forwardfiles = ForwardFile.objects.filter(id__in=file_ids) # pylint: disable=no-member forwardfiles = ForwardFile.objects.filter(id__in=file_ids) # pylint: disable=no-member
for forwardfile in forwardfiles: for forwardfile in forwardfiles:
assert forwardfile.upload_status == 'success' assert forwardfile.upload_status == 'success'
@ -691,10 +693,10 @@ def test_get_dossier(atreal_openads):
assert unicode(exception.value) == "HTTP error: 502" assert unicode(exception.value) == "HTTP error: 502"
fake_resp_json = { fake_resp_json = {
'etat' : u"Non préemption en cours", 'etat': u"Non préemption en cours",
'date_depot' : "24/04/2019", 'date_depot': "24/04/2019",
'date_decision' : "", 'date_decision': "",
'decision' : "", 'decision': "",
'date_limite_instruction': "24/06/2019" 'date_limite_instruction': "24/06/2019"
} }
fake_resp = Response() fake_resp = Response()
@ -702,7 +704,7 @@ def test_get_dossier(atreal_openads):
fake_resp.headers = {'Content-Type': 'application/json'} fake_resp.headers = {'Content-Type': 'application/json'}
fake_resp.encoding = 'utf-8' fake_resp.encoding = 'utf-8'
fake_resp.reason = 'OK' fake_resp.reason = 'OK'
fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access
with mock.patch('passerelle.utils.Request.get') as requests_get: with mock.patch('passerelle.utils.Request.get') as requests_get:
requests_get.return_value = fake_resp requests_get.return_value = fake_resp
jresp = atreal_openads.get_dossier(None, 'DIA', FAKE_NUMERO_DOSSIER) jresp = atreal_openads.get_dossier(None, 'DIA', FAKE_NUMERO_DOSSIER)
@ -712,7 +714,7 @@ def test_get_dossier(atreal_openads):
assert jresp['decision'] == fake_resp_json['decision'] assert jresp['decision'] == fake_resp_json['decision']
assert jresp['date_limite_instruction'] == fake_resp_json['date_limite_instruction'] assert jresp['date_limite_instruction'] == fake_resp_json['date_limite_instruction']
fake_resp._content = 'df[{gfd;g#vfd' # pylint: disable=protected-access fake_resp._content = 'df[{gfd;g#vfd' # pylint: disable=protected-access
with pytest.raises(APIError) as exception: with pytest.raises(APIError) as exception:
with mock.patch('passerelle.utils.Request.get') as requests_get: with mock.patch('passerelle.utils.Request.get') as requests_get:
requests_get.return_value = fake_resp requests_get.return_value = fake_resp
@ -721,15 +723,15 @@ def test_get_dossier(atreal_openads):
assert unicode(exception.value) == u'No JSON content returned: %r' % fake_resp._content assert unicode(exception.value) == u'No JSON content returned: %r' % fake_resp._content
fake_resp_json = { fake_resp_json = {
'errors' : [{ 'errors': [{
'location' : 'path', 'location': 'path',
'name' : 'Invalid Type', 'name': 'Invalid Type',
'description' : '"invalid_type" is not one of DIA, PC, DP, AT, PD' 'description': '"invalid_type" is not one of DIA, PC, DP, AT, PD'
}] }]
} }
fake_resp.status_code = 404 fake_resp.status_code = 404
fake_resp.reason = 'Resource not found' fake_resp.reason = 'Resource not found'
fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access
with pytest.raises(APIError) as exception: with pytest.raises(APIError) as exception:
with mock.patch('passerelle.utils.Request.get') as requests_get: with mock.patch('passerelle.utils.Request.get') as requests_get:
requests_get.return_value = fake_resp requests_get.return_value = fake_resp
@ -765,7 +767,7 @@ def test_get_fwd_files(atreal_openads):
jresp = atreal_openads.get_fwd_files(None, FAKE_NUMERO_DOSSIER, fichier_id=None) jresp = atreal_openads.get_fwd_files(None, FAKE_NUMERO_DOSSIER, fichier_id=None)
assert jresp is not None assert jresp is not None
assert len(jresp) == 1 assert len(jresp) == 1
assert jresp[0]['id'] == forwardfile.id # pylint: disable=no-member assert jresp[0]['id'] == forwardfile.id # pylint: disable=no-member
for attr in ['numero_dossier', 'type_fichier', 'file_hash', 'orig_filename', 'content_type', for attr in ['numero_dossier', 'type_fichier', 'file_hash', 'orig_filename', 'content_type',
'upload_status', 'upload_msg']: 'upload_status', 'upload_msg']:
assert jresp[0][attr] == getattr(forwardfile, attr) assert jresp[0][attr] == getattr(forwardfile, attr)
@ -777,7 +779,7 @@ def test_get_fwd_files(atreal_openads):
jresp = atreal_openads.get_fwd_files(None, FAKE_NUMERO_DOSSIER, fichier_id=forwardfile.id) jresp = atreal_openads.get_fwd_files(None, FAKE_NUMERO_DOSSIER, fichier_id=forwardfile.id)
assert jresp is not None assert jresp is not None
assert len(jresp) == 1 assert len(jresp) == 1
assert jresp[0]['id'] == forwardfile.id # pylint: disable=no-member assert jresp[0]['id'] == forwardfile.id # pylint: disable=no-member
for attr in ['numero_dossier', 'type_fichier', 'file_hash', 'orig_filename', 'content_type', for attr in ['numero_dossier', 'type_fichier', 'file_hash', 'orig_filename', 'content_type',
'upload_status', 'upload_msg']: 'upload_status', 'upload_msg']:
assert jresp[0][attr] == getattr(forwardfile, attr) assert jresp[0][attr] == getattr(forwardfile, attr)
@ -846,9 +848,9 @@ def test_get_courrier(atreal_openads):
fake_resp_json = { fake_resp_json = {
'files': [{ 'files': [{
'filename' : "instruction_4.pdf", 'filename': "instruction_4.pdf",
'content_type' : "text/plain", 'content_type': "text/plain",
'b64_content' : get_file_data(TEST_FILE_CERFA_DIA) 'b64_content': get_file_data(TEST_FILE_CERFA_DIA)
}] }]
} }
fake_resp = Response() fake_resp = Response()
@ -856,7 +858,7 @@ def test_get_courrier(atreal_openads):
fake_resp.headers = {'Content-Type': 'application/json'} fake_resp.headers = {'Content-Type': 'application/json'}
fake_resp.encoding = 'utf-8' fake_resp.encoding = 'utf-8'
fake_resp.reason = 'OK' fake_resp.reason = 'OK'
fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access
with mock.patch('passerelle.utils.Request.get') as requests_get: with mock.patch('passerelle.utils.Request.get') as requests_get:
requests_get.return_value = fake_resp requests_get.return_value = fake_resp
jresp = atreal_openads.get_courrier(None, 'DIA', FAKE_NUMERO_DOSSIER, lettre_type) jresp = atreal_openads.get_courrier(None, 'DIA', FAKE_NUMERO_DOSSIER, lettre_type)
@ -865,14 +867,14 @@ def test_get_courrier(atreal_openads):
assert jresp['courrier']['b64_content'] == fake_resp_json['files'][0]['b64_content'] assert jresp['courrier']['b64_content'] == fake_resp_json['files'][0]['b64_content']
fake_resp_json['files'][0]['b64_content'] = 'invalid_;{[content}' fake_resp_json['files'][0]['b64_content'] = 'invalid_;{[content}'
fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access
with pytest.raises(APIError) as exception: with pytest.raises(APIError) as exception:
with mock.patch('passerelle.utils.Request.get') as requests_get: with mock.patch('passerelle.utils.Request.get') as requests_get:
requests_get.return_value = fake_resp requests_get.return_value = fake_resp
atreal_openads.get_courrier(None, 'DIA', FAKE_NUMERO_DOSSIER, lettre_type) atreal_openads.get_courrier(None, 'DIA', FAKE_NUMERO_DOSSIER, lettre_type)
assert unicode(exception.value) == u'Failed to decode courrier content from base 64' assert unicode(exception.value) == u'Failed to decode courrier content from base 64'
fake_resp._content = 'df[{gfd;g#vfd' # pylint: disable=protected-access fake_resp._content = 'df[{gfd;g#vfd' # pylint: disable=protected-access
with pytest.raises(APIError) as exception: with pytest.raises(APIError) as exception:
with mock.patch('passerelle.utils.Request.get') as requests_get: with mock.patch('passerelle.utils.Request.get') as requests_get:
requests_get.return_value = fake_resp requests_get.return_value = fake_resp
@ -888,8 +890,8 @@ def test_get_response_error(atreal_openads):
fake_resp_json = { fake_resp_json = {
'errors': [ 'errors': [
{ {
'location' : 'entity.name', 'location': 'entity.name',
'name' : 'constraint', 'name': 'constraint',
'description': 'Must start with an uppercase letter' 'description': 'Must start with an uppercase letter'
} }
] ]
@ -899,7 +901,7 @@ def test_get_response_error(atreal_openads):
fake_resp.headers = {'Content-Type': 'application/json'} fake_resp.headers = {'Content-Type': 'application/json'}
fake_resp.encoding = 'utf-8' fake_resp.encoding = 'utf-8'
fake_resp.reason = 'Not Found' fake_resp.reason = 'Not Found'
fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access
error_msg = atreal_openads.get_response_error(fake_resp) error_msg = atreal_openads.get_response_error(fake_resp)
expected_msg = u'[%s] (%s) %s' % ( expected_msg = u'[%s] (%s) %s' % (
@ -909,7 +911,7 @@ def test_get_response_error(atreal_openads):
) )
assert error_msg == u"HTTP error: %s, %s" % (fake_resp.status_code, ','.join([expected_msg])) assert error_msg == u"HTTP error: %s, %s" % (fake_resp.status_code, ','.join([expected_msg]))
fake_resp._content = 'invalid_;{[content}' # pylint: disable=protected-access fake_resp._content = 'invalid_;{[content}' # pylint: disable=protected-access
error_msg = atreal_openads.get_response_error(fake_resp) error_msg = atreal_openads.get_response_error(fake_resp)
# pylint: disable=protected-access # pylint: disable=protected-access
assert error_msg == u"HTTP error: %s, %s" % (fake_resp.status_code, fake_resp._content) assert error_msg == u"HTTP error: %s, %s" % (fake_resp.status_code, fake_resp._content)
@ -921,19 +923,19 @@ def test_upload_user_files(atreal_openads):
"""Test the method AtrealOpenads.upload_user_files().""" """Test the method AtrealOpenads.upload_user_files()."""
req = HttpRequest() req = HttpRequest()
req._body = '' # pylint: disable=protected-access req._body = '' # pylint: disable=protected-access
req.path = '/upload_user_files' req.path = '/upload_user_files'
req.method = 'GET' req.method = 'GET'
req.encoding = 'utf-8' req.encoding = 'utf-8'
req.GET = QueryDict(mutable=True) # required because of encoding setter req.GET = QueryDict(mutable=True) # required because of encoding setter
req.POST = QueryDict(mutable=True) # required because of encoding setter req.POST = QueryDict(mutable=True) # required because of encoding setter
req.content_type = 'application/json' req.content_type = 'application/json'
req.content_params = None req.content_params = None
req.COOKIES = {} req.COOKIES = {}
req.META = {} req.META = {}
req._read_started = False # pylint: disable=protected-access req._read_started = False # pylint: disable=protected-access
with pytest.raises(ForwardFile.DoesNotExist) as exception: # pylint: disable=no-member with pytest.raises(ForwardFile.DoesNotExist) as exception: # pylint: disable=no-member
atreal_openads.upload_user_files(req, 'DIA', FAKE_NUMERO_DOSSIER, file_ids=[999]) atreal_openads.upload_user_files(req, 'DIA', FAKE_NUMERO_DOSSIER, file_ids=[999])
assert unicode(exception.value) == u"The following ForwardFile IDs were not found: %s." % [999] assert unicode(exception.value) == u"The following ForwardFile IDs were not found: %s." % [999]
@ -945,10 +947,10 @@ def test_upload_user_files(atreal_openads):
with pytest.raises(TypeError) as exception: with pytest.raises(TypeError) as exception:
atreal_openads.upload_user_files(req, 'DIA', FAKE_NUMERO_DOSSIER, atreal_openads.upload_user_files(req, 'DIA', FAKE_NUMERO_DOSSIER,
file_ids={'invalid':'type'}) file_ids={'invalid': 'type'})
assert unicode(exception.value) == ( assert unicode(exception.value) == (
u"Invalid 'file_ids' argument type '%s' (must be string or list)" % ( u"Invalid 'file_ids' argument type '%s' (must be string or list)" % (
type({'invalid':'type'}))) type({'invalid': 'type'})))
forwardfile = build_forwardfile_from_path(atreal_openads, forwardfile = build_forwardfile_from_path(atreal_openads,
TEST_FILE_CERFA_DIA, TEST_FILE_CERFA_DIA,
@ -957,7 +959,7 @@ def test_upload_user_files(atreal_openads):
forwardfile.save() forwardfile.save()
assert isinstance(forwardfile, ForwardFile) assert isinstance(forwardfile, ForwardFile)
assert forwardfile.upload_status == 'pending' assert forwardfile.upload_status == 'pending'
file_id = forwardfile.id # pylint: disable=no-member file_id = forwardfile.id # pylint: disable=no-member
assert file_id assert file_id
fake_resp_bad = Response() fake_resp_bad = Response()
@ -971,7 +973,7 @@ def test_upload_user_files(atreal_openads):
file_ids=str(file_id)) file_ids=str(file_id))
assert unicode(exception.value) == u'HTTP error: 502' assert unicode(exception.value) == u'HTTP error: 502'
ffup = ForwardFile.objects.get(id=file_id) # pylint: disable=no-member ffup = ForwardFile.objects.get(id=file_id) # pylint: disable=no-member
assert isinstance(ffup, ForwardFile) assert isinstance(ffup, ForwardFile)
for k in ['numero_dossier', 'type_fichier', 'file_hash', 'orig_filename', 'content_type']: for k in ['numero_dossier', 'type_fichier', 'file_hash', 'orig_filename', 'content_type']:
assert getattr(ffup, k) == getattr(forwardfile, k) assert getattr(ffup, k) == getattr(forwardfile, k)
@ -988,14 +990,14 @@ def test_upload_user_files(atreal_openads):
fake_resp.encoding = 'utf-8' fake_resp.encoding = 'utf-8'
fake_resp.reason = 'OK' fake_resp.reason = 'OK'
fake_resp._content = 'invalid_;{[content}' # pylint: disable=protected-access fake_resp._content = 'invalid_;{[content}' # pylint: disable=protected-access
with pytest.raises(APIError) as exception: with pytest.raises(APIError) as exception:
with mock.patch('passerelle.utils.Request.post') as requests_post: with mock.patch('passerelle.utils.Request.post') as requests_post:
requests_post.return_value = fake_resp requests_post.return_value = fake_resp
atreal_openads.upload_user_files(req, 'DIA', FAKE_NUMERO_DOSSIER, file_ids=[file_id]) atreal_openads.upload_user_files(req, 'DIA', FAKE_NUMERO_DOSSIER, file_ids=[file_id])
assert unicode(exception.value) == u'No JSON content returned: %r' % fake_resp.content assert unicode(exception.value) == u'No JSON content returned: %r' % fake_resp.content
ffup = ForwardFile.objects.get(id=file_id) # pylint: disable=no-member ffup = ForwardFile.objects.get(id=file_id) # pylint: disable=no-member
assert isinstance(ffup, ForwardFile) assert isinstance(ffup, ForwardFile)
for k in ['numero_dossier', 'type_fichier', 'file_hash', 'orig_filename', 'content_type']: for k in ['numero_dossier', 'type_fichier', 'file_hash', 'orig_filename', 'content_type']:
assert getattr(ffup, k) == getattr(forwardfile, k) assert getattr(ffup, k) == getattr(forwardfile, k)
@ -1007,18 +1009,18 @@ def test_upload_user_files(atreal_openads):
jresp = atreal_openads.upload_user_files(req, 'DIA', FAKE_NUMERO_DOSSIER) jresp = atreal_openads.upload_user_files(req, 'DIA', FAKE_NUMERO_DOSSIER)
assert jresp == {'message': 'no file to transfer'} assert jresp == {'message': 'no file to transfer'}
ffup = ForwardFile.objects.get(id=file_id) # pylint: disable=no-member ffup = ForwardFile.objects.get(id=file_id) # pylint: disable=no-member
ffup.upload_status = 'pending' ffup.upload_status = 'pending'
ffup.save() ffup.save()
fake_resp_json = "You want add some files on %s " % FAKE_NUMERO_DOSSIER fake_resp_json = "You want add some files on %s " % FAKE_NUMERO_DOSSIER
fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access fake_resp._content = json.dumps(fake_resp_json) # pylint: disable=protected-access
with mock.patch('passerelle.utils.Request.post') as requests_post: with mock.patch('passerelle.utils.Request.post') as requests_post:
requests_post.return_value = fake_resp requests_post.return_value = fake_resp
jresp = atreal_openads.upload_user_files(req, 'DIA', FAKE_NUMERO_DOSSIER) jresp = atreal_openads.upload_user_files(req, 'DIA', FAKE_NUMERO_DOSSIER)
assert jresp == {'message': 'all files transfered successfully'} assert jresp == {'message': 'all files transfered successfully'}
ffup = ForwardFile.objects.get(id=file_id) # pylint: disable=no-member ffup = ForwardFile.objects.get(id=file_id) # pylint: disable=no-member
assert isinstance(ffup, ForwardFile) assert isinstance(ffup, ForwardFile)
for k in ['numero_dossier', 'type_fichier', 'file_hash', 'orig_filename', 'content_type']: for k in ['numero_dossier', 'type_fichier', 'file_hash', 'orig_filename', 'content_type']:
assert getattr(ffup, k) == getattr(forwardfile, k) assert getattr(ffup, k) == getattr(forwardfile, k)

View File

@ -70,26 +70,28 @@ def atreal_openads(db):
basic_auth_password=OPENADS_API_PASSWORD basic_auth_password=OPENADS_API_PASSWORD
) )
@pytest.fixture @pytest.fixture
# pylint: disable=unused-argument,redefined-outer-name,invalid-name # pylint: disable=unused-argument,redefined-outer-name,invalid-name
def collectivite_1(db, atreal_openads): def collectivite_1(db, atreal_openads):
"""Return an instance of a 'Collectivite'.""" """Return an instance of a 'Collectivite'."""
return Collectivite.objects.create( # pylint: disable=no-member return Collectivite.objects.create( # pylint: disable=no-member
name=u'Macollectivité', name=u'Macollectivité',
connecteur=atreal_openads, connecteur=atreal_openads,
openADS_id='3' openADS_id='3'
) )
@pytest.fixture @pytest.fixture
# pylint: disable=unused-argument,redefined-outer-name,invalid-name # pylint: disable=unused-argument,redefined-outer-name,invalid-name
def collectivite_1_guichet(db, atreal_openads, collectivite_1): def collectivite_1_guichet(db, atreal_openads, collectivite_1):
"""Return an instance of a 'Guichet'.""" """Return an instance of a 'Guichet'."""
return Guichet.objects.create( # pylint: disable=no-member return Guichet.objects.create( # pylint: disable=no-member
collectivite=collectivite_1, collectivite=collectivite_1,
ouverture_jour_h=datetime.time(9, 0), ouverture_jour_h=datetime.time(9, 0),
fermeture_jour_h=datetime.time(17, 0), fermeture_jour_h=datetime.time(17, 0),
ouverture_sem_d=1, # Lundi ouverture_sem_d=1, # Lundi
fermeture_sem_d=5, # Vendredi fermeture_sem_d=5, # Vendredi
ouverture_sem_h=datetime.time(8, 30), ouverture_sem_h=datetime.time(8, 30),
fermeture_sem_h=datetime.time(12, 15) fermeture_sem_h=datetime.time(12, 15)
) )

View File

@ -27,7 +27,7 @@ import datetime
import pytest import pytest
from django.core.files import File from django.core.files import File
from django.core.files.base import ContentFile from django.core.files.base import ContentFile
from atreal_openads.utils import ( from atreal_openads.utils import (
@ -80,26 +80,28 @@ def atreal_openads(db):
basic_auth_password=OPENADS_API_PASSWORD basic_auth_password=OPENADS_API_PASSWORD
) )
@pytest.fixture @pytest.fixture
# pylint: disable=unused-argument,redefined-outer-name,invalid-name # pylint: disable=unused-argument,redefined-outer-name,invalid-name
def collectivite_1(db, atreal_openads): def collectivite_1(db, atreal_openads):
"""Return an instance of a 'Collectivite'.""" """Return an instance of a 'Collectivite'."""
return Collectivite.objects.create( # pylint: disable=no-member return Collectivite.objects.create( # pylint: disable=no-member
name=u'Macollectivité', name=u'Macollectivité',
connecteur=atreal_openads, connecteur=atreal_openads,
openADS_id='3' openADS_id='3'
) )
@pytest.fixture @pytest.fixture
# pylint: disable=unused-argument,redefined-outer-name,invalid-name # pylint: disable=unused-argument,redefined-outer-name,invalid-name
def collectivite_1_guichet(db, atreal_openads, collectivite_1): def collectivite_1_guichet(db, atreal_openads, collectivite_1):
"""Return an instance of a 'Guichet'.""" """Return an instance of a 'Guichet'."""
return Guichet.objects.create( # pylint: disable=no-member return Guichet.objects.create( # pylint: disable=no-member
collectivite=collectivite_1, collectivite=collectivite_1,
ouverture_jour_h=datetime.time(9, 0), ouverture_jour_h=datetime.time(9, 0),
fermeture_jour_h=datetime.time(17, 0), fermeture_jour_h=datetime.time(17, 0),
ouverture_sem_d=1, # Lundi ouverture_sem_d=1, # Lundi
fermeture_sem_d=5, # Vendredi fermeture_sem_d=5, # Vendredi
ouverture_sem_h=datetime.time(8, 30), ouverture_sem_h=datetime.time(8, 30),
fermeture_sem_h=datetime.time(12, 15) fermeture_sem_h=datetime.time(12, 15)
) )
@ -114,7 +116,7 @@ def test_to_dash_case():
assert to_dash_case('') == '' assert to_dash_case('') == ''
def test_force_encoded_string_output(): # pylint: disable=invalid-name def test_force_encoded_string_output(): # pylint: disable=invalid-name
"""Test for function 'force_encoded_string_output()'.""" """Test for function 'force_encoded_string_output()'."""
def a_str_function(): def a_str_function():
@ -242,17 +244,17 @@ def test_trunc_str_values():
dic = {'a': '123456789', 'b123456789': '987654321'} dic = {'a': '123456789', 'b123456789': '987654321'}
assert trunc_str_values(dic, 5) == {'a': u'12345…', 'b123456789': u'98765…'} assert trunc_str_values(dic, 5) == {'a': u'12345…', 'b123456789': u'98765…'}
dic = {'a': '123456789', 'b123456789': '987654321', 'c': {'c1':'ABCDEFGHIJK'}} dic = {'a': '123456789', 'b123456789': '987654321', 'c': {'c1': 'ABCDEFGHIJK'}}
assert trunc_str_values(dic, 5) == {'a': u'12345…', 'b123456789': u'98765…', assert trunc_str_values(dic, 5) == {'a': u'12345…', 'b123456789': u'98765…',
'c': {'c1': u'ABCDE…'}} 'c': {'c1': u'ABCDE…'}}
dic = {'a': '123456789', 'b123456789': '987654321', 'c': {'c1':'ABCDEFGHIJK'}, dic = {'a': '123456789', 'b123456789': '987654321', 'c': {'c1': 'ABCDEFGHIJK'},
'd': ['123456789']} 'd': ['123456789']}
assert trunc_str_values(dic, 5) == {'a': u'12345…', 'b123456789': u'98765…', assert trunc_str_values(dic, 5) == {'a': u'12345…', 'b123456789': u'98765…',
'c': {'c1': u'ABCDE…'}, 'd': [u'12345…']} 'c': {'c1': u'ABCDE…'}, 'd': [u'12345…']}
dic = {'a': '123456789', 'b123456789': '987654321', 'c': {'c1':'ABCDEFGHIJK'}, dic = {'a': '123456789', 'b123456789': '987654321', 'c': {'c1': 'ABCDEFGHIJK'},
'd': ['123456789', {'eeeeeeeeee':'132456789'}]} 'd': ['123456789', {'eeeeeeeeee': '132456789'}]}
assert trunc_str_values(dic, 5) == {'a': u'12345…', 'b123456789': u'98765…', assert trunc_str_values(dic, 5) == {'a': u'12345…', 'b123456789': u'98765…',
'c': {'c1': u'ABCDE…'}, 'c': {'c1': u'ABCDE…'},
'd': [u'12345…', {'eeeeeeeeee': u'13245…'}]} 'd': [u'12345…', {'eeeeeeeeee': u'13245…'}]}

View File

@ -26,9 +26,9 @@ import datetime
import pytest import pytest
from django.http.request import HttpRequest, QueryDict from django.http.request import HttpRequest, QueryDict
from django.urls.base import resolve from django.urls.base import resolve
from django.core.files import File from django.core.files import File
from atreal_openads.views import ( from atreal_openads.views import (
get_connecteur_from_request, get_connecteur_from_request,
@ -85,35 +85,38 @@ def atreal_openads(db):
basic_auth_password=OPENADS_API_PASSWORD basic_auth_password=OPENADS_API_PASSWORD
) )
@pytest.fixture @pytest.fixture
# pylint: disable=unused-argument,redefined-outer-name,invalid-name # pylint: disable=unused-argument,redefined-outer-name,invalid-name
def collectivite_1(db, atreal_openads): def collectivite_1(db, atreal_openads):
"""Return an instance of a 'Collectivite'.""" """Return an instance of a 'Collectivite'."""
return Collectivite.objects.create( # pylint: disable=no-member return Collectivite.objects.create( # pylint: disable=no-member
name=u'Macollectivité', name=u'Macollectivité',
connecteur=atreal_openads, connecteur=atreal_openads,
openADS_id='3' openADS_id='3'
) )
@pytest.fixture @pytest.fixture
# pylint: disable=unused-argument,redefined-outer-name,invalid-name # pylint: disable=unused-argument,redefined-outer-name,invalid-name
def collectivite_1_guichet(db, atreal_openads, collectivite_1): def collectivite_1_guichet(db, atreal_openads, collectivite_1):
"""Return an instance of a 'Guichet'.""" """Return an instance of a 'Guichet'."""
return Guichet.objects.create( # pylint: disable=no-member return Guichet.objects.create( # pylint: disable=no-member
collectivite=collectivite_1, collectivite=collectivite_1,
ouverture_jour_h=datetime.time(9, 0), ouverture_jour_h=datetime.time(9, 0),
fermeture_jour_h=datetime.time(17, 0), fermeture_jour_h=datetime.time(17, 0),
ouverture_sem_d=1, # Lundi ouverture_sem_d=1, # Lundi
fermeture_sem_d=5, # Vendredi fermeture_sem_d=5, # Vendredi
ouverture_sem_h=datetime.time(8, 30), ouverture_sem_h=datetime.time(8, 30),
fermeture_sem_h=datetime.time(12, 15) fermeture_sem_h=datetime.time(12, 15)
) )
@pytest.fixture @pytest.fixture
# pylint: disable=unused-argument,redefined-outer-name,invalid-name # pylint: disable=unused-argument,redefined-outer-name,invalid-name
def forwardfile_1(db, atreal_openads, collectivite_1): def forwardfile_1(db, atreal_openads, collectivite_1):
"""Return an instance of a 'ForwardFile'.""" """Return an instance of a 'ForwardFile'."""
return ForwardFile.objects.create( # pylint: disable=no-member return ForwardFile.objects.create( # pylint: disable=no-member
connecteur=atreal_openads, connecteur=atreal_openads,
collectivite=collectivite_1, collectivite=collectivite_1,
numero_demande='45641531', numero_demande='45641531',
@ -128,7 +131,7 @@ def forwardfile_1(db, atreal_openads, collectivite_1):
# pylint: disable=unused-argument,redefined-outer-name # pylint: disable=unused-argument,redefined-outer-name
def test_get_connecteur_from_request(atreal_openads, forwardfile_1): # pylint: disable=invalid-name def test_get_connecteur_from_request(atreal_openads, forwardfile_1): # pylint: disable=invalid-name
"""Test for function 'get_connecteur_from_request()'.""" """Test for function 'get_connecteur_from_request()'."""
req = HttpRequest() req = HttpRequest()
@ -136,12 +139,12 @@ def test_get_connecteur_from_request(atreal_openads, forwardfile_1): # pylint: d
atreal_openads.slug, forwardfile_1.id) atreal_openads.slug, forwardfile_1.id)
req.method = 'GET' req.method = 'GET'
req.encoding = 'utf-8' req.encoding = 'utf-8'
req.GET = QueryDict(mutable=True) # required because of encoding setter req.GET = QueryDict(mutable=True) # required because of encoding setter
req.POST = QueryDict(mutable=True) # required because of encoding setter req.POST = QueryDict(mutable=True) # required because of encoding setter
req.content_params = None req.content_params = None
req.COOKIES = {} req.COOKIES = {}
req.META = {} req.META = {}
req._read_started = False # pylint: disable=protected-access req._read_started = False # pylint: disable=protected-access
req.resolver_match = resolve(req.path) req.resolver_match = resolve(req.path)
view = ForwardFileView() view = ForwardFileView()
@ -153,7 +156,7 @@ def test_get_connecteur_from_request(atreal_openads, forwardfile_1): # pylint: d
# pylint: disable=unused-argument,redefined-outer-name # pylint: disable=unused-argument,redefined-outer-name
def test_get_collectivite_from_request(atreal_openads, collectivite_1): # pylint: disable=invalid-name def test_get_collectivite_from_request(atreal_openads, collectivite_1): # noqa: E501, pylint: disable=invalid-name
"""Test for function 'get_collectivite_from_request()'.""" """Test for function 'get_collectivite_from_request()'."""
req = HttpRequest() req = HttpRequest()
@ -161,12 +164,12 @@ def test_get_collectivite_from_request(atreal_openads, collectivite_1): # pylint
atreal_openads.slug, collectivite_1.id) atreal_openads.slug, collectivite_1.id)
req.method = 'GET' req.method = 'GET'
req.encoding = 'utf-8' req.encoding = 'utf-8'
req.GET = QueryDict(mutable=True) # required because of encoding setter req.GET = QueryDict(mutable=True) # required because of encoding setter
req.POST = QueryDict(mutable=True) # required because of encoding setter req.POST = QueryDict(mutable=True) # required because of encoding setter
req.content_params = None req.content_params = None
req.COOKIES = {} req.COOKIES = {}
req.META = {} req.META = {}
req._read_started = False # pylint: disable=protected-access req._read_started = False # pylint: disable=protected-access
req.resolver_match = resolve(req.path) req.resolver_match = resolve(req.path)
view = ForwardFileListView() view = ForwardFileListView()
@ -186,12 +189,12 @@ def test_forwardfile_view(atreal_openads, collectivite_1, forwardfile_1):
atreal_openads.slug, forwardfile_1.id) atreal_openads.slug, forwardfile_1.id)
req.method = 'GET' req.method = 'GET'
req.encoding = 'utf-8' req.encoding = 'utf-8'
req.GET = QueryDict(mutable=True) # required because of encoding setter req.GET = QueryDict(mutable=True) # required because of encoding setter
req.POST = QueryDict(mutable=True) # required because of encoding setter req.POST = QueryDict(mutable=True) # required because of encoding setter
req.content_params = None req.content_params = None
req.COOKIES = {} req.COOKIES = {}
req.META = {} req.META = {}
req._read_started = False # pylint: disable=protected-access req._read_started = False # pylint: disable=protected-access
req.resolver_match = resolve(req.path) req.resolver_match = resolve(req.path)
view = ForwardFileView() view = ForwardFileView()
@ -287,12 +290,12 @@ def test_collectivite_view(atreal_openads, collectivite_1, forwardfile_1):
atreal_openads.slug, collectivite_1.id) atreal_openads.slug, collectivite_1.id)
req.method = 'GET' req.method = 'GET'
req.encoding = 'utf-8' req.encoding = 'utf-8'
req.GET = QueryDict(mutable=True) # required because of encoding setter req.GET = QueryDict(mutable=True) # required because of encoding setter
req.POST = QueryDict(mutable=True) # required because of encoding setter req.POST = QueryDict(mutable=True) # required because of encoding setter
req.content_params = None req.content_params = None
req.COOKIES = {} req.COOKIES = {}
req.META = {} req.META = {}
req._read_started = False # pylint: disable=protected-access req._read_started = False # pylint: disable=protected-access
req.resolver_match = resolve(req.path) req.resolver_match = resolve(req.path)
view = CollectiviteView() view = CollectiviteView()
@ -384,12 +387,12 @@ def test_guichet_view(atreal_openads, collectivite_1, collectivite_1_guichet):
atreal_openads.slug, collectivite_1.id, collectivite_1_guichet.id) atreal_openads.slug, collectivite_1.id, collectivite_1_guichet.id)
req.method = 'GET' req.method = 'GET'
req.encoding = 'utf-8' req.encoding = 'utf-8'
req.GET = QueryDict(mutable=True) # required because of encoding setter req.GET = QueryDict(mutable=True) # required because of encoding setter
req.POST = QueryDict(mutable=True) # required because of encoding setter req.POST = QueryDict(mutable=True) # required because of encoding setter
req.content_params = None req.content_params = None
req.COOKIES = {} req.COOKIES = {}
req.META = {} req.META = {}
req._read_started = False # pylint: disable=protected-access req._read_started = False # pylint: disable=protected-access
req.resolver_match = resolve(req.path) req.resolver_match = resolve(req.path)
view = GuichetView() view = GuichetView()
@ -443,12 +446,12 @@ def test_connecteur_view(atreal_openads):
req.path = '/atreal-openads/%s/' % atreal_openads.slug req.path = '/atreal-openads/%s/' % atreal_openads.slug
req.method = 'GET' req.method = 'GET'
req.encoding = 'utf-8' req.encoding = 'utf-8'
req.GET = QueryDict(mutable=True) # required because of encoding setter req.GET = QueryDict(mutable=True) # required because of encoding setter
req.POST = QueryDict(mutable=True) # required because of encoding setter req.POST = QueryDict(mutable=True) # required because of encoding setter
req.content_params = None req.content_params = None
req.COOKIES = {} req.COOKIES = {}
req.META = {} req.META = {}
req._read_started = False # pylint: disable=protected-access req._read_started = False # pylint: disable=protected-access
req.resolver_match = resolve(req.path) req.resolver_match = resolve(req.path)
view = AtrealOpenadsView() view = AtrealOpenadsView()