agar

The agar package contains a number of general purpose utility modules containing classes and functions to help develop with Google App Engine python and webapp2.

agar.auth

The agar.auth module contains classes, functions, and decorators to help secure a webapp2.Requesthandler.

agar.auth.authenticate_abort_403(handler)

An authenticate function for use with the authentication_required() decorator. Simply aborts the call with a status code of 403.

agar.auth.authentication_required(authenticate=None, require_https=False)

A decorator to authenticate a webapp2.RequestHandler. The decorator will assign the return value from the authenticate function to the request user attribute (or any re-configured name via the config AUTHENTICATION_PROPERTY), that is passed to the decorated handler. The authenticate function can call webapp2.abort if there was a problem authenticating the call.

Parameters:
  • authenticate – The authentication function. It should take a single webapp2.RequestHandler argument, and return a value representing the authentication or call webapp2.abort to short circuit the decorated handler. The type of the returned value can be anything, but it should be a type that your webapp2.RequestHandler expects. If None, the configured DEFAULT_AUTHENTICATE_FUNCTION will be used.
  • require_https – If True, this will enforce that a request was made via HTTPS, otherwise a 403 response will be returned.
agar.auth.https_authentication_required(authenticate=None)

A decorator to authenticate a secure request to a webapp2.RequestHandler. Simply calls the authentication_required() decorator with require_https=True.

Parameters:authenticate – The authentication function passed to the authentication_required() decorator.
class agar.auth.AuthConfig(**kwargs)

Config settings for the agar.auth library. Settings are under the agar_auth namespace.

The following settings (and defaults) are provided:

agar_auth_AUTHENTICATION_PROPERTY = 'user'
agar_auth_DEFAULT_AUTHENTICATE_FUNCTION = agar.auth.authenticate_abort_403

To override agar.auth settings, define values in the appengine_config.py file in the root of your project.

AUTHENTICATION_PROPERTY

The property name under which to place the authentication object on the request.

DEFAULT_AUTHENTICATE_FUNCTION

The default authenticate function. It should take a single webapp2.RequestHandler argument, and return a value representing the authentication or call webapp2.abort to short circuit the decorated handler. The type of the returned value can be anything, but it should be a type that your webapp2.RequestHandler expects. The default implementation always calls webapp2.abort with a status code of 403.

Parameters:handler – The webapp2.RequestHandler object to authenticate.
Returns:The result of the authentication.

agar.config

The agar.config module contains a class to help work with the google.appengine.api.lib_config configuration library.

class agar.config.Config(**kwargs)

Configurable constants base class for use with the excellent google.appengine.api.lib_config configuration library.

To use this class, create a subclass that redefines _prefix to the appengine_config prefix you’d like the configs to appear under. Then, simply create class-level properties/functions/default values for each constant.

When instantiating an instance of this class, you can override the default values for that instance by passing in new defaults via the constructor. Of course, if there is an entry in appengine_config.py for your constant, that value will supersede any defined in the class or passed in via the constructor.

Example subclass:

class SampleConfig(Config):
    _prefix = 'test'

    STRING_CONFIG = 'defaultstring'

Example usage:

>>> config = SampleConfig.get_config()
>>> custom_config = SampleConfig.get_config(STRING_CONFIG='customstring')

Assuming there is no override for test_STRING_CONFIG in appengine_config.py:

>>> config.STRING_CONFIG == 'defaultstring'
True
>>> custom_config.STRING_CONFIG == 'customstring'
True

Assuming appengine_config.py contains the following line:

test_STRING_CONFIG = 'settingstring'

Then:

>>> config.STRING_CONFIG == custom_config.STRING_CONFIG == 'settingstring'
True
_prefix

The appengine_config prefix that the configs should appear under. Override in subclasses. The default is agar.

classmethod get_config(**kwargs)

Registers and returns the google.appengine.api.lib_config ConfigHandle for the class. Keyword arguments will override default values defined in the Config subclass (but, of course, will still defer to values in the appengine_config.py file).

Parameters:kwargs – Defaults to use for the config instance. Values in appengine_config.py will still override any values you specify.
Returns:The google.appengine.api.lib_config ConfigHandle for the class.
classmethod get_config_as_dict(**kwargs)

