How to use the moto.core.BaseModel function in moto

To help you get started, we’ve selected a few moto examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github spulec / moto / moto / ecs / models.py View on Github external
import uuid
from datetime import datetime
from random import random, randint
import boto3

import pytz
from moto.core.exceptions import JsonRESTError
from moto.core import BaseBackend, BaseModel
from moto.core.utils import unix_time
from moto.ec2 import ec2_backends
from copy import copy

from .exceptions import ServiceNotFoundException, TaskDefinitionNotFoundException


class BaseObject(BaseModel):
    def camelCase(self, key):
        words = []
        for i, word in enumerate(key.split("_")):
            if i > 0:
                words.append(word.title())
            else:
                words.append(word)
        return "".join(words)

    def gen_response_object(self):
        response_object = copy(self.__dict__)
        for key, value in self.__dict__.items():
            if "_" in key:
                response_object[self.camelCase(key)] = value
                del response_object[key]
        return response_object
github spulec / moto / moto / ses / models.py View on Github external
elif msg_type == SESFeedback.DELIVERY:
            msg["delivery"] = DELIVERY

        return msg


class Message(BaseModel):
    def __init__(self, message_id, source, subject, body, destinations):
        self.id = message_id
        self.source = source
        self.subject = subject
        self.body = body
        self.destinations = destinations


class TemplateMessage(BaseModel):
    def __init__(self, message_id, source, template, template_data, destinations):
        self.id = message_id
        self.source = source
        self.template = template
        self.template_data = template_data
        self.destinations = destinations


class RawMessage(BaseModel):
    def __init__(self, message_id, source, destinations, raw_data):
        self.id = message_id
        self.source = source
        self.destinations = destinations
        self.raw_data = raw_data
github spulec / moto / moto / dynamodb2 / models.py View on Github external
return self.type == "N"

    def is_set(self):
        return self.type == "SS" or self.type == "NS" or self.type == "BS"

    def is_list(self):
        return self.type == "L"

    def is_map(self):
        return self.type == "M"

    def same_type(self, other):
        return self.type == other.type


class Item(BaseModel):
    def __init__(self, hash_key, hash_key_type, range_key, range_key_type, attrs):
        self.hash_key = hash_key
        self.hash_key_type = hash_key_type
        self.range_key = range_key
        self.range_key_type = range_key_type

        self.attrs = {}
        for key, value in attrs.items():
            self.attrs[key] = DynamoType(value)

    def __repr__(self):
        return "Item: {0}".format(self.to_json())

    def to_json(self):
        attributes = {}
        for attribute_key, attribute in self.attrs.items():
github spulec / moto / moto / s3 / models.py View on Github external
def __getstate__(self):
        state = self.__dict__.copy()
        state["value"] = self.value
        del state["_value_buffer"]
        return state

    def __setstate__(self, state):
        self.__dict__.update({k: v for k, v in six.iteritems(state) if k != "value"})

        self._value_buffer = tempfile.SpooledTemporaryFile(
            max_size=self._max_buffer_size
        )
        self.value = state["value"]


class FakeMultipart(BaseModel):
    def __init__(self, key_name, metadata):
        self.key_name = key_name
        self.metadata = metadata
        self.parts = {}
        self.partlist = []  # ordered list of part ID's
        rand_b64 = base64.b64encode(os.urandom(UPLOAD_ID_BYTES))
        self.id = rand_b64.decode("utf-8").replace("=", "").replace("+", "")

    def complete(self, body):
        decode_hex = codecs.getdecoder("hex_codec")
        total = bytearray()
        md5s = bytearray()

        last = None
        count = 0
        for pn, etag in body:
github spulec / moto / moto / glue / models.py View on Github external
raise TableNotFoundException(table_name)

    def get_tables(self, database_name):
        database = self.get_database(database_name)
        return [table for table_name, table in database.tables.items()]

    def delete_table(self, database_name, table_name):
        database = self.get_database(database_name)
        try:
            del database.tables[table_name]
        except KeyError:
            raise TableNotFoundException(table_name)
        return {}


class FakeDatabase(BaseModel):
    def __init__(self, database_name):
        self.name = database_name
        self.tables = OrderedDict()


class FakeTable(BaseModel):
    def __init__(self, database_name, table_name, table_input):
        self.database_name = database_name
        self.name = table_name
        self.partitions = OrderedDict()
        self.versions = []
        self.update(table_input)

    def update(self, table_input):
        self.versions.append(table_input)
