<commit_before># -*- coding: utf-8 -*-

# Standard library imports
# Third party imports
from django.core.urlresolvers import reverse
from django.db.models import get_model
from guardian.shortcuts import assign_perm
from guardian.utils import get_anonymous_user

# Local application / specific library imports
from machina.apps.conversation.signals import topic_viewed
from machina.core.loading import get_class
from machina.test.factories import create_forum
from machina.test.factories import create_topic
from machina.test.factories import ForumReadTrackFactory
from machina.test.factories import PostFactory
from machina.test.factories import TopicReadTrackFactory
from machina.test.testcases import BaseClientTestCase
from machina.test.utils import mock_signal_receiver

ForumReadTrack = get_model('tracking', 'ForumReadTrack')
Post = get_model('conversation', 'Post')
Topic = get_model('conversation', 'Topic')
TopicReadTrack = get_model('tracking', 'TopicReadTrack')

PermissionHandler = get_class('permission.handler', 'PermissionHandler')

class TestTopicView(BaseClientTestCase):
    def setUp(self):
        super(TestTopicView, self).setUp()

        # Permission handler
        self.perm_handler = PermissionHandler()

        # Set up a top-level forum and a link forum
        self.top_level_forum = create_forum()

        # Set up a topic and some posts
        self.topic = create_topic(forum=self.top_level_forum, poster=self.user)
        self.post = PostFactory.create(topic=self.topic, poster=self.user)

        # Mark the forum as read
        ForumReadTrackFactory.create(forum=self.top_level_forum, user=self.user)

        # Assign some permissions
        assign_perm('can_read_forum', self.user, self.top_level_forum)

    def test_browsing_works(self):
        # Setup
        correct_url = self.topic.get_absolute_url()
        # Run
        response = self.client.get(correct_url, follow=True)
        # Check
        self.assertIsOk(response)

    def test_triggers_a_viewed_signal(self):
        # Setup
        correct_url = self.topic.get_absolute_url()
        # Run & check
        with mock_signal_receiver(topic_viewed) as receiver:
            self.client.get(correct_url, follow=True)
            self.assertEqual(receiver.call_count, 1)

    def test_increases_the_views_counter_of_the_topic(self):
        # Setup
        correct_url = self.topic.get_absolute_url()
        initial_views_count = self.topic.views_count
        # Run
        self.client.get(correct_url)
        # Check
        topic = self.topic.__class__._default_manager.get(pk=self.topic.pk)
        self.assertEqual(topic.views_count, initial_views_count + 1)

    def test_cannot_change_the_updated_date_of_the_topic(self):
        # Setup
        correct_url = self.topic.get_absolute_url()
        initial_updated_date = self.topic.updated
        # Run
        self.client.get(correct_url)
        # Check
        topic = self.topic.__class__._default_manager.get(pk=self.topic.pk)
        self.assertEqual(topic.updated, initial_updated_date)

    def test_marks_the_related_forum_as_read_if_no_other_unread_topics_are_present(self):
        # Setup
        new_topic = create_topic(forum=self.top_level_forum, poster=self.user)
        PostFactory.create(topic=new_topic, poster=self.user)
        TopicReadTrackFactory.create(topic=new_topic, user=self.user)
        TopicReadTrackFactory.create(topic=self.topic, user=self.user)
        PostFactory.create(topic=self.topic, poster=self.user)
        correct_url = self.topic.get_absolute_url()
        # Run
        self.client.get(correct_url)
        # Check
        forum_tracks = ForumReadTrack.objects.all()
        topic_tracks = TopicReadTrack.objects.all()
        self.assertEqual(forum_tracks.count(), 1)
        self.assertFalse(len(topic_tracks))
        self.assertEqual(forum_tracks[0].forum, self.topic.forum)
        self.assertEqual(forum_tracks[0].user, self.user)

    def test_marks_the_related_topic_as_read_if_other_unread_topics_are_present(self):
        # Setup
        new_topic = create_topic(forum=self.top_level_forum, poster=self.user)
        PostFactory.create(topic=new_topic, poster=self.user)
        PostFactory.create(topic=self.topic, poster=self.user)
        correct_url = self.topic.get_absolute_url()
        # Run
        self.client.get(correct_url)
        # Check
        topic_tracks = TopicReadTrack.objects.all()
        self.assertEqual(topic_tracks.count(), 1)
        self.assertEqual(topic_tracks[0].topic, self.topic)
        self.assertEqual(topic_tracks[0].user, self.user)

    def test_cannot_create_any_track_if_the_user_is_not_authenticated(self):
        # Setup
        ForumReadTrack.objects.all().delete()
        assign_perm('can_read_forum', get_anonymous_user(), self.top_level_forum)
        self.client.logout()
        correct_url = self.topic.get_absolute_url()
        # Run
        self.client.get(correct_url)
        # Check
        forum_tracks = ForumReadTrack.objects.all()
        topic_tracks = TopicReadTrack.objects.all()
        self.assertFalse(len(forum_tracks))
        self.assertFalse(len(topic_tracks))

    def test_can_paginate_based_on_a_post_id(self):
        # Setup
        for _ in range(0, 40):
            # 15 posts per page
            PostFactory.create(topic=self.topic, poster=self.user)
        correct_url = self.topic.get_absolute_url()
        # Run & check
        first_post_pk = self.topic.first_post.pk
        response = self.client.get(correct_url, {'post': first_post_pk}, follow=True)
        self.assertEqual(response.context_data['page_obj'].number, 1)
        mid_post_pk = self.topic.first_post.pk + 18
        response = self.client.get(correct_url, {'post': mid_post_pk}, follow=True)
        self.assertEqual(response.context_data['page_obj'].number, 2)
        last_post_pk = self.topic.last_post.pk
        response = self.client.get(correct_url, {'post': last_post_pk}, follow=True)
        self.assertEqual(response.context_data['page_obj'].number, 3)

    def test_properly_handles_a_bad_post_id_in_parameters(self):
        # Setup
        for _ in range(0, 40):
            # 15 posts per page
            PostFactory.create(topic=self.topic, poster=self.user)
        correct_url = self.topic.get_absolute_url()
        # Run & check
        bad_post_pk = self.topic.first_post.pk + 50000
        response = self.client.get(correct_url, {'post': bad_post_pk}, follow=True)
        self.assertEqual(response.context_data['page_obj'].number, 1)
        response = self.client.get(correct_url, {'post': 'I\'m a post'}, follow=True)
        self.assertEqual(response.context_data['page_obj'].number, 1)

class TestTopicCreateView(BaseClientTestCase):
    def setUp(self):
        super(TestTopicCreateView, self).setUp()

        # Permission handler
        self.perm_handler = PermissionHandler()

        # Set up a top-level forum and a link forum
        self.top_level_forum = create_forum()

        # Set up a topic and some posts
        self.topic = create_topic(forum=self.top_level_forum, poster=self.user)
        self.post = PostFactory.create(topic=self.topic, poster=self.user)

        # Mark the forum as read
        ForumReadTrackFactory.create(forum=self.top_level_forum, user=self.user)

        # Assign some permissions
        assign_perm('can_read_forum', self.user, self.top_level_forum)
        assign_perm('can_start_new_topics', self.user, self.top_level_forum)

    def test_browsing_works(self):
        # Setup
        correct_url = reverse('conversation:topic-create', kwargs={'forum_pk': self.top_level_forum.pk})
        # Run
        response = self.client.get(correct_url, follow=True)
        # Check
        self.assertIsOk(response)

    def test_pembed_the_current_forum_into_the_context(self):
        # Setup
        correct_url = reverse('conversation:topic-create', kwargs={'forum_pk': self.top_level_forum.pk})
        # Run
        response = self.client.get(correct_url, follow=True)
        # Check
        self.assertEqual(response.context_data['forum'], self.top_level_forum)
<commit_msg>'conversation' functional tests updated<commit_after># -*- coding: utf-8 -*-

# Standard library imports
# Third party imports
from django.core.urlresolvers import reverse
from django.db.models import get_model
from guardian.shortcuts import assign_perm
from guardian.utils import get_anonymous_user

# Local application / specific library imports
from machina.apps.conversation.abstract_models import TOPIC_TYPES
from machina.apps.conversation.signals import topic_viewed
from machina.core.loading import get_class
from machina.test.factories import create_forum
from machina.test.factories import create_topic
from machina.test.factories import ForumReadTrackFactory
from machina.test.factories import PostFactory
from machina.test.factories import TopicReadTrackFactory
from machina.test.testcases import BaseClientTestCase
from machina.test.utils import mock_signal_receiver

ForumReadTrack = get_model('tracking', 'ForumReadTrack')
Post = get_model('conversation', 'Post')
Topic = get_model('conversation', 'Topic')
TopicReadTrack = get_model('tracking', 'TopicReadTrack')

PermissionHandler = get_class('permission.handler', 'PermissionHandler')

