コード例 #1
0
 def test_data_type(self):
     self.assertTrue(
         types.Array(element_template=types.Boolean()).is_scalar)
     self.assertTrue(types.Array(element_template=types.Float()).is_scalar)
     self.assertTrue(
         types.Array(element_template=types.Integer()).is_scalar)
     self.assertTrue(types.Array(element_template=types.String()).is_scalar)
コード例 #2
0
    def test_add_filter_dependency(self):
        base = Base(template_engine=None,
                    models_definition="models.py",
                    namespace="namespace.filters",
                    output_directory="namespace/filters")
        self.assertEqual(base._dependencies, [])

        class User(types.Model):
            first_name = types.String()

        user_blueprint = User().blueprint()
        user_blueprint["map_name"] = "a"

        base.add_filter_dependency(AttributeMetaData("user", user_blueprint))
        self.assertEqual(base._dependencies, ["namespace.filters.User"])

        users_blueprint = types.Array(element_template=User()).blueprint()
        users_blueprint["map_name"] = "b"

        base.add_filter_dependency(AttributeMetaData("users", users_blueprint))
        self.assertEqual(base._dependencies, ["namespace.filters.User"])

        class Log(types.Model):
            message = types.String()

        logs_blueprint = types.Array(element_template=Log()).blueprint()
        logs_blueprint["map_name"] = "c"

        base.add_filter_dependency(AttributeMetaData("logs", logs_blueprint))
        self.assertEqual(base._dependencies,
                         ["namespace.filters.User", "namespace.filters.Log"])
コード例 #3
0
    def test_blueprint(self):
        array_default = types.Array(element_template=types.String())
        blueprint_default = array_default.blueprint()
        self.assertEqual(blueprint_default["type"], "array")
        self.assertEqual(blueprint_default["constraints"]["required"], True)
        self.assertEqual(blueprint_default["constraints"]["min_length"], None)
        self.assertEqual(blueprint_default["constraints"]["max_length"], None)
        self.assertEqual(blueprint_default["constraints"]["element_template"],
                         types.String().blueprint())
        self.assertEqual(blueprint_default["constraints"]["description"], None)

        array_custom = types.Array(
            required=False,
            min_length=1,
            max_length=10,
            element_template=types.String(default="cat"),
            description="description")
        blueprint_custom = array_custom.blueprint()
        self.assertEqual(blueprint_custom["type"], "array")
        self.assertEqual(blueprint_custom["constraints"]["required"], False)
        self.assertEqual(blueprint_custom["constraints"]["min_length"], 1)
        self.assertEqual(blueprint_custom["constraints"]["max_length"], 10)
        self.assertEqual(blueprint_custom["constraints"]["element_template"],
                         types.String(default="cat").blueprint())
        self.assertEqual(blueprint_custom["constraints"]["description"],
                         "description")
コード例 #4
0
    def test_data_type(self):
        array_empty = types.Array(element_template=types.String())
        self.assertEqual(array_empty.as_serializable(), [])

        array_strings = types.Array(element_template=types.String())
        array_strings.append("cat")
        array_strings.append("dog")
        self.assertEqual(array_strings.as_serializable(), ["cat", "dog"])
コード例 #5
0
 def test_data_structure(self):
     self.assertIsNone(
         types.Array(element_template=types.Date()).attribute_rewrite_map())
     self.assertIsNone(
         types.Array(
             element_template=types.DateTime()).attribute_rewrite_map())
     self.assertIsNone(
         types.Array(element_template=types.Time()).attribute_rewrite_map())
コード例 #6
0
    def test_data_structure(self):
        from datetime import date
        array_empty = types.Array(element_template=types.Date())
        self.assertEqual(array_empty.as_serializable(), [])

        array_dates = types.Array(element_template=types.Date())
        array_dates.append(date(2018, 1, 1))
        array_dates.append("2018-01-02")
        self.assertEqual(array_dates.as_serializable(),
                         ["2018-01-01", "2018-01-02"])
コード例 #7
0
class PersonREST(types.Model):
    first_name = types.String()
    last_name = types.String()
    short_string = types.String(max_length=10)

    address = AddressREST(required=False)

    addresses = types.Array(element_template=AddressREST())

    booleans = types.Array(element_template=types.Boolean())
    floats = types.Array(element_template=types.Float())
    integers = types.Array(element_template=types.Integer())
    strings = types.Array(element_template=types.String())
