Fixes to batch_add mechanisms and spawner batch creation for passing unittests.

This commit is contained in:
Griatch 2017-04-09 18:53:39 +02:00
parent d44f7c4670
commit ee4dd20fd9
4 changed files with 42 additions and 27 deletions

View file

@ -943,21 +943,20 @@ class DefaultObject(with_metaclass(TypeclassBase, ObjectDB)):
self.save(update_fields=updates) self.save(update_fields=updates)
if cdict.get("permissions"): if cdict.get("permissions"):
self.permissions.batch_add(cdict["permissions"]) self.permissions.batch_add(*cdict["permissions"])
if cdict.get("locks"): if cdict.get("locks"):
self.locks.add(cdict["locks"]) self.locks.add(cdict["locks"])
if cdict.get("aliases"): if cdict.get("aliases"):
self.aliases.batch_add(cdict["aliases"]) self.aliases.batch_add(*cdict["aliases"])
if cdict.get("location"): if cdict.get("location"):
cdict["location"].at_object_receive(self, None) cdict["location"].at_object_receive(self, None)
self.at_after_move(None) self.at_after_move(None)
if cdict.get("tags"): if cdict.get("tags"):
# this should be a list of tags # this should be a list of tags
self.tags.batch_add(cdict["tags"]) self.tags.batch_add(*cdict["tags"])
if cdict.get("attributes"): if cdict.get("attributes"):
# this should be a dict of attrname:value # this should be a dict of attrname:value
keys, values = list(cdict["attributes"]), listvalues(cdict["attributes"]) self.attributes.batch_add(*cdict["attributes"])
self.attributes.batch_add(keys, values)
if cdict.get("nattributes"): if cdict.get("nattributes"):
# this should be a dict of nattrname:value # this should be a dict of nattrname:value
for key, value in cdict["nattributes"].items(): for key, value in cdict["nattributes"].items():

View file

@ -624,7 +624,7 @@ class DefaultPlayer(with_metaclass(TypeclassBase, PlayerDB)):
permissions = cdict["permissions"] permissions = cdict["permissions"]
del self._createdict del self._createdict
self.permissions.batch_add(permissions) self.permissions.batch_add(*permissions)
def at_access(self, result, accessing_obj, access_type, **kwargs): def at_access(self, result, accessing_obj, access_type, **kwargs):
""" """

View file

