Exemplo n.º 1
0
class TestFormList(TestBase):
    def setUp(self):
        super(TestFormList, self).setUp()
        self.profile = UserProfile.objects.create(user=self.user,
                                                  require_auth=True)
        self.profile.save()
        self.digest_client = DigestClient()

    def test_returns_200_for_owner(self):
        self.digest_client.set_authorization('bob', 'bob')
        response = self.digest_client.get(
            reverse(formList, kwargs={'username': '******'}))
        self.assertEqual(response.status_code, 200)

    def test_returns_401_for_anon(self):
        response = self.anon.get(reverse(formList, kwargs={'username': '******'}))
        self.assertEqual(response.status_code, 401)

    def test_returns_200_for_authenticated_non_owner(self):
        credentials = (
            'alice',
            'alice',
        )
        self._create_user(*credentials)
        self.digest_client.set_authorization(*credentials)
        response = self.digest_client.get(
            reverse(formList, kwargs={'username': '******'}))
        self.assertEqual(response.status_code, 200)
Exemplo n.º 2
0
class TestFormList(TestBase):
    def setUp(self):
        super(TestFormList, self).setUp()
        self.profile = UserProfile.objects.create(
            user=self.user, require_auth=True)
        self.profile.save()
        self.digest_client = DigestClient()

    def test_returns_200_for_owner(self):
        self.digest_client.set_authorization('bob', 'bob')
        response = self.digest_client.get(reverse(formList, kwargs={
            'username': '******'
        }))
        self.assertEqual(response.status_code, 200)

    def test_returns_401_for_anon(self):
        response = self.anon.get(reverse(formList, kwargs={
            'username': '******'
        }))
        self.assertEqual(response.status_code, 401)

    def test_returns_200_for_authenticated_non_owner(self):
        credentials = ('alice', 'alice',)
        self._create_user(*credentials)
        self.digest_client.set_authorization(*credentials)
        response = self.digest_client.get(reverse(formList, kwargs={
            'username': '******'
        }))
        self.assertEqual(response.status_code, 200)
 def _authenticated_client(
         self, url, username='******', password='******', extra={}):
     client = DigestClient()
     # request with no credentials
     req = client.get(url, {}, **extra)
     self.assertEqual(req.status_code, 401)
     # apply credentials
     client.set_authorization(username, password, 'Digest')
     req = client.get(url, {}, **extra)
     # if 204 authorization successfull, proceed
     self.assertEqual(req.status_code, 204)
     # submissions should use this authenticated client
     return client
Exemplo n.º 4
0
def instances_xml(url, request, **kwargs):
    response = requests.Response()
    client = DigestClient()
    client.set_authorization('bob', 'bob', 'Digest')
    res = client.get('%s?%s' % (url.path, url.query))
    if res.status_code == 302:
        res = client.get(res['Location'])
        response.encoding = res.get('content-type')
        response._content = get_streaming_content(res)
    else:
        response._content = res.content
    response.status_code = 200
    return response
Exemplo n.º 5
0
def instances_xml(url, request, **kwargs):
    response = requests.Response()
    client = DigestClient()
    client.set_authorization('bob', 'bob', 'Digest')
    res = client.get('%s?%s' % (url.path, url.query))
    if res.status_code == 302:
        res = client.get(res['Location'])
        response.encoding = res.get('content-type')
        response._content = get_streaming_content(res)
    else:
        response._content = res.content
    response.status_code = 200
    return response
Exemplo n.º 6
0
    def test_retrieve_xform_manifest_linked_form(self):
        # for linked forms check if manifest media download url for csv
        # has a group_delimiter param
        data_type = 'media'
        data_value = 'xform {} transportation'.format(self.xform.pk)
        media = self._add_form_metadata(self.xform, data_type, data_value)

        self.view = XFormListViewSet.as_view(
            {
                "get": "manifest",
                "head": "manifest"
            }
        )

        # sign in bob
        request = self.factory.head('/')
        auth_response = self.view(request, pk=self.xform.pk)
        auth = DigestAuth('bob', 'bobbob')

        # set up bob's request
        request = self.factory.get('/xformsManifest')
        request.META.update(auth(request.META, auth_response))

        # make request
        response = self.view(request, pk=self.xform.pk, format='csv')

        # test
        manifest_media_url = '{}{}'.format(
            media.data['media_url'],
            '?group_delimiter=.&repeat_index_tags=_,_')
        download_url = response.data[0]['downloadUrl']
        self.assertEqual(manifest_media_url, download_url)

        url = '/bob/xformsMedia/{}/{}.csv?group_delimiter=.'\
            .format(self.xform.pk, self.metadata.pk)
        username = '******'
        password = '******'

        client = DigestClient()
        client.set_authorization(username, password, 'Digest')

        req = client.get(url)
        self.assertEqual(req.status_code, 200)

        # enable meta perms
        data_value = "editor-minor|dataentry"
        MetaData.xform_meta_permission(self.xform, data_value=data_value)

        req = client.get(url)
        self.assertEqual(req.status_code, 401)
