Example #1
0
 def default(self,obj):
     if isinstance(obj,QuerySet):
         """ Queryset实例
         直接使用Django内置的序列化工具进行序列化
         但是如果直接返回serialize('json',obj)
         则在simplejson序列化时会被从当成字符串处理
         则会多出前后的双引号
         因此这里先获得序列化后的对象
         然后再用simplejson反序列化一次
         得到一个标准的字典(dict)对象
         """
         return simplejson.loads(serialize('json',obj))
     if isinstance(obj,models.Model):
         """
         如果传入的是单个对象,区别于QuerySet的就是
         Django不支持序列化单个对象
         因此,首先用单个对象来构造一个只有一个对象的数组
         这是就可以看做是QuerySet对象
         然后此时再用Django来进行序列化
         就如同处理QuerySet一样
         但是由于序列化QuerySet会被'[]'所包围
         因此使用string[1:-1]来去除
         由于序列化QuerySet而带入的'[]'
         """
         jsonstr = simplejson.loads(serialize('json',[obj])[1:-1])
         res = jsonstr.get('fields')
         res["id"]=jsonstr.get("pk")
         return res
     if hasattr(obj, 'isoformat'):
         #处理日期类型
         return obj.isoformat()
     return simplejson.JSONEncoder.default(self,obj)
Example #2
0
 def clean(self):
     """Validates message. It must have json format"""
     
     try:
         simplejson.loads(self.message)
     except ValueError as err:
         raise ValidationError(_("Message has wrong format: %s") % err)
Example #3
0
 def fetch_topic():
     response = urlfetch.fetch('http://api.ihackernews.com/page', deadline=10)
     topics = json.loads(response.content)
     topic_id = str(topics['items'][0]['id'])
     
     logging.error(topic_id)
     response = urlfetch.fetch('http://api.ihackernews.com/post/' + topic_id, deadline=10)
     topic = json.loads(response.content)
     topic['graph'] = {}
     topic['all_comments'] = []
     
     def generate_graph(comments):
         """Generates an id mapping between comments and their children.
         This graph is used for javascript layout.
             {
                 "comment_id": ["child_id", "child_id2"],
                 "comment_id2": ...
             }
         """
         for comment in comments:
             topic['all_comments'].append(comment)
             parent = topic['graph'].setdefault(comment['parentId'], [])
             parent.append(comment['id'])
             generate_graph(comment['children'])
     
     generate_graph(topic['comments'])
     return topic
Example #4
0
 def get(self, action=""):
     url = self.request.get("url")
     try: #bit.ly
         result = urllib.urlopen("http://api.bit.ly/v3/shorten?login=crowy&apiKey=R_57bab6c0fb01da4e1e0a5e22f73c3a4a&format=json&longUrl=%s" % urllib.quote(url)).read()
         json = simplejson.loads(result)
         if json['status_code'] == 200:
             self.response.out.write(json['data']['url'])
             return
         else:
             logging.warn(result)
     except:
         logging.warn("Unexpected error.")
     try: #goo.gl
         api_url = 'https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyBRoz9ItBIQgHwWbZbmkF45dFiRKub2XzI&userip='+self.request.remote_addr
         post_data = simplejson.dumps({'longUrl':url})
         result = urlfetch.fetch(url=api_url,
                     payload=post_data,
                     method=urlfetch.POST,
                     headers={'Content-Type': 'application/json'})
         if result.status_code == 200:
             result = simplejson.loads(result.content)
             self.response.out.write(result['id'])
             return
         else:
             logging.warn(result.content)
     except:
         logging.warn("Unexpected error.")
     try:#tinyurl
         short_url = urllib.urlopen("http://tinyurl.com/api-create.php?url=%s" % urllib.quote(url))
         self.response.out.write(short_url.read())
         return
     except:
         logging.warn("Unexpected error.")
     self.error(400)
Example #5
0
  def _lookup_user_info(self, access_token, access_secret):
    """Lookup User Info.

    Lookup the user on Yahoo!
    """

    user_info = self._get_default_user_info()

    # 1) Obtain the user's GUID.
    response = self.make_request(
        "http://social.yahooapis.com/v1/me/guid", token=access_token,
        secret=access_secret, additional_params={"format": "json"},
        protected=True)

    data = json.loads(response.content)["guid"]
    guid = data["value"]

    # 2) Inspect the user's profile.
    response = self.make_request(
        "http://social.yahooapis.com/v1/user/%s/profile/usercard" % guid,
         token=access_token, secret=access_secret,
         additional_params={"format": "json"}, protected=True)

    data = json.loads(response.content)["profile"]

    user_info["id"] = guid
    user_info["username"] = data["nickname"].lower()
    user_info["name"] = data["nickname"]
    user_info["picture"] = data["image"]["imageUrl"]

    return user_info
Example #6
0
def retrievelattice(params):
    '''
    '''
    name = params['name']
    version = params['version']
    branch=params['branch']
    if params.has_key('description'):
        description = params['description']
    else:
        description = None
    if params.has_key('latticetype'):
        latticetype = params['latticetype']
        latticetype = json.loads(latticetype)
        if not isinstance(latticetype, dict):
            raise TypeError("Lattice type data parameter format error.")
    else:
        latticetype = None  
    if params.has_key('withdata'):
        withdata = bool(json.loads(params['withdata'].lower()))
    else:
        withdata = False  
    if params.has_key('rawdata'):
        rawdata = bool(json.loads(params['rawdata'].lower()))
    else:
        rawdata = False  
        
    result = latinst.retrievelattice(name, version, branch, description=description, latticetype=latticetype, withdata=withdata, rawdata=rawdata)
    
    return result
Example #7
0
    def test_correct_setup(self):
        request = MockRequest()
        request.GET = {"format": "json"}
        request.method = "GET"

        # Verify the explicit 'through' relationships has been created correctly
        resource = api.canonical_resource_for("taggabletag")
        resp = resource.wrap_view("dispatch_detail")(request, pk=self.taggabletag_1.pk)
        data = json.loads(resp.content)
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(data["tag"], "/v1/tag/1/")
        self.assertEqual(data["taggable"], "/v1/taggable/1/")

        resource = api.canonical_resource_for("taggable")
        resp = resource.wrap_view("dispatch_detail")(request, pk=self.taggable_1.pk)
        data = json.loads(resp.content)
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(data["name"], "exam")

        resource = api.canonical_resource_for("tag")
        resp = resource.wrap_view("dispatch_detail")(request, pk=self.tag_1.pk)
        data = json.loads(resp.content)
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(data["name"], "important")

        # and check whether the extradata is present
        self.assertEqual(data["extradata"]["name"], u"additional")