class TestTopicView(BaseClientTestCase):
    def setUp(self):
        super(TestTopicView, self).setUp()

        # Permission handler
        self.perm_handler = PermissionHandler()

        # Set up a top-level forum and a link forum
        self.top_level_forum = create_forum()

        # Set up a topic and some posts
        self.topic = create_topic(forum=self.top_level_forum, poster=self.user)
        self.post = PostFactory.create(topic=self.topic, poster=self.user)

        # Mark the forum as read
        ForumReadTrackFactory.create(forum=self.top_level_forum, user=self.user)

        # Assign some permissions
        assign_perm('can_read_forum', self.user, self.top_level_forum)

    def test_browsing_works(self):
        # Setup
        correct_url = self.topic.get_absolute_url()
        # Run
        response = self.client.get(correct_url, follow=True)
        # Check
        self.assertIsOk(response)

    def test_triggers_a_viewed_signal(self):
        # Setup
        correct_url = self.topic.get_absolute_url()
        # Run & check
        with mock_signal_receiver(topic_viewed) as receiver:
            self.client.get(correct_url, follow=True)
            self.assertEqual(receiver.call_count, 1)

    def test_increases_the_views_counter_of_the_topic(self):
        # Setup
        correct_url = self.topic.get_absolute_url()
        initial_views_count = self.topic.views_count
        # Run
        self.client.get(correct_url)
        # Check
        topic = self.topic.__class__._default_manager.get(pk=self.topic.pk)
        self.assertEqual(topic.views_count, initial_views_count + 1)

    def test_cannot_change_the_updated_date_of_the_topic(self):
        # Setup
        correct_url = self.topic.get_absolute_url()
        initial_updated_date = self.topic.updated
        # Run
        self.client.get(correct_url)
        # Check
        topic = self.topic.__class__._default_manager.get(pk=self.topic.pk)
        self.assertEqual(topic.updated, initial_updated_date)

    def test_marks_the_related_forum_as_read_if_no_other_unread_topics_are_present(self):
        # Setup
        new_topic = create_topic(forum=self.top_level_forum, poster=self.user)
        PostFactory.create(topic=new_topic, poster=self.user)
        TopicReadTrackFactory.create(topic=new_topic, user=self.user)
        TopicReadTrackFactory.create(topic=self.topic, user=self.user)
        PostFactory.create(topic=self.topic, poster=self.user)
        correct_url = self.topic.get_absolute_url()
        # Run
        self.client.get(correct_url)
        # Check
        forum_tracks = ForumReadTrack.objects.all()
        topic_tracks = TopicReadTrack.objects.all()
        self.assertEqual(forum_tracks.count(), 1)
        self.assertFalse(len(topic_tracks))
        self.assertEqual(forum_tracks[0].forum, self.topic.forum)
        self.assertEqual(forum_tracks[0].user, self.user)

    def test_marks_the_related_topic_as_read_if_other_unread_topics_are_present(self):
        # Setup
        new_topic = create_topic(forum=self.top_level_forum, poster=self.user)
        PostFactory.create(topic=new_topic, poster=self.user)
        PostFactory.create(topic=self.topic, poster=self.user)
        correct_url = self.topic.get_absolute_url()
        # Run
        self.client.get(correct_url)
        # Check
        topic_tracks = TopicReadTrack.objects.all()
        self.assertEqual(topic_tracks.count(), 1)
        self.assertEqual(topic_tracks[0].topic, self.topic)
        self.assertEqual(topic_tracks[0].user, self.user)

    def test_cannot_create_any_track_if_the_user_is_not_authenticated(self):
        # Setup
        ForumReadTrack.objects.all().delete()
        assign_perm('can_read_forum', get_anonymous_user(), self.top_level_forum)
        self.client.logout()
        correct_url = self.topic.get_absolute_url()
        # Run
        self.client.get(correct_url)
        # Check
        forum_tracks = ForumReadTrack.objects.all()
        topic_tracks = TopicReadTrack.objects.all()
        self.assertFalse(len(forum_tracks))
        self.assertFalse(len(topic_tracks))

    def test_can_paginate_based_on_a_post_id(self):
        # Setup
        for _ in range(0, 40):
            # 15 posts per page
            PostFactory.create(topic=self.topic, poster=self.user)
        correct_url = self.topic.get_absolute_url()
        # Run & check
        first_post_pk = self.topic.first_post.pk
        response = self.client.get(correct_url, {'post': first_post_pk}, follow=True)
        self.assertEqual(response.context_data['page_obj'].number, 1)
        mid_post_pk = self.topic.first_post.pk + 18
        response = self.client.get(correct_url, {'post': mid_post_pk}, follow=True)
        self.assertEqual(response.context_data['page_obj'].number, 2)
        last_post_pk = self.topic.last_post.pk
        response = self.client.get(correct_url, {'post': last_post_pk}, follow=True)
        self.assertEqual(response.context_data['page_obj'].number, 3)

    def test_properly_handles_a_bad_post_id_in_parameters(self):
        # Setup
        for _ in range(0, 40):
            # 15 posts per page
            PostFactory.create(topic=self.topic, poster=self.user)
        correct_url = self.topic.get_absolute_url()
        # Run & check
        bad_post_pk = self.topic.first_post.pk + 50000
        response = self.client.get(correct_url, {'post': bad_post_pk}, follow=True)
        self.assertEqual(response.context_data['page_obj'].number, 1)
        response = self.client.get(correct_url, {'post': 'I\'m a post'}, follow=True)
        self.assertEqual(response.context_data['page_obj'].number, 1)

class TestTopicCreateView(BaseClientTestCase):
    def setUp(self):
        super(TestTopicCreateView, self).setUp()

        # Permission handler
        self.perm_handler = PermissionHandler()

        # Set up a top-level forum and a link forum
        self.top_level_forum = create_forum()

        # Set up a topic and some posts
        self.topic = create_topic(forum=self.top_level_forum, poster=self.user)
        self.post = PostFactory.create(topic=self.topic, poster=self.user)

        # Mark the forum as read
        ForumReadTrackFactory.create(forum=self.top_level_forum, user=self.user)

        # Assign some permissions
        assign_perm('can_read_forum', self.user, self.top_level_forum)
        assign_perm('can_start_new_topics', self.user, self.top_level_forum)

    def test_browsing_works(self):
        # Setup
        correct_url = reverse('conversation:topic-create', kwargs={'forum_pk': self.top_level_forum.pk})
        # Run
        response = self.client.get(correct_url, follow=True)
        # Check
        self.assertIsOk(response)

    def test_embed_the_current_forum_into_the_context(self):
        # Setup
        correct_url = reverse('conversation:topic-create', kwargs={'forum_pk': self.top_level_forum.pk})
        # Run
        response = self.client.get(correct_url, follow=True)
        # Check
        self.assertEqual(response.context_data['forum'], self.top_level_forum)

    def test_can_detect_that_a_preview_should_be_done(self):
        # Setup
        correct_url = reverse('conversation:topic-create', kwargs={'forum_pk': self.top_level_forum.pk})
        post_data = {
            'subject': 'My topic',
            'content': '[b]This is my topic[/b]',
            'topic_type': TOPIC_TYPES.topic_post,
            'preview': 'Preview',
        }
        # Run
        response = self.client.post(correct_url, post_data, follow=True)
        # Check
        self.assertTrue(response.context_data['preview'])
<|endoftext|>


<commit_before>#!/usr/bin/python3
"""
A Machine learning algorithm for K Nearest Neighbor.
Date: 17th Feb, 2015 8:51 am

Suppose we have data from some survey (that asks people’s opinions)
on whether certain toilet papers are good or bad.
The toilet papers have two attributes (acid durability and strength)

TASK:
 We want to determine whether a toilet paper with attributes X1=3 and X2= 7 is GOOD or BAD

 Given:
 {
 		Acid Durability(seconds),	strength, Classification
 		7, 7, bad
 		7, 4, bad
 		3, 4, good
 }
"""
__author__ = "Denis Karanja"
__version__ = "1.0.0"

import collections

def get_coordinates(points):
	#get coordinates for the points given in tuple form
	'''
	@param -> tuple
	@return -> list of tuples
	'''
	print("Please provide coordinates for the {} training set. (x, y, label)".format(points))
	coordinates = []

	for coords in range(points):
		#read as a tuple i.e (x, y)
		user_coords = input()
		user_coords = user_coords.split(',')
		x, y, label = int(user_coords[0]), int(user_coords[1]), user_coords[2]

		coordinates.append((x, y, label))

	return coordinates

def get_coords(file_name):
	'''Gets coordinates form a file'''
	file_handle = open(file_name, "r")
	for coords in file_handle:
		pass

def add_set(file_name, coords_list):
	'''Writes coodinates to file. As part of the learning set'''
	file_handle = open(file_name, "a")
	array = ''
	file_handle.write(str((coords_list[0])))

def distance_apart(query_instance, training_set, cluster_size, file_name):
	'''
	Determines how far a query set is from the training set
	@params -> tuple, list of tuples, int, string(file_name)
	@return -> tuple
	'''
	assert type(training_set) is list
	assert type(query_instance) is tuple
	assert type(cluster_size) is int

	distance = []
	x_query, y_query = query_instance

	for value in training_set:
		x_train_set, y_train_set, label = value
		dist = ((x_train_set - x_query) ** 2) + ((y_train_set - y_query) ** 2)
		distance.append((dist, label))

	#get the K nearest neigbours
	distance = sorted(distance)[:cluster_size]
	print(distance)
	#get all labels only in the K nearest neigbours
	final_label = []
	for result in distance:
		score, k_label = result
		final_label.append(k_label)

	#get frequecies of labels
	conc_array = []
	label_freq = collections.Counter(final_label)
	query_label = (max(label_freq, key = label_freq.get), )
	conclusion = query_instance + query_label
	conc_array.append(conclusion)

	#add set to learning set
	add_set(file_name, conc_array)

	return conclusion, "Set added to {}".format(file_name)

if __name__ == "__main__":
	query, training, cluster_size, file_name = (5, 6), [(7, 7, 'bad'), (7, 4, 'bad'), (3, 4, 'good'), (1, 4, 'good')], 3, "../data_files/knn.txt"
	print(distance_apart(query, training, cluster_size, file_name ))
	#print(get_coords("data_files/knn.txt"))
	<commit_msg>Code: read_csv() function and create 70% training set and 30% query set from the heart.data.csv file<commit_after>#!/usr/bin/python3
"""
A Machine learning algorithm for K Nearest Neighbor.
Date: 17th Feb, 2015 8:51 am

Suppose we have data from some survey (that asks people’s opinions)
on whether certain toilet papers are good or bad.
The toilet papers have two attributes (acid durability and strength)

TASK:
 We want to determine whether a toilet paper with attributes X1=3 and X2= 7 is GOOD or BAD

 Given:
 {
 		Acid Durability(seconds),	strength, Classification
 		7, 7, bad
 		7, 4, bad
 		3, 4, good
 }
"""
__author__ = "Denis Karanja"
__version__ = "1.0.0"

import collections, csv

def get_coordinates(points):
	#get coordinates for the points given in tuple form
	'''
	@param -> tuple
	@return -> list of tuples
	'''
	print("Please provide coordinates for the {} training set. (x, y, label)".format(points))
	coordinates = []

	for coords in range(points):
		#read as a tuple i.e (x, y)
		user_coords = input()
		user_coords = user_coords.split(',')
		x, y, label = int(user_coords[0]), int(user_coords[1]), user_coords[2]

		coordinates.append((x, y, label))

	return coordinates