Exemplo n.º 7
0
    def test_retrieve_xform_manifest_linked_form(self):
        # for linked forms check if manifest media download url for csv
        # has a group_delimiter param
        data_type = 'media'
        data_value = 'xform {} transportation'.format(self.xform.pk)
        media = self._add_form_metadata(self.xform, data_type, data_value)

        self.view = XFormListViewSet.as_view(
            {
                "get": "manifest",
                "head": "manifest"
            }
        )

        # sign in bob
        request = self.factory.head('/')
        auth_response = self.view(request, pk=self.xform.pk)
        auth = DigestAuth('bob', 'bobbob')

        # set up bob's request
        request = self.factory.get('/xformsManifest')
        request.META.update(auth(request.META, auth_response))

        # make request
        response = self.view(request, pk=self.xform.pk, format='csv')

        # test
        manifest_media_url = '{}{}'.format(
            media.data['media_url'],
            '?group_delimiter=.&repeat_index_tags=_,_')
        download_url = response.data[0]['downloadUrl']
        self.assertEqual(manifest_media_url, download_url)

        url = '/bob/xformsMedia/{}/{}.csv?group_delimiter=.'\
            .format(self.xform.pk, self.metadata.pk)
        username = '******'
        password = '******'

        client = DigestClient()
        client.set_authorization(username, password, 'Digest')

        req = client.get(url)
        self.assertEqual(req.status_code, 200)

        # enable meta perms
        data_value = "editor-minor|dataentry"
        MetaData.xform_meta_permission(self.xform, data_value=data_value)

        req = client.get(url)
        self.assertEqual(req.status_code, 401)
Exemplo n.º 8
0
 def _authenticated_client(self,
                           url,
                           username='******',
                           password='******',
                           extra={}):
     client = DigestClient()
     # request with no credentials
     req = client.get(url, {}, **extra)
     self.assertEqual(req.status_code, 401)
     # apply credentials
     client.set_authorization(username, password, 'Digest')
     req = client.get(url, {}, **extra)
     # if 204 authorization successfull, proceed
     self.assertEqual(req.status_code, 204)
     # submissions should use this authenticated client
     return client
Exemplo n.º 9
0
    def _download_xform(self):
        client = DigestClient()
        client.set_authorization('bob', 'bob')
        response = client.get(self.download_url)
        response_doc = minidom.parseString(response.content)

        xml_path = os.path.join(self.this_directory, "fixtures",
                                "transportation", "transportation.xml")
        with open(xml_path) as xml_file:
            expected_doc = minidom.parse(xml_file)

        model_node = [
            n for n in
            response_doc.getElementsByTagName("h:head")[0].childNodes
            if n.nodeType == Node.ELEMENT_NODE and
            n.tagName == "model"][0]

        # check for UUID and remove
        uuid_nodes = [node for node in model_node.childNodes
                      if node.nodeType == Node.ELEMENT_NODE and
                      node.getAttribute("nodeset") ==
                      "/transportation/formhub/uuid"]
        self.assertEqual(len(uuid_nodes), 1)
        uuid_node = uuid_nodes[0]
        uuid_node.setAttribute("calculate", "''")

        response_xml = response_doc.toxml().replace(
            self.xform.version, u"201411120717")
        # check content without UUID
        self.assertEqual(response_xml, expected_doc.toxml())
