-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex41RMC_mailpile_init.py
307 lines (240 loc) · 11.4 KB
/
ex41RMC_mailpile_init.py
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# forked from https://github.com/mailpile/Mailpile/raw/a93bf3d6da0ff82d23ba5e1f833254f1cf68af82/mailpile/tests/gui/__init__.py to fulfil "Learn Python the Hard Way | Exercise 41: Learning To Speak Object Oriented | Reading More Code" http://learnpythonthehardway.org/book/ex41.html
try:
from selenium import webdriver
from selenium.common.exceptions import WebDriverException, StaleElementReferenceException
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
except ImportError:
pass
from mailpile.httpd import HttpWorker
from mailpile.tests import MailPileUnittest, get_shared_mailpile
from mailpile.safe_popen import MakePopenUnsafe
MakePopenUnsafe()
# RMC 1. Class "ElementHasClass" inherits from "object"...
class ElementHasClass(object):
# RMC 2. ...And has an "__init__" function that takes parameters "self", "locator_tuple" and "class_name"...
def __init__(self, locator_tuple, class_name):
# RMC 3. & 4. ...Sets its own attributes "locator" and "class_name" to "locator_tuple" and "class_name"
self.locator = locator_tuple
self.class_name = class_name
# RMC 2. It also has a function "__call__" that takes parameters "self" and "driver".
def __call__(self, driver):
try:
e = driver.find_element(self.locator[0], self.locator[1])
return self.class_name in e.get_attribute('class')
except (NoSuchElementException, StaleElementReferenceException):
return False
# RMC 1. Class "ElementHasNotClass" inherits from "object"... Same as above!
class ElementHasNotClass(object):
# RMC 2. ...And has an "__init__" function that takes parameters "self", "locator_tuple" and "class_name"...
def __init__(self, locator_tuple, class_name):
# RMC 3. & 4. ...Sets its own attributes "locator" and "class_name" to "locator_tuple" and "class_name"
self.locator = locator_tuple
self.class_name = class_name
# RMC 2. It also has a function "__call__" that takes parameters "self" and "driver".
def __call__(self, driver):
try:
e = driver.find_element(self.locator[0], self.locator[1])
return self.class_name not in e.get_attribute('class')
except (NoSuchElementException, StaleElementReferenceException):
return True
# RMC 1. Class "SeleniumScreenshotOnExceptionAspecter" inherits from "type"...
class SeleniumScreenshotOnExceptionAspecter(type):
"""Wraps all methods starting with *test* with a screenshot aspect.
The screenshot file is named *methodname*_screenshot.png.
Notes:
This class defines a type that has to be used as a metaclass:
>>> class Foobar()
... __metaclass__ = SeleniumScreenshotOnExceptionAspecter
...
... def take_screenshot(self, filename):
... # take screenshot
... pass
The class has to provide a take_screenshot(filename) method
Attributes:
none
"""
# RMC 2. ...And has a function "new" that takes parameters "mcs", "name", "bases" & "dict"
def __new__(mcs, name, bases, dict):
for key, value in dict.items():
if (hasattr(value, "__call__")
and key != "__metaclass__"
and key.startswith('test')):
dict[key] = SeleniumScreenshotOnExceptionAspecter.wrap_method(
value)
return super(SeleniumScreenshotOnExceptionAspecter,
mcs).__new__(mcs, name, bases, dict)
# RMC 2. ...And has a method "wrap_method" that takes parameters "mcs", "method"
@classmethod
def wrap_method(mcs, method):
"""Wraps method with a screenshot on exception aspect."""
# method name has to start with test, otherwise unittest runner
# won't detect it
# RMC 2. ...Which itself has a function "test_call_wrapper_method" that takes parameters "*args" (unpacked command arguments?) and "**kw"
def test_call_wrapper_method(*args, **kw):
"""The wrapper method
Notes:
The method name has to start with *test*, otherwise the
unittest runner won't detect is as a test method
Args:
*args: Variable argument list of original method
**kw: Arbitrary keyword arguments of the original method
Returns:
The result of the original method call
"""
try:
results = method(*args, **kw)
except:
test_self = args[0]
filename = '%s_screenshot.png' % method.__name__
test_self.take_screenshot(filename)
raise
return results
return test_call_wrapper_method
# RMC 1. Class "MailpileSeleniumTest" inherits from "MailPileUnittest"...
class MailpileSeleniumTest(MailPileUnittest):
"""Base class for all selenium GUI tests
Attributes:
DRIVER (WebDriver): The webdriver instance
Examples:
>>> class Sometest(MailpileSeleniumTest):
...
... def test_something(self):
... self.go_to_mailpile_home()
... self.take_screenshot('screen.png')
... self.dump_source_to('source.html')
...
... self.navigate_to('Contacts')
...
... self.driver.save_screenshot('screen2.png')
... self.assertIn('Contacts', self.driver.title)
"""
# RMC 3. & 4. ...Which has an attribute "__metaclass__" which is set to (an instance of class?) "SeleniumScreenshotOnExceptionAspecter"
__metaclass__ = SeleniumScreenshotOnExceptionAspecter
# RMC 3. ...And has the attributes "DRIVER" and "http_worker" set to None
DRIVER = None
http_worker = None
# RMC 2. ...And has an "__init__" function that takes parameters "self", "*args", "**kwargs".
def __init__(self, *args, **kwargs):
# RMC ...From class "MailPileUnittest" gets "__init__" function and executes it with parameters "self", "*args", "**kwargs".
MailPileUnittest.__init__(self, *args, **kwargs)
# RMC 2. ...And has a function "setUp" that takes parameter "self".
def setUp(self):
self.driver = MailpileSeleniumTest.DRIVER
def tearDown(self):
# try:
# self.driver.close()
# except WebDriverException:
# pass
pass
@classmethod
def _get_mailpile_sspec(cls):
(_, _, config, _) = get_shared_mailpile()
return (config.sys.http_host, config.sys.http_port)
@classmethod
def _get_mailpile_url(cls):
return 'http://%s:%s' % cls._get_mailpile_sspec()
@classmethod
def _start_web_server(cls):
if not MailpileSeleniumTest.http_worker:
(mp, session, config, _) = get_shared_mailpile()
sspec = MailpileSeleniumTest._get_mailpile_sspec()
MailpileSeleniumTest.http_worker = config.http_worker = HttpWorker(session, sspec)
config.http_worker.start()
@classmethod
def _start_selenium_driver(cls):
if not MailpileSeleniumTest.DRIVER:
driver = webdriver.PhantomJS() # or add to your PATH
driver.set_window_size(1280, 1024) # optional
driver.implicitly_wait(5)
driver.set_page_load_timeout(5)
MailpileSeleniumTest.DRIVER = driver
@classmethod
def _stop_selenium_driver(cls):
if MailpileSeleniumTest.DRIVER:
try:
MailpileSeleniumTest.DRIVER.quit()
MailpileSeleniumTest.DRIVER = None
except WebDriverException:
pass
@classmethod
def setUpClass(cls):
return # FIXME: Test disabled
MailpileSeleniumTest._start_selenium_driver()
MailpileSeleniumTest._start_web_server()
@classmethod
def _stop_web_server(cls):
if MailpileSeleniumTest.http_worker:
(mp, _, config, _) = get_shared_mailpile()
mp._config.http_worker = None
MailpileSeleniumTest.http_worker.quit()
MailpileSeleniumTest.http_worker = MailpileSeleniumTest.http_worker = None
@classmethod
def tearDownClass(cls):
return # FIXME: Test disabled
MailpileSeleniumTest._stop_web_server()
MailpileSeleniumTest._stop_selenium_driver()
def go_to_mailpile_home(self):
self.driver.get('%s/in/inbox' % self._get_mailpile_url())
def take_screenshot(self, filename):
try:
self.driver.save_screenshot(filename) # save a screenshot to disk
except WebDriverException:
pass
def dump_source_to(self, filename):
with open(filename, 'w') as out:
out.write(self.driver.page_source.encode('utf8'))
def navigate_to(self, name):
contacts = self.find_element_by_xpath(
'//a[@alt="%s"]/span' % name)
self.assertTrue(contacts.is_displayed())
contacts.click()
def submit_form(self, form_id):
form = self.driver.find_element_by_id(form_id)
form.submit()
def fill_form_field(self, field, text):
input_field = self.driver.find_element_by_name(field)
input_field.send_keys(text)
def assert_link_with_text(self, text):
try:
self.driver.find_element_by_link_text(text)
except NoSuchElementException:
raise AssertionError
def click_element_with_link_text(self, text):
try:
self.driver.find_element_by_link_text(text).click()
except NoSuchElementException:
raise AssertionError
def click_element_with_id(self, element_id):
self.driver.find_element_by_id(element_id).click()
def click_element_with_class(self, class_name):
self.driver.find_element_by_class_name(class_name).click()
def page_title(self):
return self.driver.title
def find_element_by_id(self, id):
return self.driver.find_element_by_id(id)
def find_element_containing_text(self, text):
return self.driver.find_element_by_xpath("//*[contains(.,'%s')]" % text)
def find_element_by_xpath(self, xpath):
return self.driver.find_element_by_xpath(xpath)
def find_element_by_class_name(self, class_name):
return self.driver.find_element_by_class_name(class_name)
def assert_text(self, text):
self.find_element_containing_text(text)
def wait_until_element_is_visible(self, element_id):
self.wait_until_element_is_visible_by_locator((By.ID, element_id))
def wait_until_element_is_visible_by_locator(self, locator_tuple):
wait = WebDriverWait(self.driver, 10)
wait.until(EC.visibility_of_element_located(locator_tuple))
def wait_until_element_is_invisible_by_locator(self, locator_tuple):
wait = WebDriverWait(self.driver, 10)
wait.until(EC.invisibility_of_element_located(locator_tuple))
def wait_until_element_has_class(self, locator_tuple, class_name):
self.wait_for_element_condition(ElementHasClass(locator_tuple, class_name))
def wait_until_element_has_not_class(self, locator_tuple, class_name):
self.wait_for_element_condition(ElementHasNotClass(locator_tuple, class_name))
def wait_for_element_condition(self, expected_conditions):
wait = WebDriverWait(self.driver, 10)
wait.until(expected_conditions)