def get_coords(file_name):
	'''Gets coordinates form a file'''
	file_handle = open(file_name, "r")
	for coords in file_handle:
		pass

def add_set(file_name, coords_list):
	'''Writes coodinates to file. As part of the learning set'''
	file_handle = open(file_name, "a")
	array = ''
	file_handle.write(str((coords_list[0])))

def distance_apart(query_instance, training_set, cluster_size, file_name):
	'''
	Determines how far a query set is from the training set
	@params -> tuple, list of tuples, int, string(file_name)
	@return -> tuple
	'''
	assert type(training_set) is list
	assert type(query_instance) is tuple
	assert type(cluster_size) is int

	distance = []
	x_query, y_query = query_instance

	for value in training_set:
		x_train_set, y_train_set, label = value
		dist = ((x_train_set - x_query) ** 2) + ((y_train_set - y_query) ** 2)
		distance.append((dist, label))

	#get the K nearest neigbours
	distance = sorted(distance)[:cluster_size]
	print(distance)
	#get all labels only in the K nearest neigbours
	final_label = []
	for result in distance:
		score, k_label = result
		final_label.append(k_label)

	#get frequecies of labels
	conc_array = []
	label_freq = collections.Counter(final_label)
	query_label = (max(label_freq, key = label_freq.get), )
	conclusion = query_instance + query_label
	conc_array.append(conclusion)

	#add set to learning set
	add_set(file_name, conc_array)

	return conclusion, "Set added to {}".format(file_name)

def read_csv(filename):
	'''
	Read from a csv file
	@params -> String(Filename)
	@return coordinates
	'''
	from_file = []
	with open(filename) as data:
		reader = csv.reader(data)

		for stuff in reader:
			stuff = stuff[0:13]
			from_file.append(stuff)

	data_length = len(from_file)
	# 70% training set, 30% query set
	training_set_len = int(0.7 * data_length)
	query_set_len = int(0.3 * data_length)

	training_set = from_file[0: training_set_len]
	query_set = from_file[training_set_len:]

	#write to training set
	with open("training.csv", "w") as train_set:
		writer = csv.writer(train_set, delimiter = ",")
		writer.writerows(training_set)

	# write to query set
	with open("query.csv", "w") as query_instance:
		writer = csv.writer(query_instance, delimiter = ",")
		writer.writerows(query_set)

	return

if __name__ == "__main__":
	query, training, cluster_size, file_name = (5, 6), [(7, 7, 'bad'), (7, 4, 'bad'), (3, 4, 'good'), (1, 4, 'good')], 3, "../data_files/knn.txt"
	#print(distance_apart(query, training, cluster_size, file_name ))
	#print(get_coords("data_files/knn.txt"))
	print(read_csv("../data_files/csv/heart.data.csv"))
	<|endoftext|>


<commit_before>from __future__ import with_statement

try:
    import json
except ImportError:
    import simplejson as json

import unittest
import logging
import sys

from remoteobjects import tests
import typepad

class TestRemoteObjects(unittest.TestCase):

    def mockHttp(self, *args, **kwargs):
        if 'credentials' in kwargs:
            del kwargs['credentials']
        return tests.MockedHttp(*args, **kwargs)

    def testUser(self):
        content = """{"displayName": "Deanna Conti", "email": "dconti@beli.com"}"""
        headers = { 'accept': 'application/json' }
        with self.mockHttp('http://127.0.0.1:8000/users/1.json', content, headers=headers) as h:
            user = typepad.User.get('http://127.0.0.1:8000/users/1.json', http=h)
            self.assertEquals(user.display_name, 'Deanna Conti')
            self.assertEquals(user.email, 'dconti@beli.com')

    def testGroup(self):
        content = """{"displayName": "Augue Tempor"}"""
        headers = { 'accept': 'application/json' }
        with self.mockHttp('http://127.0.0.1:8000/groups/1.json', content, headers=headers) as h:
            group = typepad.Group.get('http://127.0.0.1:8000/groups/1.json', http=h)
            self.assertEquals(group.display_name, 'Augue Tempor')

    def testGroupMembers(self):
        g = typepad.Group()
        g._id = 'http://127.0.0.1:8000/groups/1.json'

        adminstatus  = dict(types=["tag:api.typepad.com,2009:%s" % x for x in ('Admin', 'Member')])
        memberstatus = dict(types=["tag:api.typepad.com,2009:Member"])
        users = [
            {"displayName": "Mike", "email": "spatino@brilacsipon.info"},
            {"displayName": "Sherry Monaco", "email": "cosby@arebe.com"},
            {"displayName": "Francesca Coppola", "email": "cfrandsen@cenge.com"},
            {"displayName": "David Rosato", "email": "skemmerer@akekim.biz"},
            {"displayName": "Edgar Bach", "email": "dconti@beli.com"},
            {"displayName": "Jarad Mccaw", "email": "jmccaw@arebe.com"},
            {"displayName": "Deanna Conti", "email": "dconti@beli.com"},
        ]
        group = {
            "mumble": "butter",
        }
        content = json.dumps({
            "total-results": 5,
            "start-index":   0,
            "entries": [dict(status=adminstatus, target=group, source=users[0])] +
                [dict(status=memberstatus, target=group, source=u) for u in users[1:]],
        })

        headers = { 'accept': 'application/json' }
        with self.mockHttp('http://127.0.0.1:8000/groups/1/memberships.json', content, headers=headers) as h:
            m = g.memberships
            m._http = h
            self.assertEquals(len(m.entries), 7)
            self.assertEquals([u.source.display_name for u in m.entries],
                ['Mike', 'Sherry Monaco', 'Francesca Coppola', 'David Rosato', 'Edgar Bach', 'Jarad Mccaw', 'Deanna Conti'])

        # Test sequence behavior of the API list.
        self.assertEquals(m.entries.__len__(), 7)
        self.assertEquals(m.__len__(), 7)
        self.assertEquals(len(m), 7)
        self.assert_(isinstance(m[0], typepad.RemoteObject))
        self.assertEquals(m[0].source.display_name, 'Mike')
        self.assertEquals([u.source.display_name for u in m[1:3]],
            ['Sherry Monaco', 'Francesca Coppola'])

        # Test limit/offset parameters.
        with self.mockHttp('http://127.0.0.1:8000/groups/1/memberships.json?start-index=0', content, headers=headers) as h:
            m = g.memberships.filter(start_index=0)
            m._http = h
            m.deliver()

    def testPost(self):
        # Get post #1 directly from group #1?
        g = typepad.Group()
        g._id = 'http://127.0.0.1:8000/groups/1.json'

        headers = { 'accept': 'application/json' }
        content = """{
            "title": "Fames Vivamus Placerat at Condimentum at Primis Consectetuer Nonummy Inceptos Porta dis",
            "content": "Posuere felis vestibulum nibh justo vitae elementum.",
            "objectTypes": ["tag:api.typepad.com,2009:Post"]
        }"""
        request = dict(url='http://127.0.0.1:8000/assets/1.json', headers=headers)
        with self.mockHttp(request, content) as h:
            e = typepad.Post.get('http://127.0.0.1:8000/assets/1.json', http=h)
            self.assertEquals(e.title, 'Fames Vivamus Placerat at Condimentum at Primis Consectetuer Nonummy Inceptos Porta dis')
            self.assertEquals(e.content, 'Posuere felis vestibulum nibh justo vitae elementum.')
        old_etag = e._etag

        # Modify the existing post.
        e.title = 'Omg hai'
        e.content = 'Yay this is my post'

        # Save the modified post.
        headers = {
            'accept': 'application/json',
            'if-match': old_etag,  # default etag
        }
        content = """{"content": "Yay this is my post", "objectTypes": ["tag:api.typepad.com,2009:Post"], "title": "Omg hai"}"""
        request = dict(url='http://127.0.0.1:8000/assets/1.json', method='PUT', headers=headers, body=content)
        response = dict(content=content, etag='xyz')
        with self.mockHttp(request, response, credentials=('dconti@beli.com', 'password')) as h:
            e.put(http=h)
        self.assertEquals(e.title, 'Omg hai')
        self.assertNotEqual(e._etag, old_etag)

        # Make a new post in group #1.

if __name__ == '__main__':
    tests.log()
    unittest.main()
<commit_msg>Try creating a new post<commit_after>from __future__ import with_statement

try:
    import json
except ImportError:
    import simplejson as json

import logging
import random
import sys
import unittest

from remoteobjects import tests
import typepad