Registers the google.appengine.api.lib_config ConfigHandle and returns its settings as a dict. Keyword arguments will override default values defined in the Config subclass (but, of course, will still defer to values in the appengine_config.py file).

Parameters:kwargs – Defaults to use for the config instance. Values in appengine_config.py will still override any values you specify.
Returns:A dict of the configurations.

agar.counter

The agar.counter module contains classes to help work with scalable counters.

class agar.counter.WriteBehindCounter
classmethod flush_counter(name)

Flush the value of a counter.

Parameters:name – The name of the counter to flush.
classmethod get_value(name)

Returns the value of a counter.

Parameters:name – The name of the counter.
Returns:The integer value of the count.
classmethod incr(name, interval=5, value=1)

Increments a counter.

Parameters:
  • name – The name of the counter to increment.
  • interval – How frequently (in seconds) to call flush_counter().
  • value – The value to increment the counter by.
class agar.counter.TimedWriteBehindCounter
classmethod flush_counter(name, ts)

Flushes the value of the counter with the specified name and timestamp to the datastore.

Parameters:
  • name – The name of the counter to flush.
  • ts – The timestamp to get the counter value for.
classmethod get_value(name, ts)

Returns the value of a counter with a specified timestamp.

Parameters:
  • name – The name of the counter.
  • ts – The timestamp to get the counter value for.
Returns:

The integer value of the count.

classmethod incr(name, now=None, interval=5, countdown=0, value=1)

Increments a counter.

Parameters:
  • name – The name of the counter to increment.
  • interval – How frequently (in seconds) to call flush_counter().
  • countdown – The countdown for the flush_counter() task.
  • value – The value to increment the counter by.
class agar.counter.HourlyWriteBehindCounter
classmethod get_value(name, ts)

Returns the value of a counter with a specified timestamp.

Parameters:
  • name – The name of the counter.
  • ts – The timestamp to get the counter value for.
Returns:

The integer value of the count.

classmethod flush_counter(name, ts)

Flushes the value of the counter with the specified name and timestamp to the datastore.

Parameters:
  • name – The name of the counter to flush.
  • ts – The timestamp to get the counter value for.
classmethod incr(name, now=None, interval=5, countdown=0, value=1)

Increments a counter.

Parameters:
  • name – The name of the counter to increment.
  • interval – How frequently (in seconds) to call flush_counter().
  • countdown – The countdown for the flush_counter() task.
  • value – The value to increment the counter by.
class agar.counter.DailyWriteBehindCounter
classmethod get_value(name, ts)

Returns the value of a counter with a specified timestamp.

Parameters:
  • name – The name of the counter.
  • ts – The timestamp to get the counter value for.
Returns:

The integer value of the count.

classmethod flush_counter(name, ts)

Flushes the value of the counter with the specified name and timestamp to the datastore.

Parameters:
  • name – The name of the counter to flush.
  • ts – The timestamp to get the counter value for.
classmethod incr(name, now=None, interval=5, countdown=0, value=1)

Increments a counter.

Parameters:
  • name – The name of the counter to increment.
  • interval – How frequently (in seconds) to call flush_counter().
  • countdown – The countdown for the flush_counter() task.
  • value – The value to increment the counter by.

agar.dates

The agar.dates module contains a function to help work with dates.

agar.dates.parse_datetime(s)

Create datetime object representing date/time expressed in a string.

Takes a string in the format produced by calling str() on a python datetime object and returns a datetime instance that would produce that string.

Acceptable formats are:

  • YYYY-MM-DD HH:MM:SS.ssssss+HH:MM
  • YYYY-MM-DD HH:MM:SS.ssssss
  • YYYY-MM-DD HH:MM:SS+HH:MM
  • YYYY-MM-DD HH:MM:SS
  • YYYY-MM-DD

Where ssssss represents fractional seconds. The timezone is optional and may be either positive or negative hours/minutes east of UTC.

Parameters:s – The string to parse into a datetime.
Returns:The datetime represented by the given string.

agar.django

The agar.django package contains a number of general purpose utility modules containing classes, functions, and decorators to help develop with Google App Engine python and django.

agar.django.decorators

The agar.django.decorators module contains functions and decorators to help validate django forms, to be used to wrap agar.json.JsonRequestHandler methods that accept input.

agar.django.decorators.validate_service(form_class, pass_handler=False, log_errors=0, log_values=False)

