Example #1
0
def test_int():
    with pytest.raises(ConversionError):
        IntType().validate('foo')

    assert IntType.validate(5001) == None
Example #2
0
class Comanda(Model):
    cliente_id = IntType(required=True)
    inicio = TimestampType(required=True)
    fim = TimestampType(serialize_when_none=True)
    data_comanda = DateTimeType(required=True)
Example #3
0
class ExBestOffersOverrides(BetfairModel):
    best_prices_depth = IntType()
    rollup_model = EnumType(constants.RollupModel)
    rollup_limit = IntType()
    rollup_liability_threshold = FloatType()
    rollup_liability_factor = IntType()
class UserContribution(Model):
    """ User contribution for a project """
    username = StringType()
    mapped = IntType()
    validated = IntType()
class Card(Model):
    name = StringType()
    price = IntType()
class ProjectStatsDTO(Model):
    """ DTO for detailed stats on a project """

    project_id = IntType(required=True, serialized_name="projectId")
    area = FloatType(serialized_name="projectArea(in sq.km)")
    total_mappers = IntType(serialized_name="totalMappers")
    total_tasks = IntType(serialized_name="totalTasks")
    total_comments = IntType(serialized_name="totalComments")
    total_mapping_time = IntType(serialized_name="totalMappingTime")
    total_validation_time = IntType(serialized_name="totalValidationTime")
    total_time_spent = IntType(serialized_name="totalTimeSpent")
    average_mapping_time = IntType(serialized_name="averageMappingTime")
    average_validation_time = IntType(serialized_name="averageValidationTime")
    percent_mapped = IntType(serialized_name="percentMapped")
    percent_validated = IntType(serialized_name="percentValidated")
    percent_bad_imagery = IntType(serialized_name="percentBadImagery")
    aoi_centroid = BaseType(serialized_name="aoiCentroid")
Example #7
0
class UserOSMDTO(Model):
    """ DTO containing OSM details for the user """
    account_created = StringType(required=True,
                                 serialized_name='accountCreated')
    changeset_count = IntType(required=True, serialized_name='changesetCount')
Example #8
0
class PostSerializer(Model):
    id = IntType()
    title = StringType()
Example #9
0
def player_schema():
    schema = Schema('Player', Field('id', IntType()),
                    Field('first_name', StringType(required=True)),
                    Field('last_name', StringType(required=True)))
    return schema
class CampaignOrganisationDTO(Model):
    """ DTO used to define avaliable campaign connnected projects"""

    organisation_id = IntType()
    campaign_id = IntType()
Example #11
0
class PersonSerializer(Model):
    id = IntType()
    name = StringType()
class CampaignProjectDTO(Model):
    """ DTO used to define avaliable campaign connnected projects"""

    project_id = IntType()
    campaign_id = IntType()
Example #13
0
class CFASelectionUATender(BaseTender):
    """Data regarding tender process - publicly inviting prospective contractors
    to submit bids for evaluation and selecting a winner or winners.
    """
    class Options:
        namespace = "Tender"
        _core_roles = BaseTender.Options.roles
        _not_implemented = whitelist("mainProcurementCategory", "milestones")
        _base_edit = (_core_roles["edit"] - _not_implemented + whitelist(
            "procuringEntity",
            "numberOfBidders",
            "serializable_guarantee",
            "items",
            "next_check",
            "tender_guarantee",
            "numberOfBids",
            "agreements",
            "hasEnquiries",
        ))
        _edit_role = _base_edit + whitelist(
            "enquiryPeriod", "tender_minimalStep", "contracts", "tenderPeriod",
            "features", "serializable_minimalStep")
        _draft_view_role = (_core_roles["view"] - _not_implemented + whitelist(
            "tender_guarantee",
            "awardPeriod",
            "auctionUrl",
            "auctionPeriod",
            "next_check",
            "procuringEntity",
            "questions",
            "complaints",
            "lots",
            "items",
            "cancellations",
            "contracts",
            "agreements",
            "numberOfBidders",
            "awards",
            "serializable_guarantee",
            "hasEnquiries",
        ))
        _view_tendering_role = _draft_view_role + whitelist(
            "tender_value",
            "tenderPeriod",
            "features",
            "enquiryPeriod",
            "tender_minimalStep",
            "serializable_value",
            "serializable_minimalStep",
        )
        _view_role = _view_tendering_role + whitelist("bids", "numberOfBids")
        _procurement_method_details = whitelist("procurementMethodDetails")
        roles = {
            "create":
            _base_edit + whitelist("lots", "procurementMethodType", "mode"),
            "edit_draft":
            _core_roles["edit_draft"] + _procurement_method_details,
            "edit_draft.pending":
            whitelist("agreements", "unsuccessfulReason") +
            _procurement_method_details,
            "edit_cancelled":
            _procurement_method_details,
            "edit_complete":
            _procurement_method_details,
            "edit_unsuccessful":
            _procurement_method_details,
            "edit_active.awarded":
            _procurement_method_details,
            "edit_active.auction":
            _procurement_method_details,
            "edit_active.tendering":
            _procurement_method_details,
            "edit_active.qualification":
            _procurement_method_details,
            "edit_active.enquiries":
            whitelist(
                "description",
                "description_en",
                "description_ru",
                "documents",
                "items",
                "lots",
                "procurementMethodDetails",
                "serializable_guarantee",
                "tenderPeriod",
                "tender_guarantee",
                "title",
                "title_en",
                "title_ru",
            ),
            "edit":
            _edit_role,
            "edit_agreement_selection":
            whitelist("agreements", "procurementMethodDetails", "status"),
            "active.tendering":
            _view_tendering_role,
            "active.enquiries":
            _view_tendering_role,
            "active.auction":
            _view_tendering_role,
            "draft":
            _draft_view_role,
            "draft.pending":
            _draft_view_role + whitelist("features"),
            "draft.unsuccessful":
            _draft_view_role + whitelist("features", "unsuccessfulReason"),
            "active.awarded":
            _view_role,
            "unsuccessful":
            _view_role,
            "cancelled":
            _view_role,
            "view":
            _view_role,
            "active.qualification":
            _view_role,
            "complete":
            _view_role,
            "chronograph":
            _core_roles["chronograph"] + _procurement_method_details,
            "chronograph_view":
            _core_roles["chronograph_view"] + whitelist("agreements") +
            _procurement_method_details,
            "Administrator":
            _core_roles["Administrator"] + _procurement_method_details,
            "contracting":
            _core_roles["contracting"] + _procurement_method_details,
            "auction_post":
            _core_roles["auction_post"] + _procurement_method_details,
            "auction_patch":
            _core_roles["auction_patch"] + _procurement_method_details,
            "auction_view":
            _core_roles["auction_view"] - whitelist("minimalStep") +
            whitelist("serializable_minimalStep") +
            _procurement_method_details,
            "listing":
            _core_roles["listing"] + _procurement_method_details,
            "embedded":
            _core_roles["embedded"],
            "plain":
            _core_roles["plain"],
            "default":
            _core_roles["default"],
        }

    items = ListType(
        ModelType(Item, required=True),
        min_size=1,
        validators=[validate_items_uniq]
    )  # The goods and services to be purchased, broken into line items wherever possible. Items should not be duplicated, but a quantity of 2 specified instead.
    value = ModelType(Value)  # The total estimated value of the procurement.
    enquiryPeriod = ModelType(
        PeriodEndRequired, required=False
    )  # The period during which enquiries may be made and will be answered.
    tenderPeriod = ModelType(
        PeriodEndRequired, required=False
    )  # The period when the tender is open for submissions. The end date is the closing date for tender submissions.
    hasEnquiries = BooleanType(
    )  # A Yes/No field as to whether enquiries were part of tender process.
    awardPeriod = ModelType(
        Period
    )  # The date or period on which an award is anticipated to be made.
    numberOfBidders = IntType(
    )  # The number of unique tenderers who participated in the tender
    bids = ListType(ModelType(Bid, required=True), default=list(
    ))  # A list of all the companies who entered submissions for the tender.
    procuringEntity = ModelType(
        ProcuringEntity, required=True
    )  # The entity managing the procurement, which may be different from the buyer who is paying / using the items being procured.
    awards = ListType(ModelType(Award, required=True), default=list())
    contracts = ListType(ModelType(Contract, required=True), default=list())
    auctionPeriod = ModelType(TenderAuctionPeriod, default={})
    minimalStep = ModelType(Value, required=False)
    auctionUrl = URLType()
    cancellations = ListType(ModelType(Cancellation, required=True),
                             default=list())
    features = ListType(ModelType(Feature, required=True),
                        validators=[validate_features_uniq])
    lots = ListType(ModelType(Lot, required=True),
                    default=list(),
                    validators=[validate_lots_uniq],
                    min_size=1,
                    max_size=1)
    guarantee = ModelType(Guarantee)
    status = StringType(
        choices=[
            "draft",
            "draft.pending",
            "draft.unsuccessful",
            "active.enquiries",
            "active.tendering",
            "active.auction",
            "active.qualification",
            "active.awarded",
            "complete",
            "cancelled",
            "unsuccessful",
        ],
        default="draft",
    )  # TODO Refactoring status
    agreements = ListType(ModelType(Agreement, required=True),
                          default=list(),
                          min_size=1,
                          max_size=1)

    procurementMethod = StringType(choices=["open", "selective", "limited"],
                                   default="selective")
    procurementMethodType = StringType(
        default="closeFrameworkAgreementSelectionUA")
    unsuccessfulReason = ListType(StringType, serialize_when_none=False)
    procuring_entity_kinds = [
        "general", "special", "defense", "central", "other"
    ]

    def get_role(self):
        root = self.__parent__
        request = root.request
        if request.authenticated_role == "Administrator":
            role = "Administrator"
        elif request.authenticated_role == "chronograph":
            role = "chronograph"
        elif request.authenticated_role == "auction":
            role = "auction_{}".format(request.method.lower())
        elif request.authenticated_role == "contracting":
            role = "contracting"
        elif request.authenticated_role == "agreement_selection":
            role = "edit_{}".format(request.authenticated_role)
        else:
            role = "edit_{}".format(request.context.status)
        return role

    def __acl__(self):
        acl = [(Allow, "{}_{}".format(i.owner,
                                      i.owner_token), "create_award_complaint")
               for i in self.bids]
        acl.extend([
            (Allow, "{}_{}".format(self.owner,
                                   self.owner_token), "edit_tender"),
            (Allow, "{}_{}".format(self.owner, self.owner_token),
             "upload_tender_documents"),
            (Allow, "{}_{}".format(self.owner,
                                   self.owner_token), "edit_complaint"),
            (Allow, "g:agreement_selection", "edit_agreement_selection"),
            (Allow, "g:agreement_selection", "edit_tender"),
        ])
        return acl

    def __local_roles__(self):
        roles = dict([("{}_{}".format(self.owner,
                                      self.owner_token), "tender_owner")])
        for i in self.bids:
            roles["{}_{}".format(i.owner, i.owner_token)] = "bid_owner"
        return roles

    # Non-required mainProcurementCategory
    def validate_mainProcurementCategory(self, data, value):
        pass

    # Not required milestones
    def validate_milestones(self, data, value):
        pass
