From 1066fea04d068e9b312d18ade278276164fc20c2 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 | 385 +++++++++++++++++++++++++++++++++++-
 1 file changed, 381 insertions(+), 4 deletions(-)

diff --git a/tests/test_tracking_code.py b/tests/test_tracking_code.py
index c6fc2829..aec4281b 100644
--- a/tests/test_tracking_code.py
+++ b/tests/test_tracking_code.py
@@ -1,19 +1,108 @@
 import pytest
+import contextlib
+import re
 
+from quixote import cleanup
+from wcs import fields
+from wcs.wf.form import FormWorkflowStatusItem, WorkflowFormFieldsFormDef
 from wcs.formdef import FormDef
+from wcs.qommon.ident.password_accounts import PasswordAccount
+from wcs.roles import Role
+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
 
-def teardown_module(module):
-    clean_temporary_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()
+
+        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
+
+    from wcs.admin.settings import UserFieldsFormDef
+    formdef = UserFieldsFormDef(pub)
+    formdef.url_name = 'user'
+    formdef.id = 'bof'
+    formdef.data_class().wipe()
+
+    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='Submiters')
+    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 None, user1, user2, agent1, agent2, admin1  # None for anonymous
+
+def create_formdef():
+    FormDef.wipe()
+    formdef = FormDef()
+    formdef.name = 'test'
+    formdef.fields = []
+    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 test_tracking_code(pub):
     klass = pub.tracking_code_class
@@ -74,3 +163,291 @@ def test_tracking_code_duplicate(pub):
 
     assert marker.get('done') # makes sure we got to the real new id code
     assert klass.count() == 2
