Example #1
0
        ptable = current.s3db.pr_person
        ktablename, key, multiple = s3_get_foreign_key(ptable.pe_id)
        self.assertEqual(ktablename, "pr_pentity")
        self.assertEqual(key, "pe_id")
        self.assertFalse(multiple)

        # @todo: restore with a different list:reference
        #otable = s3db.org_organisation
        #ktablename, key, multiple = s3_get_foreign_key(otable.multi_sector_id)
        #self.assertEqual(ktablename, "org_sector")
        #self.assertEqual(key, "id")
        #self.assertTrue(multiple)

        # @todo: restore with a different list:reference
        #ktablename, key, multiple = s3_get_foreign_key(otable.multi_sector_id, m2m=False)
        #self.assertEqual(ktablename, None)
        #self.assertEqual(key, None)
        #self.assertEqual(multiple, None)


# =============================================================================
if __name__ == "__main__":

    run_suite(
        S3TypeConverterTests,
        S3FKWrappersTests,
    )

# END ========================================================================
Example #2
0
        values2 = [5, 3, 9, 8]
        ga2 = S3GroupAggregate("avg", "Example", values2)
        assertEqual(ga2.result, 6.25)

        # Combine the two aggregates
        ga = S3GroupAggregate.aggregate((ga1, ga2))
        assertEqual(ga.result, 6.125)
        for value in values1 + values2:
            assertTrue(value in ga.values)

        # Combine with method mismatch
        ga = S3GroupAggregate("min", "Example", values1)
        with assertRaises(TypeError):
            S3GroupAggregate((ga1, ga2, ga))

        # Combine with key mismatch
        ga = S3GroupAggregate("avg", "Other", values1)
        with assertRaises(TypeError):
            S3GroupAggregate((ga1, ga2, ga))


# =============================================================================
if __name__ == "__main__":

    run_suite(
        S3GroupedItemsTests,
        S3GroupAggregateTests,
    )

# END ========================================================================
Example #3
0
            required=msg,
        )
        widget.alias = "default"

        form = Storage(
            vars=Storage(link_defaultcomponent=[1, 2]),
            errors=Storage(),
        )

        widget.validate(form)
        errors = form.errors
        self.assertNotIn("link_defaultcomponent", errors)

        form = Storage(
            vars=Storage(),
            errors=Storage(),
        )

        widget.validate(form)
        errors = form.errors
        self.assertIn("link_defaultcomponent", errors)
        self.assertEqual(errors.link_defaultcomponent, msg)


# =============================================================================
if __name__ == "__main__":

    run_suite(InlineLinkTests, )

# END ========================================================================
Example #4
0
        # @todo: restore with a different list:reference
        #ktablename, key, multiple = s3_get_foreign_key(otable.multi_sector_id, m2m=False)
        #self.assertEqual(ktablename, None)
        #self.assertEqual(key, None)
        #self.assertEqual(multiple, None)


# =============================================================================
class S3MarkupStripperTests(unittest.TestCase):
    """ Test for S3MarkupStripper """
    def testConstructor(self):
        """ Verify Python-2 compatibility of constructor """

        # Base class of S3MarkupStripper is a Python-2 old-style class,
        # so super() call in constructor could raise a TypeError unless
        # multiple inheritance with object enforces a new-style class
        stripper = S3MarkupStripper()


# =============================================================================
if __name__ == "__main__":

    run_suite(
        S3TypeConverterTests,
        S3FKWrappersTests,
        S3MarkupStripperTests,
    )

# END ========================================================================
Example #5
0
        xml = current.xml

        tree = xml.parse(StringIO(self.relpath))
        self.assertNotEqual(tree, None)
        self.assertEqual(xml.error, None)

    # -------------------------------------------------------------------------
    def testImportWithForbiddenFileAccess(self):
        """ Verify parser error breaks imports with forbidden file access """

        resource = current.s3db.resource("org_organisation")

        with self.assertRaises(SyntaxError):
            resource.import_xml(StringIO(self.forbidden))

# =============================================================================
if __name__ == "__main__":

    run_suite(
        TreeBuilderTests,
        JSONMessageTests,
        XMLFormatTests,
        GetFieldOptionsTests,
        S3JSONParsingTests,
        LookupListRepresentTests,
        EntityResolverTests,
    )

# END ========================================================================
Example #6
0
        self.assertEqual(r.url(method="deduplicate", target=0, vars={}),
                         "/%s/pr/person/%s/contact/deduplicate.xml" % (a, p))

        # Test request without component
        r = S3Request(prefix="pr",
                      name="person",
                      c="pr",
                      f="person",
                      args=[self.p, "method"],
                      vars=Storage(format="xml", test="test"))

        self.assertEqual(r.url(method="", id=5),
                         "/%s/pr/person/5.xml?test=test" % a)
        self.assertEqual(r.url(method="", vars=None),
                         "/%s/pr/person.xml?test=test" % a)
        self.assertEqual(r.url(id="[id]", method="review"),
                         "/%s/pr/person/%%5Bid%%5D/review.xml?test=test" % a)
        self.assertEqual(r.url(method="deduplicate", target=0, vars={}),
                         "/%s/pr/person/deduplicate.xml" % a)


# =============================================================================
if __name__ == "__main__":

    run_suite(
        POSTFilterTests,
        URLBuilderTests,
    )

# END ========================================================================
Example #7
0
            rep(self.a2.id),
            "%s" % self.a2.name,
        )

        self.assertEqual(
            rep(None),
            current.messages.NONE,
        )

        self.assertEqual(
            rep(self.a1),
            "%s - %s" % (self.p1.code, self.a1.name),
        )

        self.assertEqual(
            rep(self.a1.id, self.a1),
            "%s - %s" % (self.p1.code, self.a1.name),
        )

    def tearDown(self):
        db.rollback()
        auth.override = False


# =============================================================================
if __name__ == "__main__":

    run_suite(ProjectTests, )