Example #8
0
 def save(self):
     data = self.cleaned_data
     name = data['name']
     handler = ImageHandlerAlbumCoverTemp()
     handler.load_by_url(data['thumb'])
     new_handler = handler.store()
     new_handler.save_thumbnails()
     artist = self.artist
     new = True
     try:
         album = Album.objects.get(name=name, artist=artist)
         new = False
     except Album.DoesNotExist:
         album = Album.objects.create(
             name=name,
             year=data['year'],
             artist=artist
         )
     self.is_new = new
     styles = []
     for style in simplejson.loads(data['style']):
         styles.append(AlbumStyle.objects.get_or_create(name=style)[0])
     genres = []
     for genre in simplejson.loads(data['genre']):
         genres.append(AlbumGenre.objects.get_or_create(name=genre)[0])
     album.set_metadata_object(self.metadata)
     album.artist = artist
     album.style = styles
     album.genre = genres
     album.year = data['year']
     album.thumb = handler.storage.filename
     album.save()
     return album
Example #9
0
def updatelattice(params):
    '''
    '''
    name=params['name']
    version=params['version']
    branch=params['branch']
    if params.has_key('latticetype'):
        latticetype = params['latticetype']
        latticetype = json.loads(latticetype)
        if not isinstance(latticetype, dict):
            raise TypeError("Lattice type data parameter format error.")
    else:
        latticetype=None
    if params.has_key('creator'):
        creator = params['creator']
    else:
        creator = None
        
    if params.has_key('description'):
        description = params['description']
    else:
        description = None
    if params.has_key('lattice'):
        lattice = params['lattice']
        lattice = json.loads(lattice)
        if not isinstance(lattice, dict):
            raise TypeError("Lattice type data parameter format error.")
    else:
        lattice = None
    
    result = latinst.updatelattice(name, version, branch, creator=creator, description=description, 
                                   latticetype=latticetype, lattice=lattice)
    return {'result': result}
Example #10
0
    def test_get(self):
        # Import so that there will be a task object
        self.dataset.import_data(self.user, self.upload, 0)

        utils.wait()

        # Refetch dataset so that attributes will be updated
        self.dataset = Dataset.objects.get(id=self.dataset.id)

        response = self.client.get('/api/1.0/dataset/%s/' % self.dataset.slug, **self.auth_headers)

        self.assertEqual(response.status_code, 200)

        body = json.loads(response.content)

        self.assertEqual(body['name'], self.dataset.name)
        self.assertEqual(body['description'], self.dataset.description)
        self.assertEqual(body['row_count'], self.dataset.row_count)
        self.assertEqual(body['sample_data'], self.dataset.sample_data)
        self.assertEqual(body['column_schema'], self.dataset.column_schema)
        self.assertEqual(body['creator']['email'], self.dataset.creator.email)

        task_response = self.client.get('/api/1.0/task/%i/' % self.dataset.current_task.id, **self.auth_headers)

        self.assertEqual(task_response.status_code, 200)

        self.assertEqual(body['current_task'], json.loads(task_response.content))

        self.assertEqual(len(body['related_uploads']), 0)
        self.assertEqual(len(body['data_uploads']), 1)
        self.assertEqual(body['initial_upload'], '/api/1.0/data_upload/%i/' % self.dataset.initial_upload.id)
Example #11
0
    def test_search_datasets(self):
        second_dataset = Dataset.objects.create(
            name='Second dataset',
            description='contributors',
            creator=self.dataset.creator)
        second_dataset.update_full_text()

        # Should match both
        response = self.client.get('/api/1.0/dataset/?q=contributors', **self.auth_headers)

        self.assertEqual(response.status_code, 200)

        body = json.loads(response.content)

        self.assertEqual(body['meta']['total_count'], 2)
        self.assertEqual(len(body['objects']), 2)

        # Should match only the second dataset
        response = self.client.get('/api/1.0/dataset/?q=second', **self.auth_headers)

        self.assertEqual(response.status_code, 200)

        body = json.loads(response.content)

        self.assertEqual(body['meta']['total_count'], 1)
        self.assertEqual(len(body['objects']), 1)
        self.assertEqual(int(body['objects'][0]['id']), second_dataset.id)
Example #12
0
def tweet_new_post_task(post_id):

    try:
        twitter = Twitter()
    except:
        return

    post = Post.objects.get(id=post_id)

    is_mod = post.author.is_administrator_or_moderator()
    if is_mod or post.author.reputation > askbot_settings.MIN_REP_TO_TWEET_ON_OTHERS_ACCOUNTS:
        tweeters = User.objects.filter(social_sharing_mode=const.SHARE_EVERYTHING)
        tweeters = tweeters.exclude(id=post.author.id)
        access_tokens = tweeters.values_list('twitter_access_token', flat=True)
    else:
        access_tokens = list()

    tweet_text = post.as_tweet()

    for raw_token in access_tokens:
        token = simplejson.loads(raw_token)
        twitter.tweet(tweet_text, access_token=token)

    if post.author.social_sharing_mode != const.SHARE_NOTHING:
        token = simplejson.loads(post.author.twitter_access_token)
        twitter.tweet(tweet_text, access_token=token)
Example #13
0
    def test_create_put_twice(self):
        new_dataset = {
            'name': 'New dataset!',
            'description': 'Its got yummy data!'
        }

        response = self.client.put('/api/1.0/dataset/new-slug/', content_type='application/json', data=json.dumps(new_dataset), **self.auth_headers)

        self.assertEqual(response.status_code, 201)

        update_dataset = {
            'name': 'Updated dataset!'
        }
        
        body = json.loads(response.content)

        self.assertEqual(body['name'], 'New dataset!')
        self.assertEqual(body['slug'], 'new-slug')
        dataset_id = body['id']

        response = self.client.put('/api/1.0/dataset/new-slug/', content_type='application/json', data=json.dumps(update_dataset), **self.auth_headers)

        self.assertEqual(response.status_code, 202)

        body = json.loads(response.content)

        self.assertEqual(body['name'], 'Updated dataset!')
        self.assertEqual(body['slug'], 'new-slug')
        self.assertEqual(body['id'], dataset_id)

        # One dataset is created by setup
        self.assertEqual(Dataset.objects.all().count(), 2)
Example #14
0
    def testEnrollUser(self):
        c = self.login("admin", "test")

        user = User.objects.get(username="******")

        course = Course.objects.all()[0]
        user.courses.remove(course)

        url = "/siteadmin/users/%d/enroll/" % user.id

        self.assertFalse(user.courses.filter(id=course.id).exists())
        response = c.post(url, {"course_id": course.id})
        self.assertEqual(response.status_code, 200)
        json_response = json.loads(response.content)
        self.assertTrue(json_response["success"])
        self.assertTrue(user.courses.filter(id=course.id).exists())

        response = c.post(url, {"course_id": course.id})
        self.assertEqual(response.status_code, 200)
        json_response = json.loads(response.content)
        self.assertTrue(json_response["success"])
        self.assertTrue(user.courses.filter(id=course.id).exists())

        response = c.post(url, {"course_id": 12309123098120398})
        self.assertEqual(response.status_code, 200)
        json_response = json.loads(response.content)
        self.assertFalse(json_response["success"])