+
+def test_access_to_formdata(pub, users, nocache):
+    """
+    1-  Direct access to ressources
+     a-  Drafts
+
+    | sumitter / accesser | anonymous | user1 | user2 | agent1 | agent2 | admin1 |
+    +---------------------+-----------+-------+-------+--------+--------+--------+
+    | anonymous           |  login    | deny  | deny  | deny   | deny   | deny   |
+    | agent1 (submiter))  |  login    | deny  | deny  | deny   | deny   | deny   |
+    | user1               |  login    | allow | deny  | deny   | deny   | deny   |
+
+     b-  Demands
+
+    | sumitter / accesser | anonymous | user1 | user2 | agent1 | agent2 | admin1 |
+    +---------------------+-----------+-------+-------+--------+--------+--------+
+    | anonymous           |  login    | deny  | deny  | deny   | back   | back   |
+    | agent1 (submiter)   |  login    | deny  | deny  | deny   | back   | back   |
+    | user1               |  login    | allow | deny  | deny   | back   | back   |
+
+    2- New user on prefill fields when accessing using tracking code :
+     a-  Drafts
+
+    | sumitter / accesser | anonymous | user1 | user2 | agent1 | agent2 | admin1 |
+    +---------------------+-----------+-------+-------+--------+--------+--------+
+    | anonymous           | anonymous | user1 | user2 | agent1 | agent2 | admin  |
+    | agent1 (submiter)   | anonymous | user1 | user2 | agent1 | agent2 | admin  |
+    | user1               | anonymous | user1 | user2 | agent1 | agent2 | admin  |
+
+     b-  Demands (evolving into Workflows forms)
+
+    | sumitter / accesser | anonymous | user1 | user2 | agent1 | agent2 | admin1 |
+    +---------------------+-----------+-------+-------+--------+--------+--------+
+    | anonymous           | anonymous | user1 | user2 | agent1 | agent2 | admin  |
+    | agent1 (submiter)   | anonymous | user1 | user2 | agent1 | agent2 | admin  |
+    | user1               | anonymous | user1 | user2 | agent1 | agent2 | admin  |
+    """
+    (anonymous, user1, user2, agent1, agent2, admin1) = users
+    tracking_code = None
+    formdata_id = None
+    is_draft = None
+    formdef = create_formdef()
+    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 = agent1.roles[:]
+    formdef.workflow_roles = {'_receiver': 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()
+
+    @contextlib.contextmanager
+    def submit(user, is_front=True):
+        """submit form or draft"""
+        pub.session_manager.session_class.wipe()
+        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
+        yield (tracking_code, formdata.id)
+
+    def check_direct_access(user, access=None):
+        """direct access from the URLs"""
+        pub.session_manager.session_class.wipe()
+        app = get_app(pub)
+        if user:
+            app = login(app, username=user.name, password=user.name)
+
+        if is_draft:
+            if access == 'deny':
+                resp = app.get('/test/%s' % formdata_id, status=403)
+                return
+
+            resp = app.get('/test/%s' % formdata_id)
+
+            if access == 'login':
+                assert resp.location.startswith('http://example.net/login/?next=')
+            elif access == 'front':
+                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':
+                resp = 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 resp.location == 'http://example.net/backoffice/management/test/%s/' % formdata_id
+                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')
+
+    def check_tracking_code_access(user, owner=None, new_owner=None):
+        """
+        load the formdata using the tracking code and prefill user name fields.
+        new_owner is used to show that user fields change on drafts.
+        """
+        pub.session_manager.session_class.wipe()
+        app = get_app(pub)
+
+        # access form sumary/draft
+        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()
+        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 = formdef.data_class().select()[0]
+        formdata_user = getattr(formdata.user, 'name', '')
+        expected_owner = getattr(owner, 'name', '')
+        expected_new_owner = getattr(new_owner, 'name', '')
+
+        if is_draft:
+            if new_owner:
+                assert formdata_user == expected_new_owner  # !!
+            else:  # formdata_user is not overidden by anonymous user
+                assert formdata_user == expected_owner
+            assert get_comment_value() == expected_new_owner  # !!
+            assert get_field_value('prefill-string-page1') == expected_owner
+            assert get_field_value('prefill-user-page1') == expected_owner
+            assert get_field_value('prefill-string-page2') == expected_new_owner  # !!
+            assert get_field_value('prefill-user-page2') == expected_new_owner  # !!
+        else:
+            assert formdata_user == expected_owner
+            assert get_comment_value() == expected_owner
+            assert get_field_value('prefill-string-page1') == expected_owner
+            assert get_field_value('prefill-user-page1') == expected_owner
+            assert get_field_value('prefill-string-workflow') == expected_owner
+            assert get_field_value('prefill-user-workflow') == expected_new_owner  # !!
+
+    # direct access to formdata
+    is_draft = True  # drafts
+    with submit(anonymous, is_front=True) as (tracking_code, formdata_id):
+        access = ('login', 'deny', 'deny', 'deny', 'deny', 'deny')
+        for i in range(len(users)):
+            check_direct_access(users[i], access[i])
+    with submit(agent1, is_front=False) as (tracking_code, formdata_id):
+        access = ('login', 'deny', 'deny', 'deny', 'deny', 'deny')
+        for i in range(len(users)):
+            check_direct_access(users[i], access[i])
+    with submit(user1, is_front=True) as (tracking_code, formdata_id):
+        access = ('login', 'front', 'deny', 'deny', 'deny', 'deny')
+        for i in range(len(users)):
+            check_direct_access(users[i], access[i])
+
+    is_draft = False  # demands
+    with submit(anonymous, is_front=True) as (tracking_code, formdata_id):
+        access = ('login', 'deny', 'deny', 'deny', 'back', 'back')
+        for i in range(len(users)):
+            check_direct_access(users[i], access[i])
+    with submit(agent1, is_front=False) as (tracking_code, formdata_id):
+        access = ('login', 'deny', 'deny', 'deny', 'back', 'back')
+        for i in range(len(users)):
+            check_direct_access(users[i], access[i])
+    with submit(user1, is_front=True) as (tracking_code, formdata_id):
+        access = ('login', 'front', 'deny', 'deny', 'back', 'back')
+        for i in range(len(users)):
+            check_direct_access(users[i], access[i])
+
+    # access to formdata using the tracking code
+    is_draft = True  # drafts
+    for user in users:
+        with submit(anonymous, is_front=True) as (tracking_code, formdata_id):
+            check_tracking_code_access(user, owner=anonymous, new_owner=user)
+        with submit(agent1, is_front=False) as (tracking_code, formdata_id):
+            check_tracking_code_access(user, owner=anonymous, new_owner=user)
+        with submit(user1, is_front=True) as (tracking_code, formdata_id):
+            check_tracking_code_access(user, owner=user1, new_owner=user)
+
+    is_draft = False  # demands
+    for user in users:
+        with submit(anonymous, is_front=True) as (tracking_code, formdata_id):
+            check_tracking_code_access(user, owner=anonymous, new_owner=user)
+        with submit(agent1, is_front=False) as (tracking_code, formdata_id):
+            check_tracking_code_access(user, owner=anonymous, new_owner=user)
+        with submit(user1, is_front=True) as (tracking_code, formdata_id):
+            check_tracking_code_access(user, owner=user1, new_owner=user)
-- 
2.24.1