コード例 #8
0
 def test_data_type(self):
     self.assertIsNone(
         types.Array(element_template=types.Boolean()).
         attribute_rewrite_reverse_map())
     self.assertIsNone(
         types.Array(element_template=types.Float()).
         attribute_rewrite_reverse_map())
     self.assertIsNone(
         types.Array(element_template=types.Integer()).
         attribute_rewrite_reverse_map())
     self.assertIsNone(
         types.Array(element_template=types.String()).
         attribute_rewrite_reverse_map())
コード例 #9
0
def adapt_persistent_collection(persistent_collection,
                                target_rest_class=None,
                                attribute_filter=None):
    # ensure that collection is iterable and has at least one element
    persistent_collection_length = 0

    # attempt to detect the length of the persistent_collection
    if persistent_collection and isinstance(persistent_collection,
                                            (list, tuple)):
        persistent_collection_length = len(persistent_collection)
    # SQLAlchemy query
    elif persistent_collection and persistent_collection.__module__ == "sqlalchemy.orm.query":
        persistent_collection_length = persistent_collection.count()
    # Google App Engine NDB
    elif persistent_collection and persistent_collection.__module__ == "google.appengine.ext.ndb":
        persistent_collection_length = persistent_collection.count()

    # if the persistent_collection is empty then return a blank array
    if persistent_collection_length == 0:
        return types.Array(element_template=target_rest_class())

    # try and get the adapter and the REST class for the persistent object
    if target_rest_class is None:
        adapter_instance = registry.get_adapter_for_persistent_model(
            persistent_collection[0])
    else:
        if inspect.isclass(target_rest_class):
            target_rest_class = target_rest_class()

        adapter_instance = registry.get_adapter_for_persistent_model(
            persistent_collection[0], target_rest_class)

    # would raise an exception if the attribute_filter differs from the target_rest_class
    if attribute_filter is not None and isinstance(attribute_filter,
                                                   parser.AttributeFilter):
        parser.AttributeFilter.from_model(
            target_rest_class).conforms_to_template_filter(attribute_filter)

    # convert filter to immutable if it isn't already
    if isinstance(attribute_filter, parser.AttributeFilter):
        attribute_filter = attribute_filter.as_immutable()

    adapted_models = types.Array(
        element_template=adapter_instance.rest_model_class())

    for persistent_object in persistent_collection:
        adapted_models.append(
            adapter_instance.adapt_persistent_to_rest(persistent_object,
                                                      attribute_filter))

    return adapted_models
コード例 #10
0
 def test_custom(self):
     self.assertEqual(
         types.Array(element_template=types.Boolean(),
                     max_length=1).max_length, 1)
     self.assertEqual(
         types.Array(element_template=types.Float(),
                     max_length=2).max_length, 2)
     self.assertEqual(
         types.Array(element_template=types.Integer(),
                     max_length=3).max_length, 3)
     self.assertEqual(
         types.Array(element_template=types.String(),
                     max_length=4).max_length, 4)
     self.assertEqual(
         types.Array(element_template=types.Date(),
                     max_length=5).max_length, 5)
     self.assertEqual(
         types.Array(element_template=types.DateTime(),
                     max_length=6).max_length, 6)
     self.assertEqual(
         types.Array(element_template=types.Time(),
                     max_length=7).max_length, 7)
     self.assertEqual(
         types.Array(element_template=types.Model(),
                     max_length=8).max_length, 8)
コード例 #11
0
    def test_data_structure(self):
        date_array = types.Array(element_template=types.Date())
        self.assertFalse(date_array.get_attribute_filter())
        self.assertFalse(date_array.get_attribute_filter(False))
        self.assertTrue(date_array.get_attribute_filter(True))

        datetime_array = types.Array(element_template=types.DateTime())
        self.assertFalse(datetime_array.get_attribute_filter())
        self.assertFalse(datetime_array.get_attribute_filter(False))
        self.assertTrue(datetime_array.get_attribute_filter(True))

        time_array = types.Array(element_template=types.Time())
        self.assertFalse(time_array.get_attribute_filter())
        self.assertFalse(time_array.get_attribute_filter(False))
        self.assertTrue(time_array.get_attribute_filter(True))