class TestRemoteObjects(unittest.TestCase):

    def mockHttp(self, *args, **kwargs):
        if 'credentials' in kwargs:
            del kwargs['credentials']
        return tests.MockedHttp(*args, **kwargs)

    def testUser(self):
        content = """{"displayName": "Deanna Conti", "email": "dconti@beli.com"}"""
        headers = { 'accept': 'application/json' }
        with self.mockHttp('http://127.0.0.1:8000/users/1.json', content, headers=headers) as h:
            user = typepad.User.get('http://127.0.0.1:8000/users/1.json', http=h)
            self.assertEquals(user.display_name, 'Deanna Conti')
            self.assertEquals(user.email, 'dconti@beli.com')

    def testGroup(self):
        content = """{"displayName": "Augue Tempor"}"""
        headers = { 'accept': 'application/json' }
        with self.mockHttp('http://127.0.0.1:8000/groups/1.json', content, headers=headers) as h:
            group = typepad.Group.get('http://127.0.0.1:8000/groups/1.json', http=h)
            self.assertEquals(group.display_name, 'Augue Tempor')

    def testGroupMembers(self):
        g = typepad.Group()
        g._id = 'http://127.0.0.1:8000/groups/1.json'

        adminstatus  = dict(types=["tag:api.typepad.com,2009:%s" % x for x in ('Admin', 'Member')])
        memberstatus = dict(types=["tag:api.typepad.com,2009:Member"])
        users = [
            {"displayName": "Mike", "email": "spatino@brilacsipon.info"},
            {"displayName": "Sherry Monaco", "email": "cosby@arebe.com"},
            {"displayName": "Francesca Coppola", "email": "cfrandsen@cenge.com"},
            {"displayName": "David Rosato", "email": "skemmerer@akekim.biz"},
            {"displayName": "Edgar Bach", "email": "dconti@beli.com"},
            {"displayName": "Jarad Mccaw", "email": "jmccaw@arebe.com"},
            {"displayName": "Deanna Conti", "email": "dconti@beli.com"},
        ]
        group = {
            "mumble": "butter",
        }
        content = json.dumps({
            "total-results": 5,
            "start-index":   0,
            "entries": [dict(status=adminstatus, target=group, source=users[0])] +
                [dict(status=memberstatus, target=group, source=u) for u in users[1:]],
        })

        headers = { 'accept': 'application/json' }
        with self.mockHttp('http://127.0.0.1:8000/groups/1/memberships.json', content, headers=headers) as h:
            m = g.memberships
            m._http = h
            self.assertEquals(len(m.entries), 7)
            self.assertEquals([u.source.display_name for u in m.entries],
                ['Mike', 'Sherry Monaco', 'Francesca Coppola', 'David Rosato', 'Edgar Bach', 'Jarad Mccaw', 'Deanna Conti'])

        # Test sequence behavior of the API list.
        self.assertEquals(m.entries.__len__(), 7)
        self.assertEquals(m.__len__(), 7)
        self.assertEquals(len(m), 7)
        self.assert_(isinstance(m[0], typepad.RemoteObject))
        self.assertEquals(m[0].source.display_name, 'Mike')
        self.assertEquals([u.source.display_name for u in m[1:3]],
            ['Sherry Monaco', 'Francesca Coppola'])

        # Test limit/offset parameters.
        with self.mockHttp('http://127.0.0.1:8000/groups/1/memberships.json?start-index=0', content, headers=headers) as h:
            m = g.memberships.filter(start_index=0)
            m._http = h
            m.deliver()

    def testCreateDeletePost(self):
        g = typepad.Group.get('http://127.0.0.1:8000/groups/1.json')

        somenum = random.randint(1, 10000)
        p = typepad.Post(
            title="New post #%d" % (somenum,),
            content="Hi this post has some content is it not nifty"
        )

        headers = { 'accept': 'application/json' }
        content = """{"content": "Hi this post has some content is it not nifty", "objectTypes": ["tag:api.typepad.com,2009:Post"], "title": "New post #%d"}""" % (somenum,)
        request = dict(url='http://127.0.0.1:8000/groups/1.json', headers=headers, body=content, method='POST')
        resp_content = """{
            "title": "New post #%d",
            "content": "Hi this post has some content is it not nifty",
            "published": "2009-03-23T00:00:00Z",
            "updated": "2009-03-23T00:00:00Z"
        }""" % (somenum,)
        response = dict(status=201, content=resp_content)
        response['content-location'] = 'http://127.0.0.1:8000/assets/307.json'
        with self.mockHttp(request, response) as h:
            g.post(p, http=h)

        self.assert_(p._id is not None)
        self.assertEquals(p.title, "New post #%d" % (somenum,))
        self.assert_(hasattr(p, 'published'))
        self.assert_(p.published is not None)

        request = dict(url=p._id, headers=headers)
        with self.mockHttp(request, resp_content) as h:
            post_got = typepad.Post.get(p._id, http=h)
            self.assertEquals(post_got.title, 'New post #%d' % (somenum,))

    def testChangePost(self):
        # Get post #1 directly from group #1?
        g = typepad.Group.get('http://127.0.0.1:8000/groups/1.json')

        headers = { 'accept': 'application/json' }
        content = """{
            "title": "Fames Vivamus Placerat at Condimentum at Primis Consectetuer Nonummy Inceptos Porta dis",
            "content": "Posuere felis vestibulum nibh justo vitae elementum.",
            "objectTypes": ["tag:api.typepad.com,2009:Post"]
        }"""
        request = dict(url='http://127.0.0.1:8000/assets/1.json', headers=headers)
        with self.mockHttp(request, content) as h:
            e = typepad.Post.get('http://127.0.0.1:8000/assets/1.json', http=h)
            self.assertEquals(e.title, 'Fames Vivamus Placerat at Condimentum at Primis Consectetuer Nonummy Inceptos Porta dis')
            self.assertEquals(e.content, 'Posuere felis vestibulum nibh justo vitae elementum.')
        old_etag = e._etag

        # Modify the existing post.
        e.title = 'Omg hai'
        e.content = 'Yay this is my post'

        # Save the modified post.
        headers = {
            'accept': 'application/json',
            'if-match': old_etag,  # default etag
        }
        content = """{"content": "Yay this is my post", "objectTypes": ["tag:api.typepad.com,2009:Post"], "title": "Omg hai"}"""
        request = dict(url='http://127.0.0.1:8000/assets/1.json', method='PUT', headers=headers, body=content)
        response = dict(content=content, etag='xyz')
        with self.mockHttp(request, response, credentials=('dconti@beli.com', 'password')) as h:
            e.put(http=h)
        self.assertEquals(e.title, 'Omg hai')
        self.assertNotEqual(e._etag, old_etag)

        # Make a new post in group #1.

if __name__ == '__main__':
    tests.log()
    unittest.main()
<|endoftext|>


<commit_before>__author__ = 'abuddenberg'

import requests
import pickle
import json

def http_resp(fn):
    def wrapped(*args, **kwargs):
        resp = fn(*args, **kwargs)
        if resp.status_code == 200:
            return resp
        else:
            raise Exception('Status: {code} \n{txt}'.format(code=resp.status_code, txt=resp.text))
    return wrapped

class Nca3Client(object):
    def __init__(self, url, username, password, http_basic_user=None, http_basic_pass=None):
        self.base_url = url
        self.s = requests.Session()
        self.s.auth = (http_basic_user, http_basic_pass)
        self.s.headers = {'content-type': 'application/json'}

        self.drupal_user = username
        self.drupal_pass = password
        self.cookie_jar = '/tmp/cookies'
        try:
            self.s.cookies = pickle.load(open(self.cookie_jar, 'r'))
        except Exception, e:
            pass

    def do_login(self):
        url = '{b}/user'.format(b=self.base_url)
        resp = self.s.post(
            url,
            data={
                'name': self.drupal_user,
                'pass': self.drupal_pass,
                'form_id': 'user_login',
                'op': 'Log in'
            },
            allow_redirects=False
        )
        pickle.dump(self.s.cookies, open(self.cookie_jar, 'wb'))

        return resp

    @http_resp
    def get_all_captions(self):
        url = '{b}/gcis/figure-table-captions'.format(b=self.base_url)

        resp = self.s.get(url, verify=False, cookies=self.s.cookies)
        return resp

    def get_figure(self, nid):
        url = '{b}/gcis/node/{nid}'.format(b=self.base_url, nid=nid)

        return self.s.get(url, verify=False, cookies=self.s.cookies).json()

    def update_figure(self, nid, figure_frag):
        url = '{b}/gcis/node/{nid}'.format(b=self.base_url, nid=nid)
        token_url = '{b}/services/session/token'.format(b=self.base_url)
        token = self.s.get(token_url, verify=False, cookies=self.s.cookies).text

        return self.s.put(url, data=json.dumps(figure_frag), verify=False, cookies=self.s.cookies, headers={'X-CSRF-Token': token})

<commit_msg>Added some extra goodness to spoof Drupal's login. Removed application/json from login headers since Drupal doesn't send cookies with it<commit_after>__author__ = 'abuddenberg'

import requests
import pickle
import json
from bs4 import BeautifulSoup

def http_resp(fn):
    def wrapped(*args, **kwargs):
        resp = fn(*args, **kwargs)
        if resp.status_code == 200:
            return resp
        else:
            raise Exception('Status: {code} \n{txt}'.format(code=resp.status_code, txt=resp.text))
    return wrapped

class Nca3Client(object):
    def __init__(self, url, username, password, http_basic_user=None, http_basic_pass=None):
        self.base_url = url
        self.s = requests.Session()
        self.s.auth = (http_basic_user, http_basic_pass)
        # self.s.headers = {'content-type': 'application/json'}

        self.drupal_user = username
        self.drupal_pass = password
        self.cookie_jar = '/tmp/cookies'
        try:
            self.s.cookies = pickle.load(open(self.cookie_jar, 'r'))
        except Exception, e:
            pass

    def do_login(self):
        url = '{b}/user'.format(b=self.base_url)
        form = BeautifulSoup(self.s.get(url).text).find('form', id='user-login')
        form_build_id = form.find_all('input', attrs={'name': 'form_build_id'})

        resp = self.s.post(
            url,
            data={
                'name': self.drupal_user,
                'pass': self.drupal_pass,
                'form_id': 'user_login',
                'form_build_id': form_build_id,
                'op': 'Log in'
            },
            allow_redirects=False
        )

        pickle.dump(self.s.cookies, open(self.cookie_jar, 'wb'))

        return resp

    @http_resp
    def get_all_captions(self):
        url = '{b}/gcis/figure-table-captions'.format(b=self.base_url)

        resp = self.s.get(url, verify=False, headers={'content-type': 'application/json'}, cookies=self.s.cookies)
        return resp

    def get_figure(self, nid):
        url = '{b}/gcis/node/{nid}'.format(b=self.base_url, nid=nid)

        return self.s.get(url, verify=False, headers={'content-type': 'application/json'}, cookies=self.s.cookies).json()

    def update_figure(self, nid, figure_frag):
        url = '{b}/gcis/node/{nid}'.format(b=self.base_url, nid=nid)
        token_url = '{b}/services/session/token'.format(b=self.base_url)
        token = self.s.get(token_url, verify=False, cookies=self.s.cookies).text

        return self.s.put(url, data=json.dumps(figure_frag), verify=False, cookies=self.s.cookies, headers={'X-CSRF-Token': token, 'content-type': 'application/json'})

<|endoftext|>


