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

File MockitoOldcoreRule.java

 

Coverage histogram

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

Code metrics

88
275
53
1
926
670
101
0.37
5.19
53
1.91

Classes

Class Line # Actions
MockitoOldcoreRule 102 275 0% 101 45
0.891826989.2%
 

Contributing tests

This file is covered by 295 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 com.xpn.xwiki.test;
21   
22    import java.io.File;
23    import java.util.ArrayList;
24    import java.util.Date;
25    import java.util.List;
26    import java.util.Locale;
27    import java.util.Map;
28    import java.util.concurrent.ConcurrentHashMap;
29   
30    import javax.inject.Provider;
31    import javax.script.ScriptContext;
32    import javax.script.SimpleScriptContext;
33    import javax.servlet.ServletContext;
34   
35    import org.apache.commons.lang3.StringUtils;
36    import org.junit.rules.MethodRule;
37    import org.junit.runners.model.FrameworkMethod;
38    import org.junit.runners.model.Statement;
39    import org.mockito.internal.util.MockUtil;
40    import org.mockito.invocation.InvocationOnMock;
41    import org.mockito.stubbing.Answer;
42    import org.xwiki.bridge.event.DocumentCreatedEvent;
43    import org.xwiki.bridge.event.DocumentDeletedEvent;
44    import org.xwiki.bridge.event.DocumentUpdatedEvent;
45    import org.xwiki.component.descriptor.DefaultComponentDescriptor;
46    import org.xwiki.component.manager.ComponentLookupException;
47    import org.xwiki.component.manager.ComponentManager;
48    import org.xwiki.configuration.ConfigurationSource;
49    import org.xwiki.configuration.internal.MemoryConfigurationSource;
50    import org.xwiki.context.Execution;
51    import org.xwiki.context.ExecutionContext;
52    import org.xwiki.context.ExecutionContextManager;
53    import org.xwiki.environment.Environment;
54    import org.xwiki.environment.internal.ServletEnvironment;
55    import org.xwiki.model.reference.DocumentReference;
56    import org.xwiki.model.reference.DocumentReferenceResolver;
57    import org.xwiki.model.reference.LocalDocumentReference;
58    import org.xwiki.model.reference.WikiReference;
59    import org.xwiki.observation.ObservationManager;
60    import org.xwiki.query.QueryManager;
61    import org.xwiki.rendering.syntax.Syntax;
62    import org.xwiki.script.ScriptContextManager;
63    import org.xwiki.script.internal.ScriptExecutionContextInitializer;
64    import org.xwiki.security.authorization.AuthorizationManager;
65    import org.xwiki.security.authorization.ContextualAuthorizationManager;
66    import org.xwiki.test.annotation.AllComponents;
67    import org.xwiki.test.internal.MockConfigurationSource;
68    import org.xwiki.test.mockito.MockitoComponentManagerRule;
69    import org.xwiki.wiki.descriptor.WikiDescriptorManager;
70   
71    import com.xpn.xwiki.CoreConfiguration;
72    import com.xpn.xwiki.XWiki;
73    import com.xpn.xwiki.XWikiContext;
74    import com.xpn.xwiki.doc.XWikiAttachment;
75    import com.xpn.xwiki.doc.XWikiDocument;
76    import com.xpn.xwiki.internal.XWikiCfgConfigurationSource;
77    import com.xpn.xwiki.objects.classes.BaseClass;
78    import com.xpn.xwiki.store.XWikiHibernateStore;
79    import com.xpn.xwiki.store.XWikiStoreInterface;
80    import com.xpn.xwiki.store.XWikiVersioningStoreInterface;
81    import com.xpn.xwiki.user.api.XWikiGroupService;
82    import com.xpn.xwiki.user.api.XWikiRightService;
83    import com.xpn.xwiki.util.XWikiStubContextProvider;
84    import com.xpn.xwiki.web.Utils;
85   
86    import static com.xpn.xwiki.test.mockito.OldcoreMatchers.anyXWikiContext;
87    import static com.xpn.xwiki.test.mockito.OldcoreMatchers.anyXWikiDocument;
88    import static org.mockito.ArgumentMatchers.any;
89    import static org.mockito.ArgumentMatchers.anyBoolean;
90    import static org.mockito.Mockito.doAnswer;
91    import static org.mockito.Mockito.doReturn;
92    import static org.mockito.Mockito.mock;
93    import static org.mockito.Mockito.spy;
94    import static org.mockito.Mockito.when;
95   
96    /**
97    * Test rule to initialize and manipulate various oldcore APIs.
98    *
99    * @version $Id: 23b19031aab002d684987f571d252f8c53b42ffb $
100    * @since 5.2M1
101    */
 
102    public class MockitoOldcoreRule implements MethodRule
103    {
104    public static final LocalDocumentReference USER_CLASS = new LocalDocumentReference("XWiki", "XWikiUsers");
105   
106    public static final LocalDocumentReference GROUP_CLASS = new LocalDocumentReference("XWiki", "XWikiGroups");
107   
108    private final MethodRule parent;
109   
110    private final MockitoComponentManagerRule componentManager;
111   
112    private XWikiContext context;
113   
114    private XWiki spyXWiki;
115   
116    protected File permanentDirectory;
117   
118    protected File temporaryDirectory;
119   
120    private XWikiHibernateStore mockHibernateStore;
121   
122    private XWikiVersioningStoreInterface mockVersioningStore;
123   
124    private XWikiRightService mockRightService;
125   
126    private XWikiGroupService mockGroupService;
127   
128    private AuthorizationManager mockAuthorizationManager;
129   
130    private ContextualAuthorizationManager mockContextualAuthorizationManager;
131   
132    private QueryManager queryManager;
133   
134    private WikiDescriptorManager wikiDescriptorManager;
135   
136    protected Map<DocumentReference, XWikiDocument> documents = new ConcurrentHashMap<>();
137   
138    private boolean notifyDocumentCreatedEvent;
139   
140    private boolean notifyDocumentUpdatedEvent;
141   
142    private boolean notifyDocumentDeletedEvent;
143   
144    private MemoryConfigurationSource configurationSource;
145   
146    private MemoryConfigurationSource xwikicfgConfigurationSource;
147   
148    private MemoryConfigurationSource wikiConfigurationSource;
149   
150    private MemoryConfigurationSource spaceConfigurationSource;
151   
152    private ScriptContext scriptContext;
153   
 
154  317 toggle public MockitoOldcoreRule()
155    {
156  317 this(new MockitoComponentManagerRule());
157    }
158   
 
159  372 toggle public MockitoOldcoreRule(MockitoComponentManagerRule componentManager)
160    {
161  372 this(componentManager, componentManager);
162    }
163   
 
164  372 toggle public MockitoOldcoreRule(MockitoComponentManagerRule componentManager, MethodRule parent)
165    {
166  372 this.componentManager = componentManager;
167  372 this.parent = parent;
168    }
169   
 
170  6787 toggle public MockitoComponentManagerRule getMocker()
171    {
172  6787 return this.componentManager;
173    }
174   
 
175  15 toggle public void notifyDocumentCreatedEvent(boolean notifyDocumentCreatedEvent)
176    {
177  15 this.notifyDocumentCreatedEvent = notifyDocumentCreatedEvent;
178    }
179   
 
180  16 toggle public void notifyDocumentUpdatedEvent(boolean notifyDocumentUpdatedEvent)
181    {
182  16 this.notifyDocumentUpdatedEvent = notifyDocumentUpdatedEvent;
183    }
184   
 
185  13 toggle public void notifyDocumentDeletedEvent(boolean notifyDocumentDeletedEvent)
186    {
187  13 this.notifyDocumentDeletedEvent = notifyDocumentDeletedEvent;
188    }
189   
190    /**
191    * Enabled notification of component descriptor registration/unregistration.
192    *
193    * @throws ComponentLookupException when failing to lookup {@link ObservationManager} component
194    */
 
195  5 toggle public void notifyComponentDescriptorEvent() throws ComponentLookupException
196    {
197  5 getMocker().notifyComponentDescriptorEvent();
198    }
199   
 
200  372 toggle @Override
201    public Statement apply(final Statement base, final FrameworkMethod method, final Object target)
202    {
203  372 final Statement statement = new Statement()
204    {
 
205  372 toggle @Override
206    public void evaluate() throws Throwable
207    {
208  372 before(target.getClass());
209  372 try {
210  372 base.evaluate();
211    } finally {
212  372 after();
213    }
214    }
215    };
216   
217  372 return this.parent != null ? this.parent.apply(statement, method, target) : statement;
218    }
219   
 
220  372 toggle protected void before(Class<?> testClass) throws Exception
221    {
222    // Statically store the component manager in {@link Utils} to be able to access it without
223    // the context.
224  372 Utils.setComponentManager(getMocker());
225   
226  372 this.context = new XWikiContext();
227   
228  372 this.context.setWikiId("xwiki");
229  372 this.context.setMainXWiki("xwiki");
230   
231  372 this.spyXWiki = spy(new XWiki());
232  372 getXWikiContext().setWiki(this.spyXWiki);
233   
234  372 this.mockHibernateStore = mock(XWikiHibernateStore.class);
235  372 this.mockVersioningStore = mock(XWikiVersioningStoreInterface.class);
236  372 this.mockRightService = mock(XWikiRightService.class);
237  372 this.mockGroupService = mock(XWikiGroupService.class);
238   
239  372 doReturn(this.mockHibernateStore).when(this.spyXWiki).getStore();
240  372 doReturn(this.mockHibernateStore).when(this.spyXWiki).getHibernateStore();
241  372 doReturn(this.mockVersioningStore).when(this.spyXWiki).getVersioningStore();
242  372 doReturn(this.mockRightService).when(this.spyXWiki).getRightService();
243  372 doReturn(this.mockGroupService).when(this.spyXWiki).getGroupService(getXWikiContext());
244   
245    // We need to initialize the Component Manager so that the components can be looked up
246  372 getXWikiContext().put(ComponentManager.class.getName(), getMocker());
247   
248  372 if (testClass.getAnnotation(AllComponents.class) != null) {
249    // If @AllComponents is enabled force mocking AuthorizationManager and ContextualAuthorizationManager if not
250    // already mocked
251  55 this.mockAuthorizationManager = getMocker().registerMockComponent(AuthorizationManager.class, false);
252  55 this.mockContextualAuthorizationManager =
253    getMocker().registerMockComponent(ContextualAuthorizationManager.class, false);
254    } else {
255    // Make sure an AuthorizationManager and a ContextualAuthorizationManager is available
256  317 if (!getMocker().hasComponent(AuthorizationManager.class)) {
257  311 this.mockAuthorizationManager = getMocker().registerMockComponent(AuthorizationManager.class);
258    }
259  317 if (!getMocker().hasComponent(ContextualAuthorizationManager.class)) {
260  315 this.mockContextualAuthorizationManager =
261    getMocker().registerMockComponent(ContextualAuthorizationManager.class);
262    }
263    }
264   
265    // Make sure a default ConfigurationSource is available
266  372 if (!getMocker().hasComponent(ConfigurationSource.class)) {
267  372 this.configurationSource = getMocker().registerMemoryConfigurationSource();
268    }
269   
270    // Make sure a "xwikicfg" ConfigurationSource is available
271  372 if (!getMocker().hasComponent(ConfigurationSource.class, XWikiCfgConfigurationSource.ROLEHINT)) {
272  317 this.xwikicfgConfigurationSource = new MockConfigurationSource();
273  317 getMocker().registerComponent(MockConfigurationSource.getDescriptor(XWikiCfgConfigurationSource.ROLEHINT),
274    this.xwikicfgConfigurationSource);
275    }
276    // Make sure a "wiki" ConfigurationSource is available
277  372 if (!getMocker().hasComponent(ConfigurationSource.class, "wiki")) {
278  366 this.wikiConfigurationSource = new MockConfigurationSource();
279  366 getMocker().registerComponent(MockConfigurationSource.getDescriptor("wiki"), this.wikiConfigurationSource);
280    }
281   
282    // Make sure a "space" ConfigurationSource is available
283  372 if (!getMocker().hasComponent(ConfigurationSource.class, "space")) {
284  371 this.spaceConfigurationSource = new MockConfigurationSource();
285  371 getMocker().registerComponent(MockConfigurationSource.getDescriptor("space"),
286    this.spaceConfigurationSource);
287    }
288   
289    // Since the oldcore module draws the Servlet Environment in its dependencies we need to ensure it's set up
290    // correctly with a Servlet Context.
291  372 if (getMocker().hasComponent(Environment.class)
292    && getMocker().getInstance(Environment.class) instanceof ServletEnvironment) {
293  45 ServletEnvironment environment = getMocker().getInstance(Environment.class);
294   
295  45 ServletContext servletContextMock = mock(ServletContext.class);
296  45 environment.setServletContext(servletContextMock);
297  45 when(servletContextMock.getAttribute("javax.servlet.context.tempdir"))
298    .thenReturn(new File(System.getProperty("java.io.tmpdir")));
299   
300  45 File testDirectory = new File("target/test-" + new Date().getTime());
301  45 this.temporaryDirectory = new File(testDirectory, "temporary-dir");
302  45 this.permanentDirectory = new File(testDirectory, "permanent-dir");
303  45 environment.setTemporaryDirectory(this.temporaryDirectory);
304  45 environment.setPermanentDirectory(this.permanentDirectory);
305    }
306   
307    // Initialize the Execution Context
308  372 if (this.componentManager.hasComponent(ExecutionContextManager.class)) {
309  62 ExecutionContextManager ecm = this.componentManager.getInstance(ExecutionContextManager.class);
310  62 ExecutionContext ec = new ExecutionContext();
311  62 ecm.initialize(ec);
312    }
313   
314    // Bridge with old XWiki Context, required for old code.
315  372 Execution execution;
316  372 if (this.componentManager.hasComponent(Execution.class)) {
317  63 execution = this.componentManager.getInstance(Execution.class);
318    } else {
319  309 execution = this.componentManager.registerMockComponent(Execution.class);
320    }
321  372 ExecutionContext econtext;
322  372 if (MockUtil.isMock(execution)) {
323  310 econtext = new ExecutionContext();
324  310 when(execution.getContext()).thenReturn(econtext);
325    } else {
326  62 econtext = execution.getContext();
327    }
328   
329    // Set a few standard things in the ExecutionContext
330  372 econtext.setProperty(XWikiContext.EXECUTIONCONTEXT_KEY, this.context);
331  372 this.scriptContext = (ScriptContext) econtext.getProperty(ScriptExecutionContextInitializer.SCRIPT_CONTEXT_ID);
332  372 if (this.scriptContext == null) {
333  310 this.scriptContext = new SimpleScriptContext();
334  310 econtext.setProperty(ScriptExecutionContextInitializer.SCRIPT_CONTEXT_ID, this.scriptContext);
335    }
336   
337  372 if (!this.componentManager.hasComponent(ScriptContextManager.class)) {
338  309 ScriptContextManager scriptContextManager =
339    this.componentManager.registerMockComponent(ScriptContextManager.class);
340  309 when(scriptContextManager.getCurrentScriptContext()).thenReturn(this.scriptContext);
341  309 when(scriptContextManager.getScriptContext()).thenReturn(this.scriptContext);
342    }
343   
344    // Initialize XWikiContext provider
345  372 if (!this.componentManager.hasComponent(XWikiContext.TYPE_PROVIDER)) {
346  299 Provider<XWikiContext> xcontextProvider =
347    this.componentManager.registerMockComponent(XWikiContext.TYPE_PROVIDER);
348  299 when(xcontextProvider.get()).thenReturn(this.context);
349    } else {
350  73 Provider<XWikiContext> xcontextProvider = this.componentManager.getInstance(XWikiContext.TYPE_PROVIDER);
351  73 if (MockUtil.isMock(xcontextProvider)) {
352  18 when(xcontextProvider.get()).thenReturn(this.context);
353    }
354    }
355   
356    // Initialize readonly XWikiContext provider
357  372 if (!this.componentManager.hasComponent(XWikiContext.TYPE_PROVIDER, "readonly")) {
358  317 Provider<XWikiContext> xcontextProvider =
359    this.componentManager.registerMockComponent(XWikiContext.TYPE_PROVIDER, "readonly");
360  317 when(xcontextProvider.get()).thenReturn(this.context);
361    } else {
362  55 Provider<XWikiContext> xcontextProvider = this.componentManager.getInstance(XWikiContext.TYPE_PROVIDER);
363  55 if (MockUtil.isMock(xcontextProvider)) {
364  0 when(xcontextProvider.get()).thenReturn(this.context);
365    }
366    }
367   
368    // Initialize stub context provider
369  372 if (this.componentManager.hasComponent(XWikiStubContextProvider.class)) {
370  55 XWikiStubContextProvider stubContextProvider =
371    this.componentManager.getInstance(XWikiStubContextProvider.class);
372  55 if (!MockUtil.isMock(stubContextProvider)) {
373  55 stubContextProvider.initialize(this.context);
374    }
375    }
376   
377    // Make sure to have a mocked CoreConfiguration (even if one already exist)
378  372 if (!this.componentManager.hasComponent(CoreConfiguration.class)) {
379  317 CoreConfiguration coreConfigurationMock =
380    this.componentManager.registerMockComponent(CoreConfiguration.class);
381  317 when(coreConfigurationMock.getDefaultDocumentSyntax()).thenReturn(Syntax.XWIKI_1_0);
382    } else {
383  55 CoreConfiguration coreConfiguration =
384    this.componentManager.registerMockComponent(CoreConfiguration.class, false);
385  55 if (MockUtil.isMock(coreConfiguration)) {
386  55 when(coreConfiguration.getDefaultDocumentSyntax()).thenReturn(Syntax.XWIKI_1_0);
387    }
388    }
389   
390    // Set a context ComponentManager if none exist
391  372 if (!this.componentManager.hasComponent(ComponentManager.class, "context")) {
392  317 DefaultComponentDescriptor<ComponentManager> componentManagerDescriptor =
393    new DefaultComponentDescriptor<>();
394  317 componentManagerDescriptor.setRoleHint("context");
395  317 componentManagerDescriptor.setRoleType(ComponentManager.class);
396  317 this.componentManager.registerComponent(componentManagerDescriptor, this.componentManager);
397    }
398   
399    // XWiki
400   
401  372 doAnswer(new Answer<XWikiDocument>()
402    {
 
403  1 toggle @Override
404    public XWikiDocument answer(InvocationOnMock invocation) throws Throwable
405    {
406  1 XWikiDocument doc = invocation.getArgument(0);
407  1 String revision = invocation.getArgument(1);
408   
409  1 if (StringUtils.equals(revision, doc.getVersion())) {
410  0 return doc;
411    }
412   
413    // TODO: implement version store mocking
414  1 return new XWikiDocument(doc.getDocumentReference());
415    }
416    }).when(getSpyXWiki()).getDocument(anyXWikiDocument(), any(), anyXWikiContext());
417  372 doAnswer(new Answer<XWikiDocument>()
418    {
 
419  2068 toggle @Override
420    public XWikiDocument answer(InvocationOnMock invocation) throws Throwable
421    {
422  2068 DocumentReference target = invocation.getArgument(0);
423   
424  2068 if (target.getLocale() == null) {
425  860 target = new DocumentReference(target, Locale.ROOT);
426    }
427   
428  2068 XWikiDocument document = documents.get(target);
429   
430  2068 if (document == null) {
431  1499 document = new XWikiDocument(target, target.getLocale());
432  1499 document.setSyntax(Syntax.PLAIN_1_0);
433  1499 document.setOriginalDocument(document.clone());
434    }
435   
436  2068 return document;
437    }
438    }).when(getSpyXWiki()).getDocument(any(DocumentReference.class), anyXWikiContext());
439  372 doAnswer(new Answer<XWikiDocument>()
440    {
 
441  24 toggle @Override
442    public XWikiDocument answer(InvocationOnMock invocation) throws Throwable
443    {
444  24 XWikiDocument target = invocation.getArgument(0);
445   
446  24 return getSpyXWiki().getDocument(target.getDocumentReferenceWithLocale(), invocation.getArgument(1));
447    }
448    }).when(getSpyXWiki()).getDocument(anyXWikiDocument(), any(XWikiContext.class));
449  372 doAnswer(new Answer<Boolean>()
450    {
 
451  19 toggle @Override
452    public Boolean answer(InvocationOnMock invocation) throws Throwable
453    {
454  19 DocumentReference target = (DocumentReference) invocation.getArguments()[0];
455   
456  19 if (target.getLocale() == null) {
457  19 target = new DocumentReference(target, Locale.ROOT);
458    }
459   
460  19 return documents.containsKey(target);
461    }
462    }).when(getSpyXWiki()).exists(any(DocumentReference.class), anyXWikiContext());
463  372 doAnswer(new Answer<Void>()
464    {
 
465  515 toggle @Override
466    public Void answer(InvocationOnMock invocation) throws Throwable
467    {
468  515 XWikiDocument document = invocation.getArgument(0);
469  515 String comment = invocation.getArgument(1);
470  515 boolean minorEdit = invocation.getArgument(2);
471   
472  515 boolean isNew = document.isNew();
473   
474  515 document.setComment(StringUtils.defaultString(comment));
475  515 document.setMinorEdit(minorEdit);
476   
477  515 if (document.isContentDirty() || document.isMetaDataDirty()) {
478  499 document.setDate(new Date());
479  499 if (document.isContentDirty()) {
480  463 document.setContentUpdateDate(new Date());
481  463 document.setContentAuthorReference(document.getAuthorReference());
482    }
483  499 document.incrementVersion();
484   
485  499 document.setContentDirty(false);
486  499 document.setMetaDataDirty(false);
487    }
488  515 document.setNew(false);
489  515 document.setStore(getMockStore());
490   
491  515 XWikiDocument previousDocument = documents.get(document.getDocumentReferenceWithLocale());
492   
493  515 if (previousDocument != null && previousDocument != document) {
494  12 for (XWikiAttachment attachment : document.getAttachmentList()) {
495  4 if (!attachment.isContentDirty()) {
496  0 attachment.setAttachment_content(
497    previousDocument.getAttachment(attachment.getFilename()).getAttachment_content());
498    }
499    }
500    }
501   
502  515 XWikiDocument originalDocument = document.getOriginalDocument();
503  515 if (originalDocument == null) {
504  390 originalDocument = spyXWiki.getDocument(document.getDocumentReferenceWithLocale(), context);
505  390 document.setOriginalDocument(originalDocument);
506    }
507   
508  515 XWikiDocument savedDocument = document.clone();
509   
510  515 documents.put(document.getDocumentReferenceWithLocale(), savedDocument);
511   
512  515 if (isNew) {
513  475 if (notifyDocumentCreatedEvent) {
514  29 getObservationManager().notify(new DocumentCreatedEvent(document.getDocumentReference()),
515    document, getXWikiContext());
516    }
517    } else {
518  40 if (notifyDocumentUpdatedEvent) {
519  20 getObservationManager().notify(new DocumentUpdatedEvent(document.getDocumentReference()),
520    document, getXWikiContext());
521    }
522    }
523   
524    // Set the document as it's original document
525  515 savedDocument.setOriginalDocument(savedDocument.clone());
526   
527  515 return null;
528    }
529    }).when(getSpyXWiki()).saveDocument(anyXWikiDocument(), any(String.class), anyBoolean(), anyXWikiContext());
530  372 doAnswer(new Answer<Void>()
531    {
 
532  64 toggle @Override
533    public Void answer(InvocationOnMock invocation) throws Throwable
534    {
535  64 XWikiDocument document = invocation.getArgument(0);
536   
537  64 documents.remove(document.getDocumentReferenceWithLocale());
538   
539  64 if (notifyDocumentDeletedEvent) {
540  1 getObservationManager().notify(new DocumentDeletedEvent(document.getDocumentReference()), document,
541    getXWikiContext());
542    }
543   
544  64 return null;
545    }
546    }).when(getSpyXWiki()).deleteDocument(anyXWikiDocument(), any(Boolean.class), anyXWikiContext());
547  372 doAnswer(new Answer<Void>()
548    {
 
549  64 toggle @Override
550    public Void answer(InvocationOnMock invocation) throws Throwable
551    {
552  64 XWikiDocument document = invocation.getArgument(0);
553   
554  64 spyXWiki.deleteDocument(document, true, context);
555   
556  64 return null;
557    }
558    }).when(getSpyXWiki()).deleteDocument(anyXWikiDocument(), anyXWikiContext());
559  372 doAnswer(new Answer<Void>()
560    {
 
561  1 toggle @Override
562    public Void answer(InvocationOnMock invocation) throws Throwable
563    {
564  1 XWikiDocument document = invocation.getArgument(0);
565   
566  1 DocumentReference reference = document.getDocumentReference();
567   
568  1 List<Locale> locales = document.getTranslationLocales(context);
569   
570  1 for (Locale locale : locales) {
571  0 XWikiDocument translation = spyXWiki.getDocument(new DocumentReference(reference, locale), context);
572  0 spyXWiki.deleteDocument(translation, context);
573    }
574   
575  1 spyXWiki.deleteDocument(document, context);
576   
577  1 return null;
578    }
579    }).when(getSpyXWiki()).deleteAllDocuments(anyXWikiDocument(), any(Boolean.class), anyXWikiContext());
580  372 doAnswer(new Answer<Void>()
581    {
 
582  1 toggle @Override
583    public Void answer(InvocationOnMock invocation) throws Throwable
584    {
585  1 XWikiDocument document = invocation.getArgument(0);
586   
587  1 spyXWiki.deleteAllDocuments(document, true, context);
588   
589  1 return null;
590    }
591    }).when(getSpyXWiki()).deleteAllDocuments(anyXWikiDocument(), anyXWikiContext());
592  372 doAnswer(new Answer<BaseClass>()
593    {
 
594  429 toggle @Override
595    public BaseClass answer(InvocationOnMock invocation) throws Throwable
596    {
597  429 return getSpyXWiki()
598    .getDocument((DocumentReference) invocation.getArguments()[0], invocation.getArgument(1))
599    .getXClass();
600    }
601    }).when(getSpyXWiki()).getXClass(any(DocumentReference.class), anyXWikiContext());
602  372 doAnswer(new Answer<String>()
603    {
 
604  48 toggle @Override
605    public String answer(InvocationOnMock invocation) throws Throwable
606    {
607  48 return getXWikiContext().getLanguage();
608    }
609    }).when(getSpyXWiki()).getLanguagePreference(anyXWikiContext());
610   
611  372 getXWikiContext().setLocale(Locale.ENGLISH);
612   
613    // XWikiStoreInterface
614   
615  372 when(getMockStore().getTranslationList(anyXWikiDocument(), anyXWikiContext())).then(new Answer<List<String>>()
616    {
 
617  4 toggle @Override
618    public List<String> answer(InvocationOnMock invocation) throws Throwable
619    {
620  4 XWikiDocument document = invocation.getArgument(0);
621   
622  4 List<String> translations = new ArrayList<String>();
623   
624  4 for (XWikiDocument storedDocument : documents.values()) {
625  11 Locale storedLocale = storedDocument.getLocale();
626  11 if (!storedLocale.equals(Locale.ROOT)
627    && storedDocument.getDocumentReference().equals(document.getDocumentReference())) {
628  0 translations.add(storedLocale.toString());
629    }
630    }
631   
632  4 return translations;
633    }
634    });
635  372 when(getMockStore().loadXWikiDoc(anyXWikiDocument(), anyXWikiContext())).then(new Answer<XWikiDocument>()
636    {
 
637  2 toggle @Override
638    public XWikiDocument answer(InvocationOnMock invocation) throws Throwable
639    {
640  2 return getSpyXWiki().getDocument(invocation.<XWikiDocument>getArgument(0),
641    invocation.<XWikiContext>getArgument(1));
642    }
643    });
644   
645    // Users
646   
647  372 doAnswer(new Answer<BaseClass>()
648    {
 
649  3 toggle @Override
650    public BaseClass answer(InvocationOnMock invocation) throws Throwable
651    {
652  3 XWikiContext xcontext = invocation.getArgument(0);
653   
654  3 XWikiDocument userDocument = getSpyXWiki()
655    .getDocument(new DocumentReference(USER_CLASS, new WikiReference(xcontext.getWikiId())), xcontext);
656   
657  3 final BaseClass userClass = userDocument.getXClass();
658   
659  3 if (userDocument.isNew()) {
660  2 userClass.addTextField("first_name", "First Name", 30);
661  2 userClass.addTextField("last_name", "Last Name", 30);
662  2 userClass.addEmailField("email", "e-Mail", 30);
663  2 userClass.addPasswordField("password", "Password", 10);
664  2 userClass.addBooleanField("active", "Active", "active");
665  2 userClass.addTextAreaField("comment", "Comment", 40, 5);
666  2 userClass.addTextField("avatar", "Avatar", 30);
667  2 userClass.addTextField("phone", "Phone", 30);
668  2 userClass.addTextAreaField("address", "Address", 40, 3);
669   
670  2 getSpyXWiki().saveDocument(userDocument, xcontext);
671    }
672   
673  3 return userClass;
674    }
675    }).when(getSpyXWiki()).getUserClass(anyXWikiContext());
676  372 doAnswer(new Answer<BaseClass>()
677    {
 
678  6 toggle @Override
679    public BaseClass answer(InvocationOnMock invocation) throws Throwable
680    {
681  6 XWikiContext xcontext = invocation.getArgument(0);
682   
683  6 XWikiDocument groupDocument = getSpyXWiki()
684    .getDocument(new DocumentReference(GROUP_CLASS, new WikiReference(xcontext.getWikiId())), xcontext);
685   
686  6 final BaseClass groupClass = groupDocument.getXClass();
687   
688  6 if (groupDocument.isNew()) {
689  2 groupClass.addTextField("member", "Member", 30);
690   
691  2 getSpyXWiki().saveDocument(groupDocument, xcontext);
692    }
693   
694  6 return groupClass;
695    }
696    }).when(getSpyXWiki()).getGroupClass(anyXWikiContext());
697   
698    // Query Manager
699    // If there's already a Query Manager registered, use it instead.
700    // This allows, for example, using @ComponentList to use the real Query Manager, in integration tests.
701  372 if (!this.componentManager.hasComponent(QueryManager.class)) {
702  313 mockQueryManager();
703    }
704  372 when(getMockStore().getQueryManager()).then(new Answer<QueryManager>()
705    {
706   
 
707  1 toggle @Override
708    public QueryManager answer(InvocationOnMock invocation) throws Throwable
709    {
710  1 return getQueryManager();
711    }
712    });
713   
714    // WikiDescriptorManager
715    // If there's already a WikiDescriptorManager registered, use it instead.
716    // This allows, for example, using @ComponentList to use the real WikiDescriptorManager, in integration tests.
717  372 if (!this.componentManager.hasComponent(WikiDescriptorManager.class)) {
718  359 this.wikiDescriptorManager = getMocker().registerMockComponent(WikiDescriptorManager.class);
719  359 when(this.wikiDescriptorManager.getMainWikiId()).then(new Answer<String>()
720    {
 
721  0 toggle @Override
722    public String answer(InvocationOnMock invocation) throws Throwable
723    {
724  0 return getXWikiContext().getMainXWiki();
725    }
726    });
727  359 when(this.wikiDescriptorManager.getCurrentWikiId()).then(new Answer<String>()
728    {
 
729  12016 toggle @Override
730    public String answer(InvocationOnMock invocation) throws Throwable
731    {
732  12016 return getXWikiContext().getWikiId();
733    }
734    });
735    }
736    }
737   
 
738  0 toggle protected DocumentReference resolveDocument(String documentName) throws ComponentLookupException
739    {
740  0 DocumentReferenceResolver<String> resolver =
741    getMocker().getInstance(DocumentReferenceResolver.TYPE_STRING, "current");
742   
743  0 return resolver.resolve(documentName);
744    }
745   
 
746  372 toggle protected void after() throws Exception
747    {
748  372 Utils.setComponentManager(null);
749   
750  372 Execution execution = this.componentManager.getInstance(Execution.class);
751  372 execution.removeContext();
752    }
753   
 
754  15168 toggle public XWikiContext getXWikiContext()
755    {
756  15168 return this.context;
757    }
758   
759    /**
760    * @since 7.3RC1
761    */
 
762  5795 toggle public XWiki getSpyXWiki()
763    {
764  5795 return this.spyXWiki;
765    }
766   
767    /**
768    * @deprecated since 7.3RC1, use {@link #getSpyXWiki()} instead
769    */
 
770  0 toggle @Deprecated
771    public XWiki getMockXWiki()
772    {
773  0 return getSpyXWiki();
774    }
775   
 
776  0 toggle public File getPermanentDirectory()
777    {
778  0 return this.permanentDirectory;
779    }
780   
 
781  0 toggle public File getTemporaryDirectory()
782    {
783  0 return this.temporaryDirectory;
784    }
785   
 
786  96 toggle public XWikiRightService getMockRightService()
787    {
788  96 return this.mockRightService;
789    }
790   
 
791  0 toggle public XWikiGroupService getMockGroupService()
792    {
793  0 return this.mockGroupService;
794    }
795   
 
796  23 toggle public AuthorizationManager getMockAuthorizationManager()
797    {
798  23 return this.mockAuthorizationManager;
799    }
800   
 
801  40 toggle public ContextualAuthorizationManager getMockContextualAuthorizationManager()
802    {
803  40 return this.mockContextualAuthorizationManager;
804    }
805   
 
806  1633 toggle public XWikiStoreInterface getMockStore()
807    {
808  1633 return this.mockHibernateStore;
809    }
810   
811    /**
812    * @since 7.2M2
813    */
 
814  0 toggle public XWikiVersioningStoreInterface getMockVersioningStore()
815    {
816  0 return this.mockVersioningStore;
817    }
818   
819    /**
820    * @since 6.0RC1
821    */
 
822  12 toggle public ExecutionContext getExecutionContext() throws ComponentLookupException
823    {
824  12 return this.componentManager.<Execution>getInstance(Execution.class).getContext();
825    }
826   
827    /**
828    * @since 8.3M1
829    */
 
830  4 toggle public ScriptContext getScriptContext()
831    {
832  4 return this.scriptContext;
833    }
834   
835    /**
836    * @since 6.1M2
837    */
 
838  53 toggle public Map<DocumentReference, XWikiDocument> getDocuments()
839    {
840  53 return this.documents;
841    }
842   
843    /**
844    * @since 6.1M2
845    */
 
846  50 toggle public ObservationManager getObservationManager() throws ComponentLookupException
847    {
848  50 return getMocker().getInstance(ObservationManager.class);
849    }
850   
851    /**
852    * @since 7.0RC1
853    */
 
854  9 toggle public QueryManager getQueryManager() throws ComponentLookupException
855    {
856  9 if (this.queryManager == null) {
857  0 this.queryManager = this.componentManager.getInstance(QueryManager.class);
858    }
859   
860  9 return this.queryManager;
861    }
862   
863    /**
864    * Force mocking query manager.
865    *
866    * @return 7.2M1
867    */
 
868  313 toggle public QueryManager mockQueryManager() throws Exception
869    {
870  313 this.queryManager = getMocker().registerMockComponent(QueryManager.class);
871   
872  313 return this.queryManager;
873    }
874   
875    /**
876    * @since 7.2M1
877    */
 
878  0 toggle public WikiDescriptorManager getWikiDescriptorManager() throws ComponentLookupException
879    {
880  0 if (this.wikiDescriptorManager == null) {
881    // Avoid initializing it if not needed
882  0 if (this.componentManager.hasComponent(WikiDescriptorManager.class)) {
883  0 this.wikiDescriptorManager = this.componentManager.getInstance(WikiDescriptorManager.class);
884    }
885    }
886   
887  0 return this.wikiDescriptorManager;
888    }
889   
890    /**
891    * @since 7.1M1
892    */
 
893  0 toggle public MemoryConfigurationSource getConfigurationSource()
894    {
895  0 return this.configurationSource;
896    }
897   
898    /**
899    * @since 7.2M2
900    */
 
901  24 toggle public MemoryConfigurationSource getMockXWikiCfg()
902    {
903  24 return this.xwikicfgConfigurationSource;
904    }
905   
906    /**
907    * @since 7.2RC1
908    */
 
909  0 toggle public MemoryConfigurationSource getMockWikiConfigurationSource()
910    {
911  0 return this.wikiConfigurationSource;
912    }
913   
914    /**
915    * @since 7.2M2
916    */
 
917  96 toggle public void registerMockEnvironment() throws Exception
918    {
919  96 Environment environment = getMocker().registerMockComponent(Environment.class);
920   
921  96 File temp = new File(new File(System.getProperty("java.io.tmpdir")), "test-" + new Date().getTime());
922   
923  96 when(environment.getTemporaryDirectory()).thenReturn(new File(temp, "temporary"));
924  96 when(environment.getPermanentDirectory()).thenReturn(new File(temp, "permanent"));
925    }
926    }