Example #15
0
 def test_update_annotation(self):
     annot = Annotation.annotations.active()[0]
     self.api_client.login(username='******', password='******')
     url = reverse('annotation_handler',
                   kwargs=dict(creator_id=1,
                              annotation_id=annot.id)
                  )
     data='''
         {"annotation":
             {
             "text": "Annotation body TEST updated",
             "type": "Comment",
             "target": [
                 {"url": "http://dlib.nyu.edu/awdl/books/derportrtkopfd00borc/test"}
                 ]
             }
         }'''
     resp = self.api_client.put(
         url,
         data=data,
         content_type="application/json; charset=UTF-8",
     )
     eq_(resp.status_code, 200)
     eq_(
         simplejson.loads(resp.content)['text'],
         simplejson.loads(data)['annotation']['text'],
     )
     eq_(
         Annotation.annotations.active().get(id=annot.id).text,
         "Annotation body TEST updated"
     )
Example #16
0
    def testCampListAuth(self):
        user, key = AUTHS['playaevents']
        seed = random.randint(0,1000000000)
        url = sign_url('/events/api/%s/2011/camp/' % APIS['playaevents'], user, key, seed=str(seed))
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        # use one of the camps to get details
        camps = simplejson.loads(response.content)
        self.assert_(len(camps) > 0)

        camp = random.choice(camps)
        seed += 1
        url = sign_url('/events/api/%s/2011/camp/%i/' % (APIS['playaevents'], camp['id']), user, key, seed=str(seed))
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        camp2 = simplejson.loads(response.content)

        self.assert_(len(camp2) > 0)
        camp2 = camp2[0]

        keys1 = camp.keys()
        keys2 = camp.keys()
        keys1.sort()
        keys2.sort()

        self.assertEqual(keys1, keys2)

        for key in keys1:
            self.assertEqual(camp[key], camp2[key])
Example #17
0
    def testRemoveUserFromCourse(self):
        c = self.login("admin", "test")

        course = Course.objects.all()[0]

        url = "/siteadmin/courses/%d/remove_user/" % course.id

        user = course.users.all()[0]

        self.assertTrue(course.users.filter(id=user.id).exists())  # user is in course
        response = c.post(url, {"username": user.username})
        self.assertEqual(response.status_code, 200)
        json_response = json.loads(response.content)
        self.assertTrue(json_response["success"])
        self.assertFalse(course.users.filter(username=user.username).exists())

        response = c.post(url, {"username": user.username})
        self.assertEqual(response.status_code, 200)
        json_response = json.loads(response.content)
        self.assertFalse(json_response["success"])

        response = c.post(url, {"username": "******"})
        self.assertEqual(response.status_code, 200)
        json_response = json.loads(response.content)
        self.assertFalse(json_response["success"])

        response = c.post(url)
        self.assertEqual(response.status_code, 200)
        json_response = json.loads(response.content)
        self.assertFalse(json_response["success"])
Example #18
0
    def test_layer_acls(self):
        """ Verify that the layer_acls view is behaving as expected
        """

        # Test that HTTP_AUTHORIZATION in request.META is working properly
        valid_uname_pw = "%s:%s" % (settings.GEOSERVER_CREDENTIALS[0],settings.GEOSERVER_CREDENTIALS[1])
        invalid_uname_pw = "%s:%s" % ("n0t", "v@l1d")

        valid_auth_headers = {
            'HTTP_AUTHORIZATION': 'basic ' + base64.b64encode(valid_uname_pw),
        }
        
        invalid_auth_headers = {
            'HTTP_AUTHORIZATION': 'basic ' + base64.b64encode(invalid_uname_pw),
        }
       
        # Test that requesting when supplying the GEOSERVER_CREDENTIALS returns the expected json 
        expected_result = {'rw': [],'ro': [],'name': settings.GEOSERVER_CREDENTIALS[0],'is_superuser':  True,'is_anonymous': False}
        c = Client()
        response = c.get('/data/acls', **valid_auth_headers)
        response_json = json.loads(response.content)
        self.assertEquals(expected_result, response_json) 

        # Test that requesting when supplying invalid credentials returns the appropriate error code
        response = c.get('/data/acls', **invalid_auth_headers)
        self.assertEquals(response.status_code, 401)
       
        # Test logging in using Djangos normal auth system 
        c.login(username='******', password='******')
       
        # Basic check that the returned content is at least valid json
        response = c.get("/data/acls")
        response_json = json.loads(response.content)
Example #19
0
    def test_people_friends_filter_by_has_app(self):
        """
        Tests /people/1/@friends filtered by hasApp
        """
        path = '/people/1/@friends'

        params = { 'xoauth_requestor_id': 1,
                   'filterBy'           : 'hasApp',
                   'count'              : 500,
                   }
        headers = self.get_headers(path, 'GET', params)
        res = self.client.get(path, params, **headers)
        self.assertEquals(res.status_code, 200)

        data1 = json.loads(res.content)
        self.assertEqual(all([x['hasApp'] for x in data1.get('entry')]), True)

        params = { 'xoauth_requestor_id': 1,
                   'count'              : 500,
                   }
        headers = self.get_headers(path, 'GET', params)
        res = self.client.get(path, params, **headers)
        self.assertEquals(res.status_code, 200)

        data2 = json.loads(res.content)
        self.assertEqual([x['id'] for x in data1.get('entry') if x['hasApp']],
                         [x['id'] for x in data2.get('entry') if x['hasApp']])