<commit_before># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Lint as: python3
"""Stub API calls used in gcs.py for testing.

Instead of doing real API calls, we return test JSON data.
"""

from typing import Optional

from gcpdiag.queries import apis_stub

# pylint: disable=unused-argument
# pylint: disable=invalid-name

NO_PROJECT_ID_ERROR = 'Not able to call {} without setting project_id for API.'

class BucketApiStub:
  """Mock object to simulate storage api calls.

  Attributes:
    project_id: Since buckets are not explicitly assigned to projects we need a
      project_id to be provided by user to know where to find json_directory
      with bucket data. Without providing it you can still list buckets per
      project.
  """

  def __init__(self, project_id: Optional[str] = None):
    self.project_id = project_id

  def buckets(self):
    return self

  def list(self, project):
    return apis_stub.RestCallStub(project, 'storage')

  def get(self, bucket):
    return apis_stub.RestCallStub(self.project_id, f'bucket-{bucket}.json')

  def getIamPolicy(self, bucket):
    if not self.project_id:
      raise ValueError(NO_PROJECT_ID_ERROR.format('getIamPolicy'))
    return apis_stub.RestCallStub(self.project_id, 'bucket-roles')
<commit_msg>Fix tests.<commit_after># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Lint as: python3
"""Stub API calls used in gcs.py for testing.

Instead of doing real API calls, we return test JSON data.
"""

from typing import Optional

from gcpdiag.queries import apis_stub

# pylint: disable=unused-argument
# pylint: disable=invalid-name

NO_PROJECT_ID_ERROR = 'Not able to call {} without setting project_id for API.'

class BucketApiStub:
  """Mock object to simulate storage api calls.

  Attributes:
    project_id: Since buckets are not explicitly assigned to projects we need a
      project_id to be provided by user to know where to find json_directory
      with bucket data. Without providing it you can still list buckets per
      project.
  """

  def __init__(self, project_id: Optional[str] = None):
    self.project_id = project_id

  def buckets(self):
    return self

  def list(self, project):
    return apis_stub.RestCallStub(project, 'storage')

  def get(self, bucket):
    return apis_stub.RestCallStub(self.project_id, f'bucket-{bucket}')

  def getIamPolicy(self, bucket):
    if not self.project_id:
      raise ValueError(NO_PROJECT_ID_ERROR.format('getIamPolicy'))
    return apis_stub.RestCallStub(self.project_id, 'bucket-roles')
<|endoftext|>


<commit_before>from django.conf import settings
from django.test import TestCase, override_settings

from django_slack import slack_message
from django_slack.utils import get_backend
from django_slack.app_settings import app_settings

from tests.backends import RaisingBackend

class TestOverride(TestCase):
    def test_override(self):
        """
        Ensure that accessing a setting in an override works.
        """
        DISABLED_BACKEND = 'django_slack.backends.DisabledBackend'
        with override_settings(SLACK_BACKEND=DISABLED_BACKEND):
            self.assertEqual(settings.SLACK_BACKEND, DISABLED_BACKEND)
            self.assertEqual(app_settings.BACKEND, DISABLED_BACKEND)

    def test_backend_cache(self):
        """
        Ensure that the backend is cached once it is called once.
        """
        self.assertEqual(id(get_backend()), id(get_backend()))

    def test_backend_override(self):
        """
        Ensure the backend can be overridden.
        """
        with override_settings(SLACK_BACKEND='tests.backends.RaisingBackend'):
            self.assertRaises(RaisingBackend.RaisedException,
                              slack_message('test.slack', {'text': 'test'}))

    def test_fail_silently(self):
        """
        Ensure fail silently can be overridden.
        """
        # Note that this will fail if test_backend_override ever fails.
        with override_settings(SLACK_FAIL_SILENTLY=True,
                               SLACK_BACKEND='tests.backends.RaisingBackend'):
            slack_message('test.slack', {'text': 'test'})
<commit_msg>Reflow to diff-friendly format<commit_after>from django.conf import settings
from django.test import TestCase, override_settings

from django_slack import slack_message
from django_slack.utils import get_backend
from django_slack.app_settings import app_settings

from tests.backends import RaisingBackend

class TestOverride(TestCase):
    def test_override(self):
        """
        Ensure that accessing a setting in an override works.
        """
        DISABLED_BACKEND = 'django_slack.backends.DisabledBackend'
        with override_settings(SLACK_BACKEND=DISABLED_BACKEND):
            self.assertEqual(settings.SLACK_BACKEND, DISABLED_BACKEND)
            self.assertEqual(app_settings.BACKEND, DISABLED_BACKEND)

    def test_backend_cache(self):
        """
        Ensure that the backend is cached once it is called once.
        """
        self.assertEqual(id(get_backend()), id(get_backend()))

    def test_backend_override(self):
        """
        Ensure the backend can be overridden.
        """
        with override_settings(SLACK_BACKEND='tests.backends.RaisingBackend'):
            self.assertRaises(
                RaisingBackend.RaisedException,
                slack_message('test.slack', {'text': 'test'}),
            )

    def test_fail_silently(self):
        """
        Ensure fail silently can be overridden.
        """
        # Note that this will fail if test_backend_override ever fails.
        with override_settings(
            SLACK_FAIL_SILENTLY=True,
            SLACK_BACKEND='tests.backends.RaisingBackend',
        ):
            slack_message('test.slack', {'text': 'test'})
<|endoftext|>


<commit_before>import unittest

from katas.kyu_8.classy_extensions import Cat

class CatTestCase(unittest.TestCase):
    def test_equals(self):
        self.assertEqual(Cat('Mr Whiskers').speak(), 'Mr Whiskers meows.')

    def test_equals_2(self):
        self.assertEqual(Cat('Lamp').speak(), 'Lamp meows.')

    def test_equals_3(self):
        self.assertEqual(Cat('$$Money Bags$$').speak(),
                         '$$Money Bags$$ meows.')
<commit_msg>Added a test for code coverage<commit_after>import unittest

from katas.kyu_8.classy_extensions import Animal, Cat

class CatTestCase(unittest.TestCase):
    def test_equal_1(self):
        self.assertEqual(Cat('Mr Whiskers').speak(), 'Mr Whiskers meows.')

    def test_equal_2(self):
        self.assertEqual(Cat('Lamp').speak(), 'Lamp meows.')

    def test_equal_3(self):
        self.assertEqual(Cat('$$Money Bags$$').speak(),
                         '$$Money Bags$$ meows.')

    def test_equal_4(self):
        self.assertEqual(Animal('Rover').speak(), 'Some other message?!?!')
<|endoftext|>


<commit_before>import argparse
import logging

from functools import partial

from .. import defaults

from . import manifest
from . import exceptions

from .client import GDCUploadClient

def validate_args(parser, args):
    """ Validate argparse namespace.
    """
    if args.manifest:
        return

    if all([
        args.project_id,
        args.identifier,
        args.path,
    ]): return

    these = ', '.join([
        '--project-id',
        '--identifier',
        '--path',
    ])

    msg = 'must specify either --manifest or {these}'.format(these=these)
    parser.error(msg)

def upload(parser, args):
    """ Upload data to the GDC.
    """
    validate_args(parser, args)

    files = read_manifest(args.manifest) if args.manifest else []

    if not args.manifest:
        files.append({
            'id': args.identifier,
            'project_id': args.project_id,
            'path': args.path,
            'upload_id': args.upload_id,
        })

    # TODO remove debug - handled by logger
    debug = logging.DEBUG in args.log_levels

    manifest_name = args.manifest.name if args.manifest else args.identifier

    client = GDCUploadClient(
        token=args.token, processes=args.n_processes,
        multipart=args.disable_multipart,
        part_size=args.part_size, server=args.server,
        files=files, verify=args.insecure, debug=debug, manifest_name=manifest_name)

    if args.abort:
        client.abort()
    elif args.delete:
        client.delete()
    else:
        client.upload()

def config(parser):
    """ Configure a parser for upload.
    """
    func = partial(upload, parser)
    parser.set_defaults(func=func)

    parser.add_argument('--project-id', '-p', type=str,
                        help='The project ID that owns the file')
    parser.add_argument('--identifier', '-i', type=str,
                        help='The file id')
    parser.add_argument('--path', '-f', metavar='path',
                        help='directory path to find file')
    parser.add_argument('--upload-id', '-u',
                        help='Multipart upload id')

    parser.add_argument('--insecure', '-k',
                        action='store_false',
                        help='Allow connections to server without certs')
    # TODO remove this and replace w/ top level host and port
    parser.add_argument('--server', '-s',
                        default=defaults.tcp_url,
                        help='GDC API server address')
    parser.add_argument('--part-size', '-ps',
                        default=defaults.part_size,
                        type=int,
                        help='Part size for multipart upload')
    parser.add_argument('-n', '--n-processes', type=int,
                        default=defaults.processes,
                        help='Number of client connections')
    parser.add_argument('--disable-multipart',
                        action="store_false",
                        help='Disable multipart upload')
    parser.add_argument('--abort',
                        action="store_true",
                        help='Abort previous multipart upload')
    parser.add_argument('--resume', '-r',
                        action="store_true",
                        help='Resume previous multipart upload')
    parser.add_argument('--delete',
                        action="store_true",
                        help='Delete an uploaded file')

    parser.add_argument('--manifest', '-m',
                        type=argparse.FileType('r'),
                        help='Manifest which describes files to be uploaded')
<commit_msg>fix(upload): revert parser verification<commit_after>import argparse
import logging

from functools import partial

from .. import defaults

from . import manifest
from . import exceptions

from .client import GDCUploadClient

def validate_args(parser, args):
    """ Validate argparse namespace.
    """
    if args.manifest or args.identifier:
        return

    msg = 'must specify either --manifest or --identifier'
    parser.error(msg)

