chachan
chachan

Reputation: 2452

Can't test datastore operations

I've been trying to test "reading a post from my blog" but looks like the datastore used by the handler is different than the one used by the test.

This is the test:

def test_read_handler(self):
    self.testbed.init_memcache_stub()
    self.testbed.init_datastore_v3_stub()
    self.testbed.init_user_stub()
    data = {
        'primary_title': 'Primary Post Title',
        'secondary_title': 'Secondary Post Title',
        'content': 'This is a sample'
    }
    new_post = models.Post(primary_title=data['primary_title'], secondary_title=data['secondary_title'],
                           content=data['content'])
    key = new_post.put()

    response = self.test_app.get('/read', {'id': key.id()})

    self.assertEqual(response.status_int, 200)
    self.assertEqual(response.content_type, 'application/json')
    self.assertEqual(response.json, 'OK')

This is the handler:

class ReadHandler(webapp2.RequestHandler):
    def get(self):
        post_id = self.request.get('id')
        returned_post = models.Post.get_by_id(post_id)
        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps(returned_post.to_dict()))

This is the error I'm getting:

test_read_handler (tests.BlogTest) ... ERROR:root:'NoneType' object has no attribute 'to_dict'
Traceback (most recent call last):
  File "/usr/local/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1535, in __call__
    rv = self.handle_exception(request, response, e)
  File "/usr/local/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1529, in __call__
    rv = self.router.dispatch(request, response)
  File "/usr/local/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
    return route.handler_adapter(request, response)
  File "/usr/local/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1102, in __call__
    return handler.dispatch()
  File "/usr/local/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 572, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "/usr/local/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 570, in dispatch
    return method(*args, **kwargs)
  File "/vagrant/blog.py", line 28, in get
    self.response.out.write(json.dumps(returned_post.to_dict()))
AttributeError: 'NoneType' object has no attribute 'to_dict'

Any idea what could I be missing?

Upvotes: 0

Views: 48

Answers (1)

Greg
Greg

Reputation: 10360

In your handler, you need to cast the id you're looking up to an int - as a request parameter, it will be treated as a string:

class ReadHandler(webapp2.RequestHandler):
    def get(self):
        post_id = int(self.request.get('id'))
        returned_post = models.Post.get_by_id(post_id)
        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps(returned_post.to_dict()))

Upvotes: 1

Related Questions