@ -10,6 +10,7 @@ which is a non-db version of Attributes.
""" """
from builtins import object from builtins import object
import re import re
import fnmatch
import weakref import weakref
from django.db import models from django.db import models
@ -20,7 +21,7 @@ from evennia.locks.lockhandler import LockHandler
from evennia.utils.idmapper.models import SharedMemoryModel from evennia.utils.idmapper.models import SharedMemoryModel
from evennia.utils.dbserialize import to_pickle, from_pickle from evennia.utils.dbserialize import to_pickle, from_pickle
from evennia.utils.picklefield import PickledObjectField from evennia.utils.picklefield import PickledObjectField
from evennia.utils.utils import lazy_property, to_str, make_iter from evennia.utils.utils import lazy_property, to_str, make_iter, is_iter
_TYPECLASS_AGGRESSIVE_CACHE = settings.TYPECLASS_AGGRESSIVE_CACHE _TYPECLASS_AGGRESSIVE_CACHE = settings.TYPECLASS_AGGRESSIVE_CACHE
@ -221,7 +222,11 @@ class AttributeHandler(object):
query = {"%s__id" % self._model: self._objid, query = {"%s__id" % self._model: self._objid,
"attribute__db_model": self._model, "attribute__db_model": self._model,
"attribute__db_attrtype": self._attrtype} "attribute__db_attrtype": self._attrtype}
attrs = [conn.attribute for conn in getattr(self.obj, self._m2m_fieldname).through.objects.filter(**query)] attrs = [
conn.attribute for conn in getattr(
self.obj,
self._m2m_fieldname).through.objects.filter(
**query)]
self._cache = dict(("%s-%s" % (to_str(attr.db_key).lower(), self._cache = dict(("%s-%s" % (to_str(attr.db_key).lower(),
attr.db_category.lower() if attr.db_category else None), attr.db_category.lower() if attr.db_category else None),
attr) for attr in attrs) attr) for attr in attrs)
@ -421,6 +426,7 @@ class AttributeHandler(object):
class RetDefault(object): class RetDefault(object):
"""Holds default values""" """Holds default values"""
def __init__(self): def __init__(self):
self.key = None self.key = None
self.value = default self.value = default
@ -441,7 +447,8 @@ class AttributeHandler(object):
if accessing_obj: if accessing_obj:
# check 'attrread' locks # check 'attrread' locks
ret = [attr for attr in ret if attr.access(accessing_obj, self._attrread, default=default_access)] ret = [attr for attr in ret if attr.access(accessing_obj,
self._attrread, default=default_access)]
if strattr: if strattr:
ret = ret if return_obj else [attr.strvalue for attr in ret if attr] ret = ret if return_obj else [attr.strvalue for attr in ret if attr]
else: else:
@ -473,7 +480,8 @@ class AttributeHandler(object):
`attrcreate` is defined on the Attribute in question. `attrcreate` is defined on the Attribute in question.
""" """
if accessing_obj and not self.obj.access(accessing_obj, self._attrcreate, default=default_access): if accessing_obj and not self.obj.access(accessing_obj, self._attrcreate,
default=default_access):
# check create access # check create access
return return
@ -547,14 +555,17 @@ class AttributeHandler(object):
ntup = len(tup) ntup = len(tup)
keystr = str(tup[0]).strip().lower() keystr = str(tup[0]).strip().lower()
new_value = tup[1] new_value = tup[1]
category = str(tup[2]).strip().lower() if tup > 2 else None category = str(tup[2]).strip().lower() if ntup > 2 else None
lockstring = tup[3] if tup > 3 else "" lockstring = tup[3] if ntup > 3 else ""
attr_objs = self._getcache(keystr, category) attr_objs = self._getcache(keystr, category)
if attr_objs: if attr_objs:
attr_obj = attr_objs[0] attr_obj = attr_objs[0]
# update an existing attribute object # update an existing attribute object
attr_obj.db_category = category
attr_obj.db_lock_storage = lockstring
attr_obj.save(update_fields=["db_category", "db_lock_storage"])
if strattr: if strattr:
# store as a simple string (will not notify OOB handlers) # store as a simple string (will not notify OOB handlers)
attr_obj.db_strvalue = new_value attr_obj.db_strvalue = new_value
@ -569,7 +580,8 @@ class AttributeHandler(object):
"db_model": self._model, "db_model": self._model,
"db_attrtype": self._attrtype, "db_attrtype": self._attrtype,
"db_value": None if strattr else to_pickle(new_value), "db_value": None if strattr else to_pickle(new_value),
"db_strvalue": value if strattr else None} "db_strvalue": new_value if strattr else None,
"db_lock_storage": lockstring}
new_attr = Attribute(**kwargs) new_attr = Attribute(**kwargs)
new_attr.save() new_attr.save()
new_attrobjs.append(new_attr) new_attrobjs.append(new_attr)
@ -605,8 +617,11 @@ class AttributeHandler(object):
for keystr in make_iter(key): for keystr in make_iter(key):
attr_objs = self._getcache(keystr, category) attr_objs = self._getcache(keystr, category)
for attr_obj in attr_objs: for attr_obj in attr_objs:
if not (accessing_obj and not attr_obj.access(accessing_obj, if not (
self._attredit, default=default_access)): accessing_obj and not attr_obj.access(
accessing_obj,
self._attredit,
default=default_access)):
try: try:
attr_obj.delete() attr_obj.delete()
except AssertionError: except AssertionError:
@ -698,7 +713,6 @@ Custom arg markers
$N argument position (1-99) $N argument position (1-99)
""" """
import fnmatch
_RE_NICK_ARG = re.compile(r"\\(\$)([1-9][0-9]?)") _RE_NICK_ARG = re.compile(r"\\(\$)([1-9][0-9]?)")
_RE_NICK_TEMPLATE_ARG = re.compile(r"(\$)([1-9][0-9]?)") _RE_NICK_TEMPLATE_ARG = re.compile(r"(\$)([1-9][0-9]?)")
_RE_NICK_SPACE = re.compile(r"\\ ") _RE_NICK_SPACE = re.compile(r"\\ ")
@ -816,7 +830,8 @@ class NickHandler(AttributeHandler):
else: else:
retval = super(NickHandler, self).get(key=key, category=category, **kwargs) retval = super(NickHandler, self).get(key=key, category=category, **kwargs)
if retval: if retval:
return retval[3] if isinstance(retval, tuple) else [tup[3] for tup in make_iter(retval)] return retval[3] if isinstance(retval, tuple) else \
[tup[3] for tup in make_iter(retval)]
return None return None
def add(self, key, replacement, category="inputline", **kwargs): def add(self, key, replacement, category="inputline", **kwargs):
@ -836,7 +851,8 @@ class NickHandler(AttributeHandler):
nick_regex, nick_template = initialize_nick_templates(key + " $1", replacement + " $1") nick_regex, nick_template = initialize_nick_templates(key + " $1", replacement + " $1")
else: else:
nick_regex, nick_template = initialize_nick_templates(key, replacement) nick_regex, nick_template = initialize_nick_templates(key, replacement)
super(NickHandler, self).add(key, (nick_regex, nick_template, key, replacement), category=category, **kwargs) super(NickHandler, self).add(key, (nick_regex, nick_template, key, replacement),
category=category, **kwargs)
def remove(self, key, category="inputline", **kwargs): def remove(self, key, category="inputline", **kwargs):
""" """
@ -873,13 +889,12 @@ class NickHandler(AttributeHandler):
""" """
nicks = {} nicks = {}
for category in make_iter(categories): for category in make_iter(categories):
nicks.update({nick.key: nick nicks.update({nick.key: nick for nick in make_iter(
for nick in make_iter(self.get(category=category, return_obj=True)) if nick and nick.key}) self.get(category=category, return_obj=True)) if nick and nick.key})
if include_player and self.obj.has_player: if include_player and self.obj.has_player:
for category in make_iter(categories): for category in make_iter(categories):
nicks.update({nick.key: nick nicks.update({nick.key: nick for nick in make_iter(self.obj.player.nicks.get(
for nick in make_iter(self.obj.player.nicks.get(category=category, return_obj=True)) category=category, return_obj=True)) if nick and nick.key})
if nick and nick.key})
for key, nick in nicks.iteritems(): for key, nick in nicks.iteritems():
nick_regex, template, _, _ = nick.value nick_regex, template, _, _ = nick.value
regex = self._regex_cache.get(nick_regex) regex = self._regex_cache.get(nick_regex)
@ -900,6 +915,7 @@ class NAttributeHandler(object):
by the `.ndb` handler in the same way as `.db` does by the `.ndb` handler in the same way as `.db` does
for the `AttributeHandler`. for the `AttributeHandler`.
""" """
def __init__(self, obj): def __init__(self, obj):
""" """
Initialized on the object Initialized on the object