Exemplo n.º 10
0
    def _download_xform(self):
        client = DigestClient()
        client.set_authorization('bob', 'bob')
        response = client.get(self.download_url)
        response_doc = minidom.parseString(response.content)

        xml_path = os.path.join(self.this_directory, "fixtures",
                                "transportation", "transportation.xml")
        with open(xml_path) as xml_file:
            expected_doc = minidom.parse(xml_file)

        model_node = [
            n
            for n in response_doc.getElementsByTagName("h:head")[0].childNodes
            if n.nodeType == Node.ELEMENT_NODE and n.tagName == "model"
        ][0]

        # check for UUID and remove
        uuid_nodes = [
            node for node in model_node.childNodes
            if node.nodeType == Node.ELEMENT_NODE
            and node.getAttribute("nodeset") == "/transportation/formhub/uuid"
        ]
        self.assertEqual(len(uuid_nodes), 1)
        uuid_node = uuid_nodes[0]
        uuid_node.setAttribute("calculate", "''")

        # check content without UUID
        self.assertEqual(response_doc.toxml(), expected_doc.toxml())
Exemplo n.º 11
0
 def _get_authenticated_client(self, url, username="******", password="******", extra={}):
     client = DigestClient()
     # request with no credentials
     req = client.get(url, {}, **extra)
     self.assertEqual(req.status_code, 401)
     # apply credentials
     client.set_authorization(username, password, "Digest")
     return client
Exemplo n.º 12
0
    def testOtaRestore(self, password=None):
        client = Client()

        client.set_authorization(self.couch_user.username, password if password else self.password, method='Digest')

        resp = client.get('/a/%s/phone/restore' % self.domain, follow=True)
        self.assertEqual(resp.status_code, 200)
        self.assertTrue(resp.content.count("Successfully restored account %s!" % self.username) > 0)
Exemplo n.º 13
0
 def _get_authenticated_client(
         self, url, username='******', password='******', extra={}):
     client = DigestClient()
     # request with no credentials
     req = client.get(url, {}, **extra)
     self.assertEqual(req.status_code, 401)
     # apply credentials
     client.set_authorization(username, password, 'Digest')
     return client
Exemplo n.º 14
0
 def test_attachment_url_with_digest_auth(self):
     self.client.logout()
     response = self.client.get(self.url,
                                {'media_file': self.attachment_media_file})
     self.assertEqual(response.status_code, 401)  # nginx is used as proxy
     self.assertTrue('WWW-Authenticate' in response)
     digest_client = DigestClient()
     digest_client.set_authorization(self.login_username,
                                     self.login_password)
     response = digest_client.get(
         self.url, {'media_file': self.attachment_media_file})
     self.assertEqual(response.status_code, 200)
Exemplo n.º 15
0
    def testOtaRestore(self, password=None):
        client = Client()

        client.set_authorization(self.couch_user.username,
                                 password if password else self.password,
                                 method='Digest')

        resp = client.get('/a/%s/phone/restore' % self.domain, follow=True)
        self.assertEqual(resp.status_code, 200)
        self.assertTrue(
            resp.content.count("Successfully restored account %s!" %
                               self.username) > 0)
Exemplo n.º 16
0
    def _check_formlist(self):
        url = '/%s/formList' % self.user.username
        client = DigestClient()
        client.set_authorization('bob', 'bob')
        response = client.get(url)
        self.download_url = \
            'http://testserver/%s/forms/%s/form.xml'\
            % (self.user.username, self.xform.pk)
        md5_hash = md5(self.xform.xml.encode('utf-8')).hexdigest()
        expected_content = """<?xml version="1.0" encoding="utf-8"?>
<xforms xmlns="http://openrosa.org/xforms/xformsList"><xform><formID>transportation_2011_07_25</formID><name>transportation_2011_07_25</name><version>2014111</version><hash>md5:%(hash)s</hash><descriptionText></descriptionText><downloadUrl>%(download_url)s</downloadUrl><manifestUrl></manifestUrl></xform></xforms>"""  # noqa
        expected_content = expected_content % {
            'download_url': self.download_url,
            'hash': md5_hash
        }
        self.assertEqual(response.content.decode('utf-8'), expected_content)
        self.assertTrue(response.has_header('X-OpenRosa-Version'))
        self.assertTrue(response.has_header('Date'))