Example #20
0
    def test_keys_collection_get(self):
        resp = self.client.get(self.keys_url)
        self.assertEqual(resp.content, "[]")

        PublicKeyPair.objects.create(user=self.user, name="key pair 1",
                content="content1")

        resp = self.client.get(self.keys_url)
        resp_list = json.loads(resp.content);
        exp_list = [{"content": "content1", "id": 1,
                    "uri": self.keys_url + "/1", "name": "key pair 1",
                    "fingerprint": "unknown fingerprint"}]
        self.assertEqual(resp_list, exp_list)

        PublicKeyPair.objects.create(user=self.user, name="key pair 2",
                content="content2")

        resp = self.client.get(self.keys_url)
        resp_list = json.loads(resp.content)
        exp_list = [{"content": "content1", "id": 1,
                     "uri": self.keys_url + "/1", "name": "key pair 1",
                     "fingerprint": "unknown fingerprint"},
                    {"content": "content2", "id": 2,
                     "uri": self.keys_url + "/2",
                     "name": "key pair 2",
                     "fingerprint": "unknown fingerprint"}]

        self.assertEqual(resp_list, exp_list)
  def get(self):
    for i in range(10):
      error = random.choice(range(4))
      project = 'frontend'
      try:
        if error == 0:
          x = 10 / 0
          project = 'backend'
        elif error == 1:
          json.loads('{"abc", [1, 2')
        elif error == 2:
          x = {}
          y = x['y']
        elif error == 3:
          x = {}
          y = x['z']
      except:
        excInfo = sys.exc_info()
        stack = traceback.format_exc()
        env = random.choice([''])
        exception = {
          'timestamp': time.time(),    
          'project': project,
          'serverName':'%s %s %d' % (env, project, random.choice(range(3))),
          'type': excInfo[0].__module__ + '.' + excInfo[0].__name__,
          'environment': env,
          'message': str(excInfo[1]),
          'logMessage': 'Log message goes here',
          'backtrace': stack,
          'context':{'userId':random.choice(range(20))}
        }
        putException(exception)

    self.response.out.write('Done!')
Example #22
0
    def test_people_self_with_xoauth_requestor_id(self):
        """
        Tests people_self
        """
        params = { 'xoauth_requestor_id': 1 }
        path = '/people/1/@self'
        headers = self.get_headers(path, 'GET', params)
        res = self.client.get(path, params, **headers)
        self.failUnlessEqual(res.status_code, 200)

        data = json.loads(res.content)
        self.assertEqual(data['entry']['isOwner'], True)
        self.assertEqual(data['entry']['isViewer'], True)

        # invalid xoauth_requestor_id
        params = { 'xoauth_requestor_id': 0 }
        path = '/people/1/@self'
        headers = self.get_headers(path, 'GET', params)
        res = self.client.get(path, params, **headers)
        self.failUnlessEqual(res.status_code, 200)

        data = json.loads(res.content)
        self.assertEqual(data['entry']['isOwner'], False)
        self.assertEqual(data['entry']['isViewer'], False)

        # Getting another's page
        params = { 'xoauth_requestor_id': 1 }
        path = '/people/3/@self'
        headers = self.get_headers(path, 'GET', params)
        res = self.client.get(path, params, **headers)
        self.failUnlessEqual(res.status_code, 200)

        data = json.loads(res.content)
        self.assertEqual(data['entry']['isOwner'], False)
        self.assertEqual(data['entry']['isViewer'], False)
Example #23
0
    def create(self, request, workspace_id, tab_id):
        user = get_user_authentication(request)

        if 'igadget' not in request.POST:
            return HttpResponseBadRequest(get_xml_error(_("iGadget JSON expected")), mimetype='application/xml; charset=UTF-8')

        # Data checking and parsing
        try:
            igadget = simplejson.loads(request.POST['igadget'])
        except:
            return HttpResponseBadRequest(get_xml_error(_('iGadget data is not valid JSON')))

        initial_variable_values = None
        if 'variable_values' in request.POST:
            try:
                initial_variable_values = simplejson.loads(request.POST['variable_values'])
            except:
                return HttpResponseBadRequest(get_xml_error(_('variables_values must be a valid JSON value')))

        # iGadget creation
        try:
            tab = Tab.objects.get(workspace__users__id=user.id, workspace__pk=workspace_id, pk=tab_id)
            igadget = SaveIGadget(igadget, user, tab, initial_variable_values)
            igadget_data = get_igadget_data(igadget, user, tab.workspace)

            return HttpResponse(json_encode(igadget_data), mimetype='application/json; charset=UTF-8')
        except Gadget.DoesNotExist, e:
            msg = _('referred gadget %(gadget_uri)s does not exist.') % {'gadget_uri': igadget['gadget']}

            raise TracedServerError(e, {'igadget': igadget, 'user': user, 'tab': tab}, request, msg)
Example #24
0
    def testCampListNoAuth(self):
        """Test getting an unauthenticated camp list"""
        url = '/events/api/%s/2011/camp/' % APIS['playaevents']
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        # use one of the camps to get details
        camps = simplejson.loads(response.content)
        self.assert_(len(camps) > 0)

        camp = random.choice(camps)
        response = self.client.get('%s%i/' % (url, camp['id']))
        self.assertEqual(response.status_code, 200)

        camp2 = simplejson.loads(response.content)

        self.assert_(len(camp2) > 0)
        camp2 = camp2[0]

        keys1 = camp.keys()
        keys2 = camp.keys()
        keys1.sort()
        keys2.sort()

        self.assertEqual(keys1, keys2)

        for key in keys1:
            self.assertEqual(camp[key], camp2[key])
Example #25
0
    def test_get_stats(self):
        # Get all of the cpu-system stat data
        response = test_get_rest_data(
            'v1/stats/data/local/controller/192.168.1.1/cpu-system', {
                'start-time': make_timestamp(1, 0),
                'end-time': make_timestamp(10, 11),
                'sample-interval': 0
            })
        self.assertEqual(response.status_code, 200)
        results = simplejson.loads(response.content)
        self.check_stats_results(
            results,
            self.STATS_DATA['controller-stats']['192.168.1.1']['cpu-system'])

        # Get just one days data of the cpu-system stat
        response = test_get_rest_data(
            'v1/stats/data/local/controller/192.168.1.1/cpu-system', {
                'start-time': make_timestamp(1, 0),
                'end-time': make_timestamp(1, 4),
                'sample-interval': 0
            })
        self.assertEqual(response.status_code, 200)
        results = simplejson.loads(response.content)
        self.check_stats_results(
            results, self.STATS_DATA['controller-stats']['192.168.1.1']
            ['cpu-system'][:5])

        # Get two day range for cpu-system
        response = test_get_rest_data(
            'v1/stats/data/local/controller/192.168.1.1/cpu-system', {
                'start-time': make_timestamp(1, 2, 10),
                'end-time': make_timestamp(2, 2, 20),
                'sample-interval': 0
            })
        self.assertEqual(response.status_code, 200)
        results = simplejson.loads(response.content)
        self.check_stats_results(
            results, self.STATS_DATA['controller-stats']['192.168.1.1']
            ['cpu-system'][3:7])

        # Get all of the flow-count switch stat data
        response = test_get_rest_data(
            'v1/stats/data/local/switch/00:01:02:03:04:05/flow-count', {
                'start-time': make_timestamp(1, 0),
                'end-time': make_timestamp(2, 0),
                'sample-interval': 0
            })
        self.assertEqual(response.status_code, 200)
        results = simplejson.loads(response.content)
        self.check_stats_results(
            results,
            self.STATS_DATA['switch-stats']['00:01:02:03:04:05']['flow-count'])

        # Get part of the packet-count switch stat data
        response = test_get_rest_data(
            'v1/stats/data/local/switch/00:01:02:03:04:05/packet-count', {
                'start-time': make_timestamp(1, 0),
                'end-time': make_timestamp(1, 1),
                'sample-interval': 0
            })
        self.assertEqual(response.status_code, 200)
        results = simplejson.loads(response.content)
        self.check_stats_results(
            results, self.STATS_DATA['switch-stats']['00:01:02:03:04:05']
            ['packet-count'][:2])
