foxfirefey: Fox stealing an egg. (Default)
[personal profile] foxfirefey posting in [community profile] python
Makes me love Python. I needed an class for a test suite for the DWMinion module I'm making to make it easy to create DWAccount objects on the fly. I figured out that I could do this by subclassing the dict class.

Basically, this subclassed dict *always* returns a DWAccount for a given account name. And I have a function to have it return a set of accounts, all at once.

class DWAccountMaker(dict):
    """A cheap class extending a dictionary that will always give back an account.  
    Start the account names with p, i, c, and f to get different account types."""

    def make_account(self, key):
        """Make an account type depending on the starting letter.
        Personal is the default otherwise."""
        if key.startswith("p"):
            return e.DWAccount(key, "personal")
        elif key.startswith("i"):
            return e.DWAccount(key, "identity")
        elif key.startswith("c"):
            return e.DWAccount(key, "community")
        elif key.startswith("f"):
            return e.DWAccount(key, "feed")
            return e.DWAccount(key, "personal")

    def get_set(self, *keys):
        """Get a set of accounts."""
        return set([self.__getitem__(key) for key in keys])

    def __getitem__( self, key ):
        # Set the key to a new account if it doesn't exist
        if not self.has_key( key ):
            super(DWAccountMaker,self).__setitem__( key, self.make_account(key) )
        return super(DWAccountMaker,self).__getitem__( key )

So, now my testing becomes a lot simpler, for example:

class DWUserBasicsTest(unittest.TestCase):
    """Test DWUser"""
    def setUp(self):
        self.user = e.DWUser("testuser") = DWAccountMaker()
        self.user.watched_by ="pa", "pb", "pc", "pd", "ia", "ib", "ic") ="pa", "pc", "pe", "ca", "cb") ="pa", "ib")
        self.user.trusted_by ="pa", "pc", "pd", "ic")
        self.user.member_of ="ca")
    def testName(self):
        self.assertEqual(self.user.account_name, "testuser")
    def testMutualWatchers(self):
        should_be ="pa", "pc")
        self.assertEqual(self.user.get_mutual_watch(), should_be)

The subclassed DWAccountMaker dict is useful because instead of having to create lots of individual DWAccount classes, I can just let the DWAccountMaker manage the classes instead and retrieve sets from it at will.
Anonymous( )Anonymous This account has disabled anonymous posting.
OpenID( )OpenID You can comment on this post while signed in with an account from many other sites, once you have confirmed your email address. Sign in using OpenID.
Account name:
If you don't have an account you can create one now.
HTML doesn't work in the subject.


Notice: This account is set to log the IP addresses of everyone who comments.
Links will be displayed as unclickable URLs to help prevent spam.

February 2017

2627 28    

Style Credit

Expand Cut Tags

No cut tags