1 package com.atlassian.webdriver.testing.rule;
2
3 import com.atlassian.webdriver.testing.annotation.WindowSize;
4 import com.google.common.base.Supplier;
5 import org.junit.rules.TestWatcher;
6 import org.junit.runner.Description;
7 import org.openqa.selenium.Dimension;
8 import org.openqa.selenium.WebDriver;
9 import org.openqa.selenium.WebDriverException;
10 import org.slf4j.Logger;
11 import org.slf4j.LoggerFactory;
12
13 import javax.inject.Inject;
14
15 import static com.google.common.base.Preconditions.checkState;
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 public class WindowSizeRule extends TestWatcher
68 {
69 private final static Logger log = LoggerFactory.getLogger(WindowSizeRule.class);
70
71 private final WebDriverSupport<? extends WebDriver> support;
72
73 @Inject
74 public WindowSizeRule(WebDriver webDriver)
75 {
76 this.support = WebDriverSupport.forInstance(webDriver);
77 }
78
79 public WindowSizeRule(Supplier<? extends WebDriver> driverSupplier)
80 {
81 this.support = WebDriverSupport.forSupplier(driverSupplier);
82 }
83
84 public WindowSizeRule()
85 {
86 this.support = WebDriverSupport.fromAutoInstall();
87 }
88
89 @Override
90 protected void starting(Description description)
91 {
92 try
93 {
94 WindowSize windowSize = findAnnotation(description);
95 if (windowSize != null)
96 {
97 handleWindowSize(windowSize);
98 }
99 else
100 {
101 maximizeWindow();
102 }
103 }
104 catch (WebDriverException e)
105 {
106
107 log.warn("Caught exception while trying to adjust window size.");
108 log.debug("Exception while trying to adjust window size", e);
109 }
110 }
111
112 private WindowSize findAnnotation(Description description)
113 {
114 if (description.getAnnotation(WindowSize.class) != null)
115 {
116 return description.getAnnotation(WindowSize.class);
117 }
118 else if (description.getTestClass() != null && description.getTestClass().isAnnotationPresent(WindowSize.class))
119 {
120 return description.getTestClass().getAnnotation(WindowSize.class);
121 }
122 else
123 {
124 return null;
125 }
126 }
127
128 private void handleWindowSize(WindowSize windowSize)
129 {
130 if (windowSize.maximize())
131 {
132 maximizeWindow();
133 }
134 else
135 {
136 setSize(computeDimension(windowSize));
137 }
138 }
139
140 private void maximizeWindow()
141 {
142 support.getDriver().manage().window().maximize();
143 }
144
145 private void setSize(Dimension dimension)
146 {
147 support.getDriver().manage().window().setSize(dimension);
148 }
149
150 private Dimension computeDimension(WindowSize windowSize)
151 {
152 checkState(windowSize.width() > 0, "@WindowSize width must be greater than 0, was: " + windowSize.width());
153 checkState(windowSize.height() > 0, "@WindowSize height must be greater than 0, was: " + windowSize.height());
154 return new Dimension(windowSize.width(), windowSize.height());
155 }
156 }