Example #26
0
 def load_context_data(self):
     if self.context == '':
         self.context = '{}'
     self.context_data = simplejson.loads(self.context)
     return self.context_data
Example #27
0
    def test_PATCH_detail(self):
        '''
            Test PATCH request to the detail endpoint. Check if specific fields have been updated successfully.
        '''

        # sign in
        sign_in_resp = client.get('/{0}/me/'.format(self.api),
                                  data={
                                      "user": self.userprofile[0].username,
                                      "password": "******",
                                      "stay_signed_in": "True"
                                  })
        # check that sign-in was successful
        self.assertEqual(
            sign_in_resp.status_code, 200,
            'Status code should be 200. Instead, it is {status_code}.'.format(
                status_code=sign_in_resp.status_code))

        itemtag = self.itemtag[0]

        # create test object to PATCH to the server
        new_item = self.item[1]
        new_image = self.image[1]
        new_owner = self.userprofile[
            1]  # owner must be person who signs in. otherwise, it will be overwritten by default to be the person who signs in
        image_uri = construct_detail_uri(
            version=self.api,
            resource=ImageResource._meta.resource_name,
            uuid=new_image.uuid)
        item_uri = construct_detail_uri(
            version=self.api,
            resource=ItemResource._meta.resource_name,
            uuid=new_item.uuid)
        owner_uri = construct_detail_uri(
            version=self.api,
            resource=UserResource._meta.resource_name,
            uuid=new_owner.uuid)
        x = 1
        y = 1
        num = 100
        t = itemtag.created_time

        PATCH_data = {
            'item':
            item_uri,
            'image':
            image_uri,
            'x':
            y,
            'y':
            x,
            'num':
            num,
            'owner':
            owner_uri,
            'created_time':
            datetime.datetime(1, 1, 1, 0, 0, 0, 0, t.tzinfo).isoformat(),
            'updated_time':
            datetime.datetime(1, 1, 1, 0, 0, 0, 0, t.tzinfo).isoformat(),
            'resource_uri':
            'NA'
        }

        # PATCH object to detail URI
        resp = client.patch(self.detail_uri, data=PATCH_data)

        # check status code if object was successfully updated
        self.assertEqual(
            resp.status_code, 202,
            'Status code should be 202. Instead, it is {status_code}.'.format(
                status_code=resp.status_code))

        # URI of the new object that is created in the database
        new_uri = json.loads(resp.content)['resource_uri']

        # data of GETting new_uri
        GET_resp = client.get(new_uri, data=None)
        GET_data = json.loads(GET_resp.content)

        # make sure writable PATCHed fields are updated, unmodifiable fields are are not updated
        # if an AssertionError occurs here, check self.writeable_fields and verify the write permissions on that field
        for field, is_writable in self.fields.iteritems():
            if is_writable:
                # if the field is writable, show that the fields are updated
                self.assertEqual(
                    PATCH_data[field], GET_data[field],
                    'GET Value for writable Field \'{field}\' differs from PATCHed Value. They should be the same.'
                    .format(field=field))
            else:
                # if the field is not writable, show that the fields are not equal
                self.assertNotEqual(
                    PATCH_data[field], GET_data[field],
                    'GET Value for non-writable Field \'{field}\' is the same as the PATCHed Value. They should be different.'
                )
Example #28
0
    def render(self, name, value, *args, **kwargs):
        if value is None:
            lat, lon, address = DEFAULT_LAT, DEFAULT_LNG, DEFAULT_ADDRESS
            value = {'lat': lat, 'lon': lon, 'address': address}
        else:
            value = json.loads(value)
            lat, lon, address = float(value['lat']), float(value['lon']), value['address']
        curLocation = json.dumps(value, cls=DjangoJSONEncoder)

        js = '''
            <script type="text/javascript">
            //<![CDATA[
                var map_%(id)s;

                function save_position_%(id)s(point, address) {
                    var input = document.getElementById("id_%(name)s");
                    var location = {'lat':point.getLat().toFixed(12), 'lon':point.getLon().toFixed(12)};
                    location.address = '%(address)s';
                    if (address) {
                        location.address = address;
                    }
                    input.value = JSON.stringify(location);
                    document.getElementById('address_%(name)s').value = location.address;

                    var marker = new DG.Markers.Common({geoPoint:point});
                    map_%(id)s.markers.removeAll();
                    map_%(id)s.markers.add(marker);
                    map_%(id)s.setCenter(point, 16);

                    map_%(id)s.geocoder.get(point, {
                        types: ['district'],
                        success: function(geocoderObjects) {
                            var district = geocoderObjects[0].getShortName();
                            if ( district ) {
                                if ( $('#id_1-map2gis_district').length ) {
                                    $('#id_1-map2gis_district').val(district);
                                    console.log(district);
                                }
                            }
                        }
                    });
                }

                function load_%(id)s() {
                    map_%(id)s = new DG.Map("map_%(name)s");
                    map_%(id)s.controls.add(new DG.Controls.Zoom());
                    var point = new DG.GeoPoint(%(lon)f, %(lat)f);
                    map_%(id)s.setCenter(point, 16);

                    if ('%(address)s' && %(lon)f && %(lat)f) {
                        var marker = new DG.Markers.Common({geoPoint: point});
                        map_%(id)s.markers.add(marker);
                    }

                    map_%(id)s.addEventListener(map_%(id)s.getContainerId(), 'DgClick', function(evt){
                        map_%(id)s.geocoder.get(evt.getGeoPoint(), {
                            types: ['district', 'street', 'living_area', 'place', 'house'],
                            success: function(geocoderObjects) {
                                save_position_%(id)s(geocoderObjects[0].getCenterGeoPoint(), geocoderObjects[0].getName());
                            }
                        });
                    });

                    $('#address_%(name)s').autocomplete({
                        source: function(request, response) {
                            if (request.term.length > 2) {
                                map_%(id)s.geocoder.get(request.term, {
                                    types: ['district', 'street', 'living_area', 'place', 'house'],
                                    limit: 10,
                                    success: function(geocoderObjects) {
                                        response($.map(geocoderObjects, function(item) {
                                            return {
                                                value: item.getName(),
                                                location: item.getCenterGeoPoint()
                                            }
                                        }));
                                    }
                                });
                            }
                        },
                        select: function(event, ui) {
                            save_position_%(id)s(ui.item.location, ui.item.value);
                        }
                    });

                    $('#address_%(name)s').focusout(function(){
                        save_position_%(id)s(map_%(id)s.getCenter(), $('#address_%(name)s').val());
                    });
                }

                $(document).ready(function(){
                    load_%(id)s();
                });
            //]]>
            </script>
        ''' % dict(id=name.replace('-', '_'), name=name, lat=lat, lon=lon, address=address)

        html = self.inner_widget.render("%s" % name, "%s" % curLocation, dict(id='id_%s' % name))

        html += u'<div id="map_%s" style="width:%dpx; height:%dpx"></div>' % (
            name, self.map_width, self.map_height)
        html += u'<label>%s: </label><input id="address_%s" type="text" style="width:200px" />' \
                u'<br />' % (u'Поиск по адресу', name)
        html += u'<span class="def_address">Текущий адрес: %s</span>' % (
            address if address else u'(Не указан)',)

        return mark_safe(html + js)
