Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Side by Side Diff: sitescripts/filterhits/test/api_tests.py

Issue 4615801646612480: Issue 395 - Filter hits statistics backend (Closed)
Patch Set: Create temporary log directory with tempfile module for tests. Created March 30, 2015, 7 p.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 # coding: utf-8
2
3 # This file is part of the Adblock Plus web scripts,
4 # Copyright (C) 2006-2015 Eyeo GmbH
5 #
6 # Adblock Plus is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License version 3 as
8 # published by the Free Software Foundation.
9 #
10 # Adblock Plus is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
17
18 import MySQLdb
19 import StringIO
20 import json
21 import sys
22 import unittest
23 from urllib import urlencode
24
25 from sitescripts.filterhits.test import test_helpers
26 from sitescripts.filterhits import db
27 from sitescripts.filterhits.web.query import query_handler
28 from sitescripts.filterhits.web.submit import submit as submit_handler
29
30 valid_data = """{
31 "version": 1,
32 "timeSincePush": 12345,
33 "addonName": "adblockplus",
34 "addonVersion": "2.3.4",
35 "application": "firefox",
36 "applicationVersion": "31",
37 "platform": "gecko",
38 "platformVersion": "31",
39 "filters": {
40 "||example.com^": {
41 "firstParty": {
42 "example.com": {"hits": 12, "latest": 1414817340948},
43 "example.org": {"hits": 4, "latest": 1414859271125}
44 },
45 "thirdParty": {
46 "example.com": {"hits": 5, "latest": 1414916268769}
47 },
48 "subscriptions": ["EasyList", "EasyList Germany+EasyList"]
49 }
50 }
51 }"""
52
53 class APITestCase(unittest.TestCase):
54 def clear_rows(self):
55 if self.db:
56 db.write(self.db, (("DELETE FROM filters",),
57 ("DELETE FROM frequencies",)))
58
59 def setUp(self):
60 self.config = test_helpers.setup_config()
61 try:
62 self.db = db.connect()
63 except MySQLdb.Error:
64 self.db = None
65 self.clear_rows()
66
67 def tearDown(self):
68 test_helpers.restore_config()
69 if self.db:
70 self.clear_rows()
71 self.db.close()
72 self.db = None
73
74 def assertResponse(self, handler, expected_response, expected_result=None, exp ected_headers=None, **environ):
75 def check_response(response, headers):
76 self.assertEqual(response, expected_response)
77 if not expected_headers is None:
78 self.assertEqual(headers, expected_headers)
79
80 if "body" in environ:
81 environ["CONTENT_LENGTH"] = len(environ["body"])
82 environ["wsgi.input"] = StringIO.StringIO(environ["body"])
83 del environ["body"]
84
85 if "get_params" in environ:
86 environ["QUERY_STRING"] = urlencode(environ["get_params"])
87 del environ["get_params"]
88
89 environ["wsgi.errors"] = sys.stderr
90 result = handler(environ, check_response)
91 if not expected_result is None:
92 self.assertEqual(json.loads("".join(result)), expected_result)
93
94 def test_submit(self):
95 self.assertEqual(len(db.query(self.db, "SELECT * FROM frequencies")), 0)
96 self.assertEqual(len(db.query(self.db, "SELECT * FROM filters")), 0)
97 # Ensure missing or invalid JSON results in an error
98 self.assertResponse(submit_handler, "400 Processing Error",
99 REQUEST_METHOD="POST", body="")
100 self.assertResponse(submit_handler, "400 Processing Error",
101 REQUEST_METHOD="POST", body="Oops...")
102 self.assertResponse(submit_handler, "400 Processing Error",
103 REQUEST_METHOD="POST", body="{123:]")
104 self.assertResponse(submit_handler, "400 Processing Error",
105 REQUEST_METHOD="POST", body="1")
106 self.assertEqual(len(db.query(self.db, "SELECT * FROM frequencies")), 0)
107 self.assertEqual(len(db.query(self.db, "SELECT * FROM filters")), 0)
108 # Ensure even an empty object, or one with the wrong fields returns OK
109 self.assertResponse(submit_handler, "200 OK",
110 REQUEST_METHOD="POST", body="{}")
111 self.assertResponse(submit_handler, "200 OK",
112 REQUEST_METHOD="POST", body="{\"hello\": \"world\"}")
113 self.assertEqual(len(db.query(self.db, "SELECT * FROM frequencies")), 0)
114 self.assertEqual(len(db.query(self.db, "SELECT * FROM filters")), 0)
115 # Now some actually valid data
116 self.assertResponse(submit_handler, "200 OK",
117 REQUEST_METHOD="POST", body=valid_data)
118 self.assertEqual(len(db.query(self.db, "SELECT * FROM frequencies")), 2)
119 self.assertEqual(len(db.query(self.db, "SELECT * FROM filters")), 1)
120 # Now make sure apparently valid data with timestamps that cause geometrical
121 # mean calculations to fail with MySQL errors return OK but don't change DB
122 invalid_data = json.loads(valid_data)
123 invalid_data["filters"]["||example.com^"]["firstParty"]["example.com"]["late st"] = 3
124 invalid_data = json.dumps(invalid_data)
125 self.assertResponse(submit_handler, "200 OK",
126 REQUEST_METHOD="POST", body=invalid_data)
127 self.assertEqual(len(db.query(self.db, "SELECT * FROM frequencies")), 2)
128 self.assertEqual(len(db.query(self.db, "SELECT * FROM filters")), 1)
129
130 def test_query(self):
131 # Basic query with no data, should return OK
132 self.assertResponse(query_handler, "200 OK", {"count": 0, "total": 0, "resul ts": [], "echo": 0})
133 # If echo parameter is passed and is integer it should be returned
134 self.assertResponse(query_handler, "200 OK", {"count": 0, "total": 0, "resul ts": [], "echo": 1337},
135 get_params={ "echo": 1337 })
136 self.assertResponse(query_handler, "200 OK", {"count": 0, "total": 0, "resul ts": [], "echo": 0},
137 get_params={ "echo": "naughty" })
138 # Now let's submit some data so we can query it back out
139 test_data = [json.loads(valid_data), json.loads(valid_data), json.loads(vali d_data)]
140 test_data[1]["filters"]["##Second-Filter|"] = test_data[1]["filters"].pop("| |example.com^")
141 test_data[2]["filters"]["##Third-Filter|"] = test_data[2]["filters"].pop("|| example.com^")
142 for data in test_data:
143 self.assertResponse(submit_handler, "200 OK",
144 REQUEST_METHOD="POST", body=json.dumps(data))
145 # Ordering parameters should be respected
146 self.assertResponse(query_handler, "200 OK", {"count": 1, "total": 6,
147 "results": [{'domain': 'exampl e.com',
148 'filter': '||exam ple.com^',
149 'frequency': 0}], "echo": 0},
150 get_params={ "order_by": "filter", "order": "desc", "tak e": "1" })
151 self.assertResponse(query_handler, "200 OK", {"count": 1, "total": 6,
152 "results": [{'domain': 'exampl e.com',
153 'filter': '##Seco nd-Filter|',
154 'frequency': 0}], "echo": 0},
155 get_params={ "order_by": "filter", "order": "asc", "take ": "1" })
156 # As should filtering parameters
157 self.assertResponse(query_handler, "200 OK", {"count": 1, "total": 3,
158 "results": [{'domain': 'exampl e.com',
159 'filter': '##Thir d-Filter|',
160 'frequency': 0}], "echo": 0},
161 get_params={ "domain": "example.com", "take": "1" })
162 self.assertResponse(query_handler, "200 OK", {"count": 1, "total": 2,
163 "results": [{'domain': 'exampl e.org',
164 'filter': '##Thir d-Filter|',
165 'frequency': 4}], "echo": 0},
166 get_params={ "filter": "Third", "take": 1 })
167 self.assertResponse(query_handler, "200 OK", {"count": 1, "total": 1,
168 "results": [{'domain': 'exampl e.com',
169 'filter': '##Thir d-Filter|',
170 'frequency': 0}], "echo": 0},
171 get_params={ "domain": "example.com", "filter": "Third", "take": "1" })
172 # ... and pagination parameters
173 self.maxDiff = None
174 self.assertResponse(query_handler, "200 OK", {"count": 2, "total": 6,
175 "results": [{'domain': 'exampl e.org',
176 'filter': '||exam ple.com^',
177 'frequency': 4},
178 {'domain': 'exampl e.org',
179 'filter': '##Seco nd-Filter|',
180 'frequency': 4}], "echo": 0},
181 get_params={ "skip": "1", "take": "2" })
182 self.assertResponse(query_handler, "200 OK", {"count": 2, "total": 6,
183 "results": [{'domain': 'exampl e.org',
184 'filter': '##Seco nd-Filter|',
185 'frequency': 4},
186 {'domain': 'exampl e.com',
187 'filter': '##Thir d-Filter|',
188 'frequency': 0}], "echo": 0},
189 get_params={ "skip": "2", "take": "2" })
190
191 if __name__ == '__main__':
192 unittest.main()
OLDNEW

Powered by Google App Engine
This is Rietveld