Example #14
0
class RunnerCatalog(BetfairModel):
    selection_id = IntType(required=True)
    runner_name = StringType(required=True)
    handicap = FloatType(required=True)
    sort_priority = IntType(required=True)
    metadata = DictType(StringType)
Example #15
0
class VenueResult(BetfairModel):
    venue = StringType()
    market_count = IntType()
Example #16
0
class Connection(Model):
    host = StringType(
        default="",
        required=True,
    )
    port = IntType(
        min_value=1000,
        max_value=65000,
        default=None,
        required=False,
    )
    allowed_hosts = ListType(
        field=StringType,
        min_size=0,
        required=True,
        min_length=1,
    )

    @classmethod
    def from_ini(cls, ini):
        port = field_from_ini(
            cls.port,
            ini,
            'DeviceLink',
            'port',
        )
        port = (None if port == FORBID_DEVICE_LINK_CONNECTIONS_FLAG else port)

        return cls({
            'host':
            field_from_ini(
                cls.host,
                ini,
                'DeviceLink',
                'host',
            ),
            'port':
            port,
            'allowed_hosts': (field_from_ini(
                cls.allowed_hosts,
                ini,
                'DeviceLink',
                'IPS',
                default="",
            ).split()),
        })

    def to_ini(self, ini):
        port = (FORBID_DEVICE_LINK_CONNECTIONS_FLAG
                if self.port is None else self.port)
        allowed_hosts = ' '.join(self.allowed_hosts)

        field_to_ini(port, ini, 'DeviceLink', 'port')
        field_to_ini(self.host, ini, 'DeviceLink', 'host')
        field_to_ini(allowed_hosts, ini, 'DeviceLink', 'IPS')

    @classmethod
    def default(cls):
        return cls({
            'host': cls.host.default,
            'port': cls.port.default,
            'allowed_hosts': [],
        })