github spulec / moto / moto / rds2 / models.py View on Github external
from moto.ec2.models import ec2_backends
from .exceptions import (
    RDSClientError,
    DBInstanceNotFoundError,
    DBSnapshotNotFoundError,
    DBSecurityGroupNotFoundError,
    DBSubnetGroupNotFoundError,
    DBParameterGroupNotFoundError,
    InvalidDBClusterStateFaultError,
    InvalidDBInstanceStateError,
    SnapshotQuotaExceededError,
    DBSnapshotAlreadyExistsError,
)


class Database(BaseModel):
    def __init__(self, **kwargs):
        self.status = "available"
        self.is_replica = False
        self.replicas = []
        self.region = kwargs.get("region")
        self.engine = kwargs.get("engine")
        self.engine_version = kwargs.get("engine_version", None)
        self.default_engine_versions = {
            "MySQL": "5.6.21",
            "mysql": "5.6.21",
            "oracle-se1": "11.2.0.4.v3",
            "oracle-se": "11.2.0.4.v3",
            "oracle-ee": "11.2.0.4.v3",
            "sqlserver-ee": "11.00.2100.60.v1",
            "sqlserver-se": "11.00.2100.60.v1",
            "sqlserver-ex": "11.00.2100.60.v1",
github spulec / moto / moto / dynamodb / models.py View on Github external
attributes[attribute_key] = attribute.value

        return {"Attributes": attributes}

    def describe_attrs(self, attributes):
        if attributes:
            included = {}
            for key, value in self.attrs.items():
                if key in attributes:
                    included[key] = value
        else:
            included = self.attrs
        return {"Item": included}


class Table(BaseModel):
    def __init__(
        self,
        name,
        hash_key_attr,
        hash_key_type,
        range_key_attr=None,
        range_key_type=None,
        read_capacity=None,
        write_capacity=None,
    ):
        self.name = name
        self.hash_key_attr = hash_key_attr
        self.hash_key_type = hash_key_type
        self.range_key_attr = range_key_attr
        self.range_key_type = range_key_type
        self.read_capacity = read_capacity
github spulec / moto / moto / emr / models.py View on Github external
self.id = random_step_id()

        self.action_on_failure = action_on_failure
        self.args = args or []
        self.name = name
        self.jar = jar
        self.properties = properties or {}

        self.creation_datetime = datetime.now(pytz.utc)
        self.end_datetime = None
        self.ready_datetime = None
        self.start_datetime = None
        self.state = state


class FakeCluster(BaseModel):
    def __init__(
        self,
        emr_backend,
        name,
        log_uri,
        job_flow_role,
        service_role,
        steps,
        instance_attrs,
        bootstrap_actions=None,
        configurations=None,
        cluster_id=None,
        visible_to_all_users="false",
        release_label=None,
        requested_ami_version=None,
        running_ami_version=None,
github spulec / moto / moto / s3 / models.py View on Github external
self.block_public_acls = block_public_acls or "false"
        self.ignore_public_acls = ignore_public_acls or "false"
        self.block_public_policy = block_public_policy or "false"
        self.restrict_public_buckets = restrict_public_buckets or "false"

    def to_config_dict(self):
        # Need to make the string values booleans for Config:
        return {
            "blockPublicAcls": convert_str_to_bool(self.block_public_acls),
            "ignorePublicAcls": convert_str_to_bool(self.ignore_public_acls),
            "blockPublicPolicy": convert_str_to_bool(self.block_public_policy),
            "restrictPublicBuckets": convert_str_to_bool(self.restrict_public_buckets),
        }


class FakeBucket(BaseModel):
    def __init__(self, name, region_name):
        self.name = name
        self.region_name = region_name
        self.keys = _VersionedKeyStore()
        self.multiparts = {}
        self.versioning_status = None
        self.rules = []
        self.policy = None
        self.website_configuration = None
        self.acl = get_canned_acl("private")
        self.tags = FakeTagging()
        self.cors = []
        self.logging = {}
        self.notification_configuration = None
        self.accelerate_configuration = None
        self.payer = "BucketOwner"
github spulec / moto / moto / events / models.py View on Github external
import os
import re
import json

from moto.core.exceptions import JsonRESTError
from moto.core import BaseBackend, BaseModel


class Rule(BaseModel):
    def _generate_arn(self, name):
        return "arn:aws:events:us-west-2:111111111111:rule/" + name

    def __init__(self, name, **kwargs):
        self.name = name
        self.arn = kwargs.get("Arn") or self._generate_arn(name)
        self.event_pattern = kwargs.get("EventPattern")
        self.schedule_exp = kwargs.get("ScheduleExpression")
        self.state = kwargs.get("State") or "ENABLED"
        self.description = kwargs.get("Description")
        self.role_arn = kwargs.get("RoleArn")
        self.targets = []

    def enable(self):
        self.state = "ENABLED"