Example #29
0
 def test_mary_index(self):
     response = self.run_get('mary', '/api/budgetline', {'budget': 33})
     result = simplejson.loads(response.content)
     self.assertEquals(response.status_code, 200)
     self.assertEquals(len(result), 1)
     self.assertEquals(result[0]['total_amount'], '200')
def fetch_json(url, service, list_key=None):
    fetched = urlopen(url).read()
    data = json.loads(fetched)
    if list_key:
        data = data[list_key]
    return data
Example #31
0
 def testPartyAPI(self):
     res = self.client.get(reverse('party-handler')) #, kwargs={'object_id': self.mk_1.id}),{'verbs':'posted'})
     self.assertEqual(res.status_code,200)
     parties = json.loads(res.content)
     self.assertEqual(map(lambda x:x['id'], parties), [self.party_1.id, self.party_2.id])
Example #32
0
 def _get_pk_values(serial_str):
     ret_list = []
     serial_list = simplejson.loads(serial_str)
     for obj_dict in serial_list:
         ret_list.append(obj_dict["pk"])
     return ret_list
Example #33
0
 def test_api_tag(self):
     res = self.client.get(
         self._reverse_api('api_dispatch_detail', pk=self.tags[0].id))
     self.assertEqual(res.status_code, 200)
     res_json = json.loads(res.content)
     self.assertEqual(res_json['name'], self.tags[0].name)
Example #34
0
    def test_GET_list(self):
        '''
            Test GET request to the list endpoint. Check if the returned fields are correct.
        '''

        # sign in ?

        itemtag = self.itemtag[0]
        image = self.image[0]

        # GET ItemTag list
        resp = client.get('{list_uri}?limit=0'.format(list_uri=self.list_uri),
                          data=None)
        # check status code if object was successfully received
        self.assertEqual(
            resp.status_code, 200,
            'Status code should be 200. Instead, it is {status_code}.'.format(
                status_code=resp.status_code))
        GET_data = json.loads(resp.content)

        # check list dictionary
        self.assertTrue('meta' in GET_data,
                        'GET list should return a Field \'meta\'')
        self.assertTrue('objects' in GET_data,
                        'GET list should return a Field \'objects\'')
        # assuming tastypie GET list endpoint works...
        self.assertEqual(
            len(GET_data['objects']),
            ItemTag.objects.filter(is_active=True).count(),
            'Number of returned elements does not match number of objects in the database'
        )

        # Filters
        # Image
        image_uri = construct_detail_uri(version=self.api,
                                         resource='image',
                                         uuid=image.uuid)
        # set limit=0 so that all the objects are returned (not paginated)
        resp = client.get('{itemtag_uri}?image={image_uri}&limit=0'.format(
            itemtag_uri=self.list_uri, image_uri=image_uri))
        # check status code if object was successfully received
        self.assertEqual(
            resp.status_code, 200,
            'Status code should be 200. Instead, it is {status_code}.'.format(
                status_code=resp.status_code))
        GET_data = json.loads(resp.content)
        # check if the the number of filtered objects is correct
        filtered_itemtag_uuids = ItemTag.objects.filter(
            is_active=True, image=image).values_list('uuid', flat=True)
        self.assertEqual(
            len(GET_data['objects']), filtered_itemtag_uuids.count(),
            'Number of returned filtered elements does not match number of filtered objects in the database'
        )
        # check that the objects in the list is what you would get from the database

        for obj in GET_data['objects']:
            uuid = parse_uri(obj['resource_uri'])['uuid']
            self.assertTrue(
                uuid in filtered_itemtag_uuids,
                'Returned object in list does not match any returned object from the database'
            )