class ProjectSummary(Model):
    """ Model used for PM dashboard """

    project_id = IntType(required=True, serialized_name="projectId")
    area = FloatType(serialized_name="projectArea(in sq.km)")
    author = StringType()
    created = UTCDateTimeType()
    due_date = UTCDateTimeType(serialized_name="dueDate")
    last_updated = UTCDateTimeType(serialized_name="lastUpdated")
    priority = StringType(serialized_name="projectPriority")
    campaigns = ListType(ModelType(CampaignDTO), default=[])
    organisation_name = StringType(serialized_name="organisationName")
    organisation_logo = StringType(serialized_name="organisationLogo")
    country_tag = ListType(StringType, serialized_name="countryTag")
    osmcha_filter_id = StringType(serialized_name="osmchaFilterId")
    entities_to_map = StringType(serialized_name="entitiesToMap")
    mapping_types = ListType(
        StringType, serialized_name="mappingTypes", validators=[is_known_mapping_type]
    )

    changeset_comment = StringType(serialized_name="changesetComment")
    percent_mapped = IntType(serialized_name="percentMapped")
    percent_validated = IntType(serialized_name="percentValidated")
    percent_bad_imagery = IntType(serialized_name="percentBadImagery")
    aoi_centroid = BaseType(serialized_name="aoiCentroid")
    mapper_level = StringType(serialized_name="mapperLevel")
    mapping_permission = IntType(
        serialized_name="mappingPermission", validators=[is_known_mapping_permission]
    )
    validation_permission = IntType(
        serialized_name="validationPermission",
        validators=[is_known_validation_permission],
    )
    random_task_selection_enforced = BooleanType(
        required=False, default=False, serialized_name="enforceRandomTaskSelection"
    )
    private = BooleanType(serialized_name="private")
    allowed_users = ListType(StringType, serialized_name="allowedUsernames", default=[])
    project_teams = ListType(ModelType(ProjectTeamDTO), serialized_name="teams")
    project_info = ModelType(
        ProjectInfoDTO, serialized_name="projectInfo", serialize_when_none=False
    )
    short_description = StringType(serialized_name="shortDescription")
    status = StringType()
    imagery = StringType()
    mapping_editors = ListType(
        StringType,
        min_size=1,
        required=True,
        serialized_name="mappingEditors",
        validators=[is_known_editor],
    )
    validation_editors = ListType(
        StringType,
        min_size=1,
        required=True,
        serialized_name="validationEditors",
        validators=[is_known_editor],
    )
    custom_editor = ModelType(
        CustomEditorDTO, serialized_name="customEditor", serialize_when_none=False
    )
class ZMessage(Model):
    author_id = IntType(required=True)
    created_at = DateTimeType(formats='%Y-%m-%dT%H:%M:%SZ', required=True)
    uploads = ListType(StringType, default=list)  # list of upload tokens
    public = BooleanType(required=True)
class ProjectUserStatsDTO(Model):
    """ DTO for time spent by users on a project """

    time_spent_mapping = IntType(serialized_name="timeSpentMapping")
    time_spent_validating = IntType(serialized_name="timeSpentValidating")
    total_time_spent = IntType(serialized_name="totalTimeSpent")