# END ========================================================================
Example #8
0
        )

        self.assertEqual(
            rep(None),
            current.messages.NONE,
        )

        self.assertEqual(
            rep(self.a1),
            "%s - %s" % (self.p1.code, self.a1.name),
        )

        self.assertEqual(
            rep(self.a1.id, self.a1),
            "%s - %s" % (self.p1.code, self.a1.name),
        )

    def tearDown(self):
        db.rollback()
        auth.override = False


# =============================================================================
if __name__ == "__main__":

    run_suite(
        ProjectTests,
    )

# END ========================================================================
Example #9
0
        data = {"a": 1}
        formatted = validator.formatter(data)
        assertEqual(formatted, """{"a":1}""")

        data = """{"a":1}"""
        formatted = validator.formatter(data)
        assertEqual(formatted, data)

        # Exception: None gives None
        # (would give "null" normally, but forms need to know there is no value)
        data = None
        formatted = validator.formatter(data)
        assertEqual(formatted, None)


# =============================================================================
if __name__ == "__main__":

    run_suite(
        ISLatTest,
        ISLonTest,
        ISONEOFLazyRepresentationTests,
        IS_PHONE_NUMBER_Tests,
        IS_UTC_DATETIME_Tests,
        IS_UTC_DATE_Tests,
        IS_JSONS3_Tests,
    )

# END ========================================================================
Example #10
0
    def testGetForeignKey(self):

        ptable = current.s3db.pr_person
        ktablename, key, multiple = s3_get_foreign_key(ptable.pe_id)
        self.assertEqual(ktablename, "pr_pentity")
        self.assertEqual(key, "pe_id")
        self.assertFalse(multiple)

        # @todo: restore with a different list:reference
        #otable = s3db.org_organisation
        #ktablename, key, multiple = s3_get_foreign_key(otable.multi_sector_id)
        #self.assertEqual(ktablename, "org_sector")
        #self.assertEqual(key, "id")
        #self.assertTrue(multiple)

        # @todo: restore with a different list:reference
        #ktablename, key, multiple = s3_get_foreign_key(otable.multi_sector_id, m2m=False)
        #self.assertEqual(ktablename, None)
        #self.assertEqual(key, None)
        #self.assertEqual(multiple, None)

# =============================================================================
if __name__ == "__main__":

    run_suite(
        S3TypeConverterTests,
        S3FKWrappersTests,
    )

# END ========================================================================
Example #11
0
File: s3sync.py Project: bst99/eden
        # Check the result: only the final record gets imported
        # Note that no components of the deleted duplicate would ever
        # get exported - hence no need to test the handling of it
        resource = s3db.resource("org_organisation",
                                 uid =uids, include_deleted = True)
        result = resource.select(test_fields, limit=None)["rows"]
        self.assertEqual(len(result), 1)
        for record in result:
            self.assertEqual(record[UUID], "TESTIMPORTMERGEORG7")
            self.assertFalse(record[DELETED])
            self.assertEqual(record[REPLACEDBY], None)

    def tearDown(self):

        current.auth.override = False
        current.db.rollback()

# =============================================================================
if __name__ == "__main__":

    run_suite(
        ExportMergeTests,
        ImportMergeTests,
        ImportMergeWithExistingRecords,
        ImportMergeWithExistingOriginal,
        ImportMergeWithExistingDuplicate,
        ImportMergeWithoutExistingRecords
    )

# END ========================================================================
Example #12
0
        # First selection
        menu.select(tag="a11")

        assertTrue(menu.selected)
        assertTrue(items["a1"].selected)
        assertTrue(items["a11"].selected)
        assertIsNone(items["a12"].selected)
        assertIsNone(items["a2"].selected)
        assertIsNone(items["a21"].selected)
        assertIsNone(items["a22"].selected)

        # Second selection => should completely reset the first
        menu.select(tag="a22")

        assertTrue(menu.selected)
        assertIsNone(items["a1"].selected)
        assertIsNone(items["a11"].selected)
        assertIsNone(items["a12"].selected)
        assertTrue(items["a2"].selected)
        assertIsNone(items["a21"].selected)
        assertTrue(items["a22"].selected)

# =============================================================================
if __name__ == "__main__":

    run_suite(
        SelectTests,
    )

# END ========================================================================
Example #13
0
File: s3gis.py Project: bst99/eden
        self.assertEqual(record.lat_min, 13)
        self.assertEqual(record.lat_max, 37)
        self.assertEqual(record.lon_min, 13)
        self.assertEqual(record.lon_max, 37)
        self.assertEqual(record.parent, L1_id)
        self.assertEqual(record.path, "%s/%s/%s" % (L0_id, L1_id, L3_id))
        self.assertEqual(record.wkt, POLYGON)
        self.assertEqual(record.L0, L0)
        self.assertEqual(record.L1, L1)
        self.assertEqual(record.L2, None)
        self.assertEqual(record.L3, L3)
        self.assertEqual(record.L4, None)
        self.assertEqual(record.L5, None)
        if self.spatialdb:
            self.assertTrue(record.the_geom is not None)

    # -------------------------------------------------------------------------
    @classmethod
    def tearDownClass(cls):
        current.auth.override = False
        current.db.rollback()

# =============================================================================
if __name__ == "__main__":

    run_suite(
        S3LocationTreeTests,
    )

# END ========================================================================
Example #14
0
File: s3cfg.py Project: bst99/eden
            # User can see the field if belonging to that org
            auth.user.organisation_id = org.id
            self.assertEqual(auth.root_org(), org.id)
            check = settings.set_org_dependent_field("pr_person_details", "mother_name")
            self.assertTrue(check)
            self.assertTrue(table.mother_name.readable)
            self.assertTrue(table.mother_name.writable)

            # ...but not if we haven't configured it
            settings.org.dependent_fields = None
            check = settings.set_org_dependent_field("pr_person_details", "mother_name")
            self.assertFalse(check)
            self.assertFalse(table.mother_name.readable)
            self.assertFalse(table.mother_name.writable)

        finally:
            current.db.rollback()
            auth.s3_impersonate(None)
            if s:
                settings.org.dependent_fields = s

# =============================================================================
if __name__ == "__main__":

    run_suite(
        S3ConfigTests,
    )