View file

@ -272,15 +272,15 @@ def spawn(*prototypes, **kwargs):
create_kwargs["db_typeclass_path"] = typval() if callable(typval) else typval create_kwargs["db_typeclass_path"] = typval() if callable(typval) else typval
# extract calls to handlers # extract calls to handlers
permval = prot.pop("permissions", "") permval = prot.pop("permissions", [])
permission_string = permval() if callable(permval) else permval permission_string = permval() if callable(permval) else permval
lockval = prot.pop("locks", "") lockval = prot.pop("locks", "")
lock_string = lockval() if callable(lockval) else lockval lock_string = lockval() if callable(lockval) else lockval
aliasval = prot.pop("aliases", "") aliasval = prot.pop("aliases", "")
alias_string = aliasval() if callable(aliasval) else aliasval alias_string = aliasval() if callable(aliasval) else aliasval
tagval = prot.pop("tags", "") tagval = prot.pop("tags", [])
tags = tagval() if callable(tagval) else tagval tags = tagval() if callable(tagval) else tagval
attrval = prot.pop("args", "") attrval = prot.pop("args", [])
attributes = attrval() if callable(tagval) else attrval attributes = attrval() if callable(tagval) else attrval
exval = prot.pop("exec", "") exval = prot.pop("exec", "")
@ -291,7 +291,7 @@ def spawn(*prototypes, **kwargs):
for key, value in prot.items() if key.startswith("ndb_")) for key, value in prot.items() if key.startswith("ndb_"))
# the rest are attributes # the rest are attributes
simple_attributes = [(key, value) if callable(value) else value simple_attributes = [(key, value()) if callable(value) else (key, value)
for key, value in prot.items() if not key.startswith("ndb_")] for key, value in prot.items() if not key.startswith("ndb_")]
attributes = attributes + simple_attributes attributes = attributes + simple_attributes
attributes = [tup for tup in attributes if not tup[0] in _CREATE_OBJECT_KWARGS] attributes = [tup for tup in attributes if not tup[0] in _CREATE_OBJECT_KWARGS]