Example #35
0
    def test_GET_detail(self):
        '''
            Test GET request to the detail endpoint. Check if the returned fields are correct.
            Also check for proper filtering.
        '''

        # sign in ?

        item = self.item[0]

        # GET Item detail
        resp = client.get(self.detail_uri, data=None)
        # check status code if object was successfully received
        self.assertEqual(
            resp.status_code, 200,
            'Status code should be 200. Instead, it is {status_code}.'.format(
                status_code=resp.status_code))
        GET_data = json.loads(resp.content)

        # check the number of returned fields
        self.assertEqual(
            len(GET_data), len(self.fields),
            'Total number of fields outputed is {wrong_num}. It should be {right_num}.'
            .format(wrong_num=len(GET_data), right_num=len(self.fields)))
        # make sure all the right fields are outputed in the API
        for key in self.fields:
            self.assertTrue(
                key in GET_data,
                'Field \'{field}\' is not in the returned JSON object.'.format(
                    field=key))

        # check the accuracy of each field
        self.assertEqual(GET_data['name'], item.name,
                         'Value for Field \'name\' is incorrect.')
        self.assertEqual(GET_data['brand_name'], item.brand_name,
                         'Value for Field \'brand_name\' is incorrect.')
        self.assertEqual(GET_data['description'], item.description,
                         'Value for Field \'description\' is incorrect.')
        self.assertEqual(GET_data['size'], item.size,
                         'Value for Field \'size\' is incorrect.')
        self.assertEqual(GET_data['color'], item.color,
                         'Value for Field \'color\' is incorrect.')
        self.assertEqual(GET_data['price'], item.price,
                         'Value for Field \'price\' is incorrect.')
        self.assertEqual(GET_data['url'], item.url,
                         'Value for Field \'price\' is incorrect.')
        self.assertEqual(GET_data['total_comments'], item.total_comments(),
                         'Value for Field \'total_comments\' is incorrect.')
        self.assertEqual(GET_data['total_votes'], item.total_votes(),
                         'Value for Field \'total_votes\' is incorrect.')
        # take out microsecond and use timezone javascript standard
        t = item.created_time
        self.assertEqual(
            GET_data['created_time'],
            datetime.datetime(t.year, t.month, t.day, t.hour, t.minute,
                              t.second, 0, t.tzinfo).isoformat(),
            'Value for Field \'created_time\' is incorrect.')
        t = item.updated_time
        self.assertEqual(
            GET_data['updated_time'],
            datetime.datetime(t.year, t.month, t.day, t.hour, t.minute,
                              t.second, 0, t.tzinfo).isoformat(),
            'Value for Field \'updated_time\' is incorrect.')
        owner_uri = construct_detail_uri(
            version=self.api,
            resource=UserResource._meta.resource_name,
            uuid=item.owner.uuid)
        self.assertEqual(GET_data['owner'], owner_uri,
                         'Value for Field \'owner\' is incorrect.')
        item_uri = construct_detail_uri(
            version=self.api,
            resource=ItemResource._meta.resource_name,
            uuid=item.uuid)
        comment_filter_uri = construct_filter_uri(
            version=self.api,
            resource=CommentResource._meta.resource_name,
            parameter='parent',
            filter_uri=item_uri)
        self.assertEqual(GET_data['comment'], comment_filter_uri,
                         'Value for Field \'comment\' is incorrect.')
        vote_filter_uri = construct_filter_uri(
            version=self.api,
            resource=VoteResource._meta.resource_name,
            parameter='parent',
            filter_uri=item_uri)
        self.assertEqual(GET_data['vote'], vote_filter_uri,
                         'Value for Field \'vote\' is incorrect.')
        resource_uri = construct_detail_uri(version=self.api,
                                            resource=self.resource_name,
                                            uuid=item.uuid)
        self.assertEqual(GET_data['resource_uri'], resource_uri,
                         'Value for Field \'resource_uri\' is incorrect.')
Example #36
0
    def test_POST_list(self):
        '''
            Test POST request to the list endpoint. Check if the posted information is correct.
        '''

        # POST a new itemtag to the backend
        user = self.userprofile[0]

        # sign in
        sign_in_resp = client.get('/{version}/me/'.format(version=self.api),
                                  data={
                                      "user": user.username,
                                      "password": "******",
                                      "stay_signed_in": "True"
                                  })
        # check that sign-in was successful
        self.assertEqual(
            sign_in_resp.status_code, 200,
            'Status code should be 200. Instead, it is {status_code}.'.format(
                status_code=sign_in_resp.status_code))

        # record initial number of itemtag objects
        initial_num_itemtags = ItemTag.objects.filter(is_active=True).count()

        # create test object to POST to the server
        new_item = self.item[1]
        new_image = self.image[1]
        new_owner = user  # owner must be person who signs in. otherwise, it will be overwritten by default to be the person who signs in
        image_uri = construct_detail_uri(
            version=self.api,
            resource=ImageResource._meta.resource_name,
            uuid=new_image.uuid)
        item_uri = construct_detail_uri(
            version=self.api,
            resource=ItemResource._meta.resource_name,
            uuid=new_item.uuid)
        owner_uri = construct_detail_uri(
            version=self.api,
            resource=UserResource._meta.resource_name,
            uuid=new_owner.uuid)
        x = .7
        y = .8
        num = 1
        POST_data = {
            'image': image_uri,
            'item': item_uri,
            'owner': owner_uri,
            'num': num,
            'x': x,
            'y': y
        }

        # POST object to list URI
        resp = client.post(self.list_uri, data=POST_data)
        # check status code if object was successfully created
        self.assertEqual(
            resp.status_code, 201,
            'Status code should be 201. Instead, it is {status_code}.'.format(
                status_code=resp.status_code))

        # URI of the new object that is created in the database
        new_uri = json.loads(resp.content)['resource_uri']
        # data of GETting new_uri
        GET_resp = client.get(new_uri, data=None)
        GET_data = json.loads(GET_resp.content)

        # make sure posted object exists
        self.assertEqual(
            resp.status_code, 201,
            'Status code should be 201. Instead, it is {status_code}.'.format(
                status_code=resp.status_code))
        self.assertEqual(
            POST_data['image'], GET_data['image'],
            'GET Value for Field \'image\' differs from POSTed Value')
        self.assertEqual(
            POST_data['item'], GET_data['item'],
            'GET Value for Field \'item\' differs from POSTed Value')
        self.assertEqual(
            POST_data['owner'], GET_data['owner'],
            'GET Value for Field \'owner\' differs from POSTed Value')
        self.assertEqual(
            POST_data['num'], GET_data['num'],
            'GET Value for Field \'owner\' differs from POSTed Value')
        self.assertEqual(
            POST_data['x'], GET_data['x'],
            'GET Value for Field \'x\' differs from POSTed Value')
        self.assertEqual(
            POST_data['y'], GET_data['y'],
            'GET Value for Field \'y\' differs from POSTed Value')

        # check that the number of itemtags has increased by 1
        final_num_itemtags = ItemTag.objects.filter(is_active=True).count()
        self.assertEqual(
            initial_num_itemtags + 1, final_num_itemtags,
            'Total number of objects (after posting) is not correct')
Example #37
0
def delete_notifications(request):
    post_data = simplejson.loads(request.raw_post_data)
    memo_set = models.ActivityAuditStatus.objects.filter(
        id__in=post_data['memo_ids'], user=request.user)
    memo_set.delete()
    request.user.update_response_counts()