A decorator that validates input matches with a django form class.

If the form is valid with the given request parameters, the decorator will add the bound form to the request under the form attribute and pass control on to the wrapped handler method.

If the form doesn’t validate, it will return a well-formed JSON response with a status code of 400 including an error dictionary describing the input errors.

Parameters:
  • form_class – The django form class to use for input validation.
  • pass_handler – If True, the decorated handler will be passed to the form __init__ method in the kwargs under the key handler.
  • log_errors – The logging level for form validation errors. Defaults to agar_django_LOG_SERVICE_VALIDATION_ERRORS (off).
  • log_valuesTrue if the raw request parameter values should be logged for fields with validation errors. Defaults to agar_django_LOG_SERVICE_VALIDATION_VALUE.

agar.django.forms

The agar.django.forms module contains form classes to help using django forms with a webapp2.Request.

class agar.django.forms.RequestForm(*args, **kwargs)

A django form class that holds a reference to the current webapp2.Request.

request

The form’s webapp2.Request.

class agar.django.forms.StrictRequestForm(*args, **kwargs)

A RequestForm that validates all passed parameters are expected by the form.

agar.django.templates

The agar.django.templates module contains function(s) to render django templates in a manner that is aware of template loaders and dirs configured in the DJANGO_SETTINGS_MODULE

agar.django.templates.render_template(response, template_path, context=None)

A helper function that renders django templates in a manner that is aware of the loaders and dirs configured in the DJANGO_SETTINGS_MODULE

Parameters:
  • template_path – the template path relative to a configured module directory
  • context – a dictionary of context attributes to referenced within the template
agar.django.templates.render_template_to_string(template_path, context={})

A helper function that renders a Django template as a string in a manner that is aware of the loaders and dirs configured in the DJANGO_SETTINGS_MODULE.

Parameters:
  • template_path – the template path relative to a configured module directory
  • context – a dictionary of context attributes to referenced within the template

agar.env

The agar.env module contains a number of constants to help determine which environment code is running in.

agar.env.on_development_server

True if running in the dev server, False otherwise.

agar.env.on_integration_server

True if running on a google server and the application ID ends in -int, False otherwise.

agar.env.on_production_server

True if running on a google server and the application ID does not end in -int, False otherwise.

agar.env.on_server

True if running on a google server, False otherwise.

agar.image

The agar.image module contains classes to help work with images stored in the Blobstore.

class agar.image.Image

A model class that helps create and work with images stored in the Blobstore. Please note that you should never call the constructor for this class directly when creating an image. Instead, use the create() method.

classmethod create(blob_info=None, data=None, filename=None, url=None, mime_type=None, parent=None, key_name=None)

Create an Image. Use this class method rather than creating an image with the constructor. You must provide one of the following parameters blob_info, data, or url to specify the image data to use.

Parameters:
  • blob_info – The Blobstore data to use as the image data. If this parameter is not None, all other parameters will be ignored as they are not needed.
  • data – The image data that should be put in the Blobstore and used as the image data.
  • filename – The filename of the image data. If not provided, the filename will be guessed from the URL or, if there is no URL, it will be set to the stringified Key of the image entity.
  • url – The URL to fetch the image data from and then place in the Blobstore to be used as the image data.
  • mime_type – The mime type to use for the Blobstore image data. If None, it will attempt to guess the mime type from the url fetch response headers or the filename.
  • parent – Inherited from Model. The Model instance or Key instance for the entity that is the new image’s parent.
  • key_name – Inherited from Model. The name for the new entity. The name becomes part of the primary key.
  • key – Inherited from Model. The explicit Key instance for the new entity. Cannot be used with key_name or parent. If None, falls back on the behavior for key_name and parent.
  • kwargs – Initial values for the instance’s properties, as keyword arguments. Useful if subclassing.
Returns:

An instance of the Image class.

blob_info

The BlobInfo entity for the image’s Blobstore value.

blob_key

The BlobKey entity for the image’s Blobstore value.

classmethod create_new_entity(**kwargs)

Called to create a new entity. The default implementation simply creates the entity with the default constructor and calls put(). This method allows the class to be mixed-in with agar.models.NamedModel.

Parameters:kwargs – Parameters to be passed to the constructor.
created

The create timestamp.

delete(**kwargs)

Delete the image and its attached Blobstore storage.