# END ========================================================================
Example #15
0
            # User can see the field if belonging to that org
            auth.user.organisation_id = org.id
            self.assertEqual(auth.root_org(), org.id)
            check = settings.set_org_dependent_field("pr_person_details",
                                                     "mother_name")
            self.assertTrue(check)
            self.assertTrue(table.mother_name.readable)
            self.assertTrue(table.mother_name.writable)

            # ...but not if we haven't configured it
            settings.org.dependent_fields = None
            check = settings.set_org_dependent_field("pr_person_details",
                                                     "mother_name")
            self.assertFalse(check)
            self.assertFalse(table.mother_name.readable)
            self.assertFalse(table.mother_name.writable)

        finally:
            current.db.rollback()
            auth.s3_impersonate(None)
            if s:
                settings.org.dependent_fields = s


# =============================================================================
if __name__ == "__main__":

    run_suite(S3ConfigTests, )

# END ========================================================================
Example #16
0
        self.assertEqual(
            self.represent(
                "unicode ßñö chars, urls for https://sahanafoundation.org/ and "
                "www.github.com/sahana/eden"), "unicode ßñö chars, urls for "
            "<a href=\"https://sahanafoundation.org/\" target=\"_blank\">"
            "https://sahanafoundation.org/</a> and "
            "<a href=\"www.github.com/sahana/eden\" target=\"_blank\">"
            "www.github.com/sahana/eden</a>")

    # -------------------------------------------------------------------------
    def testURLsWithHrefs(self):
        """ Test that if there is already at least one href, then no hrefs are added """

        self.assertEqual(
            self.represent(
                "unicode ßñö chars and urls for "
                "<a href=\"https://sahanafoundation.org/\" target=\"_blank\">"
                "https://sahanafoundation.org/ and www.github.com/sahana/eden"
            ), "unicode ßñö chars and urls for "
            "<a href=\"https://sahanafoundation.org/\" target=\"_blank\">"
            "https://sahanafoundation.org/ and www.github.com/sahana/eden")


# =============================================================================
if __name__ == "__main__":

    run_suite(CMSPostBodyRepresentTests, )

# END ========================================================================
Example #17
0
                                                  )),
                                         TD(INPUT(_type="checkbox",
                                                  _name="roles",
                                                  _value="38"
                                                  )),
                                         TD(INPUT(_type="checkbox",
                                                  _name="roles",
                                                  _value="39",
                                                  value=True
                                                  )),
                                         TD(INPUT(_type="checkbox",
                                                  _name="roles",
                                                  _value="40",
                                                  value=True
                                                  ))
                                         ),
                                    )
                                 )
        self.assertEqual(str(self.widget(self.field, self.value)),
                         str(expected_result))


# =============================================================================
if __name__ == "__main__":

    run_suite(
        TestS3OptionsMatrixWidget,
    )

# END ========================================================================
Example #18
0
        # A JSON list gives the same JSON string
        value_list = root.findall('resource/data[@field="jsonlist"]')[0]
        v = value_list.get("value")
        assertEqual(v, '["value1", "value2"]')
        assertEqual(json.loads(v), ["value1", "value2"])

        # A string gives the same string
        value_list = root.findall('resource/data[@field="valuestring"]')[0]
        v = value_list.get("value")
        assertEqual(v, "value1")

        # A numeric value gives its string representation
        value_list = root.findall('resource/data[@field="valueinteger"]')[0]
        v = value_list.get("value")
        assertEqual(v, "2")


# =============================================================================
if __name__ == "__main__":

    run_suite(
        TreeBuilderTests,
        JSONMessageTests,
        XMLFormatTests,
        GetFieldOptionsTests,
        S3JSONParsingTests,
    )

# END ========================================================================
Example #19
0
            raise AssertionError("Referenced record not imported!")

        # Get the JSON object
        table = s3db.ort_master
        row = db(table.uuid == muid).select(table.jsontest,
                                            limitby=(0, 1)).first()

        # Inspect the JSON object, verify that the reference is resolved
        obj = row.jsontest
        self.assertNotIn("$k_referenced_id", obj)
        self.assertIn("referenced_id", obj)
        self.assertEqual(obj["referenced_id"], record_id)


# =============================================================================
if __name__ == "__main__":

    run_suite(
        ListStringImportTests,
        DefaultApproverOverrideTests,
        ComponentDisambiguationTests,
        PostParseTests,
        FailedReferenceTests,
        DuplicateDetectionTests,
        MtimeImportTests,
        ObjectReferencesTests,
        ObjectReferencesImportTests,
    )

# END ========================================================================
Example #20
0
File: inv.py Project: bst99/eden
class InvTests(unittest.TestCase):
    """ Inv Tests """

    def setUp(self):
        """ Set up location records """
        auth = current.auth
        auth.override = True

        self.location_code = Storage()
        self.location_ids = Storage()
        s3db = current.s3db


        #---------------------------------------------------------------------



    def tearDown(self):

        current.db.rollback()
        current.auth.override = False

# =============================================================================
if __name__ == "__main__":

    run_suite(
        StatsTests,
    )

# END ========================================================================
Example #21
0
        # TODO: improve/extend

        table = current.s3db.pr_person

        rules = {"first_name": ("set", "Anonymous"),
                 "last_name": "remove",
                 "comments": "remove",
                 }

        S3Anonymize.apply_field_rules(table, (self.person_id,), rules)

        query = (table.id == self.person_id)
        row = current.db(query).select(table.first_name,
                                       table.last_name,
                                       table.comments,
                                       limitby = (0, 1),
                                       ).first()

        self.assertEqual(row.first_name, "Anonymous")
        self.assertEqual(row.last_name, None)
        self.assertEqual(row.comments, None)

# =============================================================================
if __name__ == "__main__":

    run_suite(
        S3AnonymizeTests,
    )

# END ========================================================================
Example #22
0
File: org.py Project: bst99/eden
        result = json.loads(result)
        msg = result["message"]

        error_tree = resource.error_tree
        assertNotEqual(error_tree, None)

        elements = error_tree.xpath("resource[data[@field='name']/text()='DeDupBranch2']")
        assertEqual(len(elements), 1)

        attrib = elements[0].attrib
        assertTrue("error" in attrib)
        assertTrue(attrib["error"] in msg)

        # Verify that nothing has changed in the database
        query = (otable.name == "DeDupBranch2") & \
                (otable.deleted != True)
        rows = db(query).select(otable.id, otable.comments)
        assertEqual(len(rows), 2)
        for row in rows:
            assertEqual(row.comments, None)

