summaryrefslogtreecommitdiff
path: root/docs/chipy-presentation/rest-api-example.py
blob: c2e7201d3216cb6acddb328f16bebdd6bef6d563 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import os
import shutil
from paste.fixture import TestApp
from paste.urlparser import StaticURLParser
from dvhoster.wsgiapp import make_app
import wsgi_intercept
import httplib
for attr in ['get_app', 'connect']:
    setattr(httplib.HTTPConnection, attr,
            getattr(wsgi_intercept.WSGI_HTTPConnection, attr).im_func)
from wsgifilter.proxyapp import DebugHeaders
from simplejson import loads as json_loads

data_filename = os.path.join(os.path.dirname(__file__), 'test-data')
wsgi_app = make_app({}, data_dir=data_filename)
app = TestApp(wsgi_app)

def put(uri, data):
    return app.post(
        uri, data, extra_environ={'REQUEST_METHOD': 'PUT'},
        status=(201, 204))

rule_data = '''\
<?xml version="1.0" encoding="UTF-8"?>
  <rules xmlns="http://www.plone.org/deliverance">
    <append-or-replace theme="//head" content="//head/title" />
    <append theme="//head" content="//head/link" />
    <append theme="//head" content="//head/script" onerror="ignore"/>    
    <append theme="//head" content="//head/style" onerror="ignore"/>    
    <append theme="//head" content="//head/meta" onerror="ignore"/>
    <copy theme="//div[@id='content']" content="//div[@id='portal-content']" />
  </rules>
'''


def test_everything():
    yield (reset_env,)
    yield (create_api,)
    yield (use_api, 'localhost')
    yield (rename_site,)
    yield (use_api, 'localhost2')
    yield (delete_site,)

def reset_env():
    if os.path.exists(data_filename):
        shutil.rmtree(data_filename)
    os.mkdir(data_filename)
            

def create_api():
    # Theme:
    uri = 'http://wsgify.org/theme.html'
    put('/.deliverance/theme_uri', uri)
    res = app.get('/.deliverance/theme_uri')
    assert res.body == uri

    # Rules:
    put('/.deliverance/rules/rule.xml', rule_data)
    assert app.get('/.deliverance/rules/rule.xml').body == rule_data
    assert app.get('/_rules/rule.xml').body == rule_data

    # Domain (no rename test):
    res = app.get('/.deliverance/domain')
    assert res.body == 'localhost'

    # Aliases:
    data = "localhost.localhost\nexample.com\n"
    put('/.deliverance/aliases', data)
    assert app.get('/.deliverance/aliases').body == data

    data = '''
    [{"path": "/bar", "remote_uri": "http://wsgify.org/blah", "comment": "x"},
     {"path": "/", "remote_uri": "http://wsgify.org/"},
     {"path": "/testme", "headers": {"X-Test-Me": "testme"}, "remote_uri": "http://wsgify.org:9999"}
     ]
     '''

    put('/.deliverance/remote_uris', data)
    # It gets normalized, so it doesn't actually stay quite the same:
    #assert app.get('/.deliverance/remote_uris').body == data

    res = app.get('/bar', status=301)
    assert res.header('location') == 'http://localhost/bar/'
    ## @@: Right now there's a problem with StaticURLParser where it
    ## does a bad redirect here...
    #res = res.follow()
    #print res
    #assert res.status == 200
    ## So instead we just get a page we know works:
    res = app.get('/bar/index.html', status=200)

    res = app.get('/testme/', status=200)
    res.mustcontain("HTTP_X_TEST_ME: 'testme'")

    # Now lets try adding and removing via POST
    app.post('/.deliverance/remote_uris?add',
             '[{"path": "/testpost", "remote_uri": "http://blah.com"}]',
             status=204)
    res = app.get('/.deliverance/remote_uris')
    res.mustcontain('testpost')
    app.post('/.deliverance/remote_uris?remove',
             '[{"path": "/testpost"}]',
             status=204)
    res = app.get('/.deliverance/remote_uris')
    data = json_loads(res.body)
    for item in data:
        assert not item['path'].startswith('/testpost')

    data = '''
    [{"path": "/test1.html", "rewrite": "/test1"},
     {"prefix": "/test2", "rewrite": "/test3", "comment": "rename"},
     {"path": "/other.html", "rewrite": "http://otherexample.com/other.html"}]
     '''
    put('/.deliverance/redirects', data)

    app.post('/.deliverance/redirects?add',
             '[{"path": "/something-special", "rewrite": "http://whatever.com"}]',
             status=204)
    res = app.get('/.deliverance/redirects')
    res.mustcontain('whatever.com', 'otherexample.com')
    # Let's try a bad request:
    app.post('/.deliverance/redirects?remove',
             '[{"path": "/blahblah"}]', status=400)
    # Then a good one:
    app.post('/.deliverance/redirects?remove',
             '[{"path": "/something-special"}]',
             status=204)
    res = app.get('/.deliverance/redirects')
    res.mustcontain('otherexample.com')
    data = json_loads(res.body)
    for item in data:
        if not item.get('path'):
            continue
        assert not item.get('path').startswith('/something-special')
    
    data = '<html>some data!</html>'
    put('/.deliverance/static/data.html', data)
    res = app.get('/.deliverance/static/data.html')
    assert res.body == data
    app.get('/.deliverance/static/subdir',
            extra_environ={'REQUEST_METHOD': 'MKCOL'}, status=201)
    res = put('/.deliverance/static/subdir/foo.html', 'blah')
    res = app.get('/.deliverance/static/subdir/foo.html')
    assert res.body == 'blah'
    res = app.get('/subdir/foo.html')
    assert res.body == 'blah'
    # Directories don't shadow like files:
    res = app.get('/subdir/', status=404)
    