Parameters:kwargs – Parameters to be passed to parent classes delete() method.
format

The format of the image (see Image.format for possible values). If there is no image data, this will be None.

get_serving_url(size=None, crop=False)

Returns the serving URL for the image. It works just like the Image.get_serving_url function, but adds caching. The cache timeout is controlled by the SERVING_URL_TIMEOUT setting.

Parameters:
  • size – An integer supplying the size of resulting images. See Image.get_serving_url for more detailed argument information.
  • crop – Specify true for a cropped image, and false for a re-sized image. See Image.get_serving_url for more detailed argument information.
Returns:

The serving URL for the image (see Image.get_serving_url for more detailed information).

height

The height of the image in pixels (see Image.height for more documentation). If there is no image data, this will be None.

image

The Google Image entity for the image.

image_data

The raw image data as returned by a BlobReader. If there is no image data, this will be None.

modified

The last modified timestamp.

source_url

The original URL that the image data was fetched from, if applicable.

width

The width of the image in pixels (see Image.width for more documentation). If there is no image data, this will be None.

class agar.image.ImageConfig(**kwargs)

Config settings for the agar.image library. Settings are under the agar_image namespace.

The following settings (and defaults) are provided:

agar_image_SERVING_URL_TIMEOUT = 60*60
agar_image_SERVING_URL_LOOKUP_TRIES = 3
agar_image_VALID_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif']

To override agar.image settings, define values in the appengine_config.py file in the root of your project.

SERVING_URL_LOOKUP_TRIES

How many times to try to download an image from a URL (Default: 3).

SERVING_URL_TIMEOUT

How long (in seconds) to cache the image serving URL (Default: 60*60 or one hour).

VALID_MIME_TYPES

Valid image mime types (Default: ['image/jpeg', 'image/png', 'image/gif']).

agar.json

class agar.json.JsonRequestHandler(request=None, response=None)

A webapp2.RequestHandler implementation to help with json web service handlers, including error handling.

handle_exception(exception, debug_mode)

The webapp2.RequestHandler exception handler. Sets the webapp2.Response with appropriate settings.

Parameters:
  • exception – The uncaught exception.
  • debug_mode – Whether we’re running in debug mode.
json_response(model_or_query, strategy=None, status_code=200, status_text='OK', errors=None, context=None)

Fills in the webapp2.Response with the contents of the passed model or query serialized using the restler library.

Parameters:
  • model_or_query – The Model or Query to serialize.
  • strategy – The SerializationStrategy to use to serialize.
  • status_code – The HTTP status code to set in the webapp2.Response.
  • status_text – A text description of the status code.
  • errors – A dictionary of errors to add to the response.
  • context – The context to be used when serializing.
Returns:

The serialized text to be used as the HTTP response data.

class agar.json.MultiPageHandler(request=None, response=None)

A JsonRequestHandler class to help with page_size and cursor parsing and logic.

fetch_page(query)

Fetches a page of the passed query using the page_size and the cursor request parameter.

Parameters:query – The Query to fetch from.
Returns:A two-tuple containing results of the paged fetch and the next page’s cursor if there’s more results.
page_size

The requested page_size constrained between 1 and the configuration value agar_json_MAX_PAGE_SIZE. If page_size isn’t passed in, it will default to the configuration value agar_json_DEFAULT_PAGE_SIZE.

Returns:The requested page size for fetching.
class agar.json.CorsMultiPageHandler(request=None, response=None)

A MultiPageHandler to help with Cross-Origin Resource sharing .

agar.models

The agar.models module contains classes to help working with Model.

class agar.models.NamedModel(parent=None, key_name=None, _app=None, _from_entity=False, **kwds)

A base (or mix-in) Model subclass to create an entity with a key_name (either passed in or generated automatically).

This base model has a classmethod for automatically assigning a new uuid for its key_name on creation of a new entity.

classmethod create_new_entity(key_name=None, parent=None, **kwargs)

Creates and persists an entity by (optionally) generating and setting a key_name. A key_name will be generated or may be provided as a keyword arg. If a generated key_name is already in use, a new one will be generated. If, after the 3rd attempt the key_name is still not unique, a agar.models.DuplicateKeyError will be raised. This exception will also be raised if the argument key_name is not None and not unique.

