Supporting to create a 'dossier' from a real request (no more hardcoded payload)

Features:
    * added support for a payload build from the request instead of hardcoded in
      function 'create_dossier()'
    * added a warning message when an APIError is raised all functions
    * added the name/key of the error in the error message build from a response
    * added a function 'normalize()' to normalize user's input in the payload
    * changed endpoint arguments coming from request parameters instead of URI path
      in functions 'create_dossier()', 'get_dossier()', 'get_courrier()' and
      'get_fwd_files_status()'
    * changed JSON response to use an explicit key to hold file data in function
      'create_dossier()':'recepisse' and 'get_courrier()':'courrier'
    * removed the useless key 'data' in all the JSON response
    * removed useless case 'jsondata' in function 'afile()'

Cleaning:
    * Removed useless variable 'dossier_payload'

Tests:
    * added request containing the payload in the test case for 'create_dossier()'
    * added the name/key of the error in the error message build from a response
    * used the explicit keys 'recepisse' and 'courrier' in JSON responses
    * removed the 'data' key from JSON responses
This commit is contained in:
Michael Bideau 2019-05-07 16:46:02 +00:00
parent a53e30ca9e
commit 3c53170e4a
2 changed files with 266 additions and 174 deletions

View File

@ -38,6 +38,7 @@ from HTMLParser import HTMLParser
import magic
import hashlib
from django.core.files import File
from django.core.files.base import ContentFile
# TODO remove (only for debuging/development)
import time
@ -73,38 +74,12 @@ def clean_spaces(text):
return re.sub(r' +', ' ', text).strip()
dossier_payload = {
"collectivite": 3,
"terrain": {
"numero_voie": 15,
"nom_voie": "boulevard Layglize",
"lieu_dit": "Li Corne",
"code_postal": 13014,
"localite": "Marseille",
"references_cadastrales": [
{
"prefixe": "696",
"section": "M",
"numero": "0012"
}
]
},
"demandeurs": [
{
"type_personne": "particulier",
"typologie": "petitionnaire",
"nom": "Khaleesi",
"prenom": "Daenerys",
"adresse": {
"numero_voie": 1,
"nom_voie": "boulevard Targaryen",
"lieu_dit": "Dothraki Sea",
"code_postal": 13888,
"localite": "Marshhh"
}
}
]
}
def normalize(value):
"""Normalize a value to be send to openADS.API."""
if value is None:
return ''
return clean_spaces(str(value))
TEST_FILE_TRAC_ICO = '/vagrant/test_files/trac.ico'
TEST_FILE_CERFA_DIA = '/vagrant/test_files/cerfa_10072-02.pdf'
@ -167,9 +142,7 @@ class AtrealOpenads(BaseResource):
})
def hello(self, request, name='world', **kwargs):
return {
'data': {
'hello': name
}
'hello': name
}
@endpoint(
@ -206,9 +179,7 @@ class AtrealOpenads(BaseResource):
if isinstance(v, str) and ((v and len(v)) or empty):
req_infos[k][p] = v
return {
'data': {
'received': json.dumps(req_infos)
}
'received': json.dumps(req_infos)
}
@endpoint(
@ -279,7 +250,7 @@ class AtrealOpenads(BaseResource):
pattern='^(?P<format>\w+)/?$',
example_pattern='{format}/',
parameters={
'format': {'description': _('Format'), 'example_value': 'jsondata'}
'format': {'description': _('Format'), 'example_value': 'base64'}
})
def afile(self, request, format='json', **kwargs):
rand_id = base64.urlsafe_b64encode(os.urandom(6))
@ -295,8 +266,6 @@ class AtrealOpenads(BaseResource):
},
'extra_info': 'blabla'
}
if format == 'jsondata':
return { 'data': json }
return json
else:
raw_content = get_file_data(TEST_FILE_TRAC_ICO, b64=False)
@ -326,84 +295,143 @@ class AtrealOpenads(BaseResource):
@endpoint(
description="Create an openADS 'dossier' (harcoded for now)",
methods=['post'],
pattern='^(?P<type_dossier>\w+)/?$',
example_pattern='{type_dossier}/',
parameters={
'type_dossier': {'description': _("Type of 'dossier'"), 'example_value': 'DIA'}
})
def create_dossier(self, request, type_dossier, *args, **kwargs):
payload = {
"collectivite": self.collectivite,
"terrain": {
"numero_voie": 15,
"nom_voie": "boulevard Layglize",
"lieu_dit": "Li Corne",
"code_postal": 13014,
"localite": "Marseille",
"references_cadastrales": [
{
"prefixe": "999",
"section": "Z",
"numero": "0010"
},
{
"prefixe": "696",
"section": "M",
"numero": "0012"
}
]
},
"demandeurs": [
{
"type_personne": "particulier",
"typologie": "petitionnaire",
"nom": "Neige",
"prenom": "Jean",
"adresse": {
"numero_voie": 8,
"nom_voie": "boulevard Stark",
"lieu_dit": "Castleblack",
"code_postal": 13666,
"localite": "Marsnuit"
}
},
{
"type_personne": "particulier",
"typologie": "petitionnaire",
"nom": "Khaleesi",
"prenom": "Daenerys",
"adresse": {
"numero_voie": 1,
"nom_voie": "boulevard Targaryen",
"lieu_dit": "Dothraki Sea",
"code_postal": 13888,
"localite": "Marshhh"
}
}
]
self.logger.debug("----- request json (begining) -----")
json_data = json.loads(request.body)
debug_json = copy.deepcopy(json_data)
file_keys = ['cerfa'] + ['plan_cadastral_%s' % i for i in range(1,5)]
for k in file_keys:
if k in debug_json['fields'] \
and debug_json['fields'][k] \
and isinstance(debug_json['fields'][k], dict) \
and 'content' in debug_json['fields'][k]:
debug_json['fields'][k]['content'] = '<b64 content>'
self.logger.debug(json.dumps(debug_json))
self.logger.debug("----- request json (end) -----")
payload = { "collectivite": self.collectivite }
payload["terrain"] = {
"numero_voie": normalize(json_data['fields']['terrain_numero_voie']),
"nom_voie" : normalize(json_data['fields']['terrain_nom_voie']),
"code_postal": normalize(json_data['fields']['terrain_code_postal']),
"localite" : normalize(json_data['fields']['terrain_localite']),
"references_cadastrales": []
}
if 'terrain_lieu_dit' in json_data['fields'] and json_data['fields']['terrain_lieu_dit']:
payload["terrain"]["lieu_dit"] = normalize(json_data['fields']['terrain_lieu_dit'])
for ref in json_data['fields']['reference_cadastrale']:
payload["terrain"]["references_cadastrales"].append({
"prefixe": normalize(ref[0]),
"section": normalize(ref[1]),
"numero" : normalize(ref[2])
})
if json_data['fields']['autres_parcelles']:
for ref in json_data['fields']['references_cadastrales']:
payload["terrain"]["references_cadastrales"].append({
"prefixe": normalize(ref[0]),
"section": normalize(ref[1]),
"numero" : normalize(ref[2])
})
prefix = ''
if json_data['fields']['proprietaire'] != 'Oui':
prefix = 'mandataire_'
demandeur = {
"type_personne": 'particulier' if normalize(json_data['fields']['proprietaire_qualite']) == 'Un particulier' else 'personne morale',
"typologie" : 'petitionnaire' if normalize(json_data['fields']['proprietaire']) == 'Oui' else 'mandataire',
"nom" : normalize(json_data['fields']['%snom' % prefix]),
"prenom" : normalize(json_data['fields']['%sprenom' % prefix]),
"adresse": {
"numero_voie": normalize(json_data['fields']['%snumero_voie' % prefix]),
"nom_voie" : normalize(json_data['fields']['%snom_voie' % prefix]),
"code_postal": normalize(json_data['fields']['%scode_postal' % prefix]),
"localite" : normalize(json_data['fields']['%slocalite' % prefix])
}
}
if '%slieu_dit' % prefix in json_data['fields'] and json_data['fields']['%slieu_dit' % prefix]:
demandeur["adresse"]["lieu_dit"] = normalize(json_data['fields']['%slieu_dit' % prefix])
payload["demandeurs"] = [demandeur]
self.logger.debug("----- payload (begining) -----")
self.logger.debug(json.dumps(payload))
self.logger.debug("----- payload (end) -----")
files = []
file_keys = ['cerfa'] + ['plan_cadastral_%s' % i for i in range(1,5)]
for k in file_keys:
if k in json_data['fields'] \
and json_data['fields'][k] \
and isinstance(json_data['fields'][k], dict) \
and 'content' in json_data['fields'][k]:
content = base64.b64decode(json_data['fields'][k]['content'])
content_type = magic.from_buffer(content, mime=True)
upload_file = ContentFile(content)
file_hash = self.file_digest(upload_file)
filename = file_hash + '.pdf'
if 'content_type' in json_data['fields'][k]:
content_type = json_data['fields'][k]['content_type']
if k == 'cerfa' and content_type != 'application/pdf':
self.logger.warning("CERFA content type is '%s' instead of '%s'" % (content_type, 'application/pdf'))
if 'filename' in json_data['fields'][k]:
filename = json_data['fields'][k]['filename']
files.append({
'type_fichier' : 'CERFA' if k == 'cerfa' else 'plan',
'orig_filename': filename,
'content_type' : content_type,
'file_hash' : file_hash,
'upload_file' : upload_file
})
self.logger.debug("----- files (begining) -----")
self.logger.debug(files)
self.logger.debug("----- files (end) -----")
url = urlparse.urljoin(self.openADS_API_url, '/dossiers/%s' % type_dossier)
response = self.requests.post(url, json=payload)
if response.status_code // 100 != 2:
raise APIError(self.get_response_error(response))
error = self.get_response_error(response)
self.logger.warning("Request [POST] '%s' failed with error: '%s'" % (url, error))
raise APIError(error)
try:
result = response.json()
except ValueError:
raise APIError('No JSON content returned: %r' % response.content[:1000])
numero_dossier = result.get('numero_dossier')
recepisse = result['files'][0]
try:
recepisse_content = base64.b64decode(recepisse['b64_content'])
except TypeError:
raise APIError('Invalid content for recepisse')
files = [TEST_FILE_CERFA_DIA, TEST_FILE_PLAN_CADASTRAL]
if recepisse['content_type'] and recepisse['content_type'] != 'application/pdf':
self.logger.warning("Forcing 'recepisse' content type to '%s' instead of '%s'." % ('application/pdf', recepisse['content_type']))
recepisse['content_type'] = 'application/pdf'
if files:
file_ids = []
for f in files:
fwd_file = self.upload2ForwardFile(f, numero_dossier)
fwd_file.save()
file_ids.append(fwd_file.id)
rand_id = base64.urlsafe_b64encode(os.urandom(6))
FF = ForwardFile()
FF.numero_demande = rand_id
FF.numero_dossier = numero_dossier
for k in ['type_fichier', 'orig_filename', 'content_type', 'file_hash']:
setattr(FF, k, f[k])
FF.upload_file.save(FF.orig_filename, f['upload_file'])
FF.upload_status = 'pending'
FF.save()
file_ids.append(FF.id)
self.add_job('upload_user_files',
natural_id=numero_dossier,
@ -411,7 +439,10 @@ class AtrealOpenads(BaseResource):
numero_dossier=numero_dossier,
file_ids=file_ids)
return {'data': response.json()}
return {
'numero_dossier': numero_dossier,
'recepisse' : recepisse
}
def upload2ForwardFile(self, path, numero_dossier):
@ -436,8 +467,8 @@ class AtrealOpenads(BaseResource):
@endpoint(
description="Get informations about an openADS 'dossier'",
pattern='^(?P<type_dossier>\w+)/(?P<numero_dossier>\w+)/?$',
example_pattern='{type_dossier}/{numero_dossier}/',
pattern='^(?P<type_dossier>\w+)/?$',
example_pattern='{type_dossier}/',
parameters={
'type_dossier' : {'description': _("Type of 'dossier'") , 'example_value': 'DIA'},
'numero_dossier': {'description': _("Identifier for 'dossier'"), 'example_value': 'DIA0130551900001'}
@ -446,7 +477,9 @@ class AtrealOpenads(BaseResource):
url = urlparse.urljoin(self.openADS_API_url, '/dossier/%s/%s' % (type_dossier, numero_dossier))
response = self.requests.get(url)
if response.status_code // 100 != 2:
raise APIError(self.get_response_error(response))
error = self.get_response_error(response)
self.logger.warning("Request [GET] '%s' failed with error: '%s'" % (url, error))
raise APIError(error)
try:
result = response.json()
except ValueError:
@ -456,7 +489,7 @@ class AtrealOpenads(BaseResource):
date_decision = result.get('date_decision')
decision = result.get('decision')
date_limite_instruction = result.get('date_limite_instruction')
return {'data': response.json()}
return response.json()
@endpoint(
@ -480,13 +513,15 @@ class AtrealOpenads(BaseResource):
url = urlparse.urljoin(self.openADS_API_url, '/dossier/%s/%s/files' % (type_dossier, numero_dossier))
response = self.requests.post(url, json=payload)
if response.status_code // 100 != 2:
raise APIError(self.get_response_error(response))
error = self.get_response_error(response)
self.logger.warning("Request [POST] '%s' failed with error: '%s'" % (url, error))
raise APIError(error)
try:
result = response.json()
except ValueError:
raise APIError('No JSON content returned: %r' % response.content[:1000])
# TODO handle response (now its just an informational sentence in key 'data')
return {'data': response.json()}
return response.json()
@endpoint(
@ -507,18 +542,14 @@ class AtrealOpenads(BaseResource):
numero_dossier=numero_dossier,
file_ids=[fwd_file.id])
return {
'data': {
'message': 'upload is pending (async)',
'job_id' : job.id
}
'message': 'upload is pending (async)',
'job_id' : job.id
}
@endpoint(
description="Get informations about the forwarding of a user file to openADS",
methods=['get'],
pattern='^(?P<numero_dossier>\w+)(/(?P<fichier_id>\w+))?/?$',
example_pattern='{numero_dossier}/{fichier_id}/',
parameters={
'numero_dossier': {'description': _("Identifier for 'dossier'"), 'example_value': 'DIA0130551900001'},
'fichier_id' : {'description': _("File identifier") , 'example_value': '78'},
@ -562,7 +593,7 @@ class AtrealOpenads(BaseResource):
'content_type' : fwd_file.content_type,
'upload_status' : fwd_file.upload_status,
'upload_msg' : fwd_file.upload_msg,
'b64_content' : get_file_data(fwd_file.upload_file.path),
'b64_content' : base64.b64encode(fwd_file.upload_file.read()),
'last_update_datetime' : fwd_file.last_update_datetime
})
@ -575,7 +606,7 @@ class AtrealOpenads(BaseResource):
if summary_enabled:
payload = summary_data
return {'data': payload}
return payload
@endpoint(
@ -590,13 +621,13 @@ class AtrealOpenads(BaseResource):
f = TEST_FILE_CERFA_DIA
fwd_file = self.upload2ForwardFile(f, numero_dossier)
fwd_file.save()
return {'data': "ForwardFile '%s' created" % fwd_file.id}
return {'message': "ForwardFile '%s' created" % fwd_file.id}
@endpoint(
description="Get a 'courrier' from an openADS 'dossier'",
pattern='^(?P<type_dossier>\w+)/(?P<numero_dossier>\w+)/?$',
example_pattern='{type_dossier}/{numero_dossier}/',
pattern='^(?P<type_dossier>\w+)/?$',
example_pattern='{type_dossier}/',
parameters={
'type_dossier' : {'description': _("Type of 'dossier'") , 'example_value': 'DIA'},
'numero_dossier': {'description': _("Identifier for 'dossier'"), 'example_value': 'DIA0130551900001'}
@ -607,17 +638,19 @@ class AtrealOpenads(BaseResource):
'/dossier/%s/%s/courrier/%s' % (type_dossier, numero_dossier, 'dia_renonciation_preempter'))
response = self.requests.get(url)
if response.status_code // 100 != 2:
raise APIError(self.get_response_error(response))
error = self.get_response_error(response)
self.logger.warning("Request [GET] '%s' failed with error: '%s'" % (url, error))
raise APIError(error)
try:
result = response.json()
except ValueError:
raise APIError('No JSON content returned: %r' % response.content[:1000])
courrier = result.get('files')[0]
courrier = result['files'][0]
try:
courrier_content = base64.b64decode(courrier['b64_content'])
except TypeError:
raise APIError('Invalid content for courrier')
return {'data': response.json()}
return {'courrier': courrier}
def get_response_error(self, response):
@ -631,7 +664,7 @@ class AtrealOpenads(BaseResource):
location = error.get('location')
name = error.get('name')
desc = error.get('description')
msg.append('[%s] %s' % (location, clean_spaces(desc)))
msg.append('[%s] (%s) %s' % (location, normalize(name), normalize(desc)))
if msg:
return "HTTP error: %s, %s" % (response.status_code, ','.join(msg))
except ValueError:
@ -651,9 +684,9 @@ class AtrealOpenads(BaseResource):
if fwd_file:
self.logger.debug("upload_user_files() got ForwardFile")
payload.append({
'filename' : os.path.basename(fwd_file.upload_file.path) + '.pdf',
'filename' : fwd_file.orig_filename + ('.pdf' if fwd_file.orig_filename[-4:] != '.pdf' else ''),
'content_type' : fwd_file.content_type,
'b64_content' : get_file_data(fwd_file.upload_file.path),
'b64_content' : base64.b64encode(fwd_file.upload_file.read()),
'file_type' : fwd_file.type_fichier
})
self.logger.debug("upload_user_files() payload added")

View File

@ -46,6 +46,7 @@ FAKE_NUMERO_DOSSIER = base64.urlsafe_b64encode(os.urandom(10))
TEST_FILE_TRAC_ICO = '/vagrant/test_files/trac.ico'
TEST_FILE_CERFA_DIA = '/vagrant/test_files/cerfa_10072-02.pdf'
TEST_FILE_PLAN_CADASTRAL = '/vagrant/test_files/plancadastral.pdf'
def get_file_data(path, b64=True):
@ -68,10 +69,10 @@ def atreal_openads(db):
def test_openads_hello(app, atreal_openads):
resp = atreal_openads.hello(None)
assert resp['data']['hello'] == 'world'
assert resp['hello'] == 'world'
resp = atreal_openads.hello(None, 'toto')
assert resp['data']['hello'] == 'toto'
assert resp['hello'] == 'toto'
def test_openads_echo(app, atreal_openads):
@ -103,14 +104,14 @@ def test_openads_echo(app, atreal_openads):
req.META = meta
req._read_started = False
resp = atreal_openads.echo(req, body=False, cookies=False, meta=False, empty=False)
jresp = json.loads(resp['data']['received'])
jresp = json.loads(resp['received'])
assert jresp['scheme'] == 'http'
assert jresp['method'] == req.method
assert jresp['content_type'] == req.content_type
assert jresp['encoding'] == req.encoding
resp = atreal_openads.echo(req, body=True, cookies=True, meta=True, empty=True)
jresp = json.loads(resp['data']['received'])
jresp = json.loads(resp['received'])
assert jresp['body'] == req._body
assert jresp['FILES'] == []
assert jresp['content_params'] == None
@ -137,14 +138,14 @@ def test_openads_echo(app, atreal_openads):
req.META = meta
req._read_started = False
resp = atreal_openads.echo(req, body=False, cookies=False, meta=False, empty=False)
jresp = json.loads(resp['data']['received'])
jresp = json.loads(resp['received'])
assert jresp['scheme'] == 'http'
assert jresp['method'] == req.method
assert jresp['content_type'] == req.content_type
assert jresp['encoding'] == req.encoding
resp = atreal_openads.echo(req, body=True, cookies=True, meta=True, empty=True)
jresp = json.loads(resp['data']['received'])
jresp = json.loads(resp['received'])
assert jresp['body'] == req._body
assert jresp['FILES'] == []
assert jresp['content_params'] == None
@ -205,6 +206,64 @@ def test_openads_check_status(app, atreal_openads):
def test_openads_create_dossier(app, atreal_openads):
fake_req_json = {
"fields": {
"autres_parcelles": True,
"cerfa": {
"content": get_file_data(TEST_FILE_CERFA_DIA),
"content_type": "application/pdf",
"field_id": "50",
"filename": os.path.basename(TEST_FILE_CERFA_DIA)
},
"code_postal": "13004",
"localite": "Marseille",
"nom": "Loulou",
"nom_voie": "Avenue de la Blaque",
"numero_voie": "52",
"plan_cadastral_1": {
"content": get_file_data(TEST_FILE_PLAN_CADASTRAL),
"content_type": "application/pdf",
"field_id": "113",
"filename": os.path.basename(TEST_FILE_PLAN_CADASTRAL)
},
"prenom": "Toto",
"proprietaire": "Oui",
"proprietaire_qualite": "Un particulier",
"proprietaire_qualite_raw": "Un particulier",
"proprietaire_raw": "Oui",
"reference_cadastrale": [
[
"999",
"Z",
"0010"
]
],
"references_cadastrales": [
[
"123",
"D",
"9874"
]
],
"terrain_code_postal": "13002",
"terrain_localite": "Marseille",
"terrain_nom_voie": "Boulevard de la Linule",
"terrain_numero_voie": "23"
}
}
req = HttpRequest()
req._body = json.dumps(fake_req_json)
req.path = '/test'
req.method = 'POST'
req.encoding = 'utf-8'
req.GET = 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_params = None
req.COOKIES = {}
req.META = {}
req._read_started = False
fake_resp_json = {
'numero_dossier' : FAKE_NUMERO_DOSSIER,
'files': [{
@ -219,13 +278,14 @@ def test_openads_create_dossier(app, atreal_openads):
fake_resp.encoding = 'utf-8'
fake_resp.reason = 'OK'
fake_resp._content = json.dumps(fake_resp_json)
with mock.patch('passerelle.utils.Request.post') as requests_post:
requests_post.return_value = fake_resp
jresp = atreal_openads.create_dossier(None, 'DIA')
assert jresp['data']['numero_dossier'] == fake_resp_json['numero_dossier']
assert jresp['data']['files'][0]['b64_content'] == fake_resp_json['files'][0]['b64_content']
assert jresp['data']['files'][0]['content_type'] == fake_resp_json['files'][0]['content_type']
assert jresp['data']['files'][0]['filename'] == fake_resp_json['files'][0]['filename']
jresp = atreal_openads.create_dossier(req, 'DIA')
assert jresp['numero_dossier'] == fake_resp_json['numero_dossier']
assert jresp['recepisse']['b64_content'] == fake_resp_json['files'][0]['b64_content']
assert jresp['recepisse']['content_type'] == 'application/pdf'
assert jresp['recepisse']['filename'] == fake_resp_json['files'][0]['filename']
job = Job.objects.filter(natural_id=FAKE_NUMERO_DOSSIER).last()
assert job
@ -298,11 +358,11 @@ def test_openads_get_dossier(app, atreal_openads):
with mock.patch('passerelle.utils.Request.get') as requests_get:
requests_get.return_value = fake_resp
jresp = atreal_openads.get_dossier(None, 'DIA', FAKE_NUMERO_DOSSIER)
assert jresp['data']['etat'] == fake_resp_json['etat']
assert jresp['data']['date_depot'] == fake_resp_json['date_depot']
assert jresp['data']['date_decision'] == fake_resp_json['date_decision']
assert jresp['data']['decision'] == fake_resp_json['decision']
assert jresp['data']['date_limite_instruction'] == fake_resp_json['date_limite_instruction']
assert jresp['etat'] == fake_resp_json['etat']
assert jresp['date_depot'] == fake_resp_json['date_depot']
assert jresp['date_decision'] == fake_resp_json['date_decision']
assert jresp['decision'] == fake_resp_json['decision']
assert jresp['date_limite_instruction'] == fake_resp_json['date_limite_instruction']
fake_resp_json = {
'errors' : [{
@ -321,7 +381,7 @@ def test_openads_get_dossier(app, atreal_openads):
with mock.patch('passerelle.utils.Request.get') as requests_get:
requests_get.return_value = fake_resp
jresp = atreal_openads.get_dossier(None, 'invalid_type', FAKE_NUMERO_DOSSIER)
assert re.search(r'^HTTP error: 404, \[path\] "invalid_type" is not one of DIA, PC, DP, AT, PD$', str(e.value))
assert re.search(r'^HTTP error: 404, \[path\] \(Invalid Type\) "invalid_type" is not one of DIA, PC, DP, AT, PD$', str(e.value))
def test_openads_add_file(app, atreal_openads):
@ -335,14 +395,14 @@ def test_openads_add_file(app, atreal_openads):
with mock.patch('passerelle.utils.Request.post') as requests_post:
requests_post.return_value = fake_resp
jresp = atreal_openads.add_file(None, 'DIA', FAKE_NUMERO_DOSSIER)
assert jresp['data'] == fake_resp_json
assert jresp == fake_resp_json
def test_openads_add_file_async(app, atreal_openads):
jresp = atreal_openads.add_file_async(None, 'DIA', FAKE_NUMERO_DOSSIER)
assert jresp['data']['message'] == 'upload is pending (async)'
assert jresp['data']['job_id'] is not None
job_id = jresp['data']['job_id']
assert jresp['message'] == 'upload is pending (async)'
assert jresp['job_id'] is not None
job_id = jresp['job_id']
job = Job.objects.get(id=job_id)
assert job.status == 'registered'
@ -388,56 +448,56 @@ def test_openads_get_fwd_files_status(app, atreal_openads):
assert re.search(r"^No file matches 'numero_dossier=[^']+' and 'id=[^']+'.$", str(e.value))
resp404 = atreal_openads.get_fwd_files_status(None, FAKE_NUMERO_DOSSIER, fichier_id=None, summary=None)
assert resp404['data'] is not None
assert len(resp404['data']) == 0
assert resp404 is not None
assert len(resp404) == 0
FF = atreal_openads.upload2ForwardFile(TEST_FILE_TRAC_ICO, FAKE_NUMERO_DOSSIER)
FF.save()
assert isinstance(FF, ForwardFile)
jresp = atreal_openads.get_fwd_files_status(None, FAKE_NUMERO_DOSSIER, fichier_id=None, summary=None)
assert jresp['data'] is not None
assert len(jresp['data']) == 1
assert jresp['data'][0]['id'] == FF.id
assert jresp is not None
assert len(jresp) == 1
assert jresp[0]['id'] == FF.id
for k in ['numero_dossier', 'type_fichier', 'file_hash', 'orig_filename', 'content_type', 'upload_status', 'upload_msg']:
assert jresp['data'][0][k] == getattr(FF, k)
assert jresp['data'][0]['b64_content'] == get_file_data(FF.upload_file.path)
assert jresp['data'][0]['last_update_datetime'] == FF.last_update_datetime
assert jresp[0][k] == getattr(FF, k)
assert jresp[0]['b64_content'] == get_file_data(FF.upload_file.path)
assert jresp[0]['last_update_datetime'] == FF.last_update_datetime
jresp = atreal_openads.get_fwd_files_status(None, FAKE_NUMERO_DOSSIER, fichier_id=FF.id, summary=None)
assert jresp['data'] is not None
assert len(jresp['data']) == 1
assert jresp['data'][0]['id'] == FF.id
assert jresp is not None
assert len(jresp) == 1
assert jresp[0]['id'] == FF.id
for k in ['numero_dossier', 'type_fichier', 'file_hash', 'orig_filename', 'content_type', 'upload_status', 'upload_msg']:
assert jresp['data'][0][k] == getattr(FF, k)
assert jresp['data'][0]['b64_content'] == get_file_data(FF.upload_file.path)
assert jresp['data'][0]['last_update_datetime'] == FF.last_update_datetime
assert jresp[0][k] == getattr(FF, k)
assert jresp[0]['b64_content'] == get_file_data(FF.upload_file.path)
assert jresp[0]['last_update_datetime'] == FF.last_update_datetime
jresp = atreal_openads.get_fwd_files_status(None, FAKE_NUMERO_DOSSIER, fichier_id=None, summary='1')
assert jresp['data'] is not None
assert jresp['data']['all_forwarded'] == False
assert jresp is not None
assert jresp['all_forwarded'] == False
status_msg = '[%s] %s => %s' % (FF.id, FF.orig_filename, FF.upload_msg)
assert len(jresp['data']['pending']) == 1
assert jresp['data']['pending'][0] == status_msg
assert len(jresp['data']['uploading']) == 0
assert len(jresp['data']['success']) == 0
assert len(jresp['data']['failed']) == 0
assert len(jresp['pending']) == 1
assert jresp['pending'][0] == status_msg
assert len(jresp['uploading']) == 0
assert len(jresp['success']) == 0
assert len(jresp['failed']) == 0
jresp = atreal_openads.get_fwd_files_status(None, FAKE_NUMERO_DOSSIER, fichier_id=FF.id, summary='1')
assert jresp['data'] is not None
assert jresp['data']['all_forwarded'] == False
assert jresp is not None
assert jresp['all_forwarded'] == False
status_msg = '[%s] %s => %s' % (FF.id, FF.orig_filename, FF.upload_msg)
assert len(jresp['data']['pending']) == 1
assert jresp['data']['pending'][0] == status_msg
assert len(jresp['data']['uploading']) == 0
assert len(jresp['data']['success']) == 0
assert len(jresp['data']['failed']) == 0
assert len(jresp['pending']) == 1
assert jresp['pending'][0] == status_msg
assert len(jresp['uploading']) == 0
assert len(jresp['success']) == 0
assert len(jresp['failed']) == 0
def test_openads_createForwardFile(app, atreal_openads):
jresp = atreal_openads.createForwardFile(None, FAKE_NUMERO_DOSSIER)
assert jresp['data'] is not None
m = re.search(r"^ForwardFile '(\d+)' created$", jresp['data'])
assert jresp is not None
m = re.search(r"^ForwardFile '(\d+)' created$", jresp['message'])
assert m
assert int(m.group(1)) > 0
file_id = int(m.group(1))
@ -471,10 +531,9 @@ def test_openads_get_courrier(app, atreal_openads):
with mock.patch('passerelle.utils.Request.get') as requests_get:
requests_get.return_value = fake_resp
jresp = atreal_openads.get_courrier(None, 'DIA', FAKE_NUMERO_DOSSIER)
assert len(jresp['data']['files']) == len(fake_resp_json['files'])
assert jresp['data']['files'][0]['filename'] == fake_resp_json['files'][0]['filename']
assert jresp['data']['files'][0]['content_type'] == fake_resp_json['files'][0]['content_type']
assert jresp['data']['files'][0]['b64_content'] == fake_resp_json['files'][0]['b64_content']
assert jresp['courrier']['filename'] == fake_resp_json['files'][0]['filename']
assert jresp['courrier']['content_type'] == fake_resp_json['files'][0]['content_type']
assert jresp['courrier']['b64_content'] == fake_resp_json['files'][0]['b64_content']
def test_openads_upload_user_files(app, atreal_openads):