def use_api(hostname):
    res = app.get('/index.html')
    res.mustcontain(
        # From the theme:
        'This is a theme',
        # From the content:
        'This is some content')
    # Should be dropped from theme:
    assert 'replace' not in res
    # Should be lost from content:
    assert 'unthemed' not in res
    # Redirect non-canonical domains:
    res = app.get('/index.html', extra_environ=dict(HTTP_HOST='example.com'),
                  status=301)
    assert res.header('location') == 'http://%s/index.html' % hostname
    # Test the path backend redirect:
    res = app.get('/bar/foo.html')
    res.mustcontain('foo')
    res = app.get('/test1.html', status=301)
    assert res.header('location') == 'http://%s/test1/' % hostname
    res = app.get('/test2/other/stuff.html', status=301)
    assert res.header('location') == 'http://%s/test3/other/stuff.html' % hostname
    res = app.get('/test1.html/foo/bar', status=404)
    res = app.get('/data.html')
    res.mustcontain('some data!')
    assert 'Test Theme' not in res
    res = app.get('/subdir/foo.html')
    assert res.body == 'blah'
    
def rename_site():
    put('/.deliverance/domain', 'localhost2')
    app.extra_environ['HTTP_HOST'] = 'localhost2'
    res = app.get('/.deliverance/aliases')
    res.mustcontain('localhost')
    assert app.get('/.deliverance/domain').body == 'localhost2'
    print 'site renamed to localhost2'

def delete_site():
    app.extra_environ['HTTP_HOST'] = 'localhost2'
    res = app.get('/.deliverance/domain')
    res = app.get('/foo.html', status=404)
    put('/.deliverance/static/foo.html', 'text')
    res = app.get('/foo.html')
    assert res.body == 'text'
    res = app.post('/.deliverance/delete', '', status=204)
    res = app.get('/foo.html', status=404)

def setup_module(module):
    from paste.script import testapp
    static_app = StaticURLParser(os.path.join(os.path.dirname(__file__),
                                              'test-static'))

    wsgi_intercept.add_wsgi_intercept('wsgify.org', 80, lambda : static_app)
    wsgi_intercept.add_wsgi_intercept('wsgify.org', 9999, lambda : testapp.TestApplication(text=True))

def teardown_module(module):
    wsgi_intercept.remove_wsgi_intercept('wsgify.org', 80)