Beispiel #1
0
    def test_models_maintain_their_own_scope_lists(self):
        CarA = create_model(car_schema, Mock())
        CarB = create_model(car_schema, Mock())

        def scope_a():
            return {}

        def scope_b():
            return {}

        CarA.scope(scope_a)
        CarB.scope(scope_b)
        self.assertEquals(STANDARD_SCOPES + [scope_a], CarA.scopes)
        self.assertEquals(STANDARD_SCOPES + [scope_b], CarB.scopes)
Beispiel #2
0
 def setUp(self):
     self.mock_collection = Mock()
     self.mock_collection.name = "car"
     self.Car = create_model(car_schema, self.mock_collection)
     self.CarOffline = create_model_offline(car_schema, lambda: self.mock_collection, 'Car')
     self.car = self.Car(doc)
     self.car_offline = self.CarOffline(doc)
Beispiel #3
0
def get_model(db):
	Variables = create_model(var_schema, db['vars'])

	@Variables.class_method
	def get_value(cls, name, def_val=None):
		try:
			return cls.find_one({'name': name})['value']
		except:
			return def_val

	@Variables.class_method
	def set_value(cls, name, value):
		try:
			var = cls.find_one({'name': name})
			var.update({'value': value})
			var.save()
		except:
			var = Variables({'name': name, 'value': value})
			var.save()

	return Variables
Beispiel #4
0
def get_model(db):
    Variables = create_model(var_schema, db['vars'])

    @Variables.class_method
    def get_value(cls, name, def_val=None):
        try:
            return cls.find_one({'name': name})['value']
        except:
            return def_val

    @Variables.class_method
    def set_value(cls, name, value):
        try:
            var = cls.find_one({'name': name})
            var.update({'value': value})
            var.save()
        except:
            var = Variables({'name': name, 'value': value})
            var.save()

    return Variables
Beispiel #5
0
def get_model(db):
	Lists = create_model(list_schema, db['vars'])

	@Lists.class_method
	def get_list(cls, name):
		try:
			return cls.find_one({'name': name})['value']
		except:
			return [ ]

	@Lists.class_method
	def set_list(cls, name, value):
		try:
			var = cls.find_one({'name': name})
			var.update({'value': value})
			var.save()
		except:
			var = Lists({'name': name, 'value': value})
			var.save()

	@Lists.class_method
	def clear_list(cls, name):
		cls.set_list(name, [ ])

	@Lists.class_method
	def remove_from_list(cls, name, val):
		lst = cls.get_list(cls, name)
		lst.remove(val)
		cls.set_list(name, lst)

	@Lists.class_method
	def add_to_list(cls, name, val, force=True):
		lst = cls.get_list(cls, name)
		
		if force or val not in lst:
			lst.append(val)
			cls.set_list(name, lst)

	return Lists
Beispiel #6
0
def get_model(db):
    Lists = create_model(list_schema, db["vars"])

    @Lists.class_method
    def get_list(cls, name):
        try:
            return cls.find_one({"name": name})["value"]
        except:
            return []

    @Lists.class_method
    def set_list(cls, name, value):
        try:
            var = cls.find_one({"name": name})
            var.update({"value": value})
            var.save()
        except:
            var = Lists({"name": name, "value": value})
            var.save()

    @Lists.class_method
    def clear_list(cls, name):
        cls.set_list(name, [])

    @Lists.class_method
    def remove_from_list(cls, name, val):
        lst = cls.get_list(cls, name)
        lst.remove(val)
        cls.set_list(name, lst)

    @Lists.class_method
    def add_to_list(cls, name, val, force=True):
        lst = cls.get_list(cls, name)

        if force or val not in lst:
            lst.append(val)
            cls.set_list(name, lst)

    return Lists
Beispiel #7
0
import mongothon

from dbconnect import my_db

channels_schema = mongothon.Schema({
    "server": {
        "type": int,
        "required": True
    },
    "channels": {
        "type": dict
    }
})

Channels = mongothon.create_model(channels_schema, my_db["channels"])

if __name__ == "__main__":
    test = Channels({
        "server": 123456,
        "channels": {
            "town-square": 264,
            "yeah": 26
        }
    })
    test.save()
    x = Channels.find_one({"server": 123456})
    print(type(x['_id']))
    id_string = str(x['_id'])
    print(id_string)
    print(x)
