def test_notification_number_collision(self, next_number_for_team): # Simulate a potential race condition where we create notifications in # different threads. We should still get unique, increasing, # notification numbers and not get Integrity Errors next_number_for_team.return_value = 1 team = TeamFactory() notification1 = TeamNotification.create_new(team, 'http://example.com', {'foo': 'bar'}) # This next create_new() will try to save the same number as the # first. It should recover from the IntegrityError notification2 = TeamNotification.create_new(team, 'http://example.com', {'foo': 'bar'}) assert_equal(notification1.number, 1) assert_equal(notification2.number, 2) # check that the number is stored correctly in the data assert_equal(json.loads(notification1.data)['number'], 1) assert_equal(json.loads(notification2.data)['number'], 2)
def test_create_new(TestCase): team = TeamFactory() notification = TeamNotification.create_new(team, 'http://example.com', {'foo': 'bar'}) assert_equal(json.loads(notification.data), { 'foo': 'bar', 'number': notification.number, })
def do_http_post(team_id, url, data, headers, auth_username, auth_password): """Handle the HTTP POST for a notifaction This function also handles creating the TeamNotification object associated with the request. It operates inside a task so that the network call doesn't block the web app process. Args: team_id: PK of the Team this notification is for url: URL to POST to data: array of primitive data to JSON-encode and send. We will also add the number field, which will store the number of the associated TeamNotification. headers: extra headers to add to the request auth_username: authentication to send with the request auth_password: authentication to send with the request """ if auth_username: auth = HTTPBasicAuth(auth_username, auth_password) else: auth = None notification = TeamNotification.create_new(team_id, url, data) post_data = data.copy() post_data['number'] = notification.number headers.update({ 'Content-type': 'application/json', }) status_code = None error_message = None try: response = requests.post(url, data=json.dumps(post_data), headers=headers, auth=auth) except requests.ConnectionError: notification.error_message = "Connection error" except requests.Timeout: notification.error_message = "Request timeout" except requests.TooManyRedirects: notification.error_message = "Too many redirects" else: notification.response_status = response.status_code if response.status_code != 200: notification.error_message = 'Response status: {}'.format( response.status_code) notification.save()
def make_notification(): return TeamNotification.create_new(team, 'http://example.com', {'foo': 'bar'})
def test_create_new_with_team_id(TestCase): team = TeamFactory() notification = TeamNotification.create_new(team.id, 'http://example.com', {'foo': 'bar'}) assert_equal(notification.team, team)