コード例 #12
0
    def test_add_attribute_string(self):
        base = Base(template_engine=None,
                    models_definition="models.py",
                    namespace="namespace.models",
                    output_directory="namespace/models")
        self.assertEqual(base.attribute_string, "")

        string_blueprint = types.String().blueprint()
        string_blueprint["map_name"] = "a"

        base.add_attribute_string(AttributeMetaData("string",
                                                    string_blueprint))
        self.assertEqual(base.attribute_string, "this.string_")

        class MyModel(types.Model):
            field = types.String()

        model_blueprint = MyModel().blueprint()
        model_blueprint["map_name"] = "b"

        base.add_attribute_string(AttributeMetaData("model", model_blueprint))
        self.assertEqual(base.attribute_string,
                         "this.string_ || this.model_.anyFieldsEnabled()")

        array_blueprint = types.Array(element_template=MyModel()).blueprint()
        array_blueprint["map_name"] = "c"

        base.add_attribute_string(AttributeMetaData("array", array_blueprint))
        self.assertEqual(
            base.attribute_string,
            "this.string_ || this.model_.anyFieldsEnabled() || this.array_.anyFieldsEnabled()"
        )
コード例 #13
0
    def test_sub_model(self):
        class MyModel(types.Model):
            name = types.String()

        class ParentModel(types.Model):
            name = types.String()
            sub_model = MyModel()

        array_sub_model = types.Array(element_template=ParentModel())

        model_a = ParentModel(name="alice", sub_model={"name": "bob"})
        model_a.name = "alice"
        model_a.sub_model.name = "bob"
        array_sub_model.append(model_a)

        model_b = ParentModel(name="alice", sub_model={"name": "bob"})
        model_b.name = "bob"
        model_b.sub_model.name = "carol"
        array_sub_model.append(model_b)

        self.assertEqual(array_sub_model.as_serializable(), [{
            "name": "alice",
            "sub_model": {
                "name": "bob"
            }
        }, {
            "name": "bob",
            "sub_model": {
                "name": "carol"
            }
        }])
コード例 #14
0
    def test_add_model_dependency(self):
        base = Base(template_engine=None,
                    models_definition="models.py",
                    namespace="namespace.models",
                    output_directory="namespace/models")
        self.assertEqual(base._dependencies, [])

        class User(types.Model):
            first_name = types.String()

        model_blueprint = User().blueprint()
        model_blueprint["map_name"] = "a"

        base.add_model_dependency(AttributeMetaData("user", model_blueprint))
        self.assertEqual(base._dependencies, ["namespace.models.User"])

        string_blueprint = types.String().blueprint()
        string_blueprint["map_name"] = "a_b"

        base.add_model_dependency(
            AttributeMetaData("first_name", string_blueprint))
        self.assertEqual(base._dependencies,
                         ["namespace.models.User", "prestans.types.String"])

        array_basic = types.Array(element_template=types.String()).blueprint()
        array_basic["map_name"] = "c"

        base.add_model_dependency(AttributeMetaData("tags", array_basic))
        self.assertEqual(base._dependencies,
                         ["namespace.models.User", "prestans.types.String"])

        array_model = types.Array(element_template=User()).blueprint()
        array_model["map_name"] = "d"

        base.add_model_dependency(AttributeMetaData("users", array_model))
        self.assertEqual(base._dependencies,
                         ["namespace.models.User", "prestans.types.String"])

        integer_blueprint = types.Integer().blueprint()
        integer_blueprint["map_name"] = "e"

        base.add_model_dependency(
            AttributeMetaData("numbers", integer_blueprint))
        self.assertEqual(base._dependencies, [
            "namespace.models.User", "prestans.types.String",
            "prestans.types.Integer"
        ])
コード例 #15
0
    def test_len(self):
        array = types.Array(element_template=types.Integer())

        self.assertEqual(len(array), 0)
        array.append(1)
        self.assertEqual(len(array), 1)
        array.append(2)
        self.assertEqual(len(array), 2)
コード例 #16
0
    def test_data_collection(self):
        class MyModel(types.Model):
            cat = types.String()
            dog = types.String()

        array = types.Array(element_template=MyModel())
        self.assertEqual(array.attribute_rewrite_reverse_map(),
                         MyModel().attribute_rewrite_reverse_map())
