Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

certain user.py methods fail when user is first created #5

Open
MareoRaft opened this issue Mar 1, 2016 · 4 comments
Open

certain user.py methods fail when user is first created #5

MareoRaft opened this issue Mar 1, 2016 · 4 comments
Labels

Comments

@MareoRaft
Copy link
Owner

After dropping the users collection on mongo, running test_user.py results in 2-3 errors.

Each error fails the first time it is run, but then SUCCEEDS the second time.

(For example, test_set_prefs() fails to add the prefs { 'one': 'a', 'two': 'b' } to the matt user on its first try. but if you run py.test a second time, it succeeds.)

This suggests that the failure has something to do with the fact that the user was JUST CREATED in the collection.

Any ideas, @mmuddasani ?

@MareoRaft
Copy link
Owner Author

I haven't synced my user.py to the repo since it's not working yet. Here it is:

http://cl.ly/1E2J2J2k1u2T

@MareoRaft
Copy link
Owner Author

@mmuddasani Could really use your help on this. Otherwise, I'll open a Stack Overflow post.

@MareoRaft
Copy link
Owner Author

MareoRaft commented May 20, 2016

I tried running the tests again and dropping the users collection. Now I'm not getting the error anymore. I was GOING to post the following on Stack Overflow. If the error comes back, we can post it at that time.

class that uses pymongo fails first time, succeeds second time

I have a User class as follows. It has been slightly truncated:

class User:

    USERS = Mongo("provemath", "users")

    def __init__(self, initial_identifier):
        if initial_identifier['type'] in ['digg', 'google', 'reddit', 'github']:
            self.account_type = initial_identifier['type']
            self.account_id = initial_identifier['id']
            self.logged_in = True
        else:
            self.account_type = 'local'
            self.account_id = 'local account, no id set yet'
            self.logged_in = False

    @property
    def dict(self):
        # if user exists, retrieve their dictionary
        user_dict = None
        user_dicts = list(self.USERS.find(self._mongo_identifier_dict()))
        if len(user_dicts) > 1:
            raise Exception('REDUNDANT USER INFORMATION!')
        elif len(user_dicts) == 1:
            user_dict = user_dicts[0]
            print('got recent dict')
            del user_dict['_id'] # delete the ObjectId('94569463') thing because it is not JSON serializable
            return user_dict
        else:
            # otherwise, make a new dictionary and store it into the db
            user_dict = self._default_dict()
            self.USERS.insert_one(user_dict)
            return self.dict

    @property
    def identifier(self):
        return self.dict['account']

    def _mongo_identifier_dict(self):
        return {
            'account.type': self.account_type,
            'account.id': self.account_id,
        }

    def _default_dict(self):
        return {
            'account': {
                'type': self.account_type,
                'id': self.account_id,
            },
            'prefs': {
                'some_preference': None,
                'another_preference': False,
            },
        }

    def set_pref(self, pref_dict):
        one_pref_set = False
        for key, value in pref_dict.items():
            if one_pref_set:
                raise ValueError('Multiple keys existed in pref_dict.  Meant for only one key at a time.')
            self.USERS.update(self._mongo_identifier_dict(), {'$set': {('prefs.'+key): value}}, False)
            one_pref_set = True

    def set_prefs(self, pref_dict):
        for key, value in pref_dict.items():
            temp_dict = dict()
            temp_dict[key] = value
            self.set_pref(temp_dict)

It depends on Mongo, which is just a light wrapper around pymongo:

class Mongo:
    def __init__(self, database, collection):
        self.address = pymongo.MongoClient("mongodb://localhost")
        self.database = database
        self.collection = collection

    def update(self, query, update, options):
        self.address[self.database][self.collection].update(query, update, options)

    # and similar methods for insert_one, delete_many, etc

So I've got mongodb running locally on my computer. When I drop the "users" collection from my MongoDB, so as to start with a blank slate, and then run the following test code with py.test, it FAILS the first time I run it, and SUCCEEDS the second time. It ALWAYS vexes me! :)

def test_set_prefs():
    me = User({'type': 'github', 'id': 'hhsetprefshh' })
    me.set_prefs({
        'one': 'a',
        'two': 'b',
    })
    print(str(me.dict))
    assert me.dict['prefs']['one'] == 'a'
    assert me.dict['prefs']['two'] == 'b'

What could possibly cause this?

@MareoRaft
Copy link
Owner Author

I want to wait a month (until June 20) and then try it again, before closing this issue.

@MareoRaft MareoRaft added the bug label May 20, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant