1. Project Clover database Tue Dec 20 2016 21:24:09 CET
  2. Package org.xwiki.test.ui

File TestUtils.java

 

Coverage histogram

../../../../img/srcFileCovDistChart9.png
38% of files have more coverage

Code metrics

162
579
214
4
2,447
1,521
314
0.54
2.71
53.5
1.47

Classes

Class Line # Actions
TestUtils 100 356 0% 209 87
0.8552412485.5%
TestUtils.Session 1054 5 0% 4 0
1.0100%
TestUtils.RestTestUtils 1757 216 0% 100 76
0.777777877.8%
TestUtils.RestTestUtils.ResourceAPI 1763 2 0% 1 0
1.0100%
 

Contributing tests

This file is covered by 266 tests. .

Source view

1    /*
2    * See the NOTICE file distributed with this work for additional
3    * information regarding copyright ownership.
4    *
5    * This is free software; you can redistribute it and/or modify it
6    * under the terms of the GNU Lesser General Public License as
7    * published by the Free Software Foundation; either version 2.1 of
8    * the License, or (at your option) any later version.
9    *
10    * This software 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 GNU
13    * Lesser General Public License for more details.
14    *
15    * You should have received a copy of the GNU Lesser General Public
16    * License along with this software; if not, write to the Free
17    * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
18    * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
19    */
20    package org.xwiki.test.ui;
21   
22    import java.io.ByteArrayInputStream;
23    import java.io.ByteArrayOutputStream;
24    import java.io.File;
25    import java.io.FileInputStream;
26    import java.io.InputStream;
27    import java.net.URI;
28    import java.net.URLEncoder;
29    import java.util.ArrayList;
30    import java.util.Arrays;
31    import java.util.Collections;
32    import java.util.HashMap;
33    import java.util.HashSet;
34    import java.util.IdentityHashMap;
35    import java.util.List;
36    import java.util.Locale;
37    import java.util.Map;
38    import java.util.Set;
39    import java.util.regex.Matcher;
40    import java.util.regex.Pattern;
41   
42    import javax.ws.rs.core.MediaType;
43    import javax.ws.rs.core.Response.Status;
44    import javax.ws.rs.core.UriBuilder;
45    import javax.xml.bind.JAXBContext;
46    import javax.xml.bind.JAXBException;
47    import javax.xml.bind.Marshaller;
48    import javax.xml.bind.Unmarshaller;
49   
50    import org.apache.commons.httpclient.HttpClient;
51    import org.apache.commons.httpclient.HttpMethod;
52    import org.apache.commons.httpclient.UsernamePasswordCredentials;
53    import org.apache.commons.httpclient.auth.AuthScope;
54    import org.apache.commons.httpclient.methods.DeleteMethod;
55    import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
56    import org.apache.commons.httpclient.methods.GetMethod;
57    import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
58    import org.apache.commons.httpclient.methods.PostMethod;
59    import org.apache.commons.httpclient.methods.PutMethod;
60    import org.apache.commons.httpclient.methods.RequestEntity;
61    import org.apache.commons.io.IOUtils;
62    import org.apache.commons.lang.ArrayUtils;
63    import org.apache.commons.lang.StringUtils;
64    import org.junit.Assert;
65    import org.openqa.selenium.By;
66    import org.openqa.selenium.Cookie;
67    import org.openqa.selenium.NoSuchElementException;
68    import org.openqa.selenium.WebDriver;
69    import org.openqa.selenium.WebElement;
70    import org.openqa.selenium.support.ui.ExpectedCondition;
71    import org.xwiki.component.manager.ComponentManager;
72    import org.xwiki.model.EntityType;
73    import org.xwiki.model.reference.AttachmentReference;
74    import org.xwiki.model.reference.DocumentReference;
75    import org.xwiki.model.reference.EntityReference;
76    import org.xwiki.model.reference.EntityReferenceResolver;
77    import org.xwiki.model.reference.EntityReferenceSerializer;
78    import org.xwiki.model.reference.LocalDocumentReference;
79    import org.xwiki.rest.model.jaxb.Page;
80    import org.xwiki.rest.model.jaxb.Property;
81    import org.xwiki.rest.model.jaxb.Xwiki;
82    import org.xwiki.rest.resources.attachments.AttachmentResource;
83    import org.xwiki.rest.resources.classes.ClassPropertyResource;
84    import org.xwiki.rest.resources.objects.ObjectPropertyResource;
85    import org.xwiki.rest.resources.objects.ObjectResource;
86    import org.xwiki.rest.resources.objects.ObjectsResource;
87    import org.xwiki.rest.resources.pages.PageResource;
88    import org.xwiki.rest.resources.pages.PageTranslationResource;
89    import org.xwiki.test.integration.XWikiExecutor;
90    import org.xwiki.test.ui.po.ViewPage;
91    import org.xwiki.test.ui.po.editor.ClassEditPage;
92    import org.xwiki.test.ui.po.editor.ObjectEditPage;
93   
94    /**
95    * Helper methods for testing, not related to a specific Page Object. Also made available to tests classes.
96    *
97    * @version $Id: a806f31eb5ba4c08c29829271d99c959ba7bb336 $
98    * @since 3.2M3
99    */
 
100    public class TestUtils
101    {
102    /**
103    * @since 5.0M2
104    */
105    public static final UsernamePasswordCredentials ADMIN_CREDENTIALS =
106    new UsernamePasswordCredentials("Admin", "admin");
107   
108    /**
109    * @since 5.1M1
110    */
111    public static final UsernamePasswordCredentials SUPER_ADMIN_CREDENTIALS =
112    new UsernamePasswordCredentials("superadmin", "pass");
113   
114    /**
115    * @since 5.0M2
116    * @deprecated since 7.3M1, use {@link #getBaseURL()} instead
117    */
118    @Deprecated
119    public static final String BASE_URL = XWikiExecutor.URL + ":" + XWikiExecutor.DEFAULT_PORT + "/xwiki/";
120   
121    /**
122    * @since 5.0M2
123    * @deprecated since 7.3M1, use {@link #getBaseBinURL()} instead
124    */
125    @Deprecated
126    public static final String BASE_BIN_URL = BASE_URL + "bin/";
127   
128    /**
129    * @since 5.0M2
130    * @deprecated since 7.3M1, use {@link #getBaseURL()} instead
131    */
132    @Deprecated
133    public static final String BASE_REST_URL = BASE_URL + "rest/";
134   
135    /**
136    * @since 7.3M1
137    */
138    public static final int[] STATUS_OK_NOT_FOUND =
139    new int[] { Status.OK.getStatusCode(), Status.NOT_FOUND.getStatusCode() };
140   
141    /**
142    * @since 7.3M1
143    */
144    public static final int[] STATUS_OK = new int[] { Status.OK.getStatusCode() };
145   
146    /**
147    * @since 7.3M1
148    */
149    public static final int[] STATUS_NO_CONTENT = new int[] { Status.NO_CONTENT.getStatusCode() };
150   
151    /**
152    * @since 8.3RC1
153    */
154    public static final int[] STATUS_NO_CONTENT_NOT_FOUND =
155    new int[] { Status.NO_CONTENT.getStatusCode(), Status.NOT_FOUND.getStatusCode() };
156   
157    /**
158    * @since 7.3M1
159    */
160    public static final int[] STATUS_CREATED_ACCEPTED =
161    new int[] { Status.CREATED.getStatusCode(), Status.ACCEPTED.getStatusCode() };
162   
163    /**
164    * @since 7.3M1
165    */
166    public static final int[] STATUS_CREATED = new int[] { Status.CREATED.getStatusCode() };
167   
168    private static PersistentTestContext context;
169   
170    private static ComponentManager componentManager;
171   
172    private static EntityReferenceResolver<String> relativeReferenceResolver;
173   
174    private static EntityReferenceSerializer<String> referenceSerializer;
175   
176    private static EntityReferenceResolver<String> referenceResolver;
177   
178    /**
179    * Used to convert Java object into its REST XML representation.
180    */
181    private static Marshaller marshaller;
182   
183    /**
184    * Used to convert REST request XML result into its Java representation.
185    */
186    private static Unmarshaller unmarshaller;
187   
188    /** Cached secret token. TODO cache for each user. */
189    private String secretToken = null;
190   
191    private HttpClient httpClient;
192   
193    /**
194    * @since 8.0M1
195    */
196    private List<XWikiExecutor> executors;
197   
198    /**
199    * @since 7.3M1
200    */
201    private int currentExecutorIndex;
202   
203    /**
204    * @since 7.3M1
205    */
206    private String currentWiki = "xwiki";
207   
208    private RestTestUtils rest;
209   
 
210  117 toggle public TestUtils()
211    {
212  117 this.httpClient = new HttpClient();
213  117 this.httpClient.getState().setCredentials(AuthScope.ANY, SUPER_ADMIN_CREDENTIALS);
214  117 this.httpClient.getParams().setAuthenticationPreemptive(true);
215   
216  117 this.rest = new RestTestUtils(this);
217    }
218   
219    /**
220    * @since 8.0M1
221    */
 
222  20290 toggle public XWikiExecutor getCurrentExecutor()
223    {
224  20290 return this.executors != null && this.executors.size() > this.currentExecutorIndex
225    ? this.executors.get(this.currentExecutorIndex) : null;
226    }
227   
228    /**
229    * @since 8.0M1
230    */
 
231  586 toggle public void switchExecutor(int index)
232    {
233  586 this.currentExecutorIndex = index;
234    }
235   
236    /**
237    * @since 8.0M1
238    */
 
239  32 toggle public void setExecutors(List<XWikiExecutor> executors)
240    {
241  32 this.executors = executors;
242    }
243   
244    /** Used so that AllTests can set the persistent test context. */
 
245  32 toggle public static void setContext(PersistentTestContext context)
246    {
247  32 TestUtils.context = context;
248    }
249   
 
250  33 toggle public static void initializeComponent(ComponentManager componentManager) throws Exception
251    {
252  33 TestUtils.componentManager = componentManager;
253  33 TestUtils.relativeReferenceResolver =
254    TestUtils.componentManager.getInstance(EntityReferenceResolver.TYPE_STRING, "relative");
255  33 TestUtils.referenceResolver = TestUtils.componentManager.getInstance(EntityReferenceResolver.TYPE_STRING);
256  33 TestUtils.referenceSerializer = TestUtils.componentManager.getInstance(EntityReferenceSerializer.TYPE_STRING);
257    }
258   
 
259  4947 toggle public XWikiWebDriver getDriver()
260    {
261  4947 return context.getDriver();
262    }
263   
 
264  32 toggle public Session getSession()
265    {
266  32 return this.new Session(getDriver().manage().getCookies(), getSecretToken());
267    }
268   
 
269  107 toggle public void setSession(Session session)
270    {
271  107 WebDriver.Options options = getDriver().manage();
272  107 options.deleteAllCookies();
273  107 if (session != null) {
274  38 for (Cookie cookie : session.getCookies()) {
275  153 options.addCookie(cookie);
276    }
277    }
278  107 if (session != null && !StringUtils.isEmpty(session.getSecretToken())) {
279  38 this.secretToken = session.getSecretToken();
280    } else {
281  69 recacheSecretToken();
282    }
283    }
284   
285    /**
286    * @since 7.0RC1
287    */
 
288  89 toggle public void setDefaultCredentials(String username, String password)
289    {
290  89 setDefaultCredentials(new UsernamePasswordCredentials(username, password));
291    }
292   
293    /**
294    * @since 7.0RC1
295    */
 
296  160 toggle public UsernamePasswordCredentials setDefaultCredentials(UsernamePasswordCredentials defaultCredentials)
297    {
298  160 UsernamePasswordCredentials currentCredentials = getDefaultCredentials();
299   
300  160 this.httpClient.getState().setCredentials(AuthScope.ANY, defaultCredentials);
301   
302  160 return currentCredentials;
303    }
304   
 
305  164 toggle public UsernamePasswordCredentials getDefaultCredentials()
306    {
307  164 return (UsernamePasswordCredentials) this.httpClient.getState().getCredentials(AuthScope.ANY);
308    }
309   
 
310  6 toggle public void loginAsSuperAdmin()
311    {
312  6 login(SUPER_ADMIN_CREDENTIALS.getUserName(), SUPER_ADMIN_CREDENTIALS.getPassword());
313    }
314   
 
315  4 toggle public void loginAsSuperAdminAndGotoPage(String pageURL)
316    {
317  4 loginAndGotoPage(SUPER_ADMIN_CREDENTIALS.getUserName(), SUPER_ADMIN_CREDENTIALS.getPassword(), pageURL);
318    }
319   
 
320  3 toggle public void loginAsAdmin()
321    {
322  3 login(ADMIN_CREDENTIALS.getUserName(), ADMIN_CREDENTIALS.getPassword());
323    }
324   
 
325  0 toggle public void loginAsAdminAndGotoPage(String pageURL)
326    {
327  0 loginAndGotoPage(ADMIN_CREDENTIALS.getUserName(), ADMIN_CREDENTIALS.getPassword(), pageURL);
328    }
329   
 
330  178 toggle public void login(String username, String password)
331    {
332  178 loginAndGotoPage(username, password, null);
333    }
334   
 
335  184 toggle public void loginAndGotoPage(String username, String password, String pageURL)
336    {
337  184 if (!username.equals(getLoggedInUserName())) {
338    // Log in and direct to a non existent page so that it loads very fast and we don't incur the time cost of
339    // going to the home page for example.
340    // Also recache the CSRF token
341  53 getDriver().get(getURLToLoginAndGotoPage(username, password, getURL("XWiki", "Register", "register")));
342  53 recacheSecretTokenWhenOnRegisterPage();
343  53 if (pageURL != null) {
344    // Go to the page asked
345  6 getDriver().get(pageURL);
346    } else {
347  47 getDriver().get(getURLToNonExistentPage());
348    }
349   
350  53 setDefaultCredentials(username, password);
351    }
352    }
353   
354    /**
355    * Consider using setSession(null) because it will drop the cookies which is faster than invoking a logout action.
356    */
 
357  0 toggle public String getURLToLogout()
358    {
359  0 return getURL("XWiki", "XWikiLogin", "logout");
360    }
361   
 
362  7 toggle public String getURLToLoginAsAdmin()
363    {
364  7 return getURLToLoginAs(ADMIN_CREDENTIALS.getUserName(), ADMIN_CREDENTIALS.getPassword());
365    }
366   
 
367  0 toggle public String getURLToLoginAsSuperAdmin()
368    {
369  0 return getURLToLoginAs(SUPER_ADMIN_CREDENTIALS.getUserName(), SUPER_ADMIN_CREDENTIALS.getPassword());
370    }
371   
 
372  12 toggle public String getURLToLoginAs(final String username, final String password)
373    {
374  12 return getURLToLoginAndGotoPage(username, password, null);
375    }
376   
377    /**
378    * @param pageURL the URL of the page to go to after logging in.
379    * @return URL to accomplish login and goto.
380    */
 
381  36 toggle public String getURLToLoginAsAdminAndGotoPage(final String pageURL)
382    {
383  36 return getURLToLoginAndGotoPage(ADMIN_CREDENTIALS.getUserName(), ADMIN_CREDENTIALS.getPassword(), pageURL);
384    }
385   
386    /**
387    * @param pageURL the URL of the page to go to after logging in.
388    * @return URL to accomplish login and goto.
389    */
 
390  0 toggle public String getURLToLoginAsSuperAdminAndGotoPage(final String pageURL)
391    {
392  0 return getURLToLoginAndGotoPage(SUPER_ADMIN_CREDENTIALS.getUserName(), SUPER_ADMIN_CREDENTIALS.getPassword(),
393    pageURL);
394    }
395   
396    /**
397    * @param username the name of the user to log in as.
398    * @param password the password for the user to log in.
399    * @param pageURL the URL of the page to go to after logging in.
400    * @return URL to accomplish login and goto.
401    */
 
402  134 toggle public String getURLToLoginAndGotoPage(final String username, final String password, final String pageURL)
403    {
404  134 Map<String, String> parameters = new HashMap<String, String>()
405    {
 
406  134 toggle {
407  134 put("j_username", username);
408  134 put("j_password", password);
409  134 if (pageURL != null && pageURL.length() > 0) {
410  122 put("xredirect", pageURL);
411    }
412    }
413    };
414  134 return getURL("XWiki", "XWikiLogin", "loginsubmit", parameters);
415    }
416   
417    /**
418    * @return URL to a non existent page that loads very fast (we are using plain mode so that we don't even have to
419    * display the skin ;))
420    */
 
421  115 toggle public String getURLToNonExistentPage()
422    {
423  115 return getURL("NonExistentSpace", "NonExistentPage", "view", "xpage=plain");
424    }
425   
426    /**
427    * After successful completion of this function, you are guaranteed to be logged in as the given user and on the
428    * page passed in pageURL.
429    */
 
430  4 toggle public void assertOnPage(final String pageURL)
431    {
432  4 final String pageURI = pageURL.replaceAll("\\?.*", "");
433  4 getDriver().waitUntilCondition(new ExpectedCondition<Boolean>()
434    {
 
435  4 toggle @Override
436    public Boolean apply(WebDriver driver)
437    {
438  4 return getDriver().getCurrentUrl().contains(pageURI);
439    }
440    });
441    }
442   
 
443  185 toggle public String getLoggedInUserName()
444    {
445  185 By userAvatarInDrawer = By.id("tmUser");
446  185 if (!getDriver().hasElementWithoutWaiting(userAvatarInDrawer)) {
447    // Guest
448  39 return null;
449    }
450   
451  146 WebElement element = getDriver().findElementWithoutWaiting(userAvatarInDrawer);
452  146 String href = element.getAttribute("href");
453  146 String loggedInUserName = href.substring(href.lastIndexOf("/") + 1);
454   
455    // Return
456  146 return loggedInUserName;
457    }
458   
 
459  33 toggle public void createUserAndLogin(final String username, final String password, Object... properties)
460    {
461  33 createUserAndLoginWithRedirect(username, password, getURLToNonExistentPage(), properties);
462    }
463   
 
464  33 toggle public void createUserAndLoginWithRedirect(final String username, final String password, String url,
465    Object... properties)
466    {
467  33 createUser(username, password, getURLToLoginAndGotoPage(username, password, url), properties);
468   
469  33 setDefaultCredentials(username, password);
470    }
471   
 
472  39 toggle public void createUser(final String username, final String password, String redirectURL, Object... properties)
473    {
474  39 Map<String, String> parameters = new HashMap<String, String>();
475  39 parameters.put("register", "1");
476  39 parameters.put("xwikiname", username);
477  39 parameters.put("register_password", password);
478  39 parameters.put("register2_password", password);
479  39 parameters.put("register_email", "");
480  39 parameters.put("xredirect", redirectURL);
481  39 parameters.put("form_token", getSecretToken());
482  39 getDriver().get(getURL("XWiki", "Register", "register", parameters));
483  39 recacheSecretToken();
484  39 if (properties.length > 0) {
485  9 updateObject("XWiki", username, "XWiki.XWikiUsers", 0, properties);
486    }
487    }
488   
 
489  132 toggle public ViewPage gotoPage(String space, String page)
490    {
491  132 gotoPage(space, page, "view");
492  132 return new ViewPage();
493    }
494   
495    /**
496    * @since 7.2M2
497    */
 
498  18 toggle public ViewPage gotoPage(EntityReference reference)
499    {
500  18 gotoPage(reference, "view");
501  18 return new ViewPage();
502    }
503   
 
504  769 toggle public void gotoPage(String space, String page, String action)
505    {
506  769 gotoPage(space, page, action, "");
507    }
508   
509    /**
510    * @since 7.2M2
511    */
 
512  23 toggle public void gotoPage(EntityReference reference, String action)
513    {
514  23 gotoPage(reference, action, "");
515    }
516   
517    /**
518    * @since 3.5M1
519    */
 
520  32 toggle public void gotoPage(String space, String page, String action, Object... queryParameters)
521    {
522  32 gotoPage(space, page, action, toQueryString(queryParameters));
523    }
524   
 
525  16 toggle public void gotoPage(String space, String page, String action, Map<String, ?> queryParameters)
526    {
527  16 gotoPage(Collections.singletonList(space), page, action, queryParameters);
528    }
529   
530    /**
531    * @since 7.2M2
532    */
 
533  124 toggle public void gotoPage(List<String> spaces, String page, String action, Map<String, ?> queryParameters)
534    {
535  124 gotoPage(spaces, page, action, toQueryString(queryParameters));
536    }
537   
538    /**
539    * @since 7.2M2
540    */
 
541  85 toggle public void gotoPage(EntityReference reference, String action, Map<String, ?> queryParameters)
542    {
543  85 gotoPage(reference, action, toQueryString(queryParameters));
544    }
545   
 
546  927 toggle public void gotoPage(String space, String page, String action, String queryString)
547    {
548  927 gotoPage(Collections.singletonList(space), page, action, queryString);
549    }
550   
551    /**
552    * @since 7.2M2
553    */
 
554  1055 toggle public void gotoPage(List<String> spaces, String page, String action, String queryString)
555    {
556  1055 gotoPage(getURL(spaces, page, action, queryString));
557    }
558   
559    /**
560    * @since 7.2M2
561    */
 
562  110 toggle public void gotoPage(EntityReference reference, String action, String queryString)
563    {
564  110 gotoPage(getURL(reference, action, queryString));
565   
566    // Update current wiki
567  110 EntityReference wikiReference = reference.extractReference(EntityType.WIKI);
568  110 if (wikiReference != null) {
569  32 this.currentWiki = wikiReference.getName();
570    }
571    }
572   
 
573  1225 toggle public void gotoPage(String url)
574    {
575    // Only navigate if the current URL is different from the one to go to, in order to improve performances.
576  1225 if (!getDriver().getCurrentUrl().equals(url)) {
577  1217 getDriver().get(url);
578    }
579    }
580   
 
581  34 toggle public String getURLToDeletePage(String space, String page)
582    {
583  34 return getURL(space, page, "delete", "confirm=1");
584    }
585   
586    /**
587    * @since 7.2M2
588    */
 
589  3 toggle public String getURLToDeletePage(EntityReference reference)
590    {
591  3 return getURL(reference, "delete", "confirm=1");
592    }
593   
594    /**
595    * @param space the name of the space to delete
596    * @return the URL that can be used to delete the specified pace
597    * @since 4.5
598    */
 
599  29 toggle public String getURLToDeleteSpace(String space)
600    {
601  29 return getURL(space, "WebHome", "deletespace", "confirm=1&async=false&affectChidlren=on");
602    }
603   
 
604  62 toggle public ViewPage createPage(String space, String page, String content, String title)
605    {
606  62 return createPage(Collections.singletonList(space), page, content, title);
607    }
608   
609    /**
610    * @since 7.2M2
611    */