Beispiel #8
0
# Create our schema for easy access to our entries
entry_schema = Schema({
    'id': {'type': int, 'required': True},
    'org_name': {'type': basestring, 'required': True},
    'url':  {'type': basestring},
    'genre': {'type': Array(basestring), 'default':[], 'required':True},
    'judges': {'type': Array(basestring), 'default':[]},
    'keywords': {'type': Array(basestring), 'default':[]},
    'price': {'type': basestring},
    'submission_fee': {'type': float},
    'deadline': {'type': datetime, 'default': datetime.utcnow},
    'submission_type': {'type': basestring},
    'opens':  {'type': datetime, 'default': datetime.utcnow},
})
Entries = create_model(entry_schema, db['entries'])

# Start up our server
app = flask.Flask(__name__)
app.config['DEBUG'] = True

def sanitizeEntry(entry):
    e = dict(entry)
    e['genre'] =  [] if e['genre'] == "" else ast.literal_eval(e['genre'])
    e['keywords'] = [] if e['keywords'] == "" else ast.literal_eval(e['keywords'])
    e['judges'] = [] if e['judges'] == "" else ast.literal_eval(e['judges'])
    del e['_id']

    return e
    
# Routes of interest
Beispiel #9
0
def get_model(db):
	Scores = create_model(score_schema, db['scores'])

	@Scores.class_method
	def get_leaderboard(cls, leaderboard, count=10):
		if leaderboard == 'death':
			res = list(cls.find({"leaderboard": 'rooms'}))

			keyf = Code("function(doc) {return{\"death_reason\": doc.death_reason}}")
			reducer = Code("function(curr, result) { result.count++; }")
			
			res = list(cls.get_collection().group( 
				key = keyf, 
				condition = {
					"death_reason": { "$exists": True },
					"leaderboard": "rate"
				}, 
				reduce = reducer, 
				initial = { "count": 0}
			))

			def sort_death(doc):
				return -doc['count']

			res.sort(key=sort_death)

			return res[:count]
		else:
			def sort_by_score(doc):
				return doc['score']

			cursor = cls.find({"leaderboard": leaderboard})
			sorted = cursor.sort('score', pymongo.DESCENDING)
			res = list(sorted.limit(count))

			return res[:count]
		return list(cls.find({"leaderboard": leaderboard}))[:count]

	@Scores.class_method
	def add_to_leaderboard(cls, user, score, leaderboard_name='rooms'):
		name = user.name

		costume = costumes.get_costume(user.costume)
		name += ' в костюме _{0}_'.format(costume['who'])

		if user.pet:
			pet = user.get_pet()
			name += ' и {0} {1}'.format(pet.name, pet.real_name)

		doc = {
			'uid': user.uid,
			'name': name,
			'score': score,
			'leaderboard': leaderboard_name
		}
		if hasattr(user, 'death_reason'):
			doc['death_reason'] = user.death_reason

		cls.insert(doc)

	return Scores
Beispiel #10
0
    def validate(value):
        try:
            time.strptime(value, '%H:%M')
            h, m = value.split(':')
            if int(h) < 10 and len(h) < 2:
                return "Invalid time format"
        except ValueError:
            return "Invalid time format"

    return validate


def validate_warning():
    def validate(value):
        if value > 180:
            return "Warning has to be within three hours of nighttime"

    return validate


server_schema = mongothon.Schema({
    "server": {"type": int, "required": True},
    "daytime": {"type": str, "default": "08:00", "validates": time_format()},
    "nighttime": {"type": str, "default": "20:00", "validates": time_format()},
    "warning": {"type": int, "default": 30, "validates": validate_warning()},
    "announce_character": {"type": bool, "default": True},
    "prefix": {"type": str, "default": "!"}
})

Server = mongothon.create_model(server_schema, my_db['server'])
Beispiel #11
0
    },
    "voted": {
        "type": dict,
        "default": {}
    },
    "locked": {
        "type": list,
        "default": []
    },
    "lynch": {
        "type": bool,
        "default": True
    }
})

Election = mongothon.create_model(election_schema, my_db["elections"])

# x = Channels.find_one({"server": 123456})