# =============================================================================
if __name__ == "__main__":

    run_suite(
        RootOrgUpdateTests,
        OrgDeduplicationTests,
    )

# END ========================================================================
Example #23
0
File: pr.py Project: mauld/eden
        </resource>
    </resource>
</s3xml>"""

        xmltree = etree.ElementTree(etree.fromstring(xmlstr))

        resource = s3db.resource("pr_person")
        result = resource.import_xml(xmltree, ignore_errors=True)

        resource = s3db.resource("pr_contact", uid="VALIDATORTESTCONTACT1")
        self.assertEqual(resource.count(), 0)
        row = resource.select(["value"], as_rows=True).first()
        self.assertEqual(row, None)

        resource = s3db.resource("pr_contact", uid="VALIDATORTESTCONTACT2")
        self.assertEqual(resource.count(), 1)
        row = resource.select(["value"], as_rows=True).first()
        self.assertNotEqual(row, None)
        self.assertEqual(row.value, "+46733847589")

# =============================================================================
if __name__ == "__main__":

    run_suite(
        PRTests,
        PersonDeduplicateTests,
        ContactValidationTests,
    )

# END ========================================================================
Example #24
0
        request = current.request

        assertIn = self.assertIn
        assertNotIn = self.assertNotIn
        assertTrue = self.assertTrue

        fallback = request.args
        override = ["override"]

        context = S3DashboardContext(request)

        # Check fallback
        assertNotIn("args", context.__dict__)
        assertTrue(context.args is fallback)

        # Check override
        context.args = override
        assertIn("args", context.__dict__)
        assertTrue(request.args is fallback)
        assertTrue(context.args is override)

# =============================================================================
if __name__ == "__main__":

    run_suite(
        S3DashboardContextTests,
        S3DashboardAgentTests,
    )

# END ========================================================================
Example #25
0
        # Restore original get_config method
        GIS.get_config = staticmethod(cls.original_get_config)

    # -------------------------------------------------------------------------
    def testMapSetup(self):
        """ Verify that MAP setup without config produces an error message """

        map = MAP()
        setup_result = map._setup()
        self.assertIsNone(setup_result)
        self.assertIsNotNone(map.error_message)

    def testMap2Xml(self):
        """ Verify that MAP2 rendering without config produces an error message """

        map = MAP2()
        xml = map.xml()
        self.assertTrue(b"Map cannot display without GIS config!" in xml)


# =============================================================================
if __name__ == "__main__":

    run_suite(
        S3LocationTreeTests,
        S3NoGisConfigTests,
    )

# END ========================================================================
Example #26
0
        # Standard fallback
        field = rf()
        self.assertEqual(field.widget, None)

        # Deliberate default
        field = rf(widget="default")
        self.assertEqual(field.widget, None)

        # Alternative
        self.assertRaises(NameError, rf, widget="alternative")

        # Override
        field = rf(widget=self.widget1)
        self.assertEqual(field.widget, self.widget1)

        # Undefined widget
        self.assertRaises(NameError, rf, widget="other")

# =============================================================================
if __name__ == "__main__":

    run_suite(
        S3RepresentTests,
        S3ExtractLazyFKRepresentationTests,
        S3ExportLazyFKRepresentationTests,
        S3ReusableFieldTests,
    )

# END ========================================================================
Example #27
0
        assertNotEqual(error, None)

        # Must be a supported field type
        value, error = requires("nonsense")
        assertNotEqual(error, None)

        # Must not be "id"
        value, error = requires("id")
        assertNotEqual(error, None)

        # Referenced tables must be resolvable
        value, error = requires("reference nonexistent_table")
        assertNotEqual(error, None)

# =============================================================================
if __name__ == "__main__":

    run_suite(
        #ISLatTest,
        #ISLonTest,
        ISONEOFLazyRepresentationTests,
        IS_PHONE_NUMBER_Tests,
        IS_UTC_DATETIME_Tests,
        IS_UTC_DATE_Tests,
        IS_JSONS3_Tests,
        IS_DYNAMIC_FIELDNAME_Test,
        IS_DYNAMIC_FIELDTYPE_Test,
    )

# END ========================================================================
Example #28
0
File: s3crud.py Project: bst99/eden
                          method="validate",
                          get_vars=Storage(),
                          representation="json",
                          http="GET")

        crud = resource.crud

        jsonstr = """{"organisation_id":"1", "role":"1"}"""
        request.body = StringIO(jsonstr)

        output = crud.validate(request)
        self.assertTrue(isinstance(output, basestring))
        data = json.loads(output)
        self.assertTrue(isinstance(data, dict))
        self.assertEqual(len(data), 2)

        self.assertTrue("role" in data)
        role = data["role"]
        self.assertTrue(isinstance(role, dict))
        self.assertTrue("value" in role)
        self.assertTrue(isinstance(role["value"], int))

# =============================================================================
if __name__ == "__main__":

    run_suite(
        ValidateTests,
    )

# END ========================================================================
Example #29
0
File: s3msg.py Project: bst99/eden
    # -------------------------------------------------------------------------
    def send_email_error(self, recipient, *args, **kwargs):
        """ Dummy send mechanism that fails for 1 recipient """

        if recipient == "*****@*****.**":
            self.sent.append(recipient)
            return True
        else:
            return False

    # -------------------------------------------------------------------------
    def send_email_exception(self, recipient, *args, **kwargs):
        """ Dummy send mechanism that crashes for 1 recipient """

        if recipient == "*****@*****.**":
            self.sent.append(recipient)
            return True
        elif recipient == "*****@*****.**":
            raise RuntimeError
        else:
            return False

# =============================================================================
if __name__ == "__main__":

    run_suite(
        S3OutboxTests,
    )

# END ========================================================================
Example #30
0
                                            parent=parent,
                                            export_map=Storage())
        mlt = timeit.Timer(x).timeit(number=1000)
        print "S3Resource.export (incl. DB extraction) = %s ms (=%s rec/sec)" % (mlt, int(1000/mlt))
        self.assertTrue(mlt<10)

        resource = current.s3db.resource("pr_person")
        from lxml import etree
        parent = etree.Element("test")
        rfields, dfields = resource.split_fields()
        record = resource.table[1]
        x = lambda: resource._export_record(record,
                                            rfields=rfields,
                                            dfields=dfields,
                                            parent=parent,
                                            export_map=Storage())
        mlt = timeit.Timer(x).timeit(number=1000)
        print "S3Resource.export (w/o DB extraction) = %s ms (=%s rec/sec)" % (mlt, int(1000/mlt))
        self.assertTrue(mlt<10)

        current.auth.override = False

# =============================================================================
if __name__ == "__main__":

    run_suite(
        S3PerformanceTests,
    )

# END ========================================================================
Example #31
0
                                            export_map=Storage())
        mlt = timeit.Timer(x).timeit(number=1000)
        info("S3Resource.export (incl. DB extraction) = %s ms (=%s rec/sec)" %
             (mlt, int(1000 / mlt)))
        self.assertTrue(mlt < 10)

        resource = current.s3db.resource("pr_person")
        from lxml import etree
        parent = etree.Element("test")
        rfields, dfields = resource.split_fields()
        record = resource.table[1]
        x = lambda: resource._export_record(record,
                                            rfields=rfields,
                                            dfields=dfields,
                                            parent=parent,
                                            export_map=Storage())
        mlt = timeit.Timer(x).timeit(number=1000)
        info("S3Resource.export (w/o DB extraction) = %s ms (=%s rec/sec)" %
             (mlt, int(1000 / mlt)))
        self.assertTrue(mlt < 10)

        current.auth.override = False


# =============================================================================
if __name__ == "__main__":

    run_suite(S3PerformanceTests, )

# END ========================================================================
Example #32
0
        self.assertEqual(expected, actual)

        dt = S3DataTable(self.rfields,
                         self.data,
                         orderby=~table.office_type_id | table.name)
        expected = [[4, "desc"], [3, "asc"]]
        actual = dt.orderby
        self.assertEqual(expected, actual)

        otable = current.s3db.org_organisation
        dt = S3DataTable(self.rfields,
                         self.data,
                         orderby=otable.name | ~table.office_type_id
                         | table.name)
        expected = [[1, "asc"], [4, "desc"], [3, "asc"]]
        actual = dt.orderby
        self.assertEqual(expected, actual)

    # -------------------------------------------------------------------------
    def tearDown(cls):

        current.auth.override = False


# =============================================================================
if __name__ == "__main__":

    run_suite(S3DataTableTests, )

# END ========================================================================
Example #33
0
            "6:18m":
            0.11,  # Colon-notation with explicit unit, overriding assumption
            "1h15min": 1.25,  # Explicit unit
            "9h18s": 9.01,  # Explicit unit
            "4.95": "error",  # lacks unit and above limit => ambiguous
            "3h15":
            "error",  # 15 segment lacks unit and above limit => edge-case, treated as ambiguous
        }

        for s in samples.items():
            hours, error = validate(s[0])

            if s[1] == "error":
                assertNotEqual(error, None)
            else:
                assertEqual(error, None)
                assertEqual(
                    round(hours, 8), s[1],
                    "'%s' recognized as %s, expected %s" % (s[0], hours, s[1]))


# =============================================================================
if __name__ == "__main__":

    run_suite(
        S3OptionsMatrixWidgetTests,
        S3HoursWidgetTests,
    )

# END ========================================================================
Example #34
0
        # Verify fields in the component table
        assertTrue("organisation_id" in component.fields)
        assertTrue("value" in component.fields)

    # -------------------------------------------------------------------------
    def testFieldSelectorResolution(self):
        """ Test field selector resolution for dynamic components """

        s3db = current.s3db

        assertEqual = self.assertEqual

        resource = s3db.resource("org_organisation")
        rfield = resource.resolve_selector("test_rating.value")

        assertEqual(rfield.tname, self.TABLENAME)
        assertEqual(rfield.fname, "value")
        assertEqual(rfield.ftype, "integer")

# =============================================================================
if __name__ == "__main__":

    run_suite(
        #S3ModelTests,
        S3SuperEntityTests,
        S3DynamicModelTests,
        S3DynamicComponentTests,
    )

# END ========================================================================
Example #35
0
                   TD(INPUT(_type="checkbox", _name="roles", _value="32")),
                   TD(INPUT(_type="checkbox", _name="roles", _value="33")),
                   TD(INPUT(_type="checkbox", _name="roles", _value="34")),
                   TD(INPUT(_type="checkbox", _name="roles", _value="35"))),
                TR(
                    TH("Incidents", _scope="row"),
                    TD(INPUT(_type="checkbox", _name="roles", _value="36")),
                    TD(INPUT(_type="checkbox", _name="roles", _value="37")),
                    TD(INPUT(_type="checkbox", _name="roles", _value="38")),
                    TD(
                        INPUT(_type="checkbox",
                              _name="roles",
                              _value="39",
                              value=True)),
                    TD(
                        INPUT(_type="checkbox",
                              _name="roles",
                              _value="40",
                              value=True))),
            ))
        self.assertEqual(str(self.widget(self.field, self.value)),
                         str(expected_result))


# =============================================================================
if __name__ == "__main__":

    run_suite(TestS3OptionsMatrixWidget, )

# END ========================================================================
Example #36
0
        assertIn = self.assertIn
        assertNotIn = self.assertNotIn
        assertTrue = self.assertTrue

        fallback = request.args
        override = ["override"]

        context = S3DashboardContext(request)

        # Check fallback
        assertNotIn("args", context.__dict__)
        assertTrue(context.args is fallback)

        # Check override
        context.args = override
        assertIn("args", context.__dict__)
        assertTrue(request.args is fallback)
        assertTrue(context.args is override)


# =============================================================================
if __name__ == "__main__":

    run_suite(
        S3DashboardContextTests,
        S3DashboardAgentTests,
    )

# END ========================================================================
Example #37
0
        if "inv" in deployment_settings.modules:
            comment = S3PopupLink(c="inv", f="inv_item")
            # Deactivate module
            inv = deployment_settings.modules["inv"]
            del deployment_settings.modules["inv"]
            # Comment should auto-deactivate
            self.assertFalse(comment.check_active())
            # Restore module
            deployment_settings.modules["inv"] = inv
            # Comment should auto-reactivate
            self.assertTrue(comment.check_active())

        self.assertFalse(comment.check_permission())
        self.assertEqual(comment.xml(), "")
        auth.s3_impersonate("*****@*****.**")
        self.assertTrue(comment.check_permission())
        output = comment.xml()
        self.assertTrue(type(output) is str)
        self.assertNotEqual(output, "")
        auth.s3_impersonate(None)

# =============================================================================
if __name__ == "__main__":

    run_suite(
        LayoutTests,
    )

# END ========================================================================
Example #38
0
File: s3rest.py Project: bst99/eden
                         "/%s/pr/person/%%5Bid%%5D/contact/review.xml?test=test" % a)
        self.assertEqual(r.url(method="deduplicate", target=0, vars={}),
                         "/%s/pr/person/%s/contact/deduplicate.xml" % (a, p))

        # Test request without component
        r = S3Request(prefix="pr",
                      name="person",
                      c="pr",
                      f="person",
                      args=[self.p, "method"],
                      vars=Storage(format="xml", test="test"))

        self.assertEqual(r.url(method="", id=5),
                         "/%s/pr/person/5.xml?test=test" % a)
        self.assertEqual(r.url(method="", vars=None),
                         "/%s/pr/person.xml?test=test" % a)
        self.assertEqual(r.url(id="[id]", method="review"),
                         "/%s/pr/person/%%5Bid%%5D/review.xml?test=test" % a)
        self.assertEqual(r.url(method="deduplicate", target=0, vars={}),
                         "/%s/pr/person/deduplicate.xml" % a)

# =============================================================================
if __name__ == "__main__":

    run_suite(
        POSTFilterTests,
        URLBuilderTests,
    )

# END ========================================================================
Example #39
0
File: s3xml.py Project: bst99/eden
        assertEqual(json.loads(v), ["value1", "value2"])

        # A JSON list gives the same JSON string
        value_list = root.findall('resource/data[@field="jsonlist"]')[0]
        v = value_list.get("value")
        assertEqual(v, '["value1", "value2"]')
        assertEqual(json.loads(v), ["value1", "value2"])

        # A string gives the same string
        value_list = root.findall('resource/data[@field="valuestring"]')[0]
        v = value_list.get("value")
        assertEqual(v, "value1")

        # A numeric value gives its string representation
        value_list = root.findall('resource/data[@field="valueinteger"]')[0]
        v = value_list.get("value")
        assertEqual(v, "2")

# =============================================================================
if __name__ == "__main__":

    run_suite(
        TreeBuilderTests,
        JSONMessageTests,
        XMLFormatTests,
        GetFieldOptionsTests,
        S3JSONParsingTests,
    )

# END ========================================================================
Example #40
0
from gluon.storage import Storage

from unit_tests import run_suite


# =============================================================================
class InvTests(unittest.TestCase):
    """ Inv Tests """
    def setUp(self):
        """ Set up location records """
        auth = current.auth
        auth.override = True

        self.location_code = Storage()
        self.location_ids = Storage()
        s3db = current.s3db

    #--------------------------------------------------------------------------
    def tearDown(self):

        current.db.rollback()
        current.auth.override = False


# =============================================================================
if __name__ == "__main__":

    run_suite(InvTests, )

# END ========================================================================
Example #41
0
    </resource>
</s3xml>"""

        xmltree = etree.ElementTree(etree.fromstring(xmlstr))

        resource = s3db.resource("pr_person")
        result = resource.import_xml(xmltree, ignore_errors=True)

        resource = s3db.resource("pr_contact", uid="VALIDATORTESTCONTACT1")
        self.assertEqual(resource.count(), 0)
        row = resource.select(["value"], as_rows=True).first()
        self.assertEqual(row, None)

        resource = s3db.resource("pr_contact", uid="VALIDATORTESTCONTACT2")
        self.assertEqual(resource.count(), 1)
        row = resource.select(["value"], as_rows=True).first()
        self.assertNotEqual(row, None)
        self.assertEqual(row.value, "+46733847589")