Example #38
0
    def test_GET_detail(self):
        '''
            Test GET request to the detail endpoint. Check if the returned fields are correct.
            Also check for proper filtering.
        '''

        # sign in ?

        itemtag = self.itemtag[0]

        # GET ItemTag detail
        resp = client.get(self.detail_uri, data=None)
        # check status code if object was successfully received
        self.assertEqual(
            resp.status_code, 200,
            'Status code should be 200. Instead, it is {status_code}.'.format(
                status_code=resp.status_code))
        GET_data = json.loads(resp.content)

        # check the number of returned fields
        self.assertEqual(
            len(GET_data), len(self.fields),
            'Total number of fields outputed is {wrong_num}. It should be {right_num}.'
            .format(wrong_num=len(GET_data), right_num=len(self.fields)))
        # make sure all the right fields are outputed in the API
        for key in self.fields:
            self.assertTrue(
                key in GET_data,
                'Field \'{field}\' is not in the returned JSON object.'.format(
                    field=key))

        # check the accuracy of each field
        self.assertEqual(GET_data['num'], itemtag.num,
                         'Value for Field \'num\' is incorrect.')
        self.assertEqual(GET_data['x'], itemtag.x,
                         'Value for Field \'x\' is incorrect.')
        self.assertEqual(GET_data['y'], itemtag.y,
                         'Value for Field \'y\' is incorrect.')
        # take out microsecond and use timezone javascript standard
        t = itemtag.created_time
        self.assertEqual(
            GET_data['created_time'],
            datetime.datetime(t.year, t.month, t.day, t.hour, t.minute,
                              t.second, 0, t.tzinfo).isoformat(),
            'Value for Field \'created_time\' is incorrect.')
        t = itemtag.updated_time
        self.assertEqual(
            GET_data['updated_time'],
            datetime.datetime(t.year, t.month, t.day, t.hour, t.minute,
                              t.second, 0, t.tzinfo).isoformat(),
            'Value for Field \'updated_time\' is incorrect.')
        owner_uri = construct_detail_uri(
            version=self.api,
            resource=UserResource._meta.resource_name,
            uuid=itemtag.owner.uuid)
        self.assertEqual(GET_data['owner'], owner_uri,
                         'Value for Field \'owner\' is incorrect.')
        image_uri = construct_detail_uri(version=self.api,
                                         resource=itemtag.image.obj_type(),
                                         uuid=itemtag.image.uuid)
        self.assertEqual(GET_data['image'], image_uri,
                         'Value for Field \'image\' is incorrect.')
        item_uri = construct_detail_uri(version=self.api,
                                        resource=itemtag.item.obj_type(),
                                        uuid=itemtag.item.uuid)
        self.assertEqual(GET_data['item'], item_uri,
                         'Value for Field \'item\' is incorrect.')
        resource_uri = construct_detail_uri(version=self.api,
                                            resource=self.resource_name,
                                            uuid=itemtag.uuid)
        self.assertEqual(GET_data['resource_uri'], resource_uri,
                         'Value for Field \'resource_uri\' is incorrect.')
Example #39
0
def loads(txt):
    value = simplejson.loads(txt,
                             parse_float=Decimal,
                             encoding=settings.DEFAULT_CHARSET)
    assert isinstance(value, dict)
    return value
            costs_dict[a] = 1
        sf = f
        wp = create_wp(target_dict, penalty_dict, costs_dict, sf)

        ############
        print "####################################"
        print 'targets', wp.input_targets
        print 'penalties', wp.input_penalties
        print 'costs', wp.input_relativecosts

        wp.save()
        while not wp.done:
            time.sleep(2)
            print "  ", wp.status_html

        inpenalties = json.loads(wp.input_penalties)
        intargets = json.loads(wp.input_targets)

        if 'widespread' in inpenalties.keys():
            nspecies = 71
        else:
            nspecies = len(inpenalties.keys())

        r = wp.results

        #'ncosts, nspecies, sumpenalties, meanpenalties, scalefactor, meantarget, numspeciesmet, numplannningunits'
        fh.write(','.join([str(x) for x in [
            sum(json.loads(wp.input_relativecosts).values()),
            nspecies,
            sum(inpenalties.values()),
            mean(inpenalties.values()),
Example #41
0
 def test_api_party_list(self):
     res = self.client.get(reverse('party-handler'))
     self.assertEqual(res.status_code, 200)
     res_json = json.loads(res.content)
     self.assertEqual(len(res_json), 1)
     self.assertEqual(res_json[0]["name"], self.party_1.name)
Example #42
0
    def post(self, *args, **kwargs):
        form_dict = simplejson.loads(self.request.POST['form'])
        form = Form.get_by_name(kwargs['name'])
        form.update_from_dict(form_dict)

        return http.HttpResponse(_(u'Form updated with success'))
Example #43
0
 def test_api_member_list(self):
     res = self.client.get(reverse('member-handler'))
     self.assertEqual(res.status_code, 200)
     res_json = json.loads(res.content)
     self.assertEqual(len(res_json), self.num_mks)
Example #44
0
 def get_param(self, key):
     return simplejson.loads(self.params)[key]
Example #45
0
 def test_api_agenda(self):
     res = self.client.get(reverse('agenda-handler', args=[self.agenda.id]))
     self.assertEqual(res.status_code, 200)
     res_json = json.loads(res.content)
     self.assertEqual(res_json['name'], self.agenda.name)
Example #46
0
 def test_api_member(self):
     res = self.client.get(reverse('member-handler', args=[self.mks[0].id]))
     self.assertEqual(res.status_code, 200)
     res_json = json.loads(res.content)
     self.assertEqual(res_json['name'], self.mks[0].name)
Example #47
0
 def test_api_tag_for_vote(self):
     res = self.client.get(
         reverse('tag-handler', args=['laws', 'vote', self.vote_1.id]))
     self.assertEqual(res.status_code, 200)
     res_json = json.loads(res.content)
     self.assertEqual(len(res_json), 2)
Example #48
0
 def testEventlList(self):
     res = self.client.get(reverse('event-handler'))
     self.assertEqual(res.status_code, 200)
     res_json = json.loads(res.content)
     self.assertEqual(len(res_json), 1)
     self.assertEqual(res_json[0]['what'], 'ev2')
Example #49
0
 def test_api_vote(self):
     res = self.client.get(reverse('vote-handler', args=[self.vote_1.id]))
     self.assertEqual(res.status_code, 200)
     res_json = json.loads(res.content)
     self.assertEqual(len(res_json['for_votes']), self.num_mks)
Example #50
0
 def test_api_agenda_list(self):
     res = self.client.get(reverse('agenda-handler'))
     self.assertEqual(res.status_code, 200)
     res_json = json.loads(res.content)
     self.assertEqual(len(res_json), 1)
Example #51
0
 def from_json(self, content):
     """
     Given some JSON data, returns a Python dictionary of the decoded data.
     """
     return simplejson.loads(content)
Example #52
0
 def test_api_bill_list_with_days_back(self):
     res = self.client.get('%s?days_back=2' % reverse('bill-handler'))
     self.assertEqual(res.status_code, 200)
     res_json = json.loads(res.content)
     self.assertEqual(len(res_json), 1)
     self.assertEqual(len(res_json[0]['proposing_mks']), 1)
Example #53
0
 def get_my_profile(self, access_token):
     from social_urls import gmail_urls
     user_info = urllib2.urlopen(gmail_urls['get_user_profile'] %
                                 access_token)
     return simplejson.loads(user_info.read())
Example #54
0
 def test_api_vote_list(self):
     res = self.client.get(reverse('vote-handler'))
     self.assertEqual(res.status_code, 200)
     res_json = json.loads(res.content)
     self.assertEqual(len(res_json), 1)
     self.assertEqual(len(res_json[0]['for_votes']), self.num_mks)