コード例 #17
0
    def test_custom(self):
        boolean_array = types.Array(element_template=types.Boolean(),
                                    description="boolean")
        self.assertEqual(boolean_array.description, "boolean")

        float_array = types.Array(element_template=types.Float(),
                                  description="float")
        self.assertEqual(float_array.description, "float")

        integer_array = types.Array(element_template=types.Integer(),
                                    description="integer")
        self.assertEqual(integer_array.description, "integer")

        string_array = types.Array(element_template=types.String(),
                                   description="string")
        self.assertEqual(string_array.description, "string")

        date_array = types.Array(element_template=types.Date(),
                                 description="date")
        self.assertEqual(date_array.description, "date")

        datetime_array = types.Array(element_template=types.DateTime(),
                                     description="datetime")
        self.assertEqual(datetime_array.description, "datetime")

        time_array = types.Array(element_template=types.Date(),
                                 description="time")
        self.assertEqual(time_array.description, "time")
コード例 #18
0
 def test_remove(self):
     array = types.Array(element_template=types.String())
     array.append("dog")
     array.append("cat")
     self.assertEqual(len(array), 2)
     array.remove("dog")
     self.assertEqual(len(array), 1)
     array.remove("cat")
     self.assertEqual(len(array), 0)
コード例 #19
0
    def test_element_template(self):
        float_element_template = types.Float()
        string_element_template = types.String()

        self.assertRaises(TypeError, types.Array, element_template="string")

        array = types.Array(element_template=float_element_template)
        self.assertEqual(array.element_template, float_element_template)
        array.element_template = string_element_template
        self.assertEqual(array.element_template, string_element_template)
コード例 #20
0
    def test_data_type(self):
        boolean_array = types.Array(element_template=types.Boolean())
        self.assertFalse(boolean_array.get_attribute_filter())
        self.assertFalse(boolean_array.get_attribute_filter(False))
        self.assertTrue(boolean_array.get_attribute_filter(True))

        float_array = types.Array(element_template=types.Float())
        self.assertFalse(float_array.get_attribute_filter())
        self.assertFalse(float_array.get_attribute_filter(False))
        self.assertTrue(float_array.get_attribute_filter(True))

        integer_array = types.Array(element_template=types.Integer())
        self.assertFalse(integer_array.get_attribute_filter())
        self.assertFalse(integer_array.get_attribute_filter(False))
        self.assertTrue(integer_array.get_attribute_filter(True))

        string_array = types.Array(element_template=types.String())
        self.assertFalse(string_array.get_attribute_filter())
        self.assertFalse(string_array.get_attribute_filter(False))
        self.assertTrue(string_array.get_attribute_filter(True))
コード例 #21
0
    def test_append_data_type(self):
        array = types.Array(element_template=types.String())
        self.assertEqual(len(array), 0)

        array.append("dog")
        self.assertEqual(len(array), 1)
        self.assertTrue("dog" in array)

        array.append(["cat", "rat"])
        self.assertEqual(len(array), 3)
        self.assertTrue("cat" in array)
        self.assertTrue("rat" in array)
コード例 #22
0
    def test_iter(self):
        elements = ["a", "b", "c"]

        array = types.Array(element_template=types.String())
        array.append(elements[0])
        array.append(elements[1])
        array.append(elements[2])

        index = 0
        for element in array:
            self.assertEqual(element, elements[index])
            index += 1
コード例 #23
0
    def test_append_model(self):
        class MyModel(types.Model):
            name = types.String()

        array = types.Array(element_template=MyModel())
        self.assertEqual(len(array), 0)

        self.assertRaises(TypeError, array.append, "string")
        self.assertEqual(len(array), 0)

        my_model = MyModel(name="alice")
        validated = array.validate([my_model.as_serializable()])
        self.assertEqual(validated.as_serializable(), [{"name": "alice"}])
コード例 #24
0
 def test_default(self):
     self.assertIsNone(
         types.Array(element_template=types.Boolean()).min_length)
     self.assertIsNone(
         types.Array(element_template=types.Float()).min_length)
     self.assertIsNone(
         types.Array(element_template=types.Integer()).min_length)
     self.assertIsNone(
         types.Array(element_template=types.String()).min_length)
     self.assertIsNone(
         types.Array(element_template=types.Date()).min_length)
     self.assertIsNone(
         types.Array(element_template=types.DateTime()).min_length)
     self.assertIsNone(
         types.Array(element_template=types.Time()).min_length)
     self.assertIsNone(
         types.Array(element_template=types.Model()).min_length)
コード例 #25
0
    def test_data_collection(self):
        class MyModel(types.Model):
            name = types.String()

        array_model = types.Array(element_template=MyModel())
        array_model.append(MyModel(name="alice"))
        array_model.append(MyModel(name="bob"))
        array_model.append(MyModel(name="carol"))

        self.assertEqual(array_model.as_serializable(), [{
            "name": "alice"
        }, {
            "name": "bob"
        }, {
            "name": "carol"
        }])