class ZTicketUpdate(Model):
    id = IntType(required=True)
    # API for updating requires single comment
    comment = ModelType(ZMessageUpdate, required=True)
class LockTaskDTO(Model):
    """ DTO used to lock a task for mapping """
    user_id = IntType(required=True)
    task_id = IntType(required=True)
    project_id = IntType(required=True)
    preferred_locale = StringType(default='en')
class ProjectDTO(Model):
    """ Describes JSON model for a tasking manager project """

    project_id = IntType(serialized_name="projectId")
    project_status = StringType(
        required=True,
        serialized_name="status",
        validators=[is_known_project_status],
        serialize_when_none=False,
    )
    project_priority = StringType(
        required=True,
        serialized_name="projectPriority",
        validators=[is_known_project_priority],
        serialize_when_none=False,
    )
    area_of_interest = BaseType(serialized_name="areaOfInterest")
    aoi_bbox = ListType(FloatType, serialized_name="aoiBBOX")
    tasks = BaseType(serialize_when_none=False)
    default_locale = StringType(
        required=True, serialized_name="defaultLocale", serialize_when_none=False
    )
    project_info = ModelType(
        ProjectInfoDTO, serialized_name="projectInfo", serialize_when_none=False
    )
    project_info_locales = ListType(
        ModelType(ProjectInfoDTO),
        serialized_name="projectInfoLocales",
        serialize_when_none=False,
    )
    mapper_level = StringType(
        required=True,
        serialized_name="mapperLevel",
        validators=[is_known_mapping_level],
    )
    mapping_permission = StringType(
        required=True,
        serialized_name="mappingPermission",
        validators=[is_known_mapping_permission],
    )
    validation_permission = StringType(
        required=True,
        serialized_name="validationPermission",
        validators=[is_known_validation_permission],
    )
    enforce_random_task_selection = BooleanType(
        required=False, default=False, serialized_name="enforceRandomTaskSelection"
    )

    private = BooleanType(required=True)
    entities_to_map = StringType(serialized_name="entitiesToMap")
    changeset_comment = StringType(serialized_name="changesetComment")
    osmcha_filter_id = StringType(serialized_name="osmchaFilterId")
    due_date = UTCDateTimeType(serialized_name="dueDate")
    imagery = StringType()
    josm_preset = StringType(serialized_name="josmPreset", serialize_when_none=False)
    id_presets = ListType(StringType, serialized_name="idPresets", default=[])
    mapping_types = ListType(
        StringType,
        serialized_name="mappingTypes",
        default=[],
        validators=[is_known_mapping_type],
    )
    campaigns = ListType(ModelType(CampaignDTO), default=[])
    organisation = IntType()
    organisation_name = StringType(serialized_name="organisationName")
    organisation_logo = StringType(serialized_name="organisationLogo")
    country_tag = ListType(StringType, serialized_name="countryTag")

    license_id = IntType(serialized_name="licenseId")
    allowed_usernames = ListType(
        StringType(), serialized_name="allowedUsernames", default=[]
    )
    priority_areas = BaseType(serialized_name="priorityAreas")
    created = UTCDateTimeType()
    last_updated = UTCDateTimeType(serialized_name="lastUpdated")
    author = StringType()
    active_mappers = IntType(serialized_name="activeMappers")
    percent_mapped = IntType(serialized_name="percentMapped")
    percent_validated = IntType(serialized_name="percentValidated")
    percent_bad_imagery = IntType(serialized_name="percentBadImagery")
    task_creation_mode = StringType(
        required=True,
        serialized_name="taskCreationMode",
        validators=[is_known_task_creation_mode],
        serialize_when_none=False,
    )
    project_teams = ListType(ModelType(ProjectTeamDTO), serialized_name="teams")
    mapping_editors = ListType(
        StringType,
        min_size=1,
        required=True,
        serialized_name="mappingEditors",
        validators=[is_known_editor],
    )
    validation_editors = ListType(
        StringType,
        min_size=1,
        required=True,
        serialized_name="validationEditors",
        validators=[is_known_editor],
    )
    custom_editor = ModelType(
        CustomEditorDTO, serialized_name="customEditor", serialize_when_none=False
    )
    interests = ListType(ModelType(InterestDTO))
 class CardNameRequired(Model):
     name = StringType(required=True)
     price = IntType()