Parameters:
  • key_name – Used for the entity key name, otherwise will be generated.
  • parent – Optional parent key. If not supplied, defaults to None.
  • kwargs – Initial values for the instance’s properties, as keyword arguments.
Returns:

The newly created and persisted NamedModel.

Examples:

person = Person.create_new_entity()

person_with_keyname = Person.create_new_entity(key_name='bob')
classmethod generate_key_name()

Creates a (hopefully) unique string to be used as an identifier. The default implementation uses a uuid4 hex value.

Returns:A unique string to be used as an identifier.
key_name

The entity’s key().name() unicode value if available, otherwise None.

class agar.models.DuplicateKeyError

The NamedModel tried to create an instance with a key_name that is already in use.

class agar.models.ModelException

There was an exception working with a Model while processing a agar.json.JsonRequestHandler.

agar.sessions

The agar.sessions module contains classes to assist with creating webapp2.RequestHandler s.

class agar.sessions.SessionRequestHandler(request=None, response=None)

A webapp2.RequestHandler implementation that provides access to a session via the session attribute..

dispatch()

Dispatches the request after grabbing the session_store and providing access to the current webapp2.Request ‘s session.

This will first check if there’s a handler_method defined in the matched route, and if not it’ll use the method correspondent to the request method (get(), post() etc).

session

Returns a session using the default cookie key.

class agar.sessions.SessionStore(request)

A webapp2_extras.sessions.SessionStore implementation that uses Webapp2ExtrasSessionsConfig instead of the built-in webapp2 config library.

class agar.sessions.Webapp2ExtrasSessionsConfig(**kwargs)

Config settings for the webapp2_extras.sessions library. Settings are under the webapp2_extras_sessions namespace.

The following settings (and defaults) are provided:

cookie_args = {
    'max_age': None,
    'domain': None,
    'secure': None,
    'httponly': False,
    'path': '/'
}
secret_key = None,
cookie_name = 'session'
session_max_age = None
backends = {
    'datastore': 'webapp2_extras.appengine.sessions_ndb.DatastoreSessionFactory',
    'memcache': 'webapp2_extras.appengine.sessions_memcache.MemcacheSessionFactory',
    'securecookie': 'webapp2_extras.sessions.SecureCookieSessionFactory'
}

To override webapp2_extras.sessions settings, define values in the appengine_config.py file in the root of your project.

classmethod get_webapp2_config(config=None, **kwargs)

Registers the google.appengine.api.lib_config ConfigHandle and returns its settings as a webapp2 configuration dict with the webapp2_extras.sessions configurations under the key webap2_extras.sessions. Keyword arguments will override default values defined in the Config subclass (but, of course, will still defer to values in the appengine_config.py file).

Parameters:
  • config – If None (the default), the method will return a new dict with the single configuration key webap2_extras.sessions. If this is parameter is a dict, the new key will be added to the passed dict and returned.
  • kwargs – Defaults to use for the config instance. Values in appengine_config.py will still override any values you specify.
Returns:

A dict of the configurations.

agar.sessions.config

The google.appengine.api.lib_config ConfigHandle for webapp2_extras_sessions settings.

agar.templatetags

agar.templatetags.webapp2.url_for

Returns a URL matching given the route name with its parameters.

See uri_for() for more detailed parameter information.

For example:

{% uri_for route_name arg1,arg2,name1=value1 %}

{% uri_for get_client id=client.id %}

{% uri_for get_client id=client.id,_full=True %}
agar.templatetags.webapp2.on_production_server

Returns whether the code is running on a production server. See on_production_server() for more information.

Returns:True if running on a production server, False otherwise.
agar.templatetags.webapp2.create_logout_url

Inserts a Google Account logout url.

agar.test

The agar.test package contains helpers for unit testing your application.

class agar.test.BaseTest(methodName='runTest')

A base class for App Engine unit tests that sets up API proxy stubs for all available services using testbed and clears them between each test run.

Note: the images stub is only set up if PIL is found.

To use, simply inherit from BaseTest:

import agar

from models import MyModel

class MyTestCase(agar.test.BaseTest):

    def test_datastore(self):
        model = MyModel(foo='foo')
        model.put()

        # will always be true because the datastore is cleared
        # between test method runs.
        self.assertEqual(1, MyModel.all().count())