if __name__ == "__main__":
    test = Election({
        "server": 163,
        "people": ["hi", "what", "is"],
        "channel": 163263523
    })
    test.save()
    x = Election.find_one({"server": 163})
    print(type(x['_id']))
    id_string = str(x['_id'])
    print(id_string)
    x["people"].append("wow!")
Beispiel #12
0
        "type": int,
        "required": True
    },
    "spirits": {
        "type": bool,
        "default": True
    },
    "dead_wolves": {
        "type": bool,
        "default": True
    },
    "werewolves": {
        "type": bool,
        "default": True
    },
    "seer": {
        "type": bool,
        "default": True
    },
    "bodyguard": {
        "type": bool,
        "default": True
    },
    "cupid": {
        "type": bool,
        "default": True
    }
})

Abilities = mongothon.create_model(ability_schema, my_db['abilities'])
Beispiel #13
0
client = MongoClient(config.MONGO_URL)
# dbNews = client['lovel-up']
db = client['twitter_bot']

user_schema = mongothon.Schema({
    "id":               {"type": basestring, "required": True},
    "name":             {"type": basestring},
    "date_followed":    {"type": datetime },
    "date_unfollowed":  {"type": datetime },
    "following":        {"type": bool},
    "following_me":     {"type": bool}
})


User = mongothon.create_model(user_schema, db['users'])

def get_user_by_id(id):
    return User.find_one({'id': str(id)})

def get_users( following, following_me, days ):
    users = []

    query = { "following": following, "following_me": following_me }
    if following == True and following_me == False:
        query['$or'] = [
            {'date_followed': { '$lt': datetime.utcnow() - timedelta( days=days )} },
            {'date_followed': { '$exists': False } }
        ]

    if following == False and following_me == False:
Beispiel #14
0
 def test_different_classes_managed_their_own_handlers(self):
     CarA = create_model(car_schema, Mock())
     CarB = create_model(car_schema, Mock())
     handler = Mock()
     CarA.on('did_save', handler)
     self.assertEquals([], CarB.handlers('did_save'))
Beispiel #15
0
            "tire":     "Michelin",
            "diameter": 24
        },
        {
            "position": "RL",
            "tire":     "Michelin",
            "diameter": 24
        }
    ],
    "options": ['heated seats', 'leather steering wheel']
}

# This has to live here so pickle can find it.
mock_collection = Mock()
mock_collection.name = "pickleable"
Pickleable = create_model(Mock(), mock_collection)


class TestModel(TestCase):

    def setUp(self):
        self.mock_collection = Mock()
        self.mock_collection.name = "car"
        self.Car = create_model(car_schema, self.mock_collection)
        self.CarOffline = create_model_offline(car_schema, lambda: self.mock_collection, 'Car')
        self.car = self.Car(doc)
        self.car_offline = self.CarOffline(doc)

    def tearDown(self):
        self.Car.remove_all_handlers()
            Matches.LOVE: {
                'type': basestring
            },
            Matches.CAREER: {
                'type': basestring
            }
        }),
        'default': {
            Matches.FRIENDSHIP: HoroscopeType.ARIES,
            Matches.LOVE: HoroscopeType.ARIES,
            Matches.CAREER: HoroscopeType.ARIES
        }
    }
})

HoroscopeDayLog = create_model(horoscope_day_log_schema, db.horoscope_day_log,
                               "HoroscopeDayLog")
HoroscopeDayLog.collection.ensure_index([("date", -1), ('horoscope_type', -1)])

horoscope_week_log_schema = Schema({
    "date": {
        'type': basestring
    },  # %Y-%U 2018-00, 具体规则参见datetime.strftime()
    'horoscope_type': {
        'type': basestring,
        'default': HoroscopeType.ARIES
    },
    'content': {
        'type': dict,
        'default': {}
    },
})
Beispiel #17
0
import mongothon

from dbconnect import my_db

def delete_many(filter):
    my_db['villager'].delete_many(filter)

villager_schema = mongothon.Schema({
    "discord_id": {"type": int, "required": True},
    "server": {"type": int, "required": True},
    "character": {"type": str, "required": True},
    "werewolf": {"type": bool, "required": True},
    "alive": {"type": bool, "default": True},
})

Villager = mongothon.create_model(villager_schema, my_db['villager'])