def upload(parser, args):
    """ Upload data to the GDC.
    """
    validate_args(parser, args)

    files = read_manifest(args.manifest) if args.manifest else []

    if not args.manifest:
        files.append({
            'id': args.identifier,
            'project_id': args.project_id,
            'path': args.path,
            'upload_id': args.upload_id,
        })

    # TODO remove debug - handled by logger
    debug = logging.DEBUG in args.log_levels

    manifest_name = args.manifest.name if args.manifest else args.identifier

    client = GDCUploadClient(
        token=args.token, processes=args.n_processes,
        multipart=args.disable_multipart,
        part_size=args.part_size, server=args.server,
        files=files, verify=args.insecure, debug=debug, manifest_name=manifest_name)

    if args.abort:
        client.abort()
    elif args.delete:
        client.delete()
    else:
        client.upload()

def config(parser):
    """ Configure a parser for upload.
    """
    func = partial(upload, parser)
    parser.set_defaults(func=func)

    parser.add_argument('--project-id', '-p', type=str,
                        help='The project ID that owns the file')
    parser.add_argument('--identifier', '-i', type=str,
                        help='The file id')
    parser.add_argument('--path', '-f', metavar='path',
                        help='directory path to find file')
    parser.add_argument('--upload-id', '-u',
                        help='Multipart upload id')

    parser.add_argument('--insecure', '-k',
                        action='store_false',
                        help='Allow connections to server without certs')
    # TODO remove this and replace w/ top level host and port
    parser.add_argument('--server', '-s',
                        default=defaults.tcp_url,
                        help='GDC API server address')
    parser.add_argument('--part-size', '-ps',
                        default=defaults.part_size,
                        type=int,
                        help='Part size for multipart upload')
    parser.add_argument('-n', '--n-processes', type=int,
                        default=defaults.processes,
                        help='Number of client connections')
    parser.add_argument('--disable-multipart',
                        action="store_false",
                        help='Disable multipart upload')
    parser.add_argument('--abort',
                        action="store_true",
                        help='Abort previous multipart upload')
    parser.add_argument('--resume', '-r',
                        action="store_true",
                        help='Resume previous multipart upload')
    parser.add_argument('--delete',
                        action="store_true",
                        help='Delete an uploaded file')

    parser.add_argument('--manifest', '-m',
                        type=argparse.FileType('r'),
                        help='Manifest which describes files to be uploaded')
<|endoftext|>


<commit_before>import sys
import time
import unittest
from django.conf import settings
from django.db import transaction, connection
from django.db.utils import ConnectionHandler, DEFAULT_DB_ALIAS, DatabaseError
from django.test import (TransactionTestCase, skipIfDBFeature,
    skipUnlessDBFeature)
from django.utils import unittest

from models import Person

# Some tests require threading, which might not be available. So create a
# skip-test decorator for those test functions.
try:
    import threading
except ImportError:
    threading = None
requires_threading = unittest.skipUnless(threading, 'requires threading')

class SelectForUpdateTests(TransactionTestCase):

    def setUp(self):
        transaction.enter_transaction_management(True)
        transaction.managed(True)
        self.person = Person.objects.create(name='Reinhardt')

        # We have to commit here so that code in run_select_for_update can
        # see this data.
        transaction.commit()

        # We need another database connection to test that one connection
        # issuing a SELECT ... FOR UPDATE will block.
        new_connections = ConnectionHandler(settings.DATABASES)
        self.new_connection = new_connections[DEFAULT_DB_ALIAS]

        # We need to set settings.DEBUG to True so we can capture
        # the output SQL to examine.
        self._old_debug = settings.DEBUG
        settings.DEBUG = True

    def tearDown(self):
        try:
            # We don't really care if this fails - some of the tests will set
            # this in the course of their run.
            transaction.managed(False)
            transaction.leave_transaction_management()
        except transaction.TransactionManagementError:
            pass
        self.new_connection.close()
        settings.DEBUG = self._old_debug
        try:
            self.end_blocking_transaction()
        except (DatabaseError, AttributeError):
            pass

    def start_blocking_transaction(self):
        # Start a blocking transaction. At some point,
        # end_blocking_transaction() should be called.
        self.cursor = self.new_connection.cursor()
        sql = 'SELECT * FROM %(db_table)s %(for_update)s;' % {
            'db_table': Person._meta.db_table,
            'for_update': self.new_connection.ops.for_update_sql(),
            }
        self.cursor.execute(sql, ())
        result = self.cursor.fetchone()

    def end_blocking_transaction(self):
        # Roll back the blocking transaction.
        self.new_connection._rollback()

    def has_for_update_sql(self, tested_connection, nowait=False):
        # Examine the SQL that was executed to determine whether it
        # contains the 'SELECT..FOR UPDATE' stanza.
        for_update_sql = tested_connection.ops.for_update_sql(nowait)
        sql = tested_connection.queries[-1]['sql']
        return bool(sql.find(for_update_sql) > -1)

    def check_exc(self, exc):
        self.failUnless(isinstance(exc, DatabaseError))

    @skipUnlessDBFeature('has_select_for_update')
    def test_for_update_sql_generated(self):
        """
        Test that the backend's FOR UPDATE variant appears in
        generated SQL when select_for_update is invoked.
        """
        list(Person.objects.all().select_for_update())
        self.assertTrue(self.has_for_update_sql(connection))

    @skipUnlessDBFeature('has_select_for_update_nowait')
    def test_for_update_sql_generated_nowait(self):
        """
        Test that the backend's FOR UPDATE NOWAIT variant appears in
        generated SQL when select_for_update is invoked.
        """
        list(Person.objects.all().select_for_update(nowait=True))
        self.assertTrue(self.has_for_update_sql(connection, nowait=True))

    # In Python 2.6 beta and some final releases, exceptions raised in __len__
    # are swallowed (Python issue 1242657), so these cases return an empty
    # list, rather than raising an exception. Not a lot we can do about that,
    # unfortunately, due to the way Python handles list() calls internally.
    # Thus, we skip this test for Python 2.6.
    @requires_threading
    @skipUnlessDBFeature('has_select_for_update_nowait')
    @unittest.skipIf(sys.version_info[:2] == (2, 6), "Python version is 2.6")
    def test_nowait_raises_error_on_block(self):
        """
        If nowait is specified, we expect an error to be raised rather
        than blocking.
        """
        self.start_blocking_transaction()
        status = []
        thread = threading.Thread(
            target=self.run_select_for_update,
            args=(status,),
            kwargs={'nowait': True},
        )

        thread.start()
        time.sleep(1)
        thread.join()
        self.end_blocking_transaction()
        self.check_exc(status[-1])

    @skipIfDBFeature('has_select_for_update_nowait')
    @skipUnlessDBFeature('has_select_for_update')
    def test_unsupported_nowait_raises_error(self):
        """
        If a SELECT...FOR UPDATE NOWAIT is run on a database backend
        that supports FOR UPDATE but not NOWAIT, then we should find
        that a DatabaseError is raised.
        """
        self.assertRaises(
            DatabaseError,
            list,
            Person.objects.all().select_for_update(nowait=True)
        )

    def run_select_for_update(self, status, nowait=False):
        """
        Utility method that runs a SELECT FOR UPDATE against all
        Person instances. After the select_for_update, it attempts
        to update the name of the only record, save, and commit.

        In general, this will be run in a separate thread.
        """
        status.append('started')
        try:
            # We need to enter transaction management again, as this is done on
            # per-thread basis
            transaction.enter_transaction_management(True)
            transaction.managed(True)
            people = list(
                Person.objects.all().select_for_update(nowait=nowait)
            )
            people[0].name = 'Fred'
            people[0].save()
            transaction.commit()
        except DatabaseError, e:
            status.append(e)
        except Exception, e:
            raise

    @requires_threading
    @skipUnlessDBFeature('has_select_for_update')
    @skipUnlessDBFeature('supports_transactions')
    def test_block(self):
        """
        Check that a thread running a select_for_update that
        accesses rows being touched by a similar operation
        on another connection blocks correctly.
        """
        # First, let's start the transaction in our thread.
        self.start_blocking_transaction()

        # Now, try it again using the ORM's select_for_update
        # facility. Do this in a separate thread.
        status = []
        thread = threading.Thread(
            target=self.run_select_for_update, args=(status,)
        )

        # The thread should immediately block, but we'll sleep
        # for a bit to make sure.
        thread.start()
        sanity_count = 0
        while len(status) != 1 and sanity_count < 10:
            sanity_count += 1
            time.sleep(1)
        if sanity_count >= 10:
            raise ValueError, 'Thread did not run and block'

        # Check the person hasn't been updated. Since this isn't
        # using FOR UPDATE, it won't block.
        p = Person.objects.get(pk=self.person.pk)
        self.assertEqual('Reinhardt', p.name)

        # When we end our blocking transaction, our thread should
        # be able to continue.
        self.end_blocking_transaction()
        thread.join(5.0)

        # Check the thread has finished. Assuming it has, we should
        # find that it has updated the person's name.
        self.failIf(thread.isAlive())

        # We must commit the transaction to ensure that MySQL gets a fresh read,
        # since by default it runs in REPEATABLE READ mode
        transaction.commit()

        p = Person.objects.get(pk=self.person.pk)
        self.assertEqual('Fred', p.name)

    @requires_threading
    @skipUnlessDBFeature('has_select_for_update')
    def test_raw_lock_not_available(self):
        """
        Check that running a raw query which can't obtain a FOR UPDATE lock
        raises the correct exception
        """
        self.start_blocking_transaction()
        def raw(status):
            try:
                list(
                    Person.objects.raw(
                        'SELECT * FROM %s %s' % (
                            Person._meta.db_table,
                            connection.ops.for_update_sql(nowait=True)
                        )
                    )
                )
            except DatabaseError, e:
                status.append(e)
        status = []
        thread = threading.Thread(target=raw, kwargs={'status': status})
        thread.start()
        time.sleep(1)
        thread.join()
        self.end_blocking_transaction()
        self.check_exc(status[-1])

    @skipUnlessDBFeature('has_select_for_update')
    def test_transaction_dirty_managed(self):
        """ Check that a select_for_update sets the transaction to be
        dirty when executed under txn management. Setting the txn dirty
        means that it will be either committed or rolled back by Django,
        which will release any locks held by the SELECT FOR UPDATE.
        """
        people = list(Person.objects.select_for_update())
        self.assertTrue(transaction.is_dirty())

    @skipUnlessDBFeature('has_select_for_update')
    def test_transaction_not_dirty_unmanaged(self):
        """ If we're not under txn management, the txn will never be
        marked as dirty.
        """
        transaction.managed(False)
        transaction.leave_transaction_management()
        people = list(Person.objects.select_for_update())
        self.assertFalse(transaction.is_dirty())
