Revision 812b389c

b/other/astakos-test
1
#!/usr/bin/env python
2
#coding=utf8
3

  
4
# Copyright 2011-2012 GRNET S.A. All rights reserved.
5
# 
6
# Redistribution and use in source and binary forms, with or
7
# without modification, are permitted provided that the following
8
# conditions are met:
9
# 
10
#   1. Redistributions of source code must retain the above
11
#      copyright notice, this list of conditions and the following
12
#      disclaimer.
13
# 
14
#   2. Redistributions in binary form must reproduce the above
15
#      copyright notice, this list of conditions and the following
16
#      disclaimer in the documentation and/or other materials
17
#      provided with the distribution.
18
# 
19
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
20
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
23
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
26
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
27
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
29
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30
# POSSIBILITY OF SUCH DAMAGE.
31
# 
32
# The views and conclusions contained in the software and
33
# documentation are those of the authors and should not be
34
# interpreted as representing official policies, either expressed
35
# or implied, of GRNET S.A.
36

  
37

  
38
#from pithos.lib.client import Pithos_Client, Fault
39
#from pithos.lib.util import get_user, get_auth, get_server, get_api
40
#
41
#from xml.dom import minidom
42
#from StringIO import StringIO
43
#from hashlib import new as newhasher
44
#from binascii import hexlify
45
#
46
#import json
47
import unittest
48
#import time as _time
49
#import types
50
#import hashlib
51
#import mimetypes
52
#import random
53
#import datetime
54
#import string
55
#import re
56
#
57

  
58
import httplib
59
import os
60

  
61
from django.core.urlresolvers import reverse
62

  
63
from astakos.im.forms import LocalUserCreationForm
64
from astakos.im.models import AstakosUser
65
from astakos.im.util import get_current_site
66

  
67
class BaseTestCase(unittest.TestCase):
68
    def setup(self):
69
        site = get_current_site()
70
        protocal = 'http'
71
        self.host = '%s://%s' % (protocol, site.domain)
72

  
73
class ApiTestCase(unittest.TestCase):
74
    def setUp(self):
75
        kwargs = {'email':'email',
76
                 'first_name':'first_name',
77
                 'last_name':'last_name'}
78
        self.user = self.create_user(**kwargs)
79
    
80
    def tear_down(self):
81
        delete_user(self.user.id)
82
    
83
    def test_authenticatite(self):
84
        url = '%s/im/authenticate' % self.host
85
        response, content = http.request(url, 'GET', headers={'X-Auth-Token':self.user.auth_token})
86
        self.assertEqual(response.status, 400)
87

  
88
    def create_user(self, **kwargs):
89
        conn = HTTPConnection(self.host)
90
        
91
        url = '/im/signup'
92
        user = AstakosUser()
93
        for k, v in kwargs.items():
94
            setattr(user, k, v)
95
        response, content = http.request(url,
96
                                         'POST',
97
                                         body=LocalUserCreationForm(instance=u,
98
                                                                    password1=kwargs['password'],
99
                                                                    password2=kwargs['password']))
100
        self.AssertEqual(response.status, 200)
101
        try:
102
            user = AstakosUser.get.object(email = kwargs['email'])
103
            for k, v in kwargs.items():
104
                self.assertEqual(getattr(user, k), v)
105
        except AstakosUser.DoesNotExist, e:
106
            self.fail("User does not exist")
107
    
108
    def delete_user(self, id):
109
        url = '%s/%s' % (reverse('astakos.im.admin.views'), id)
110
        response, content = http.request(url, 'POST')
111

  
112
if __name__ == "__main__":
113
    unittest.main()
b/other/client.py
1
#!/usr/bin/env python
2
#coding=utf8
3

  
4
# Copyright 2011-2012 GRNET S.A. All rights reserved.
5
# 
6
# Redistribution and use in source and binary forms, with or
7
# without modification, are permitted provided that the following
8
# conditions are met:
9
# 
10
#   1. Redistributions of source code must retain the above
11
#      copyright notice, this list of conditions and the following
12
#      disclaimer.
13
# 
14
#   2. Redistributions in binary form must reproduce the above
15
#      copyright notice, this list of conditions and the following
16
#      disclaimer in the documentation and/or other materials
17
#      provided with the distribution.
18
# 
19
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
20
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
23
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
26
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
27
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
29
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30
# POSSIBILITY OF SUCH DAMAGE.
31
# 
32
# The views and conclusions contained in the software and
33
# documentation are those of the authors and should not be
34
# interpreted as representing official policies, either expressed
35
# or implied, of GRNET S.A.
36

  
37
class Fault(Exception):
38
    def __init__(self, data='', status=None):
39
        if not data:
40
            data =  httplib.responses[status]
41
        Exception.__init__(self, data)
42
        self.data = data
43
        self.status = status
44

  
45
class Client(object):
46
    def __init__(self, host, verbose=False, debug=False):
47
        """`host` can also include a port, e.g '127.0.0.1:8000'."""
48
        
49
        self.host = host
50
        self.verbose = verbose or debug
51
        self.debug = debug
52
    
53
    def req(self, method, path, body=None, headers={}, format='text', params={}):
54
        full_path = _prepare_path(path, self.api, format, params)
55
        
56
        conn = HTTPConnection(self.host)
57
        kwargs = {}
58
        kwargs['headers'] = _prepare_headers(headers)
59
        if body:
60
            kwargs['body'] = body
61
        kwargs['headers'].setdefault('content-length', len(body) if body else 0)
62
        
63
        #print '#', method, full_path, kwargs
64
        #t1 = datetime.datetime.utcnow()
65
        conn.request(method, full_path, **kwargs)
66
        
67
        resp = conn.getresponse()
68
        #t2 = datetime.datetime.utcnow()
69
        #print 'response time:', str(t2-t1)
70
        return _handle_response(resp, self.verbose, self.debug)
71
    
72
    def _prepare_path(path, api, format='text', params={}):
73
        slash = '/' if api else ''
74
        full_path = '%s%s%s?format=%s' % (slash, api, quote(path), format)
75
        
76
        for k,v in params.items():
77
            value = quote(str(v)) if v else ''
78
            full_path = '%s&%s=%s' %(full_path, quote(k), value)
79
        return full_path
80
    
81
    def _prepare_headers(headers):
82
        for k,v in headers.items():
83
            headers.pop(k)
84
            k = k.replace('_', '-')
85
            headers[quote(k)] = quote(v, safe='/=,:@ *"') if type(v) == types.StringType else v
86
        return headers
87
    
88
    def _handle_response(response, verbose=False, debug=False):
89
        headers = response.getheaders()
90
        headers = dict((unquote(h), unquote(v)) for h,v in headers)
91
        
92
        if verbose:
93
            print '%d %s' % (response.status, response.reason)
94
            for key, val in headers.items():
95
                print '%s: %s' % (key.capitalize(), val)
96
            print
97
        
98
        length = response.getheader('content-length', None)
99
        data = response.read(length)
100
        if debug:
101
            print data
102
            print
103
        
104
        if int(response.status) in ERROR_CODES.keys():
105
            raise Fault(data, int(response.status))
106
        
107
        #print '**',  response.status, headers, data, '\n'
108
        return response.status, headers, data
109

  
110
class AstakosClient(Client):
111
    def create_user(self):
112
        method =  'POST'
113
        path = '/im/signup'
114
        body = ''
115
        
116
        return self.req(method='POST', path='/im/signup', )
117
        conn = HTTPConnection(self.host)
118
        
119
        url = '/im/signup'
120
        user = AstakosUser()
121
        for k, v in kwargs.items():
122
            setattr(user, k, v)
123
        response, content = http.request(url,
124
                                         'POST',
125
                                         body=LocalUserCreationForm(instance=u,
126
                                                                    password1=kwargs['password'],
127
                                                                    password2=kwargs['password']))
128
        self.AssertEqual(response.status, 200)
129
        try:
130
            user = AstakosUser.get.object(email = kwargs['email'])
131
            for k, v in kwargs.items():
132
                self.assertEqual(getattr(user, k), v)
133
        except AstakosUser.DoesNotExist, e:
134
            self.fail("User does not exist")
135
    

Also available in: Unified diff