# =============================================================================
if __name__ == "__main__":

    run_suite(
        PRTests,
        PersonDeduplicateTests,
        ContactValidationTests,
    )

# END ========================================================================
Example #42
0
        table = current.s3db.pr_person

        rules = {
            "first_name": ("set", "Anonymous"),
            "last_name": "remove",
            "comments": "remove",
        }

        S3Anonymize.apply_field_rules(table, (self.person_id, ), rules)

        query = (table.id == self.person_id)
        row = current.db(query).select(
            table.first_name,
            table.last_name,
            table.comments,
            limitby=(0, 1),
        ).first()

        self.assertEqual(row.first_name, "Anonymous")
        self.assertEqual(row.last_name, None)
        self.assertEqual(row.comments, None)


# =============================================================================
if __name__ == "__main__":

    run_suite(S3AnonymizeTests, )

# END ========================================================================
Example #43
0
                         settings = {"sort_options": True,
                                     },
                         )
        field = define_field(self.TABLENAME, params)

        # => verify field name and type
        assertEqual(field.name, "status")
        assertEqual(field.type, "string")

        # => verify validators
        requires = field.requires
        assertTrue(isinstance(requires, IS_IN_SET))

        options = requires.options()
        # Options are sorted, no zero-option
        assertEqual(options, [('C', 'done'),
                              ('B', 'in progress'),
                              ('A', 'new'),
                              ])