<commit_msg>Fixed #16490 -- Skipped a test failure that only occurs under Python 2.6.1 (it's the old iteration-eats-exceptions problem).<commit_after>import sys
import time
import unittest
from django.conf import settings
from django.db import transaction, connection
from django.db.utils import ConnectionHandler, DEFAULT_DB_ALIAS, DatabaseError
from django.test import (TransactionTestCase, skipIfDBFeature,
    skipUnlessDBFeature)
from django.utils import unittest

from models import Person

# Some tests require threading, which might not be available. So create a
# skip-test decorator for those test functions.
try:
    import threading
except ImportError:
    threading = None
requires_threading = unittest.skipUnless(threading, 'requires threading')

class SelectForUpdateTests(TransactionTestCase):

    def setUp(self):
        transaction.enter_transaction_management(True)
        transaction.managed(True)
        self.person = Person.objects.create(name='Reinhardt')

        # We have to commit here so that code in run_select_for_update can
        # see this data.
        transaction.commit()

        # We need another database connection to test that one connection
        # issuing a SELECT ... FOR UPDATE will block.
        new_connections = ConnectionHandler(settings.DATABASES)
        self.new_connection = new_connections[DEFAULT_DB_ALIAS]

        # We need to set settings.DEBUG to True so we can capture
        # the output SQL to examine.
        self._old_debug = settings.DEBUG
        settings.DEBUG = True

    def tearDown(self):
        try:
            # We don't really care if this fails - some of the tests will set
            # this in the course of their run.
            transaction.managed(False)
            transaction.leave_transaction_management()
        except transaction.TransactionManagementError:
            pass
        self.new_connection.close()
        settings.DEBUG = self._old_debug
        try:
            self.end_blocking_transaction()
        except (DatabaseError, AttributeError):
            pass

    def start_blocking_transaction(self):
        # Start a blocking transaction. At some point,
        # end_blocking_transaction() should be called.
        self.cursor = self.new_connection.cursor()
        sql = 'SELECT * FROM %(db_table)s %(for_update)s;' % {
            'db_table': Person._meta.db_table,
            'for_update': self.new_connection.ops.for_update_sql(),
            }
        self.cursor.execute(sql, ())
        result = self.cursor.fetchone()

    def end_blocking_transaction(self):
        # Roll back the blocking transaction.
        self.new_connection._rollback()

    def has_for_update_sql(self, tested_connection, nowait=False):
        # Examine the SQL that was executed to determine whether it
        # contains the 'SELECT..FOR UPDATE' stanza.
        for_update_sql = tested_connection.ops.for_update_sql(nowait)
        sql = tested_connection.queries[-1]['sql']
        return bool(sql.find(for_update_sql) > -1)

    def check_exc(self, exc):
        self.failUnless(isinstance(exc, DatabaseError))

    @skipUnlessDBFeature('has_select_for_update')
    def test_for_update_sql_generated(self):
        """
        Test that the backend's FOR UPDATE variant appears in
        generated SQL when select_for_update is invoked.
        """
        list(Person.objects.all().select_for_update())
        self.assertTrue(self.has_for_update_sql(connection))

    @skipUnlessDBFeature('has_select_for_update_nowait')
    def test_for_update_sql_generated_nowait(self):
        """
        Test that the backend's FOR UPDATE NOWAIT variant appears in
        generated SQL when select_for_update is invoked.
        """
        list(Person.objects.all().select_for_update(nowait=True))
        self.assertTrue(self.has_for_update_sql(connection, nowait=True))

    # In Python 2.6 beta and some final releases, exceptions raised in __len__
    # are swallowed (Python issue 1242657), so these cases return an empty
    # list, rather than raising an exception. Not a lot we can do about that,
    # unfortunately, due to the way Python handles list() calls internally.
    # Python 2.6.1 is the "in the wild" version affected by this, so we skip
    # the test for that version.
    @requires_threading
    @skipUnlessDBFeature('has_select_for_update_nowait')
    @unittest.skipIf(sys.version_info[:3] == (2, 6, 1), "Python version is 2.6.1")
    def test_nowait_raises_error_on_block(self):
        """
        If nowait is specified, we expect an error to be raised rather
        than blocking.
        """
        self.start_blocking_transaction()
        status = []
        thread = threading.Thread(
            target=self.run_select_for_update,
            args=(status,),
            kwargs={'nowait': True},
        )

        thread.start()
        time.sleep(1)
        thread.join()
        self.end_blocking_transaction()
        self.check_exc(status[-1])

    # In Python 2.6 beta and some final releases, exceptions raised in __len__
    # are swallowed (Python issue 1242657), so these cases return an empty
    # list, rather than raising an exception. Not a lot we can do about that,
    # unfortunately, due to the way Python handles list() calls internally.
    # Python 2.6.1 is the "in the wild" version affected by this, so we skip
    # the test for that version.
    @skipIfDBFeature('has_select_for_update_nowait')
    @skipUnlessDBFeature('has_select_for_update')
    @unittest.skipIf(sys.version_info[:3] == (2, 6, 1), "Python version is 2.6.1")
    def test_unsupported_nowait_raises_error(self):
        """
        If a SELECT...FOR UPDATE NOWAIT is run on a database backend
        that supports FOR UPDATE but not NOWAIT, then we should find
        that a DatabaseError is raised.
        """
        self.assertRaises(
            DatabaseError,
            list,
            Person.objects.all().select_for_update(nowait=True)
        )

    def run_select_for_update(self, status, nowait=False):
        """
        Utility method that runs a SELECT FOR UPDATE against all
        Person instances. After the select_for_update, it attempts
        to update the name of the only record, save, and commit.

        In general, this will be run in a separate thread.
        """
        status.append('started')
        try:
            # We need to enter transaction management again, as this is done on
            # per-thread basis
            transaction.enter_transaction_management(True)
            transaction.managed(True)
            people = list(
                Person.objects.all().select_for_update(nowait=nowait)
            )
            people[0].name = 'Fred'
            people[0].save()
            transaction.commit()
        except DatabaseError, e:
            status.append(e)
        except Exception, e:
            raise

    @requires_threading
    @skipUnlessDBFeature('has_select_for_update')
    @skipUnlessDBFeature('supports_transactions')
    def test_block(self):
        """
        Check that a thread running a select_for_update that
        accesses rows being touched by a similar operation
        on another connection blocks correctly.
        """
        # First, let's start the transaction in our thread.
        self.start_blocking_transaction()

        # Now, try it again using the ORM's select_for_update
        # facility. Do this in a separate thread.
        status = []
        thread = threading.Thread(
            target=self.run_select_for_update, args=(status,)
        )

        # The thread should immediately block, but we'll sleep
        # for a bit to make sure.
        thread.start()
        sanity_count = 0
        while len(status) != 1 and sanity_count < 10:
            sanity_count += 1
            time.sleep(1)
        if sanity_count >= 10:
            raise ValueError, 'Thread did not run and block'

        # Check the person hasn't been updated. Since this isn't
        # using FOR UPDATE, it won't block.
        p = Person.objects.get(pk=self.person.pk)
        self.assertEqual('Reinhardt', p.name)

        # When we end our blocking transaction, our thread should
        # be able to continue.
        self.end_blocking_transaction()
        thread.join(5.0)

        # Check the thread has finished. Assuming it has, we should
        # find that it has updated the person's name.
        self.failIf(thread.isAlive())

        # We must commit the transaction to ensure that MySQL gets a fresh read,
        # since by default it runs in REPEATABLE READ mode
        transaction.commit()

        p = Person.objects.get(pk=self.person.pk)
        self.assertEqual('Fred', p.name)

    @requires_threading
    @skipUnlessDBFeature('has_select_for_update')
    def test_raw_lock_not_available(self):
        """
        Check that running a raw query which can't obtain a FOR UPDATE lock
        raises the correct exception
        """
        self.start_blocking_transaction()
        def raw(status):
            try:
                list(
                    Person.objects.raw(
                        'SELECT * FROM %s %s' % (
                            Person._meta.db_table,
                            connection.ops.for_update_sql(nowait=True)
                        )
                    )
                )
            except DatabaseError, e:
                status.append(e)
        status = []
        thread = threading.Thread(target=raw, kwargs={'status': status})
        thread.start()
        time.sleep(1)
        thread.join()
        self.end_blocking_transaction()
        self.check_exc(status[-1])

    @skipUnlessDBFeature('has_select_for_update')
    def test_transaction_dirty_managed(self):
        """ Check that a select_for_update sets the transaction to be
        dirty when executed under txn management. Setting the txn dirty
        means that it will be either committed or rolled back by Django,
        which will release any locks held by the SELECT FOR UPDATE.
        """
        people = list(Person.objects.select_for_update())
        self.assertTrue(transaction.is_dirty())

    @skipUnlessDBFeature('has_select_for_update')
    def test_transaction_not_dirty_unmanaged(self):
        """ If we're not under txn management, the txn will never be
        marked as dirty.
        """
        transaction.managed(False)
        transaction.leave_transaction_management()
        people = list(Person.objects.select_for_update())
        self.assertFalse(transaction.is_dirty())
<|endoftext|>


<commit_before># -*- coding: utf8 -*-
# This file is part of PYBOSSA.
#
# Copyright (C) 2017 SciFabric LTD.
#
# PYBOSSA is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PYBOSSA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with PYBOSSA.  If not, see <http://www.gnu.org/licenses/>.
import json
from collections import namedtuple
from pbsonesignal import PybossaOneSignal
from pbsonesignal.exceptions import *
from nose.tools import raises
from mock import patch, MagicMock

FakeRequest = namedtuple('FakeRequest', ['text', 'status_code', 'headers'])