コード例 #26
0
    def test_from_model(self):

        # check that non data collection raises exception
        self.assertRaises(TypeError,
                          AttributeFilter.from_model,
                          model_instance="string")

        # check that array scalar returns filter todo: work out how to further test this
        array_scalar = AttributeFilter.from_model(
            types.Array(element_template=types.String()))
        self.assertTrue(isinstance(array_scalar, AttributeFilter))

        # check that a model is constructed correctly and default values work
        class MyModel(types.Model):
            name = types.String()
            age = types.Integer()
            tags = types.Array(element_template=types.String())

        default = AttributeFilter.from_model(model_instance=MyModel())
        self.assertFalse(default.name)
        self.assertFalse(default.age)
        self.assertFalse(default.tags)

        default_false = AttributeFilter.from_model(model_instance=MyModel(),
                                                   default_value=False)
        self.assertFalse(default_false.name)
        self.assertFalse(default_false.age)
        self.assertFalse(default_false.tags)

        default_true = AttributeFilter.from_model(model_instance=MyModel(),
                                                  default_value=True)
        self.assertTrue(default_true.name)
        self.assertTrue(default_true.age)
        self.assertTrue(default_true.tags)

        # check keyword args
        keyword_args = AttributeFilter.from_model(model_instance=MyModel(),
                                                  age=True)
        self.assertFalse(keyword_args.name)
        self.assertTrue(keyword_args.age)
        self.assertFalse(keyword_args.tags)

        self.assertRaises(KeyError,
                          AttributeFilter.from_model,
                          model_instance=MyModel(),
                          missing=True)
コード例 #27
0
    def test_sub_array_data_type(self):
        class MyModel(types.Model):
            name = types.String()
            tags = types.Array(element_template=types.String())

        my_model = MyModel()
        my_model.name = "alice"
        my_model.tags = ["a", "b", "c"]

        array_sub_array = types.Array(element_template=MyModel())
        array_sub_array.append(my_model)

        self.assertEqual(array_sub_array.as_serializable(),
                         [{
                             "name": "alice",
                             "tags": ["a", "b", "c"]
                         }])
コード例 #28
0
    def test_array_basic_type(self):
        array = types.Array(element_template=types.String(default="default"))

        blueprint = array.blueprint()
        blueprint["map_name"] = "b_a"
        array_meta = AttributeMetaData("user_tags", blueprint)
        self.assertEqual(array_meta.name, "user_tags")
        self.assertEqual(array_meta.map_name, "b_a")
        self.assertEqual(array_meta.cc, "UserTags")
        self.assertEqual(array_meta.ccif, "userTags")
        self.assertEqual(array_meta.blueprint_type, "array")
        self.assertEqual(array_meta.client_class_name, "Array")
        self.assertEqual(array_meta.required, "true")
        self.assertEqual(array_meta.min_length, "null")
        self.assertEqual(array_meta.max_length, "null")
        self.assertFalse(array_meta.element_template_is_model)
        self.assertEqual(array_meta.element_template.blueprint_type, "string")
        self.assertEqual(array_meta.element_template.default, "\"default\"")
コード例 #29
0
    def test_data_collection(self):
        class MyModel(types.Model):
            cat = types.String()

        cat = MyModel()
        cat.cat = "cat"

        array = types.Array(element_template=MyModel())
        array.append(cat)
        attribute_filter = array.get_attribute_filter()
        self.assertTrue("cat" in attribute_filter)
        self.assertFalse("dog" in attribute_filter)
        self.assertFalse(attribute_filter.cat)

        attribute_filter = array.get_attribute_filter(True)
        self.assertTrue("cat" in attribute_filter)
        self.assertFalse("dog" in attribute_filter)
        self.assertTrue(attribute_filter.cat)
コード例 #30
0
    def test_validate_minified(self):
        class Person(types.Model):
            first_name = types.String()
            last_name = types.String()

        persons = types.Array(element_template=Person())
        persons.append(Person(first_name="John", last_name="Smith"))

        persons_validated = persons.validate(
            persons.as_serializable(minified=True), minified=True)
        self.assertEqual(persons_validated.as_serializable(minified=True),
                         [{
                             "a_c": "John",
                             "b_c": "Smith"
                         }])
        self.assertEqual(persons_validated.as_serializable(),
                         [{
                             "first_name": "John",
                             "last_name": "Smith"
                         }])