# =============================================================================
if __name__ == "__main__":

    run_suite(
        #S3ModelTests,
        S3SuperEntityTests,
        S3DynamicModelTests,
    )

# END ========================================================================
Example #44
0
        # Standard fallback
        field = rf()
        self.assertEqual(field.widget, None)

        # Deliberate default
        field = rf(widget="default")
        self.assertEqual(field.widget, None)

        # Alternative
        self.assertRaises(NameError, rf, widget="alternative")

        # Override
        field = rf(widget=self.widget1)
        self.assertEqual(field.widget, self.widget1)

        # Undefined widget
        self.assertRaises(NameError, rf, widget="other")


# =============================================================================
if __name__ == "__main__":

    run_suite(
        S3RepresentTests,
        S3ExtractLazyFKRepresentationTests,
        S3ExportLazyFKRepresentationTests,
        S3ReusableFieldTests,
    )

# END ========================================================================
Example #45
0
        tree = etree.ElementTree(etree.fromstring(xmlstr))

        # Import the data
        resource = s3db.resource("org_facility")
        result = resource.import_xml(tree)

        # Verify outer resource
        resource = s3db.resource("org_facility", uid="MTFAC")
        row = resource.select(["id", "modified_on"], as_rows=True)[0]
        assertEqual(row.modified_on, mtime)

        # Verify inner resource
        resource = s3db.resource("org_organisation", uid="MTORG")
        row = resource.select(["id", "modified_on"], as_rows=True)[0]
        assertEqual(row.modified_on, mtime)