import os
from pymongo.connection import Connection
import unittest
from mongothon import create_model
from sample import blog_post_schema, valid_doc, expected_db_doc
from contextlib import contextmanager

host = os.environ.get("DB_IP", "localhost")
port = int(os.environ.get("DB_PORT", 27017))


def get_db(*args, **kwargs):
    return Connection(host, port, *args, **kwargs).mongothon_test

blog_post_collection = get_db().blog_post
BlogPost = create_model(blog_post_schema, blog_post_collection)


class TestPyMongoIntegration(unittest.TestCase):
    """Test that when we use a model against an actual database using
    pymongo, everything works as it should."""
    def setUp(self):
        self.maxDiff = None

    def tearDown(self):
        blog_post_collection.remove()

    @contextmanager
    def assert_no_difference(self, func):
        """Context manager which asserts the given function returns the
        same value either side of the wrapped block."""
Beispiel #19
0
 def test_class_name_defaults_to_camelcased_collection_name(self):
     mock_collection = Mock()
     mock_collection.name = "some_model"
     SomeModel = create_model(Schema({}), mock_collection)
     self.assertEquals("SomeModel", SomeModel.__name__)
Beispiel #20
0
 def setUp(self):
     self.mock_collection = Mock()
     self.mock_collection.name = "car"
     self.Car = create_model(car_schema, self.mock_collection)
     self.car = self.Car(doc)
    },
    "formula_img": {
        "type": basestring,
        "required": True
    },
    "notes": {
        "type": basestring
    },
    "correct_count": {
        "type": basestring
    },
    "incorrect_count": {
        "type": basestring
    }
})

Compound = create_model(compound_schema, compounds)

for new_compound in encoded_images_dict.keys():
    # check to see if the named compound is already present
    compound_search = Compound.find_one({'name': new_compound})
    if compound_search:
        print new_compound + " already exists in db"
        pass
    else:
        compound = Compound({
            "name": new_compound,
            "formula_img": encoded_images_dict[new_compound]
        })
        compound.save()
Beispiel #22
0
 def test_class_name_can_be_overridden(self):
     mock_collection = Mock()
     mock_collection.name = "some_model"
     SomeModel = create_model(Schema({}), mock_collection, "SomethingElse")
     self.assertEquals("SomethingElse", SomeModel.__name__)
Beispiel #23
0
from pymongo.connection import Connection
import unittest
from mongothon import create_model
from sample import blog_post_schema, valid_doc, expected_db_doc
from contextlib import contextmanager

host = os.environ.get("DB_IP", "localhost")
port = int(os.environ.get("DB_PORT", 27017))


def get_db(*args, **kwargs):
    return Connection(host, port, *args, **kwargs).mongothon_test


blog_post_collection = get_db().blog_post
BlogPost = create_model(blog_post_schema, blog_post_collection)


class TestPyMongoIntegration(unittest.TestCase):
    """Test that when we use a model against an actual database using
    pymongo, everything works as it should."""
    def setUp(self):
        self.maxDiff = None

    def tearDown(self):
        blog_post_collection.remove()

    @contextmanager
    def assert_no_difference(self, func):
        """Context manager which asserts the given function returns the
        same value either side of the wrapped block."""
Beispiel #24
0
from dbconnect import my_db


def delete_many(filter):
    my_db['game'].delete_many(filter)


game_schema = mongothon.Schema({
    "server": {"type": int, "required": True},
    "players": {"type": list, "required": True},  # list of villager discord_id
    "inlove": {"type": list, "default": []},
    "bakerdead": {"type": bool, "default": False},
    "voting": {"type": bool, "default": False},
    "last_protected_id": {"type": int, "default": -1},
    "morning_messages": {"type": list, "default": []},
    "protected": {"type": int, "default": -1},
    "hunter_ids": {"type": list, "default": []},
    "real_time": {"type": bool, "default": True},
    "starving": {"type": list, "default": []},
    "werewolfcount": {"type": int, "required": True},
    "villagercount": {"type": int, "required": True},
})

Game = mongothon.create_model(game_schema, my_db['game'])

if __name__ == '__main__':
    x = Game.find_one({"server": 695805513480536074})
    x["villagercount"] = 15
    x.save()