Background Image
Table of Contents Table of Contents
Previous Page  403 / 478 Next Page
Information
Show Menu
Previous Page 403 / 478 Next Page
Page Background

def

tearDown

(

self

):

if

self

.

_test_has_failed

():

if

not

os

.

path

.

exists

(

SCREEN_DUMP_LOCATION

):

os

.

makedirs

(

SCREEN_DUMP_LOCATION

)

for

ix

,

handle

in

enumerate

(

self

.

browser

.

window_handles

):

self

.

_windowid

=

ix

self

.

browser

.

switch_to_window

(

handle

)

self

.

take_screenshot

()

self

.

dump_html

()

self

.

browser

.

quit

()

super

()

.

tearDown

()

def

_test_has_failed

(

self

):

# for 3.4. In 3.3, can just use self._outcomeForDoCleanups.success:

for

method

,

error

in

self

.

_outcome

.

errors

:

if

error

:

return

True

return

False

We first create a directory for our screenshots if necessary. Then we iterate through all

the open browser tabs and pages, and use some Selenium methods,

get_screen

shot_as_file

and

browser.page_source

, for our image and HTML dumps:

functional_tests/base.py (ch20l007).

def

take_screenshot

(

self

):

filename

=

self

.

_get_filename

()

+

'.png'

print

(

'screenshotting to'

,

filename

)

self

.

browser

.

get_screenshot_as_file

(

filename

)

def

dump_html

(

self

):

filename

=

self

.

_get_filename

()

+

'.html'

print

(

'dumping page HTML to'

,

filename

)

with

open

(

filename

,

'w'

)

as

f

:

f

.

write

(

self

.

browser

.

page_source

)

And finally here’s a way of generating a unique filename identifier, which includes the

name of the test and its class, as well as a timestamp:

functional_tests/base.py (ch20l008).

def

_get_filename

(

self

):

timestamp

=

datetime

.

now

()

.

isoformat

()

.

replace

(

':'

,

'.'

)[:

19

]

return

'{folder}/{classname}.{method}-window{windowid}-{timestamp}'

.

format

(

folder

=

SCREEN_DUMP_LOCATION

,

classname

=

self

.

__class__

.

__name__

,

method

=

self

.

_testMethodName

,

windowid

=

self

.

_windowid

,

timestamp

=

timestamp

)

You can test this first locally by deliberately breaking one of the tests, with a

self.fail()

for example, and you’ll see something like this:

Taking Screenshots

|

375