class ProjectFavoriteDTO(Model):
    """ DTO used to favorite a project """

    project_id = IntType(required=True)
    user_id = IntType(required=True)
class Person(Model):
    age = IntType(required=True, validators=[greater_than_zero])
    bio = StringType(max_length=5)
class ProjectSearchDTO(Model):
    """ Describes the criteria users use to filter active projects"""

    preferred_locale = StringType(default="en")
    mapper_level = StringType(validators=[is_known_mapping_level])
    mapping_types = ListType(StringType, validators=[is_known_mapping_type])
    project_statuses = ListType(StringType, validators=[is_known_project_status])
    organisation_name = StringType()
    organisation_id = IntType()
    team_id = IntType()
    campaign = StringType()
    order_by = StringType(choices=ORDER_BY_OPTIONS)
    order_by_type = StringType(choices=("ASC", "DESC"))
    country = StringType()
    page = IntType(required=True)
    text_search = StringType()
    mapping_editors = ListType(StringType, validators=[is_known_editor])
    validation_editors = ListType(StringType, validators=[is_known_editor])
    teams = ListType(StringType())
    interests = ListType(IntType())
    created_by = IntType(required=False)
    mapped_by = IntType(required=False)
    favorited_by = IntType(required=False)
    managed_by = IntType(required=False)

    def __hash__(self):
        """ Make object hashable so we can cache user searches"""
        hashable_mapping_types = ""
        if self.mapping_types:
            for mapping_type in self.mapping_types:
                hashable_mapping_types += mapping_type
        hashable_project_statuses = ""
        if self.project_statuses:
            for project_status in self.project_statuses:
                hashable_project_statuses += project_status
        hashable_teams = ""
        if self.teams:
            for team in self.teams:
                hashable_teams += team
        hashable_mapping_editors = ""
        if self.mapping_editors:
            for mapping_editor in self.mapping_editors:
                hashable_mapping_editors = hashable_mapping_editors + mapping_editor
        hashable_validation_editors = ""
        if self.validation_editors:
            for validation_editor in self.validation_editors:
                hashable_validation_editors = (
                    hashable_validation_editors + validation_editor
                )

        return hash(
            (
                self.preferred_locale,
                self.mapper_level,
                hashable_mapping_types,
                hashable_project_statuses,
                hashable_teams,
                self.organisation_name,
                self.campaign,
                self.page,
                self.text_search,
                hashable_mapping_editors,
                hashable_validation_editors,
                self.created_by,
            )
        )
Example #27
0
class RunnerProfitAndLoss(BetfairModel):
    selection_id = IntType()
    if_win = FloatType()
    if_lose = FloatType()
class ProjectSearchBBoxDTO(Model):
    bbox = ListType(FloatType, required=True, min_size=4, max_size=4)
    input_srid = IntType(required=True, choices=[4326])
    preferred_locale = StringType(required=True, default="en")
    project_author = IntType(required=False, serialized_name="projectAuthor")
Example #29
0
class CompetitionResult(BetfairModel):
    competition = ModelType(Competition)
    market_count = IntType()
    competition_region = StringType()
class LockedTasksForUser(Model):
    """ Describes all tasks locked by an individual user"""

    locked_tasks = ListType(IntType, serialized_name="lockedTasks")
    project = IntType(serialized_name="projectId")
    task_status = StringType(serialized_name="taskStatus")
 def test_number_range_validation(self):
     int_type = IntType(min_value=1, max_value=2)
     with self.assertRaises(ValidationError):
         int_type.validate(0)
     with self.assertRaises(ValidationError):
         int_type.validate(3)
Example #32
0
class TimeRangeResult(BetfairModel):

    time_range = ModelType(TimeRange)
    market_count = IntType()