class TestPybossaOnesignal(object):

    valid_notification = {u'id': u'da360e9a-09d9-4992-a803-5bca978c5e0d',
                          u'recipients': 3}

    error_notification = {u'errors': ['an example error']}

    payload = None

    def setUp(self):
        self.payload = {
                        "included_segments": ["All"],
                        "excluded_sements": [],
                        "filters": [],
                        "contents": {"en": "English Message"},
                        "headings": {"en": "Heading"},
                        "url": "https://yoursite.com/",
                        "web_buttons": [{"id": "read-more-button",
                                        "text": "Read more",
                                        "icon": "http://i.imgur.com/MIxJp1L.png",
                                        "url": "https://yoursite.com"}],
                        "chrome_web_image": "https://yourimage.com",
                        "chrome_web_icon": "https://image"}

    @patch('pbsonesignal.requests.post')
    def test_push_msg(self, mock):
        """Test push_msg works."""
        client = PybossaOneSignal(app_id="1", api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg()
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_notification

    @patch('pbsonesignal.requests.post')
    def test_push_msg_app_ids(self, mock):
        """Test push_msg with array app_ids works."""
        client = PybossaOneSignal(app_ids=["1", "2"], api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg()
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_notification

        self.payload['app_ids'] = ["1", "2"]

        mock.assert_called_with(client.api_url,
                                headers=client.header,
                                json=self.payload)

    @patch('pbsonesignal.requests.post')
    def test_push_msg_app_id(self, mock):
        """Test push_msg with array app_id works."""
        client = PybossaOneSignal(app_id="1", api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg()
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_notification

        self.payload['app_id'] = "1"

        mock.assert_called_with(client.api_url,
                                headers=client.header,
                                json=self.payload)

    @patch('pbsonesignal.requests.post')
    def test_push_msg_include_player_ids(self, mock):
        """Test push_msg with array include_player_ids works."""
        client = PybossaOneSignal(app_id="1", api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg(include_player_ids=["1"])
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_notification

        self.payload['app_id'] = "1"
        self.payload['include_player_ids'] = ["1"]

        mock.assert_called_with(client.api_url,
                                headers=client.header,
                                json=self.payload)

    @patch('pbsonesignal.requests.post')
    def test_push_msg_include_send_after(self, mock):
        """Test push_msg with array send_after works."""
        client = PybossaOneSignal(app_id="1", api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg(send_after="Thu Sep 24 2015 14:00:00 GMT-0700 (PDT)")
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_notification

        self.payload['app_id'] = "1"
        self.payload['send_after'] = "Thu Sep 24 2015 14:00:00 GMT-0700 (PDT)"

        mock.assert_called_with(client.api_url,
                                headers=client.header,
                                json=self.payload)

    @patch('pbsonesignal.requests.post')
    def test_push_msg_include_delayed_option(self, mock):
        """Test push_msg with array delayed_option works."""
        client = PybossaOneSignal(app_id="1", api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg(delayed_option="last-active")
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_notification

        self.payload['app_id'] = "1"
        self.payload['delayed_option'] = "last-active"

        mock.assert_called_with(client.api_url,
                                headers=client.header,
                                json=self.payload)

    @patch('pbsonesignal.requests.post')
    def test_push_msg_include_delivery_time_of_day(self, mock):
        """Test push_msg with array delivery_time_of_day works."""
        client = PybossaOneSignal(app_id="1", api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg(delivery_time_of_day="9:00AM")
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_notification

        self.payload['app_id'] = "1"
        self.payload['delivery_time_of_day'] = "9:00AM"

        mock.assert_called_with(client.api_url,
                                headers=client.header,
                                json=self.payload)

    @patch('pbsonesignal.requests.post')
    def test_push_msg_include_ttl(self, mock):
        """Test push_msg with array ttl works."""
        client = PybossaOneSignal(app_id="1", api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg(ttl="259200")
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_notification

        self.payload['app_id'] = "1"
        self.payload['ttl'] = "259200"

        mock.assert_called_with(client.api_url,
                                headers=client.header,
                                json=self.payload)

    @patch('pbsonesignal.requests.post')
    def test_push_msg_include_priority(self, mock):
        """Test push_msg with array priority works."""
        client = PybossaOneSignal(app_id="1", api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg(priority="10")
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_notification

        self.payload['app_id'] = "1"
        self.payload['priority'] = "10"

        mock.assert_called_with(client.api_url,
                                headers=client.header,
                                json=self.payload)

    @patch('pbsonesignal.requests.post')
    @raises(CreateNotification)
    def test_push_msg_fail(self, mock):
        """Test push_msg works."""
        client = PybossaOneSignal(app_id="1", api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 400
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.error_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg()
        assert tmp[0] == 400
        assert tmp[1] == 'BadRequest'
        assert tmp[2] == self.error_notification
<commit_msg>Refactor.<commit_after># -*- coding: utf8 -*-
# This file is part of PYBOSSA.
#
# Copyright (C) 2017 SciFabric LTD.
#
# PYBOSSA is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PYBOSSA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with PYBOSSA.  If not, see <http://www.gnu.org/licenses/>.
import json
from collections import namedtuple
from pbsonesignal import PybossaOneSignal
from pbsonesignal.exceptions import *
from nose.tools import raises
from mock import patch, MagicMock

FakeRequest = namedtuple('FakeRequest', ['text', 'status_code', 'headers'])

class TestPybossaOnesignal(object):

    valid_notification = {u'id': u'da360e9a-09d9-4992-a803-5bca978c5e0d',
                          u'recipients': 3}

    error_notification = {u'errors': ['an example error']}

    payload = None

    def setUp(self):
        self.payload = {
                        "included_segments": ["All"],
                        "excluded_sements": [],
                        "filters": [],
                        "contents": {"en": "English Message"},
                        "headings": {"en": "Heading"},
                        "url": "https://yoursite.com/",
                        "web_buttons": [{"id": "read-more-button",
                                        "text": "Read more",
                                        "icon": "http://i.imgur.com/MIxJp1L.png",
                                        "url": "https://yoursite.com"}],
                        "chrome_web_image": "https://yourimage.com",
                        "chrome_web_icon": "https://image"}

    @patch('pbsonesignal.requests.post')
    def test_push_msg(self, mock):
        """Test push_msg works."""
        client = PybossaOneSignal(app_id="1", api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg()
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_notification

    @patch('pbsonesignal.requests.post')
    def test_push_msg_app_ids(self, mock):
        """Test push_msg with array app_ids works."""
        client = PybossaOneSignal(app_ids=["1", "2"], api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg()
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_notification

        self.payload['app_ids'] = ["1", "2"]

        mock.assert_called_with(client.api_url,
                                headers=client.header("key"),
                                json=self.payload)

    @patch('pbsonesignal.requests.post')
    def test_push_msg_app_id(self, mock):
        """Test push_msg with array app_id works."""
        client = PybossaOneSignal(app_id="1", api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg()
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_notification

        self.payload['app_id'] = "1"

        mock.assert_called_with(client.api_url,
                                headers=client.header("key"),
                                json=self.payload)

    @patch('pbsonesignal.requests.post')
    def test_push_msg_include_player_ids(self, mock):
        """Test push_msg with array include_player_ids works."""
        client = PybossaOneSignal(app_id="1", api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg(include_player_ids=["1"])
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_notification

        self.payload['app_id'] = "1"
        self.payload['include_player_ids'] = ["1"]

        mock.assert_called_with(client.api_url,
                                headers=client.header("key"),
                                json=self.payload)

    @patch('pbsonesignal.requests.post')
    def test_push_msg_include_send_after(self, mock):
        """Test push_msg with array send_after works."""
        client = PybossaOneSignal(app_id="1", api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg(send_after="Thu Sep 24 2015 14:00:00 GMT-0700 (PDT)")
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_notification

        self.payload['app_id'] = "1"
        self.payload['send_after'] = "Thu Sep 24 2015 14:00:00 GMT-0700 (PDT)"

        mock.assert_called_with(client.api_url,
                                headers=client.header("key"),
                                json=self.payload)

    @patch('pbsonesignal.requests.post')
    def test_push_msg_include_delayed_option(self, mock):
        """Test push_msg with array delayed_option works."""
        client = PybossaOneSignal(app_id="1", api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg(delayed_option="last-active")
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_notification

        self.payload['app_id'] = "1"
        self.payload['delayed_option'] = "last-active"

        mock.assert_called_with(client.api_url,
                                headers=client.header("key"),
                                json=self.payload)

    @patch('pbsonesignal.requests.post')
    def test_push_msg_include_delivery_time_of_day(self, mock):
        """Test push_msg with array delivery_time_of_day works."""
        client = PybossaOneSignal(app_id="1", api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg(delivery_time_of_day="9:00AM")
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_notification

        self.payload['app_id'] = "1"
        self.payload['delivery_time_of_day'] = "9:00AM"

        mock.assert_called_with(client.api_url,
                                headers=client.header("key"),
                                json=self.payload)

    @patch('pbsonesignal.requests.post')
    def test_push_msg_include_ttl(self, mock):
        """Test push_msg with array ttl works."""
        client = PybossaOneSignal(app_id="1", api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg(ttl="259200")
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_notification

        self.payload['app_id'] = "1"
        self.payload['ttl'] = "259200"

        mock.assert_called_with(client.api_url,
                                headers=client.header("key"),
                                json=self.payload)

    @patch('pbsonesignal.requests.post')
    def test_push_msg_include_priority(self, mock):
        """Test push_msg with array priority works."""
        client = PybossaOneSignal(app_id="1", api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg(priority="10")
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_notification

        self.payload['app_id'] = "1"
        self.payload['priority'] = "10"

        mock.assert_called_with(client.api_url,
                                headers=client.header("key"),
                                json=self.payload)

    @patch('pbsonesignal.requests.post')
    @raises(CreateNotification)
    def test_push_msg_fail(self, mock):
        """Test push_msg works."""
        client = PybossaOneSignal(app_id="1", api_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 400
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.error_notification
        mock.return_value = fakeRequest
        tmp = client.push_msg()
        assert tmp[0] == 400
        assert tmp[1] == 'BadRequest'
        assert tmp[2] == self.error_notification
<|endoftext|>