From cdac81bd46fa073337829f2336978a4900a83e37 Mon Sep 17 00:00:00 2001
From: Nicolas ROCHE <nroche@entrouvert.com>
Date: Tue, 26 Nov 2019 11:03:01 +0100
Subject: [PATCH] tracking_code: add tests on formdata access (#38073)

---
 tests/test_tracking_code.py | 339 +++++++++++++++++++++++++++++++++++-
 1 file changed, 335 insertions(+), 4 deletions(-)

diff --git a/tests/test_tracking_code.py b/tests/test_tracking_code.py
index 255ef050..825e6e4f 100644
--- a/tests/test_tracking_code.py
+++ b/tests/test_tracking_code.py
@@ -1,22 +1,193 @@
 import pytest
 
+from quixote import cleanup
+from wcs import fields
+from wcs.admin.settings import UserFieldsFormDef
 from wcs.formdef import FormDef
+from wcs.qommon.ident.password_accounts import PasswordAccount
+from wcs.roles import Role
+from wcs.wf.form import FormWorkflowStatusItem, WorkflowFormFieldsFormDef
+from wcs.workflows import Workflow, ChoiceWorkflowStatusItem
 
-from utilities import create_temporary_pub, clean_temporary_pub
+from utilities import get_app, login, create_temporary_pub, clean_temporary_pub
 
 
 def pytest_generate_tests(metafunc):
     if 'pub' in metafunc.fixturenames:
         metafunc.parametrize('pub', ['pickle', 'sql'], indirect=True)
 
+def teardown_module(module):
+    clean_temporary_pub()
 
 @pytest.fixture
 def pub(request):
-    return create_temporary_pub(sql_mode=(request.param == 'sql'))
+    cleanup()
+    pub = create_temporary_pub(sql_mode=(request.param == 'sql'))
+    pub.cfg['identification'] = {'methods': ['password']}
+    pub.cfg['language'] = {'language': 'en'}
+    pub.write_cfg()
+    return pub
 
+@pytest.fixture
+def users(pub):
+    def create_user(name):
+        user = pub.user_class()
+        user.email = '%s@example.net' % name
+        user.name = name
+        user.store()
+        account = PasswordAccount(id=name)
+        account.set_password(name)
+        account.user_id = user.id
+        account.store()
 
-def teardown_module(module):
-    clean_temporary_pub()
+        user_formdef = UserFieldsFormDef(pub)
+        user_formdef.fields = [
+            fields.StringField(
+                id='_first_name', label='first name',
+                type='string', extra_css_class='autocomplete-given-name'),
+        ]
+        user_formdef.store()
+        user.form_data = {'_first_name': name}
+        user.set_attributes_from_formdata(user.form_data)
+        user.store()
+        return user
+
+    pub.user_class.wipe()
+    PasswordAccount.wipe()
+    user1 = create_user('user1')
+    user2 = create_user('user2')
+    agent1 = create_user('agent1')
+    agent2 = create_user('agent2')
+    admin1 = create_user('admin1')
+    Role.wipe()
+    role1 = Role(name='Submitters')
+    role1.allows_backoffice_access = True
+    role1.store()
+    role2 = Role(name='Receivers')
+    role2.store()
+    agent1.roles = [role1.id]
+    agent1.store()
+    agent2.roles = [role2.id]
+    agent2.store()
+    admin1.is_admin = True
+    admin1.store()
+    return {
+        'anonymous': None,
+        'user1': user1,
+        'user2': user2,
+        'agent1': agent1,
+        'agent2': agent2,
+        'admin1': admin1,
+    }
+
+@pytest.fixture
+def prefill_formdef(users):
+    FormDef.wipe()
+    formdef = FormDef()
+    formdef.name = 'test'
+    formdef.fields = [
+        fields.PageField(id='0', label='1st page', type='page'),
+        fields.CommentField(
+            id='2', type='comment', display_locations=['validation', 'summary'],
+            label='{{form_user_display_name}}'),
+        fields.StringField(
+            id='3', label='prefill-string-page1', required=False,
+            prefill={'type': 'string', 'value': '{{form_user_display_name}}'}),
+        fields.StringField(
+            id='p3', label='prefill-user-page1', required=False,
+            prefill={'type': 'user', 'value': '_first_name'}),
+
+        # updated on draft using tracking code
+        fields.PageField(id='4', label='2nd page', type='page'),
+        fields.StringField(
+            id='4', label='prefill-string-page2', required=False,
+            prefill={'type': 'string', 'value': '{{form_user_display_name}}'}),
+        fields.StringField(
+            id='p4', label='prefill-user-page2', required=False,
+            prefill={'type': 'user', 'value': '_first_name'}),
+    ]
+    formdef.backoffice_submission_roles = users['agent1'].roles[:]
+    formdef.workflow_roles = {'_receiver': users['agent2'].roles[0]}
+    formdef.enable_tracking_codes = True
+    formdef.store()
+
+    Workflow.wipe()
+    workflow = Workflow(name='test')
+    st1 = workflow.add_status('Status1')
+    st2 = workflow.add_status('Status2')
+
+    display_form = FormWorkflowStatusItem()
+    display_form.formdef = WorkflowFormFieldsFormDef(item=display_form)
+    display_form.formdef.fields = [
+        # updated on workflow using tracking code
+        fields.StringField(
+            id='5', label='prefill-string-workflow', required=False,
+            prefill={'type': 'string', 'value': '{{form_user_display_name}}'}),
+        fields.StringField(
+            id='p5', label='prefill-user-workflow', required=False,
+            prefill={'type': 'user', 'value': '_first_name'}),
+    ]
+    display_form.by = ['_submitter']
+    display_form.parent = st2
+
+    jump = ChoiceWorkflowStatusItem()
+    jump.id = '_jump'
+    jump.label = 'Go form'
+    jump.by = ['_submitter']
+    jump.status = st2.id
+    jump.parent = st1
+
+    st1.items.append(jump)
+    st2.items.append(display_form)
+    workflow.store()
+
+    formdef.workflow_id = workflow.id
+    formdef.store()
+    return formdef
+
+def get_displayed_tracking_code(resp):
+    tracking_code = None
+    if 'Forms - test' in resp.text:
+        # frontoffice
+        for a_tag in resp.html.findAll('a'):
+            if 'code/' in a_tag['href']:
+                tracking_code = a_tag.text
+                break
+    elif 'Back Office of wcs - test' in resp.text:
+        # backoffice
+        for h3_tag in resp.html.findAll('h3'):
+            if h3_tag.text == 'Tracking Code':
+                tracking_code = h3_tag.next_sibling.next_element
+                break
+    assert tracking_code
+    return tracking_code
+
+def submit_prefill_demand(pub, formdef, is_draft, user, is_front=True):
+    """submit form or draft"""
+    app = get_app(pub)
+
+    if user:
+        app = login(app, username=user.name, password=user.name)
+    if is_front:
+        resp = app.get('/test/')
+        assert '<h3>Tracking code</h3>' in resp.text
+    else:
+        resp = app.get('/backoffice/submission/test/')
+        assert '<h3>Tracking Code</h3>' in resp.text
+
+    formdef.data_class().wipe()
+    resp = resp.form.submit('submit')  # submit page 1
+    tracking_code = get_displayed_tracking_code(resp)
+
+    if not is_draft:
+        resp = resp.form.submit('submit')  # submit page 2
+        resp = resp.form.submit('submit')  # submit form
+
+    assert formdef.data_class().count() == 1
+    formdata = formdef.data_class().select()[0]
+    assert formdata.is_draft() == is_draft
+    assert formdata.tracking_code == tracking_code
+    return (tracking_code, formdata.id)
 
 
 def test_tracking_code(pub):
@@ -79,3 +250,163 @@ def test_tracking_code_duplicate(pub):
 
     assert marker.get('done') # makes sure we got to the real new id code
     assert klass.count() == 2
+
+
+@pytest.mark.parametrize("is_draft, submitter, is_front, assessor, access", [
+    (True, 'anonymous', True, 'anonymous', 'login'),
+    (True, 'anonymous', True, 'user1', 'deny'),
+    (True, 'anonymous', True, 'user2', 'deny'),
+    (True, 'anonymous', True, 'agent1', 'deny'),
+    (True, 'anonymous', True, 'agent2', 'deny'),
+    (True, 'anonymous', True, 'admin1', 'deny'),
+    (True, 'agent1', False, 'anonymous', 'login'),
+    (True, 'agent1', False, 'user1', 'deny'),
+    (True, 'agent1', False, 'user2', 'deny'),
+    (True, 'agent1', False, 'agent1', 'deny'),
+    (True, 'agent1', False, 'agent2', 'deny'),
+    (True, 'agent1', False, 'admin1', 'deny'),
+    (True, 'user1', True, 'anonymous', 'login'),
+    (True, 'user1', True, 'user1', 'front'),
+    (True, 'user1', True, 'user2', 'deny'),
+    (True, 'user1', True, 'agent1', 'deny'),
+    (True, 'user1', True, 'agent2', 'deny'),
+    (True, 'user1', True, 'admin1', 'deny'),
+    (False, 'anonymous', True, 'anonymous', 'login'),
+    (False, 'anonymous', True, 'user1', 'deny'),
+    (False, 'anonymous', True, 'user2', 'deny'),
+    (False, 'anonymous', True, 'agent1', 'deny'),
+    (False, 'anonymous', True, 'agent2', 'back'),
+    (False, 'anonymous', True, 'admin1', 'back'),
+    (False, 'agent1', False, 'anonymous', 'login'),
+    (False, 'agent1', False, 'user1', 'deny'),
+    (False, 'agent1', False, 'user2', 'deny'),
+    (False, 'agent1', False, 'agent1', 'deny'),
+    (False, 'agent1', False, 'agent2', 'back'),
+    (False, 'agent1', False, 'admin1', 'back'),
+    (False, 'user1', True, 'anonymous', 'login'),
+    (False, 'user1', True, 'user1', 'front'),
+    (False, 'user1', True, 'user2', 'deny'),
+    (False, 'user1', True, 'agent1', 'deny'),
+    (False, 'user1', True, 'agent2', 'back'),
+    (False, 'user1', True, 'admin1', 'back'),
+])
+def test_direct_access_to_formdata(nocache, pub, users, prefill_formdef,
+                                   is_draft, submitter, is_front, assessor, access):
+    (tracking_code, formdata_id) = submit_prefill_demand(
+        pub, prefill_formdef, is_draft, users[submitter], is_front)
+
+    app = get_app(pub)
+    if assessor != 'anonymous':
+        app = login(app, username=users[assessor].name, password=users[assessor].name)
+    if is_draft:
+        resp = app.get('/test/%s' % formdata_id)
+        if access == 'deny':
+            assert resp.follow(status=403)
+        elif access == 'login':
+            resp = resp.follow()
+            assert resp.location.startswith('http://example.net/login/?next=')
+        elif access == 'front':
+            resp = resp.follow()
+            assert 'http://example.net/test/?mt=' in resp.location
+            resp = resp.follow()
+            assert '<title>Forms - test</title>' in resp.text
+            assert get_displayed_tracking_code(resp) == tracking_code
+        else:
+            assert access in ('login', 'deny', 'front')
+    else:
+        resp = app.get('/test/%s' % formdata_id)
+        assert resp.location == 'http://example.net/test/%s/' % formdata_id
+        if access == 'deny':
+            assert resp.follow(status=403)
+        elif access == 'login':
+            resp = resp.follow()
+            assert resp.location.startswith('http://example.net/login/?next=')
+        elif access == 'front':
+            resp = resp.follow()
+            assert '<title>Forms - test</title>' in resp.text
+            assert get_displayed_tracking_code(resp) == tracking_code
+        elif access == 'back':
+            resp = resp.follow()
+            assert '/backoffice/management/test/%s/' % formdata_id in resp.location
+            resp = resp.follow()
+            assert ' <title>Back Office of wcs - test - %s</title>' % formdata_id in resp.text
+        else:
+            assert access in ('login', 'deny', 'front', 'back')
+
+
+@pytest.mark.parametrize("assessor", [
+    ('anonymous'), ('user1'), ('user2'), ('agent1'), ('agent2'), ('admin1')])
+@pytest.mark.parametrize("submitter, is_front, expected_owner", [
+    ('anonymous', True, 'anonymous'),
+    ('agent1', False, 'anonymous'),
+    ('user1', True, 'user1'),
+])
+@pytest.mark.parametrize("is_draft", [(True), (False)])
+def test_indirect_access_to_formdata(
+        nocache, pub, users, prefill_formdef,
+        is_draft, submitter, is_front, assessor, expected_owner):
+    (tracking_code, formdata_id) = submit_prefill_demand(
+        pub, prefill_formdef, is_draft, users[submitter], is_front)
+    user = users[assessor]
+    expected_owner = users[expected_owner]
+    expected_new_owner = user
+
+    app = get_app(pub)
+    if user:
+        app = login(app, username=user.name, password=user.name)
+    resp = app.get('/')
+    resp.forms[0]['code'] = tracking_code
+    resp = resp.forms[0].submit()
+    resp = resp.follow()
+    resp = resp.follow()
+    if is_draft:
+        resp = resp.follow()
+    assert '<title>Forms - test</title>' in resp.text
+
+    if is_draft:
+        resp = resp.forms[1].submit('submit')  # submit page 2
+    else:
+        resp = resp.form.submit('button_jump')  # go to display_form
+        resp = resp.follow()
+
+    def get_comment_value():
+        html = resp.html.find('div', attrs={'class': 'comment-field'})
+        if html:
+            return html.p.text
+        else:  # empty comment is not displayed in summary
+            return ''
+
+    def get_field_value(field_label):
+        # validation page
+        for html in resp.html.find_all('div', attrs={'class': 'WcsExtraStringWidget'}):
+            if html.label.text == field_label:
+                return html.input.get('value') or ''
+        # summary
+        for html in resp.html.find_all('div', attrs={'class': 'field'}):
+            if html.span.text == field_label:
+                return html.div.text
+        return ''  # empty field is not displayed in summary
+
+    formdata = prefill_formdef.data_class().select()[0]
+    assert formdata.id == formdata_id  # formdata must be reloaded here
+    formdata_user = getattr(formdata.user, 'name', '')
+    owner_value = getattr(expected_owner, 'name', '')
+    new_owner_value = getattr(expected_new_owner, 'name', '')
+
+    if is_draft:
+        if expected_new_owner:
+            assert formdata_user == new_owner_value
+        else:  # formdata_user is not overidden by anonymous user
+            assert formdata_user == owner_value
+        assert get_comment_value() == new_owner_value
+        assert get_field_value('prefill-string-page1') == owner_value
+        assert get_field_value('prefill-user-page1') == owner_value
+        assert get_field_value('prefill-string-page2') == new_owner_value
+        assert get_field_value('prefill-user-page2') == new_owner_value
+    else:
+        assert formdata_user == owner_value
+        assert get_comment_value() == owner_value
+        assert get_field_value('prefill-string-page1') == owner_value
+        assert get_field_value('prefill-user-page1') == owner_value
+        assert get_field_value('prefill-string-workflow') == owner_value
+        assert get_field_value('prefill-user-workflow') == new_owner_value
-- 
2.24.1