Exemplo n.º 17
0
    def test_pages(self):
        """
        Confirm that all the groups/locations/users appear on the correct pages
        """
        client = Client()
        client.login(username=self.username, password=self.password)

        # expected_id_sets is a list of sets.
        # expected_id_sets is constructed such that
        # For option with index x yielded by the view:
        #   the option's id should be in expected_ids[x]
        expected_id_sets = [{"user_location"}, {"user_parent_location"}]

        for i in self.groups:
            expected_id_sets.append(self.group_ids)
        for i in self.locations:
            expected_id_sets.append(self.location_ids)
        for i in self.users:
            expected_id_sets.append(self.user_ids)

        page_size = 3  # using a small number because more pages will hopefully be more likely to reveal bugs
        expected_num_pages = int(
            math.ceil(len(expected_id_sets) / float(page_size)))
        for i in range(expected_num_pages):
            page = i + 1
            response = client.get(reverse(CallCenterOwnerOptionsView.url_name,
                                          args=[self.domain.name]),
                                  data={
                                      "page": page,
                                      "page_limit": page_size,
                                      "q": ""
                                  })
            response_json = json.loads(response.content)
            self.assertEqual(response_json['total'], len(expected_id_sets))

            for item_index, item in enumerate(response_json['results']):
                id_ = item['id']
                option_index = ((page - 1) * page_size) + item_index
                self.assertTrue(
                    id_ in expected_id_sets[option_index],
                    "Unexpected item {} at index {}.".format(
                        item, option_index))
Exemplo n.º 18
0
    def _check_formList(self):
        url = '/%s/formList' % self.user.username
        client = DigestClient()
        client.set_authorization('bob', 'bob')
        response = client.get(url)
        self.download_url = \
            'http://testserver/%s/forms/%s/form.xml'\
            % (self.user.username, self.xform.pk)
        self.manifest_url = \
            'http://testserver/%s/xformsManifest/%s'\
            % (self.user.username, self.xform.pk)
        md5_hash = md5(self.xform.xml).hexdigest()
        expected_content = """<?xml version="1.0" encoding="utf-8"?>
<xforms xmlns="http://openrosa.org/xforms/xformsList"><xform><formID>transportation_2011_07_25</formID><name>transportation_2011_07_25</name><majorMinorVersion></majorMinorVersion><version></version><hash>md5:%(hash)s</hash><descriptionText>transportation_2011_07_25</descriptionText><downloadUrl>%(download_url)s</downloadUrl><manifestUrl>%(manifest_url)s</manifestUrl></xform></xforms>"""  # noqa
        expected_content = expected_content % {
            'download_url': self.download_url,
            'manifest_url': self.manifest_url,
            'hash': md5_hash
        }
        self.assertEqual(response.content, expected_content)
        self.assertTrue(response.has_header('X-OpenRosa-Version'))
        self.assertTrue(response.has_header('Date'))
Exemplo n.º 19
0
    def test_pages(self):
        """
        Confirm that all the groups/locations/users appear on the correct pages
        """
        client = Client()
        client.login(username=self.username, password=self.password)

        # expected_id_sets is a list of sets.
        # expected_id_sets is constructed such that
        # For option with index x yielded by the view:
        #   the option's id should be in expected_ids[x]
        expected_id_sets = [{"user_location"}, {"user_parent_location"}]

        for i in self.groups:
            expected_id_sets.append(self.group_ids)
        for i in self.locations:
            expected_id_sets.append(self.location_ids)
        for i in self.users:
            expected_id_sets.append(self.user_ids)

        page_size = 3  # using a small number because more pages will hopefully be more likely to reveal bugs
        expected_num_pages = int(math.ceil(len(expected_id_sets) / float(page_size)))
        for i in range(expected_num_pages):
            page = i + 1
            response = client.get(reverse(
                CallCenterOwnerOptionsView.url_name, args=[self.domain.name]),
                data={"page": page, "page_limit": page_size, "q": ""}
            )
            response_json = json.loads(response.content)
            self.assertEqual(response_json['total'], len(expected_id_sets))

            for item_index, item in enumerate(response_json['results']):
                id_ = item['id']
                option_index = ((page - 1) * page_size) + item_index
                self.assertTrue(
                    id_ in expected_id_sets[option_index],
                    "Unexpected item {} at index {}.".format(item, option_index)
                )