# =============================================================================
if __name__ == "__main__":

    run_suite(
        ListStringImportTests,
        DefaultApproverOverrideTests,
        ComponentDisambiguationTests,
        PostParseTests,
        FailedReferenceTests,
        DuplicateDetectionTests,
        MtimeImportTests,
    )

# END ========================================================================
Example #46
0
        archive.add("test1.xml", xmlstr1)
        archive.add("test2.xml", xmlstr2)

        # Close the archive
        fileobj = archive.close()

        # Open the archive
        archive = S3SyncDataArchive(fileobj)

        # Verify archive contents
        extracted = archive.extract("test1.xml").read()
        assertEqual(extracted, xmlstr1)
        extracted = archive.extract("test2.xml").read()
        assertEqual(extracted, xmlstr2)


# =============================================================================
if __name__ == "__main__":

    run_suite(
        ExportMergeTests,
        ImportMergeTests,
        ImportMergeWithExistingRecords,
        ImportMergeWithExistingOriginal,
        ImportMergeWithExistingDuplicate,
        ImportMergeWithoutExistingRecords,
        DataArchiveTests,
    )

# END ========================================================================
Example #47
0
from unit_tests import run_suite


# =============================================================================
class InvTests(unittest.TestCase):
    """ Inv Tests """
    def setUp(self):
        """ Set up location records """
        auth = current.auth
        auth.override = True

        self.location_code = Storage()
        self.location_ids = Storage()
        s3db = current.s3db

        #---------------------------------------------------------------------

    def tearDown(self):

        current.db.rollback()
        current.auth.override = False


# =============================================================================
if __name__ == "__main__":

    run_suite(StatsTests, )

# END ========================================================================
Example #48
0
        values2 = [5, 3, 9, 8]
        ga2 = S3GroupAggregate("avg", "Example", values2)
        assertEqual(ga2.result, 6.25)

        # Combine the two aggregates
        ga = S3GroupAggregate.aggregate((ga1, ga2))
        assertEqual(ga.result, 6.125)
        for value in values1 + values2:
            assertTrue(value in ga.values)

        # Combine with method mismatch
        ga = S3GroupAggregate("min", "Example", values1)
        with assertRaises(TypeError):
            S3GroupAggregate((ga1, ga2, ga))

        # Combine with key mismatch
        ga = S3GroupAggregate("avg", "Other", values1)
        with assertRaises(TypeError):
            S3GroupAggregate((ga1, ga2, ga))

# =============================================================================
if __name__ == "__main__":

    run_suite(
        S3GroupedItemsTests,
        S3GroupAggregateTests,
    )

# END ========================================================================
Example #49
0
    # -------------------------------------------------------------------------
    def send_email_error(self, recipient, *args, **kwargs):
        """ Dummy send mechanism that fails for 1 recipient """

        if recipient == "*****@*****.**":
            self.sent.append(recipient)
            return True
        else:
            return False

    # -------------------------------------------------------------------------
    def send_email_exception(self, recipient, *args, **kwargs):
        """ Dummy send mechanism that crashes for 1 recipient """

        if recipient == "*****@*****.**":
            self.sent.append(recipient)
            return True
        elif recipient == "*****@*****.**":
            raise RuntimeError
        else:
            return False


# =============================================================================
if __name__ == "__main__":

    run_suite(S3OutboxTests, )

# END ========================================================================
Example #50
0
        expected = [[4, "asc"], [3, "asc"]]
        actual = dt.orderby
        self.assertEqual(expected, actual)

        dt = S3DataTable(self.rfields, self.data,
                         orderby=~table.office_type_id | table.name)
        expected = [[4, "desc"], [3, "asc"]]
        actual = dt.orderby
        self.assertEqual(expected, actual)

        otable = current.s3db.org_organisation
        dt = S3DataTable(self.rfields, self.data,
                         orderby=otable.name | ~table.office_type_id | table.name)
        expected = [[1, "asc"], [4, "desc"], [3, "asc"]]
        actual = dt.orderby
        self.assertEqual(expected, actual)

    # -------------------------------------------------------------------------
    def tearDown(cls):

        current.auth.override = False

# =============================================================================
if __name__ == "__main__":

    run_suite(
        S3DataTableTests,
    )

# END ========================================================================
Example #51
0
        self.assertAlmostEqual(record.lon, 25.867625899280576, 13)
        self.assertEqual(record.lat_min, 13)
        self.assertEqual(record.lat_max, 37)
        self.assertEqual(record.lon_min, 13)
        self.assertEqual(record.lon_max, 37)
        self.assertEqual(record.parent, L1_id)
        self.assertEqual(record.path, "%s/%s/%s" % (L0_id, L1_id, L3_id))
        self.assertEqual(record.wkt, POLYGON)
        self.assertEqual(record.L0, L0)
        self.assertEqual(record.L1, L1)
        self.assertEqual(record.L2, None)
        self.assertEqual(record.L3, L3)
        self.assertEqual(record.L4, None)
        self.assertEqual(record.L5, None)
        if self.spatialdb:
            self.assertTrue(record.the_geom is not None)

    # -------------------------------------------------------------------------
    @classmethod
    def tearDownClass(cls):
        current.auth.override = False
        current.db.rollback()