BaseTest is designed to be mostly API-compatable with gaetestbed‘s assertions. However, unlike gaetestbed, the assertions are split into only two classes: BaseTest and WebTest.

assertEmailNotSent(to=None, sender=None, subject=None, body=None, html=None)

Assert that no email was sent with the specified criteria.

Parameters:
  • to – the To: email address.
  • sender – the From: email address.
  • subject – the value of the Subject:.
  • body – the value of the body of the email.
  • html – the value of the HTML body of the email.
assertEmailSent(to=None, sender=None, subject=None, body=None, html=None)

Assert that at least one email was sent with the specified criteria.

Note that App Engine does not allow emails to be sent from non-administrative users of the application. This method cannot check for that.

Examples:

mail.send_mail(to='test@example.com',
               subject='hello world',
               sender='foobar@example.com',
               body='I can has email?')
self.assertEmailSent()
self.assertEmailSent(to='test@example.com')
# this will fail
self.assertEmailSent(to='foobar@example.com')
Parameters:
  • to – the To: email address.
  • sender – the From: email address.
  • subject – the value of the Subject:.
  • body – the value of the body of the email.
  • html – the value of the HTML body of the email.
assertEmpty(iterable)

Assert that iterable is of length 0. Equivalent to self.assertLength(0, iterable).

assertLength(expected, iterable, message=None)

Assert that iterable is of length expected.

NOTE: This assertion uses the standard xUnit (expected, actual) order for parameters. However, this is the reverse of gaetestbed.

Parameters:
  • expected – an integer representing the expected length
  • iterable – an iterable which will be converted to a list.
  • message – optional message for assertion.
assertMemcacheHits(hits)

Asserts that the memcache API has had hits successful lookups.

Parameters:hits – number of memcache hits
assertMemcacheItems(items)

Asserts that the memcache API has items key-value pairs.

Parameters:items – number of items in memcache
assertTasksInQueue(n=None, url=None, name=None, queue_names=None)

Search for Task objects matching the given criteria and assert that there are n tasks.

Example:

deferred.defer(some_task, _name='some_task')
self.assertTasksInQueue(n=1, name='some_task')
Parameters:
  • n – the number of tasks in the queue. If not specified, n defaults to 0.
  • url – URL criteria tasks must match. If url is None, all tasks will be matched.
  • name – name criteria tasks must match. If name is None, all tasks will be matched.
  • queue_names – queue name criteria tasks must match. If queue_name is None tasks in all queues will be matched.
clear_datastore()

Clear the Data Store of all its data.

This method can be used inside your tests to clear the Data Store mid-test.

For example:

import unittest

from agar.test import BaseTest

class MyTestCase(BaseTest):
    def test_clear_datastore(self):
        # Add something to the Data Store
        models.MyModel(field="value").put()
        self.assertLength(models.MyModel.all(), 1)

        # And then empty the Data Store
        self.clear_datastore()
        self.assertLength(models.MyModel.all(), 0)
get_sent_messages(to=None, sender=None, subject=None, body=None, html=None)

Return a list of email messages matching the given criteria.

Parameters:
  • to – the To: email address.
  • sender – the From: email address.
  • subject – the value of the Subject:.
  • body – the value of the body of the email.
  • html – the value of the HTML body of the email.
get_tasks(url=None, name=None, queue_names=None)

Returns a list of Task objects with the specified criteria.

Parameters:
  • url – URL criteria tasks must match. If url is None, all tasks will be matched.
  • name – name criteria tasks must match. If name is None, all tasks will be matched.
  • queue_names – queue name criteria tasks must match. If queue_name is None tasks in all queues will be matched.
log_in_user(email)

Log in a User with the given email address. This will cause users.get_current_user to return a User with the same email address and user_id as if it was entered into the SDK’s log in prompt.

class agar.test.MockUrlfetchTest(methodName='runTest')

MockUrlfetchTest replaces the urlfetch API stub with a mocked version that does not make real HTTP requests.

To use it, inherit from MockUrlfetchTest instead of BaseTest, then register HTTP responses in your setUp method, or individual test case methods.

If any of the code under test results in urlfetch call to an unregistered URL, it will raise an exception.

Example:

class MyHTTPTest(MockUrlfetchTest):
    def setUp(self):
        super(MyHTTPTest, self).setUp()

        self.set_response("http://www.google.com/blah", content="foobar", status_code=404)

    def test_get_google(self):
        result = urlfetch.fetch("http://www.google.com/blah")

        self.assertEqual(404, result.status_code)
        self.assertEqual("foobar", result.content)

    def test_this_will_fail(self):
        result = urlfetch.fetch("http://www.example.com/")
set_response(url, content=None, status_code=None, headers=None, method=None)

Register an HTTP response for url with body containing content.

NOTE: MockUrlfetchTest does not follow redirects at this time.

Examples:

# Will cause a 200 OK response with no body for all HTTP methods:
self.set_response("http://example.com")

# Will cause a 404 Not Found for GET requests with 'gone fishing' as the body:
self.set_response("http://example.com/404ed", content='gone fishing', status_code=404)

# Will cause a 303 See Other for POST requests with a Location header and no body:
self.set_response("http://example.com/posts", status_code=303, headers={'Location': 'http://example.com/posts/123'})

# Will cause a DownloadError to be raised when the URL is requested:
from google.appengine.api import urlfetch
self.set_response("http://example.com/boom", content=urlfetch.DownloadError("Something Failed"))
Parameters:
  • url – the URL for the HTTP request.
  • content – the HTTP response’s body, or an instance of DownloadError to simulate a failure.
  • status_code – the expected status code. Defaults to 200 if not set.
  • headers – a dict of headers for the HTTP response.
  • method – the HTTP method that the response must match. If not set, all requests with the same URL will return the same thing.
class agar.test.WebTest(methodName='runTest')

A base class for testing web requests. Provides a wrapper around the WebTest package that is mostly compatable with gaetestbed‘s.

To use, inherit from WebTest and define a class-level variable called APPLICATION that is set to the WSGI application under test.

WebTest is usually used in conjuction with BaseTest to set up the App Engine API proxy stubs.

Example:

from agar.test import BaseTest, WebTest
import my_app

class TestMyApp(BaseTest, WebTest):

    APPLICATION = my_app.application

    def test_get_home_page(self):
        response = self.get("/")
        self.assertOK(response)
assertBadRequest(response)

Assert that response was 400 Bad Request.

assertForbidden(response)

Assert that response was 403 Forbidden.

assertNotFound(response)

Assert that response was 404 Not Found.

assertOK(response)

Assert that response was 200 OK.

assertRedirects(response, to=None)

Assert that response was a 302 redirect.

Parameters:to – an absolute or relative URL that the redirect must match.
assertUnauthorized(response, challenge=None)

Assert that response was 401 Unauthorized.

Parameters:challenge – assert that the WWW-Authenticate header matches this value, if provided

agar.url

The agar.url module contains classes to help working with application-wide URLs.

agar.url.uri_for(name, *args, **kwargs)

A wrapper around the webapp2.uri_for function that will search all applications defined in the agar_url_APPLICATIONS configuration.

Parameters:
  • name – The route name.
  • args – Tuple of positional arguments to build the URI. All positional variables defined in the route must be passed and must conform to the format set in the route. Extra arguments are ignored.
  • kwargs

    Dictionary of keyword arguments to build the URI. All variables not set in the route default values must be passed and must conform to the format set in the route. Extra keywords are appended as a query string.

    A few keywords have special meaning:
    • request: This should be the current webapp2.Request. If not passed, it will look up the current request from the webapp2.WSGIApplication instance.
    • owned_domain: If True and _full is True and _netloc is None and on_production_server() is True, the absolute URI returned will use the agar_url_PRODUCTION_DOMAIN setting for the host rather than the value from the webapp2.Request.
    • _full: If True, builds an absolute URI. Defaults to False.
    • _scheme: URI scheme, e.g., http or https. If defined, an absolute URI is always returned.
    • _netloc: Network location, e.g., www.google.com. If defined, an absolute URI is always returned.
    • _fragment: If set, appends a fragment (or “anchor”) to the generated URI.
Returns:

An absolute or relative URI.

class agar.url.UrlConfig(**kwargs)

Config settings for the agar.url library. Settings are under the agar_url namespace.

The following settings (and defaults) are provided:

agar_url_DEBUG = False
agar_url_PRODUCTION_DOMAIN = ''
agar_url_APPLICATIONS = ['main']

To override agar.url settings, define values in the appengine_config.py file in the root of your project.