# =============================================================================
if __name__ == "__main__":

    run_suite(S3LocationTreeTests, )

# END ========================================================================
Example #52
0
        # Must be a supported field type
        value, error = requires("nonsense")
        assertNotEqual(error, None)

        # Must not be "id"
        value, error = requires("id")
        assertNotEqual(error, None)

        # Referenced tables must be resolvable
        value, error = requires("reference nonexistent_table")
        assertNotEqual(error, None)


# =============================================================================
if __name__ == "__main__":

    run_suite(
        #ISLatTest,
        #ISLonTest,
        ISONEOFLazyRepresentationTests,
        IS_PHONE_NUMBER_Tests,
        IS_UTC_DATETIME_Tests,
        IS_UTC_DATE_Tests,
        IS_JSONS3_Tests,
        IS_DYNAMIC_FIELDNAME_Test,
        IS_DYNAMIC_FIELDTYPE_Test,
    )

# END ========================================================================
Example #53
0
        xml = current.xml

        tree = xml.parse(BytesIO(self.relpath.encode("utf-8")))
        self.assertNotEqual(tree, None)
        self.assertEqual(xml.error, None)

    # -------------------------------------------------------------------------
    def testImportWithForbiddenFileAccess(self):
        """ Verify parser error breaks imports with forbidden file access """

        resource = current.s3db.resource("org_organisation")

        with self.assertRaises(SyntaxError):
            resource.import_xml(BytesIO(self.forbidden.encode("utf-8")))


# =============================================================================
if __name__ == "__main__":

    run_suite(
        TreeBuilderTests,
        JSONMessageTests,
        XMLFormatTests,
        GetFieldOptionsTests,
        S3JSONParsingTests,
        LookupListRepresentTests,
        EntityResolverTests,
    )

# END ========================================================================
Example #54
0
                                 field = "test",
                                 required = msg,
                                 )
        widget.alias = "default"

        form = Storage(vars = Storage(link_defaultcomponent=[1,2]),
                       errors=Storage(),
                       )

        widget.validate(form)
        errors = form.errors
        self.assertNotIn("link_defaultcomponent", errors)

        form = Storage(vars = Storage(),
                       errors=Storage(),
                       )

        widget.validate(form)
        errors = form.errors
        self.assertIn("link_defaultcomponent", errors)
        self.assertEqual(errors.link_defaultcomponent, msg)

# =============================================================================
if __name__ == "__main__":

    run_suite(
        InlineLinkTests,
    )

# END ========================================================================
Example #55
0
        # First selection
        menu.select(tag="a11")

        assertTrue(menu.selected)
        assertTrue(items["a1"].selected)
        assertTrue(items["a11"].selected)
        assertIsNone(items["a12"].selected)
        assertIsNone(items["a2"].selected)
        assertIsNone(items["a21"].selected)
        assertIsNone(items["a22"].selected)

        # Second selection => should completely reset the first
        menu.select(tag="a22")

        assertTrue(menu.selected)
        assertIsNone(items["a1"].selected)
        assertIsNone(items["a11"].selected)
        assertIsNone(items["a12"].selected)
        assertTrue(items["a2"].selected)
        assertIsNone(items["a21"].selected)
        assertTrue(items["a22"].selected)


# =============================================================================
if __name__ == "__main__":

    run_suite(SelectTests, )

# END ========================================================================
Example #56
0
        validator = IS_JSONS3(native_json=True)

        data = {"a": 1}
        formatted = validator.formatter(data)
        assertEqual(formatted, """{"a":1}""")

        data = """{"a":1}"""
        formatted = validator.formatter(data)
        assertEqual(formatted, data)

        # Exception: None gives None
        # (would give "null" normally, but forms need to know there is no value)
        data = None
        formatted = validator.formatter(data)
        assertEqual(formatted, None)

# =============================================================================
if __name__ == "__main__":

    run_suite(
        ISLatTest,
        ISLonTest,
        ISONEOFLazyRepresentationTests,
        IS_PHONE_NUMBER_Tests,
        IS_UTC_DATETIME_Tests,
        IS_UTC_DATE_Tests,
        IS_JSONS3_Tests,
    )

# END ========================================================================
Example #57
0
        component_record = component_table[component_id]
        self.assertNotEqual(component_record, None)

        # Try delete the super-record (must return False)
        success = s3db.delete_super(master_table, record)
        self.assertFalse(success)

        # Super-key is retained
        record = master_table[self.master_id]
        self.assertEqual(record.se_id, se_id)

        # Component record is not deleted and still linked
        component_record = component_table[component_id]
        self.assertFalse(component_record.deleted)
        self.assertEqual(component_record.se_id, se_id)

        # Super-record is not deleted
        super_table = s3db.setest_super
        super_record = super_table[se_id]
        self.assertFalse(super_record.deleted)

# =============================================================================
if __name__ == "__main__":

    run_suite(
        #S3ModelTests,
        S3SuperEntityTests,
    )

# END ========================================================================
Example #58
0
File: hrm.py Project: bst99/eden
        """
            Test that a Volunteer can get their location_id updated from a
            New Home Address: with no "person_id"
        """

        current.deployment_settings.hrm.location_vol = "site_id"

        row, address_location_id, site_location_id = self._testVolUpdateFromPersonAddress(site=False)
        self.assertEqual(row.location_id, None)

    # -------------------------------------------------------------------------
    def testVolUpdateFromPersonAddress8(self):
        """
            Test that a Volunteer can get their location_id updated from a
            New Home Address: with no "person_id"
        """

        current.deployment_settings.hrm.location_vol = "site_id"

        row, address_location_id, site_location_id = self._testVolUpdateFromPersonAddress(site=True)
        self.assertEqual(row.location_id, site_location_id)

# =============================================================================
if __name__ == "__main__":

    run_suite(
        LocationSettingTests,
    )

# END ========================================================================