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

File XWikiDocumentMockitoTest.java

 

Code metrics

4
558
56
1
1,381
915
59
0.11
9.96
56
1.05

Classes

Class Line # Actions
XWikiDocumentMockitoTest 93 558 0% 59 2
0.9967637799.7%
 

Contributing tests

This file is covered by 49 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.doc;
21   
22    import java.io.ByteArrayInputStream;
23    import java.util.ArrayList;
24    import java.util.Arrays;
25    import java.util.Date;
26    import java.util.HashMap;
27    import java.util.List;
28    import java.util.Map;
29   
30    import javax.servlet.http.HttpServletRequest;
31   
32    import org.apache.commons.io.IOUtils;
33    import org.dom4j.Document;
34    import org.hamcrest.Matchers;
35    import org.junit.Assert;
36    import org.junit.Before;
37    import org.junit.Rule;
38    import org.junit.Test;
39    import org.xwiki.model.EntityType;
40    import org.xwiki.model.reference.DocumentReference;
41    import org.xwiki.model.reference.DocumentReferenceResolver;
42    import org.xwiki.model.reference.EntityReference;
43    import org.xwiki.model.reference.EntityReferenceSerializer;
44    import org.xwiki.model.reference.ObjectReference;
45    import org.xwiki.model.reference.SpaceReference;
46    import org.xwiki.model.reference.WikiReference;
47    import org.xwiki.query.Query;
48    import org.xwiki.query.QueryFilter;
49    import org.xwiki.rendering.internal.syntax.DefaultSyntaxFactory;
50    import org.xwiki.rendering.syntax.Syntax;
51    import org.xwiki.security.authorization.AccessDeniedException;
52    import org.xwiki.security.authorization.Right;
53    import org.xwiki.test.annotation.ComponentList;
54    import org.xwiki.test.mockito.MockitoComponentManagerRule;
55   
56    import com.xpn.xwiki.XWikiConstant;
57    import com.xpn.xwiki.XWikiContext;
58    import com.xpn.xwiki.XWikiException;
59    import com.xpn.xwiki.objects.BaseObject;
60    import com.xpn.xwiki.objects.StringProperty;
61    import com.xpn.xwiki.objects.classes.BaseClass;
62    import com.xpn.xwiki.objects.classes.TextAreaClass;
63    import com.xpn.xwiki.objects.meta.MetaClass;
64    import com.xpn.xwiki.objects.meta.StaticListMetaClass;
65    import com.xpn.xwiki.test.MockitoOldcoreRule;
66    import com.xpn.xwiki.test.component.XWikiDocumentFilterUtilsComponentList;
67    import com.xpn.xwiki.test.reference.ReferenceComponentList;
68    import com.xpn.xwiki.validation.XWikiValidationInterface;
69    import com.xpn.xwiki.web.EditForm;
70   
71    import static org.junit.Assert.assertEquals;
72    import static org.junit.Assert.assertFalse;
73    import static org.junit.Assert.assertNotNull;
74    import static org.junit.Assert.assertNotSame;
75    import static org.junit.Assert.assertNull;
76    import static org.junit.Assert.assertThat;
77    import static org.junit.Assert.assertTrue;
78    import static org.mockito.ArgumentMatchers.any;
79    import static org.mockito.ArgumentMatchers.eq;
80    import static org.mockito.Mockito.doReturn;
81    import static org.mockito.Mockito.doThrow;
82    import static org.mockito.Mockito.mock;
83    import static org.mockito.Mockito.verify;
84    import static org.mockito.Mockito.when;
85   
86    /**
87    * Unit tests for {@link XWikiDocument}.
88    *
89    * @version $Id: 1e32c244953b0655e9b469bedc0b8891a3fbbfa8 $
90    */
91    @ReferenceComponentList
92    @XWikiDocumentFilterUtilsComponentList
 
93    public class XWikiDocumentMockitoTest
94    {
95    private static final String DOCWIKI = "wiki";
96   
97    private static final String DOCSPACE = "space";
98   
99    private static final String DOCNAME = "page";
100   
101    private static final DocumentReference DOCUMENT_REFERENCE = new DocumentReference(DOCWIKI, DOCSPACE, DOCNAME);
102   
103    private static final DocumentReference CLASS_REFERENCE = DOCUMENT_REFERENCE;
104   
105    @Rule
106    public MockitoOldcoreRule oldcore = new MockitoOldcoreRule();
107   
108    /**
109    * The object being tested.
110    */
111    private XWikiDocument document;
112   
113    private BaseClass baseClass;
114   
115    private BaseObject baseObject;
116   
117    private BaseObject baseObject2;
118   
119    private EntityReferenceSerializer<String> defaultEntityReferenceSerializer;
120   
 
121  49 toggle @Before
122    public void setUp() throws Exception
123    {
124  49 this.oldcore.registerMockEnvironment();
125   
126    // Activate programming rights in order to be able to call com.xpn.xwiki.api.Document#getDocument().
127  49 when(this.oldcore.getMockRightService().hasProgrammingRights(this.oldcore.getXWikiContext())).thenReturn(true);
128   
129  49 this.document = new XWikiDocument(DOCUMENT_REFERENCE);
130  49 this.document.setSyntax(Syntax.PLAIN_1_0);
131   
132  49 this.baseClass = this.document.getXClass();
133  49 this.baseClass.addTextField("string", "String", 30);
134  49 this.baseClass.addTextAreaField("area", "Area", 10, 10);
135  49 this.baseClass.addTextAreaField("puretextarea", "Pure text area", 10, 10);
136    // set the text areas an non interpreted content
137  49 ((TextAreaClass) this.baseClass.getField("puretextarea")).setContentType("puretext");
138  49 this.baseClass.addPasswordField("passwd", "Password", 30);
139  49 this.baseClass.addBooleanField("boolean", "Boolean", "yesno");
140  49 this.baseClass.addNumberField("int", "Int", 10, "integer");
141  49 this.baseClass.addStaticListField("stringlist", "StringList", 1, true, "value1, value2");
142   
143  49 this.baseObject = this.document.newXObject(CLASS_REFERENCE, this.oldcore.getXWikiContext());
144  49 this.baseObject.setStringValue("string", "string");
145  49 this.baseObject.setLargeStringValue("area", "area");
146  49 this.baseObject.setStringValue("passwd", "passwd");
147  49 this.baseObject.setIntValue("boolean", 1);
148  49 this.baseObject.setIntValue("int", 42);
149  49 this.baseObject.setStringListValue("stringlist", Arrays.asList("VALUE1", "VALUE2"));
150   
151  49 this.baseObject2 = this.baseObject.clone();
152  49 this.document.addXObject(this.baseObject2);
153   
154  49 this.oldcore.getSpyXWiki().saveDocument(this.document, "", true, this.oldcore.getXWikiContext());
155   
156  49 this.defaultEntityReferenceSerializer =
157    this.oldcore.getMocker().getInstance(EntityReferenceSerializer.TYPE_STRING);
158   
159  49 this.oldcore.getXWikiContext().setWikiId(DOCWIKI);
160   
161    // Reset the cached (static) MetaClass instance because it may have been initialized during the execution of the
162    // previous test classes, so before the StaticListMetaClass component needed by this test class was loaded.
163  49 MetaClass.setMetaClass(null);
164    }
165   
 
166  1 toggle @Test
167    public void getChildrenReferences() throws Exception
168    {
169  1 Query query = mock(Query.class);
170  1 when(this.oldcore.getQueryManager().createQuery(any(), eq(Query.XWQL))).thenReturn(query);
171   
172  1 QueryFilter hiddenFilter = this.oldcore.getMocker().registerMockComponent(QueryFilter.class, "hidden");
173   
174  1 when(query.setLimit(7)).thenReturn(query);
175   
176  1 List<String> result = Arrays.asList("X.y", "A.b");
177  1 when(query.<String>execute()).thenReturn(result);
178   
179  1 List<DocumentReference> childrenReferences =
180    document.getChildrenReferences(7, 3, this.oldcore.getXWikiContext());
181   
182  1 verify(query).addFilter(hiddenFilter);
183  1 verify(query).setLimit(7);
184  1 verify(query).setOffset(3);
185   
186  1 Assert.assertEquals(2, childrenReferences.size());
187  1 Assert.assertEquals(new DocumentReference("wiki", "X", "y"), childrenReferences.get(0));
188  1 Assert.assertEquals(new DocumentReference("wiki", "A", "b"), childrenReferences.get(1));
189    }
190   
191    /**
192    * Generate a fake map for the request used in the tests of {@link #readObjectsFromForm()} and
193    * {@link #readObjectsFromFormUpdateOrCreate()}.
194    *
195    * @return Map of fake parameters which should test every cases
196    */
 
197  2 toggle private Map<String, String[]> generateFakeRequestMap()
198    {
199  2 Map<String, String[]> parameters = new HashMap<>();
200    // Testing update of values in existing object with existing properties
201  2 String[] string1 = { "bloublou" };
202  2 parameters.put("space.page_0_string", string1);
203  2 String[] int1 = { "7" };
204  2 parameters.put("space.page_1_int", int1);
205    // Testing creation and update of an object's properties when object
206    // doesn't exist
207  2 String[] string2 = { "blabla" };
208  2 String[] int2 = { "13" };
209  2 parameters.put("space.page_3_string", string2);
210  2 parameters.put("space.page_3_int", int2);
211    // Testing that objects with non-following number is not created
212  2 parameters.put("space.page_42_string", string1);
213  2 parameters.put("space.page_42_int", int1);
214    // Testing that invalid parameter are ignored
215  2 parameters.put("invalid", new String[] { "whatever" });
216    // Testing that invalid xclass page are ignored
217  2 parameters.put("InvalidSpace.InvalidPage_0_string", new String[] { "whatever" });
218    // Testing that an invalid number is ignored (first should be ignored by
219    // regexp parser, second by an exception)
220  2 parameters.put("space.page_notANumber_string", new String[] { "whatever" });
221  2 parameters.put("space.page_9999999999_string", new String[] { "whatever" });
222  2 return parameters;
223    }
224   
225    /**
226    * Generate the fake class that is used for the test of {@link #readObjectsFromForm()} and
227    * {@link #readObjectsFromFormUpdateOrCreate()}.
228    *
229    * @return The fake BaseClass
230    */
 
231  2 toggle private BaseClass generateFakeClass()
232    {
233  2 BaseClass baseClass = this.document.getXClass();
234  2 baseClass.addTextField("string", "String", 30);
235  2 baseClass.addTextAreaField("area", "Area", 10, 10);
236  2 baseClass.addTextAreaField("puretextarea", "Pure text area", 10, 10);
237    // set the text areas an non interpreted content
238  2 ((TextAreaClass) baseClass.getField("puretextarea")).setContentType("puretext");
239  2 baseClass.addPasswordField("passwd", "Password", 30);
240  2 baseClass.addBooleanField("boolean", "Boolean", "yesno");
241  2 baseClass.addNumberField("int", "Int", 10, "integer");
242  2 baseClass.addStaticListField("stringlist", "StringList", "value1, value2");
243   
244  2 return baseClass;
245    }
246   
247    /**
248    * Generate 2 clones of a fake object in the document
249    *
250    * @return Return the reference of the first clone
251    */
 
252  2 toggle private void generateFakeObjects()
253    {
254  2 BaseObject baseObject = null, baseObject2 = null, baseObject3 = null;
255  2 try {
256  2 baseObject = this.document.newXObject(this.document.getDocumentReference(), this.oldcore.getXWikiContext());
257  2 baseObject2 =
258    this.document.newXObject(this.document.getDocumentReference(), this.oldcore.getXWikiContext());
259  2 baseObject3 =
260    this.document.newXObject(this.document.getDocumentReference(), this.oldcore.getXWikiContext());
261    } catch (XWikiException e) {
262    // TODO Auto-generated catch block
263  0 e.printStackTrace();
264  0 return;
265    }
266  2 baseObject.setStringValue("string", "string");
267  2 baseObject.setIntValue("int", 42);
268  2 baseObject2.setStringValue("string", "string2");
269  2 baseObject2.setIntValue("int", 42);
270  2 baseObject3.setStringValue("string", "string3");
271  2 baseObject3.setIntValue("int", 42);
272    }
273   
274    /**
275    * Unit test for {@link XWikiDocument#readObjectsFromForm(EditForm, XWikiContext)}.
276    */
 
277  1 toggle @Test
278    public void readObjectsFromForm() throws Exception
279    {
280  1 this.document = new XWikiDocument(new DocumentReference(DOCWIKI, DOCSPACE, DOCNAME));
281  1 this.oldcore.getSpyXWiki().saveDocument(this.document, "", true, this.oldcore.getXWikiContext());
282   
283  1 HttpServletRequest request = mock(HttpServletRequest.class);
284  1 MockitoComponentManagerRule mocker = this.oldcore.getMocker();
285  1 XWikiContext context = this.oldcore.getXWikiContext();
286  1 DocumentReferenceResolver<String> documentReferenceResolverString =
287    mocker.registerMockComponent(DocumentReferenceResolver.TYPE_STRING, "current");
288    // Entity Reference resolver is used in <BaseObject>.getXClass()
289  1 DocumentReferenceResolver<EntityReference> documentReferenceResolverEntity =
290    mocker.registerMockComponent(DocumentReferenceResolver.TYPE_REFERENCE, "current");
291  1 EntityReferenceSerializer<String> entityReferenceResolver =
292    mocker.registerMockComponent(EntityReferenceSerializer.TYPE_STRING, "local");
293   
294  1 Map<String, String[]> parameters = generateFakeRequestMap();
295  1 BaseClass baseClass = generateFakeClass();
296  1 generateFakeObjects();
297   
298  1 when(request.getParameterMap()).thenReturn(parameters);
299   
300  1 DocumentReference documentReference = new DocumentReference("wiki", "space", "page");
301    // This entity resolver with this 'resolve' method is used in
302    // <BaseCollection>.getXClassReference()
303  1 when(documentReferenceResolverEntity.resolve(any(EntityReference.class), any(DocumentReference.class)))
304    .thenReturn(this.document.getDocumentReference());
305  1 when(documentReferenceResolverString.resolve("space.page")).thenReturn(documentReference);
306  1 when(entityReferenceResolver.serialize(any(EntityReference.class))).thenReturn("space.page");
307   
308  1 EditForm eform = new EditForm();
309  1 eform.setRequest(request);
310  1 document.readObjectsFromForm(eform, context);
311   
312  1 assertEquals(3, this.document.getXObjectSize(baseClass.getDocumentReference()));
313  1 assertEquals("string", this.document.getXObject(baseClass.getDocumentReference(), 0).getStringValue("string"));
314  1 assertEquals(42, this.document.getXObject(baseClass.getDocumentReference(), 0).getIntValue("int"));
315  1 assertEquals("string2", this.document.getXObject(baseClass.getDocumentReference(), 1).getStringValue("string"));
316  1 assertEquals(42, this.document.getXObject(baseClass.getDocumentReference(), 1).getIntValue("int"));
317  1 assertEquals("string3", this.document.getXObject(baseClass.getDocumentReference(), 2).getStringValue("string"));
318  1 assertEquals(42, this.document.getXObject(baseClass.getDocumentReference(), 2).getIntValue("int"));
319  1 assertNull(this.document.getXObject(baseClass.getDocumentReference(), 3));
320  1 assertNull(this.document.getXObject(baseClass.getDocumentReference(), 42));
321    }
322   
323    /**
324    * Unit test for {@link XWikiDocument#readObjectsFromFormUpdateOrCreate(EditForm, XWikiContext)} .
325    */
 
326  1 toggle @Test
327    public void readObjectsFromFormUpdateOrCreate() throws Exception
328    {
329  1 this.document = new XWikiDocument(new DocumentReference(DOCWIKI, DOCSPACE, DOCNAME));
330  1 this.oldcore.getSpyXWiki().saveDocument(this.document, "", true, this.oldcore.getXWikiContext());
331   
332  1 HttpServletRequest request = mock(HttpServletRequest.class);
333  1 MockitoComponentManagerRule mocker = this.oldcore.getMocker();
334  1 XWikiContext context = this.oldcore.getXWikiContext();
335  1 DocumentReferenceResolver<String> documentReferenceResolverString =
336    mocker.registerMockComponent(DocumentReferenceResolver.TYPE_STRING, "current");
337    // Entity Reference resolver is used in <BaseObject>.getXClass()
338  1 DocumentReferenceResolver<EntityReference> documentReferenceResolverEntity =
339    mocker.registerMockComponent(DocumentReferenceResolver.TYPE_REFERENCE, "current");
340   
341  1 Map<String, String[]> parameters = generateFakeRequestMap();
342  1 BaseClass baseClass = generateFakeClass();
343  1 generateFakeObjects();
344  1 EditForm eform = new EditForm();
345   
346  1 when(request.getParameterMap()).thenReturn(parameters);
347  1 when(documentReferenceResolverString.resolve("space.page")).thenReturn(this.document.getDocumentReference());
348  1 when(documentReferenceResolverString.resolve("InvalidSpace.InvalidPage"))
349    .thenReturn(new DocumentReference("wiki", "InvalidSpace", "InvalidPage"));
350    // This entity resolver with this 'resolve' method is used in
351    // <BaseCollection>.getXClassReference()
352  1 when(documentReferenceResolverEntity.resolve(any(EntityReference.class), any(DocumentReference.class)))
353    .thenReturn(this.document.getDocumentReference());
354  1 doReturn(this.document).when(this.oldcore.getSpyXWiki()).getDocument(this.document.getDocumentReference(),
355    context);
356   
357  1 eform.setRequest(request);
358  1 this.document.readObjectsFromFormUpdateOrCreate(eform, context);
359   
360  1 assertEquals(43, this.document.getXObjectSize(baseClass.getDocumentReference()));
361  1 assertEquals("bloublou",
362    this.document.getXObject(baseClass.getDocumentReference(), 0).getStringValue("string"));
363  1 assertEquals(42, this.document.getXObject(baseClass.getDocumentReference(), 0).getIntValue("int"));
364  1 assertEquals("string2", this.document.getXObject(baseClass.getDocumentReference(), 1).getStringValue("string"));
365  1 assertEquals(7, this.document.getXObject(baseClass.getDocumentReference(), 1).getIntValue("int"));
366  1 assertEquals("string3", this.document.getXObject(baseClass.getDocumentReference(), 2).getStringValue("string"));
367  1 assertEquals(42, this.document.getXObject(baseClass.getDocumentReference(), 2).getIntValue("int"));
368  1 assertNotNull(this.document.getXObject(baseClass.getDocumentReference(), 3));
369  1 assertEquals("blabla", this.document.getXObject(baseClass.getDocumentReference(), 3).getStringValue("string"));
370  1 assertEquals(13, this.document.getXObject(baseClass.getDocumentReference(), 3).getIntValue("int"));
371  1 assertNotNull(this.document.getXObject(baseClass.getDocumentReference(), 42));
372  1 assertEquals("bloublou",
373    this.document.getXObject(baseClass.getDocumentReference(), 42).getStringValue("string"));
374  1 assertEquals(7, this.document.getXObject(baseClass.getDocumentReference(), 42).getIntValue("int"));
375    }
376   
 
377  1 toggle @Test
378    public void testDeprecatedConstructors()
379    {
380  1 DocumentReference defaultReference = new DocumentReference("xwiki", "Main", "WebHome");
381   
382  1 XWikiDocument doc = new XWikiDocument(null);
383  1 assertEquals(defaultReference, doc.getDocumentReference());
384   
385  1 doc = new XWikiDocument();
386  1 assertEquals(defaultReference, doc.getDocumentReference());
387   
388  1 doc = new XWikiDocument("notused", "space.page");
389  1 assertEquals("space", doc.getSpaceName());
390  1 assertEquals("page", doc.getPageName());
391  1 assertEquals(this.oldcore.getXWikiContext().getWikiId(), doc.getWikiName());
392   
393  1 doc = new XWikiDocument("space", "page");
394  1 assertEquals("space", doc.getSpaceName());
395  1 assertEquals("page", doc.getPageName());
396  1 assertEquals(this.oldcore.getXWikiContext().getWikiId(), doc.getWikiName());
397   
398  1 doc = new XWikiDocument("wiki2", "space", "page");
399  1 assertEquals("space", doc.getSpaceName());
400  1 assertEquals("page", doc.getPageName());
401  1 assertEquals("wiki2", doc.getWikiName());
402   
403  1 doc = new XWikiDocument("wiki2", "notused", "notused:space.page");
404  1 assertEquals("space", doc.getSpaceName());
405  1 assertEquals("page", doc.getPageName());
406  1 assertEquals("wiki2", doc.getWikiName());
407    }
408   
 
409  1 toggle @Test
410    public void testMinorMajorVersions()
411    {
412  1 this.document = new XWikiDocument(new DocumentReference(DOCWIKI, DOCSPACE, DOCNAME));
413   
414    // there is no version in doc yet, so 1.1
415  1 assertEquals("1.1", this.document.getVersion());
416   
417  1 this.document.setMinorEdit(false);
418  1 this.document.incrementVersion();
419    // no version => incrementVersion sets 1.1
420  1 assertEquals("1.1", this.document.getVersion());
421   
422  1 this.document.setMinorEdit(false);
423  1 this.document.incrementVersion();
424    // increment major version
425  1 assertEquals("2.1", this.document.getVersion());
426   
427  1 this.document.setMinorEdit(true);
428  1 this.document.incrementVersion();
429    // increment minor version
430  1 assertEquals("2.2", this.document.getVersion());
431    }
432   
 
433  1 toggle @Test
434    public void testGetPreviousVersion() throws XWikiException
435    {
436  1 this.document = new XWikiDocument(new DocumentReference(DOCWIKI, DOCSPACE, DOCNAME));
437   
438  1 Date now = new Date();
439  1 XWikiDocumentArchive archiveDoc = new XWikiDocumentArchive(this.document.getId());
440  1 this.document.setDocumentArchive(archiveDoc);
441   
442  1 assertEquals("1.1", this.document.getVersion());
443  1 assertNull(this.document.getPreviousVersion());
444   
445  1 this.document.incrementVersion();
446  1 archiveDoc.updateArchive(this.document, "Admin", now, "", this.document.getRCSVersion(),
447    this.oldcore.getXWikiContext());
448  1 assertEquals("1.1", this.document.getVersion());
449  1 assertNull(this.document.getPreviousVersion());
450   
451  1 this.document.setMinorEdit(true);
452  1 this.document.incrementVersion();
453  1 archiveDoc.updateArchive(this.document, "Admin", now, "", this.document.getRCSVersion(),
454    this.oldcore.getXWikiContext());
455  1 assertEquals("1.2", this.document.getVersion());
456  1 assertEquals("1.1", this.document.getPreviousVersion());
457   
458  1 this.document.setMinorEdit(false);
459  1 this.document.incrementVersion();
460  1 archiveDoc.updateArchive(this.document, "Admin", now, "", this.document.getRCSVersion(),
461    this.oldcore.getXWikiContext());
462  1 assertEquals("2.1", this.document.getVersion());
463  1 assertEquals("1.2", this.document.getPreviousVersion());
464   
465  1 this.document.setMinorEdit(true);
466  1 this.document.incrementVersion();
467  1 archiveDoc.updateArchive(this.document, "Admin", now, "", this.document.getRCSVersion(),
468    this.oldcore.getXWikiContext());
469  1 assertEquals("2.2", this.document.getVersion());
470  1 assertEquals("2.1", this.document.getPreviousVersion());
471   
472  1 archiveDoc.resetArchive();
473   
474  1 assertEquals("2.2", this.document.getVersion());
475  1 assertNull(this.document.getPreviousVersion());
476    }
477   
 
478  1 toggle @Test
479    public void testCloneNullObjects()
480    {
481  1 XWikiDocument document = new XWikiDocument(new DocumentReference("wiki", DOCSPACE, DOCNAME));
482   
483  1 EntityReference relativeClassReference =
484    new EntityReference(DOCNAME, EntityType.DOCUMENT, new EntityReference(DOCSPACE, EntityType.SPACE));
485  1 DocumentReference classReference = new DocumentReference("wiki", DOCSPACE, DOCNAME);
486  1 DocumentReference duplicatedClassReference = new DocumentReference("otherwiki", DOCSPACE, DOCNAME);
487   
488    // no object
489  1 XWikiDocument clonedDocument = document.clone();
490  1 assertTrue(clonedDocument.getXObjects().isEmpty());
491   
492  1 XWikiDocument duplicatedDocument = document.duplicate(new DocumentReference("otherwiki", DOCSPACE, DOCNAME));
493  1 assertTrue(duplicatedDocument.getXObjects().isEmpty());
494   
495    // 1 null object
496   
497  1 document.addXObject(classReference, null);
498   
499  1 clonedDocument = document.clone();
500  1 assertEquals(1, clonedDocument.getXObjects(classReference).size());
501  1 assertEquals(document.getXObjects(classReference), clonedDocument.getXObjects(classReference));
502   
503  1 duplicatedDocument = document.duplicate(new DocumentReference("otherwiki", DOCSPACE, DOCNAME));
504  1 assertTrue(duplicatedDocument.getXObjects().isEmpty());
505   
506    // 1 null object and 1 object
507   
508  1 BaseObject object = new BaseObject();
509  1 object.setXClassReference(relativeClassReference);
510  1 document.addXObject(object);
511   
512  1 clonedDocument = document.clone();
513  1 assertEquals(2, clonedDocument.getXObjects(classReference).size());
514  1 assertEquals(document.getXObjects(classReference), clonedDocument.getXObjects(classReference));
515   
516  1 duplicatedDocument = document.duplicate(new DocumentReference("otherwiki", DOCSPACE, DOCNAME));
517  1 assertEquals(2, duplicatedDocument.getXObjects(duplicatedClassReference).size());
518    }
519   
 
520  1 toggle @Test
521    public void testToStringReturnsFullName()
522    {
523  1 assertEquals("space.page", this.document.toString());
524  1 assertEquals("Main.WebHome", new XWikiDocument().toString());
525    }
526   
 
527  1 toggle @Test
528    public void testCloneSaveVersions()
529    {
530  1 XWikiDocument doc1 = new XWikiDocument(new DocumentReference("qwe", "qwe", "qwe"));
531  1 XWikiDocument doc2 = doc1.clone();
532  1 doc1.incrementVersion();
533  1 doc2.incrementVersion();
534  1 assertEquals(doc1.getVersion(), doc2.getVersion());
535    }
536   
 
537  1 toggle @Test
538    public void testAddObject() throws XWikiException
539    {
540  1 XWikiDocument doc = new XWikiDocument(new DocumentReference("test", "test", "document"));
541  1 BaseObject object = BaseClass.newCustomClassInstance("XWiki.XWikiUsers", this.oldcore.getXWikiContext());
542  1 doc.addObject("XWiki.XWikiUsers", object);
543  1 assertEquals("XWikiDocument.addObject does not set the object's name", doc.getFullName(), object.getName());
544    }
545   
 
546  1 toggle @Test
547    public void testObjectNumbersAfterXMLRoundrip() throws XWikiException
548    {
549  1 String wiki = oldcore.getXWikiContext().getWikiId();
550   
551  1 XWikiDocument tagDocument = new XWikiDocument(new DocumentReference(wiki, "XWiki", "TagClass"));
552  1 BaseClass tagClass = tagDocument.getXClass();
553  1 tagClass.addStaticListField(XWikiConstant.TAG_CLASS_PROP_TAGS, "Tags", 30, true, "", "checkbox");
554  1 this.oldcore.getSpyXWiki().saveDocument(tagDocument, this.oldcore.getXWikiContext());
555   
556  1 XWikiDocument doc = new XWikiDocument(new DocumentReference(wiki, "test", "document"));
557  1 doReturn("iso-8859-1").when(this.oldcore.getSpyXWiki()).getEncoding();
558   
559  1 BaseObject object1 = doc.newXObject(tagDocument.getDocumentReference(), this.oldcore.getXWikiContext());
560  1 BaseObject object2 = doc.newXObject(tagDocument.getDocumentReference(), this.oldcore.getXWikiContext());
561  1 BaseObject object3 = doc.newXObject(tagDocument.getDocumentReference(), this.oldcore.getXWikiContext());
562   
563    // Remove first object
564  1 doc.removeXObject(object1);
565   
566  1 String docXML = doc.toXML(this.oldcore.getXWikiContext());
567  1 XWikiDocument docFromXML = new XWikiDocument(doc.getDocumentReference());
568  1 docFromXML.fromXML(docXML);
569   
570  1 List<BaseObject> objects = doc.getXObjects(tagDocument.getDocumentReference());
571  1 List<BaseObject> objectsFromXML = docFromXML.getXObjects(tagDocument.getDocumentReference());
572   
573  1 assertNotNull(objects);
574  1 assertNotNull(objectsFromXML);
575   
576  1 assertTrue(objects.size() == objectsFromXML.size());
577   
578  4 for (int i = 0; i < objects.size(); i++) {
579  3 if (objects.get(i) == null) {
580  1 assertNull(objectsFromXML.get(i));
581    } else {
582  2 assertTrue(objects.get(i).getNumber() == objectsFromXML.get(i).getNumber());
583    }
584    }
585    }
586   
 
587  1 toggle @Test
588    public void testGetXObjectWithObjectReference()
589    {
590  1 Assert.assertSame(this.baseObject, this.document.getXObject(this.baseObject.getReference()));
591   
592  1 Assert.assertSame(this.baseObject,
593    this.document.getXObject(new ObjectReference(
594    this.defaultEntityReferenceSerializer.serialize(this.baseObject.getXClassReference()),
595    this.document.getDocumentReference())));
596    }
597   
 
598  1 toggle @Test
599    public void testGetXObjectWithNumber()
600    {
601  1 Assert.assertSame(this.baseObject, this.document.getXObject(CLASS_REFERENCE, this.baseObject.getNumber()));
602  1 Assert.assertSame(this.baseObject2, this.document.getXObject(CLASS_REFERENCE, this.baseObject2.getNumber()));
603  1 Assert.assertSame(this.baseObject,
604    this.document.getXObject((EntityReference) CLASS_REFERENCE, this.baseObject.getNumber()));
605  1 Assert.assertSame(this.baseObject2,
606    this.document.getXObject((EntityReference) CLASS_REFERENCE, this.baseObject2.getNumber()));
607    }
608   
 
609  1 toggle @Test
610    public void testSetXObjectswithPreviousObject()
611    {
612  1 BaseObject object = new BaseObject();
613  1 object.setXClassReference(this.baseObject.getXClassReference());
614  1 this.document.addXObject(object);
615   
616  1 this.document.setXObjects(this.baseObject.getXClassReference(), Arrays.asList(object));
617   
618  1 Assert.assertEquals(Arrays.asList(object), this.document.getXObjects(this.baseObject.getXClassReference()));
619    }
620   
 
621  1 toggle @Test
622    public void testSetXObjectWhithNoPreviousObject()
623    {
624  1 XWikiDocument document = new XWikiDocument(this.document.getDocumentReference());
625   
626  1 document.setXObject(this.baseObject.getXClassReference(), 0, this.baseObject);
627   
628  1 Assert.assertEquals(Arrays.asList(this.baseObject), document.getXObjects(this.baseObject.getXClassReference()));
629    }
630   
631    /**
632    * Test that the parent remain the same relative value whatever the context.
633    */
 
634  1 toggle @Test
635    public void testGetParent()
636    {
637  1 XWikiDocument doc = new XWikiDocument(new DocumentReference("docwiki", "docspace", "docpage"));
638   
639  1 assertEquals("", doc.getParent());
640  1 doc.setParent(null);
641  1 assertEquals("", doc.getParent());
642   
643  1 doc.setParent("page");
644  1 assertEquals("page", doc.getParent());
645   
646  1 this.oldcore.getXWikiContext().setWikiId("otherwiki");
647  1 assertEquals("page", doc.getParent());
648   
649  1 doc.setDocumentReference(new DocumentReference("otherwiki", "otherspace", "otherpage"));
650  1 assertEquals("page", doc.getParent());
651    }
652   
 
653  1 toggle @Test
654    public void testGetParentReference()
655    {
656  1 XWikiDocument doc = new XWikiDocument(new DocumentReference("docwiki", "docspace", "docpage"));
657   
658  1 assertNull(doc.getParentReference());
659   
660  1 doc.setParent("parentpage");
661   
662    // ////////////////////////////////////////////////////////////////
663    // The following tests are checking that document reference cache is properly cleaned something could make the
664    // parent change
665   
666  1 assertEquals(new DocumentReference("docwiki", "docspace", "parentpage"), doc.getParentReference());
667   
668  1 doc.setName("docpage2");
669  1 assertEquals(new DocumentReference("docwiki", "docspace", "parentpage"), doc.getParentReference());
670   
671  1 doc.setSpace("docspace2");
672  1 assertEquals(new DocumentReference("docwiki", "docspace2", "parentpage"), doc.getParentReference());
673   
674  1 doc.setDatabase("docwiki2");
675  1 assertEquals(new DocumentReference("docwiki2", "docspace2", "parentpage"), doc.getParentReference());
676   
677  1 doc.setDocumentReference(new DocumentReference("docwiki", "docspace", "docpage"));
678  1 assertEquals(new DocumentReference("docwiki", "docspace", "parentpage"), doc.getParentReference());
679   
680  1 doc.setFullName("docwiki2:docspace2.docpage2", this.oldcore.getXWikiContext());
681  1 assertEquals(new DocumentReference("docwiki2", "docspace2", "parentpage"), doc.getParentReference());
682   
683  1 doc.setParent("parentpage2");
684  1 assertEquals(new DocumentReference("docwiki2", "docspace2", "parentpage2"), doc.getParentReference());
685    }
686   
 
687  1 toggle @Test
688    public void testSetRelativeParentReference()
689    {
690  1 XWikiDocument doc = new XWikiDocument(new DocumentReference("docwiki", "docspace", "docpage"));
691   
692  1 doc.setParentReference(new EntityReference("docpage2", EntityType.DOCUMENT));
693  1 assertEquals(new DocumentReference("docwiki", "docspace", "docpage2"), doc.getParentReference());
694  1 assertEquals("docpage2", doc.getParent());
695    }
696   
697    /**
698    * Verify that setting a new creator will create a new revision (we verify that that metadata dirty flag is set to
699    * true).
700    *
701    * @see <a href="http://jira.xwiki.org/jira/browse/XWIKI-7445">XWIKI-7445</a>
702    */
 
703  1 toggle @Test
704    public void testSetCreatorReferenceSetsMetadataDirtyFlag()
705    {
706    // Make sure we set the flag to false to verify it's changed
707  1 this.document.setMetaDataDirty(false);
708   
709  1 DocumentReference creator = new DocumentReference("Wiki", "XWiki", "Creator");
710  1 this.document.setCreatorReference(creator);
711   
712  1 assertEquals(true, this.document.isMetaDataDirty());
713    }
714   
715    /**
716    * Verify that setting a new creator that is the same as the currenet creator doesn't create a new revision (we
717    * verify that the metadata dirty flag is not set).
718    *
719    * @see <a href="http://jira.xwiki.org/jira/browse/XWIKI-7445">XWIKI-7445</a>
720    */
 
721  1 toggle @Test
722    public void testSetCreatorReferenceWithSameCreatorDoesntSetMetadataDirtyFlag()
723    {
724    // Make sure we set the metadata dirty flag to false to verify it's not changed thereafter
725  1 DocumentReference creator = new DocumentReference("Wiki", "XWiki", "Creator");
726  1 this.document.setCreatorReference(creator);
727  1 this.document.setMetaDataDirty(false);
728   
729    // Set the creator with the same reference to verify it doesn't change the flag
730  1 this.document.setCreatorReference(new DocumentReference("Wiki", "XWiki", "Creator"));
731   
732  1 assertEquals(false, this.document.isMetaDataDirty());
733    }
734   
735    /**
736    * Verify that setting a new author will create a new revision (we verify that that metadata dirty flag is set to
737    * true).
738    *
739    * @see <a href="http://jira.xwiki.org/jira/browse/XWIKI-7445">XWIKI-7445</a>
740    */
 
741  1 toggle @Test
742    public void testSetAuthorReferenceSetsMetadataDirtyFlag()
743    {
744    // Make sure we set the flag to false to verify it's changed
745  1 this.document.setMetaDataDirty(false);
746   
747  1 DocumentReference author = new DocumentReference("Wiki", "XWiki", "Author");
748  1 this.document.setAuthorReference(author);
749   
750  1 assertEquals(true, this.document.isMetaDataDirty());
751    }
752   
753    /**
754    * Verify that setting a new author that is the same as the currenet creator doesn't create a new revision (we
755    * verify that the metadata dirty flag is not set).
756    *
757    * @see <a href="http://jira.xwiki.org/jira/browse/XWIKI-7445">XWIKI-7445</a>
758    */
 
759  1 toggle @Test
760    public void testSetAuthorReferenceWithSameAuthorDoesntSetMetadataDirtyFlag()
761    {
762    // Make sure we set the metadata dirty flag to false to verify it's not changed thereafter
763  1 DocumentReference author = new DocumentReference("Wiki", "XWiki", "Author");
764  1 this.document.setAuthorReference(author);
765  1 this.document.setMetaDataDirty(false);
766   
767    // Set the author with the same reference to verify it doesn't change the flag
768  1 this.document.setAuthorReference(new DocumentReference("Wiki", "XWiki", "Author"));
769   
770  1 assertEquals(false, this.document.isMetaDataDirty());
771    }
772   
773    /**
774    * Verify that setting a new content author will create a new revision (we verify that that metadata dirty flag is
775    * set to true).
776    *
777    * @see <a href="http://jira.xwiki.org/jira/browse/XWIKI-7445">XWIKI-7445</a>
778    */
 
779  1 toggle @Test
780    public void testSetContentAuthorReferenceSetsMetadataDirtyFlag()
781    {
782    // Make sure we set the flag to false to verify it's changed
783  1 this.document.setMetaDataDirty(false);
784   
785  1 DocumentReference contentAuthor = new DocumentReference("Wiki", "XWiki", "ContentAuthor");
786  1 this.document.setContentAuthorReference(contentAuthor);
787   
788  1 assertEquals(true, this.document.isMetaDataDirty());
789    }
790   
791    /**
792    * Verify that setting a new content author that is the same as the currenet creator doesn't create a new revision
793    * (we verify that the metadata dirty flag is not set).
794    *
795    * @see <a href="http://jira.xwiki.org/jira/browse/XWIKI-7445">XWIKI-7445</a>
796    */
 
797  1 toggle @Test
798    public void testSetContentAuthorReferenceWithSameContentAuthorDoesntSetMetadataDirtyFlag()
799    {
800    // Make sure we set the metadata dirty flag to false to verify it's not changed thereafter
801  1 DocumentReference contentAuthor = new DocumentReference("Wiki", "XWiki", "ContentAuthor");
802  1 this.document.setContentAuthorReference(contentAuthor);
803  1 this.document.setMetaDataDirty(false);
804   
805    // Set the content author with the same reference to verify it doesn't change the flag
806  1 this.document.setContentAuthorReference(new DocumentReference("Wiki", "XWiki", "ContentAuthor"));
807   
808  1 assertEquals(false, this.document.isMetaDataDirty());
809    }
810   
 
811  1 toggle @Test
812    public void testSetContentSetsContentDirtyFlag()
813    {
814    // Make sure we set the flags to false to verify it's changed
815  1 this.document.setContentDirty(false);
816  1 this.document.setMetaDataDirty(false);
817   
818  1 this.document.setContent("something");
819   
820  1 assertTrue(this.document.isContentDirty());
821  1 assertFalse(this.document.isMetaDataDirty());
822    }
823   
 
824  1 toggle @Test
825    public void testSetSameContentDoesNotSetContentDirtyFlag()
826    {
827  1 this.document.setContent("something");
828    // Make sure we set the flag to false to verify it's changed
829  1 this.document.setContentDirty(false);
830   
831    // Set the same content again.
832  1 this.document.setContent("something");
833   
834  1 assertFalse(this.document.isContentDirty());
835    }
836   
 
837  1 toggle @Test
838    public void testModifyObjectsSetsOnlyMetadataDirtyFlag() throws Exception
839    {
840  1 DocumentReference classReference = this.document.getDocumentReference();
841   
842    // Make sure we set the flags to false to verify it's changed
843  1 this.document.setContentDirty(false);
844  1 this.document.setMetaDataDirty(false);
845   
846    // New objects.
847  1 BaseObject object = this.document.newXObject(classReference, this.oldcore.getXWikiContext());
848   
849  1 assertTrue(this.document.isMetaDataDirty());
850  1 assertFalse(this.document.isContentDirty());
851   
852    // Make sure we set the flags to false to verify it's changed
853  1 this.document.setContentDirty(false);
854  1 this.document.setMetaDataDirty(false);
855   
856    // Set/add objects.
857  1 this.document.setXObject(0, object);
858   
859  1 assertTrue(this.document.isMetaDataDirty());
860  1 assertFalse(this.document.isContentDirty());
861   
862    // Make sure we set the flags to false to verify it's changed
863  1 this.document.setContentDirty(false);
864  1 this.document.setMetaDataDirty(false);
865   
866    // Remove objects
867  1 this.document.removeXObject(object);
868   
869  1 assertTrue(this.document.isMetaDataDirty());
870  1 assertFalse(this.document.isContentDirty());
871    }
872   
 
873  1 toggle @Test
874    public void testModifyAttachmentsSetsOnlyMetadataDirtyFlag() throws Exception
875    {
876    // Make sure we set the flags to false to verify it's changed
877  1 this.document.setContentDirty(false);
878  1 this.document.setMetaDataDirty(false);
879   
880    // Add attachments.
881  1 XWikiAttachment attachment =
882    document.addAttachment("file", new ByteArrayInputStream(new byte[] {}), this.oldcore.getXWikiContext());
883   
884  1 assertTrue(this.document.isMetaDataDirty());
885  1 assertFalse(this.document.isContentDirty());
886   
887    // Make sure we set the flags to false to verify it's changed
888  1 this.document.setContentDirty(false);
889  1 this.document.setMetaDataDirty(false);
890   
891    // Add attachments (2).
892  1 document.addAttachment(attachment);
893   
894  1 assertTrue(this.document.isMetaDataDirty());
895  1 assertFalse(this.document.isContentDirty());
896   
897    // Make sure we set the flags to false to verify it's changed
898  1 this.document.setContentDirty(false);
899  1 this.document.setMetaDataDirty(false);
900   
901    // Modify attachment.
902  1 attachment.setContent(new ByteArrayInputStream(new byte[] { 1, 2, 3 }));
903   
904  1 assertTrue(this.document.isMetaDataDirty());
905  1 assertFalse(this.document.isContentDirty());
906   
907    // Make sure we set the flags to false to verify it's changed
908  1 this.document.setContentDirty(false);
909  1 this.document.setMetaDataDirty(false);
910   
911    // Remove objects
912  1 this.document.removeAttachment(attachment);
913   
914  1 assertTrue(this.document.isMetaDataDirty());
915  1 assertFalse(this.document.isContentDirty());
916    }
917   
 
918  1 toggle @Test
919    public void testEqualsDatas()
920    {
921  1 XWikiDocument document = new XWikiDocument(new DocumentReference("wiki", "space", "page"));
922  1 XWikiDocument otherDocument = document.clone();
923   
924  1 Assert.assertTrue(document.equals(otherDocument));
925  1 Assert.assertTrue(document.equalsData(otherDocument));
926   
927  1 otherDocument.setAuthorReference(new DocumentReference("wiki", "space", "otherauthor"));
928  1 otherDocument.setContentAuthorReference(otherDocument.getAuthorReference());
929  1 otherDocument.setCreatorReference(otherDocument.getAuthorReference());
930  1 otherDocument.setVersion("42.0");
931  1 otherDocument.setComment("other comment");
932  1 otherDocument.setMinorEdit(true);
933   
934  1 document.setMinorEdit(false);
935   
936  1 Assert.assertFalse(document.equals(otherDocument));
937  1 Assert.assertTrue(document.equalsData(otherDocument));
938    }
939   
 
940  1 toggle @Test
941    public void testEqualsAttachments() throws XWikiException
942    {
943  1 XWikiDocument document = new XWikiDocument(new DocumentReference("wiki", "space", "page"));
944  1 XWikiDocument otherDocument = document.clone();
945   
946  1 XWikiAttachment attachment =
947    document.addAttachment("file", new byte[] { 1, 2 }, this.oldcore.getXWikiContext());
948  1 XWikiAttachment otherAttachment =
949    otherDocument.addAttachment("file", new byte[] { 1, 2 }, this.oldcore.getXWikiContext());
950   
951  1 Assert.assertTrue(document.equals(otherDocument));
952  1 Assert.assertTrue(document.equalsData(otherDocument));
953   
954  1 otherAttachment.setContent(new byte[] { 1, 2, 3 });
955   
956  1 Assert.assertFalse(document.equals(otherDocument));
957  1 Assert.assertFalse(document.equalsData(otherDocument));
958    }
959   
 
960  1 toggle @Test
961    public void testSetMetadataDirtyWhenAttachmenListChanges() throws XWikiException
962    {
963  1 XWikiDocument document = new XWikiDocument();
964   
965  1 XWikiAttachment attachment =
966    document.addAttachment("file", new byte[] { 1, 2 }, this.oldcore.getXWikiContext());
967   
968    // Force the metadata not dirty.
969  1 document.setMetaDataDirty(false);
970   
971  1 List<XWikiAttachment> attachments = document.getAttachmentList();
972    // Modify (clear) the attachments list)
973  1 attachments.clear();
974   
975    // Check that the the metadata is now dirty as a result.
976  1 Assert.assertTrue(document.isMetaDataDirty());
977   
978    // Check adding to list
979  1 document.setMetaDataDirty(false);
980  1 attachments.add(new XWikiAttachment());
981  1 Assert.assertTrue(document.isMetaDataDirty());
982   
983    // Check removing from the list
984  1 document.setMetaDataDirty(false);
985  1 attachments.remove(0);
986  1 Assert.assertTrue(document.isMetaDataDirty());
987    }
988   
989    /**
990    * XWIKI-8463: Backwards compatibility issue with setting the same attachment list to a document
991    */
 
992  1 toggle @Test
993    public void testSetGetAttachmentList() throws Exception
994    {
995  1 String attachmentName1 = "someFile.txt";
996  1 String attachmentName2 = "someOtherFile.txt";
997  1 this.document.addAttachment(attachmentName1, new byte[0], this.oldcore.getXWikiContext());
998  1 this.document.addAttachment(attachmentName2, new byte[0], this.oldcore.getXWikiContext());
999   
1000  1 List<String> attachmentNames = new ArrayList<String>();
1001   
1002  1 Assert.assertEquals(2, this.document.getAttachmentList().size());
1003  1 for (XWikiAttachment attachment : this.document.getAttachmentList()) {
1004  2 attachmentNames.add(attachment.getFilename());
1005    }
1006  1 Assert.assertTrue(attachmentNames.contains(attachmentName1));
1007  1 Assert.assertTrue(attachmentNames.contains(attachmentName2));
1008   
1009    // Set back the same list returned by the getter.
1010  1 this.document.setAttachmentList(this.document.getAttachmentList());
1011   
1012    // The result needs to stay the same.
1013  1 Assert.assertEquals(2, this.document.getAttachmentList().size());
1014  1 attachmentNames.clear();
1015  1 for (XWikiAttachment attachment : this.document.getAttachmentList()) {
1016  2 attachmentNames.add(attachment.getFilename());
1017    }
1018  1 Assert.assertTrue(attachmentNames.contains(attachmentName1));
1019  1 Assert.assertTrue(attachmentNames.contains(attachmentName2));
1020    }
1021   
1022    /**
1023    * Unit test for {@link XWikiDocument#readFromTemplate(DocumentReference, XWikiContext)}.
1024    */
 
1025  1 toggle @Test
1026    public void testReadFromTemplate() throws Exception
1027    {
1028  1 SpaceReference spaceReference = new SpaceReference("Space", new WikiReference("wiki"));
1029  1 XWikiDocument template = new XWikiDocument(new DocumentReference("Template", spaceReference));
1030  1 template.setParentReference(new EntityReference("Parent", EntityType.DOCUMENT, spaceReference));
1031  1 template.setTitle("Enter title here");
1032  1 template.setSyntax(Syntax.XWIKI_2_0);
1033  1 template.setContent("Enter content here");
1034   
1035  1 XWikiAttachment templateAttachment = new XWikiAttachment(template, "test.txt");
1036  1 String testContent = "test content";
1037  1 templateAttachment.setContent(IOUtils.toInputStream(testContent));
1038  1 template.addAttachment(templateAttachment);
1039   
1040  1 this.oldcore.getSpyXWiki().saveDocument(template, this.oldcore.getXWikiContext());
1041   
1042  1 XWikiDocument target = new XWikiDocument(new DocumentReference("Page", spaceReference));
1043  1 target.readFromTemplate(template.getDocumentReference(), this.oldcore.getXWikiContext());
1044   
1045  1 Assert.assertEquals(template.getDocumentReference(), target.getTemplateDocumentReference());
1046  1 Assert.assertEquals(template.getParentReference(), target.getParentReference());
1047  1 Assert.assertEquals(template.getTitle(), target.getTitle());
1048  1 Assert.assertEquals(template.getSyntax(), target.getSyntax());
1049  1 Assert.assertEquals(template.getContent(), target.getContent());
1050  1 assertThat(target.getAttachmentList(), Matchers.containsInAnyOrder(target.getAttachmentList().toArray()));
1051    }
1052   
 
1053  1 toggle @Test
1054    public void testResolveClassReference() throws Exception
1055    {
1056  1 XWikiDocument doc = new XWikiDocument(new DocumentReference("docwiki", "docspace", "docpage"));
1057   
1058  1 DocumentReference expected1 = new DocumentReference("docwiki", "XWiki", "docpage");
1059  1 assertEquals(expected1, doc.resolveClassReference(""));
1060   
1061  1 DocumentReference expected2 = new DocumentReference("docwiki", "XWiki", "page");
1062  1 assertEquals(expected2, doc.resolveClassReference("page"));
1063   
1064  1 DocumentReference expected3 = new DocumentReference("docwiki", "space", "page");
1065  1 assertEquals(expected3, doc.resolveClassReference("space.page"));
1066   
1067  1 DocumentReference expected4 = new DocumentReference("wiki", "space", "page");
1068  1 assertEquals(expected4, doc.resolveClassReference("wiki:space.page"));
1069    }
1070   
1071    /**
1072    * Verify that cloning objects modify their references to point to the document in which they are cloned into.
1073    */
 
1074  1 toggle @Test
1075    public void testCloneObjectsHaveCorrectReference()
1076    {
1077  1 XWikiDocument doc = new XWikiDocument(new DocumentReference("somewiki", "somespace", "somepage"));
1078  1 doc.cloneXObjects(this.document);
1079  1 assertTrue(doc.getXObjects().size() > 0);
1080   
1081    // Verify that the object references point to the doc in which it's cloned.
1082  1 for (Map.Entry<DocumentReference, List<BaseObject>> entry : doc.getXObjects().entrySet()) {
1083  1 for (BaseObject baseObject : entry.getValue()) {
1084  2 assertEquals(doc.getDocumentReference(), baseObject.getDocumentReference());
1085    }
1086    }
1087    }
1088   
1089    /**
1090    * Verify that merging objects modify their references to point to the document in which they are cloned into and
1091    * that GUID for merged objects are different from the original GUIDs.
1092    */
 
1093  1 toggle @Test
1094    public void testMergeObjectsHaveCorrectReferenceAndDifferentGuids()
1095    {
1096  1 List<String> originalGuids = new ArrayList<String>();
1097  1 for (Map.Entry<DocumentReference, List<BaseObject>> entry : this.document.getXObjects().entrySet()) {
1098  1 for (BaseObject baseObject : entry.getValue()) {
1099  2 originalGuids.add(baseObject.getGuid());
1100    }
1101    }
1102   
1103    // Use a document from a different wiki to see if the class reference of the merged objects is adjusted:
1104    // documents can't have objects of types defined in a different wiki.
1105  1 XWikiDocument doc = new XWikiDocument(new DocumentReference("somewiki", "somespace", "somepage"));
1106  1 doc.mergeXObjects(this.document);
1107   
1108  1 assertTrue(doc.getXObjects().size() > 0);
1109   
1110  1 for (Map.Entry<DocumentReference, List<BaseObject>> entry : doc.getXObjects().entrySet()) {
1111    // Verify that the class reference and the target document reference have the same wiki component.
1112  1 assertEquals(doc.getDocumentReference().getWikiReference(), entry.getKey().getWikiReference());
1113  1 for (BaseObject baseObject : entry.getValue()) {
1114    // Verify that the object references point to the doc in which it's cloned.
1115  2 assertEquals(doc.getDocumentReference(), baseObject.getDocumentReference());
1116    // Verify that GUIDs are not the same as the original ones
1117  2 assertFalse("Non unique object GUID found!", originalGuids.contains(baseObject.getGuid()));
1118    }
1119    }
1120    }
1121   
1122    /**
1123    * Tests that objects are not copied again when {@link XWikiDocument#mergeXObjects(XWikiDocument)} is called twice.
1124    */
 
1125  1 toggle @Test
1126    public void testMergeObjectsTwice()
1127    {
1128    // Make sure the target document and the template document are from different wikis.
1129  1 XWikiDocument targetDoc = new XWikiDocument(new DocumentReference("someWiki", "someSpace", "somePage"));
1130   
1131    // Merge the objects.
1132  1 targetDoc.mergeXObjects(this.document);
1133   
1134  1 assertEquals(1, targetDoc.getXObjects().size());
1135  1 assertEquals(0, targetDoc.getXObjectSize(CLASS_REFERENCE));
1136  1 DocumentReference classReference = CLASS_REFERENCE.replaceParent(CLASS_REFERENCE.getWikiReference(),
1137    targetDoc.getDocumentReference().getWikiReference());
1138  1 assertEquals(2, targetDoc.getXObjectSize(classReference));
1139   
1140    // Try to merge the objects again.
1141  1 targetDoc.mergeXObjects(this.document);
1142   
1143    // Check that the object from the template document was not copied again.
1144  1 assertEquals(2, targetDoc.getXObjectSize(classReference));
1145    }
1146   
1147    /** Check that a new empty document has empty content (used to have a new line before 2.5). */
 
1148  1 toggle @Test
1149    public void testInitialContent()
1150    {
1151  1 XWikiDocument doc = new XWikiDocument(new DocumentReference("somewiki", "somespace", "somepage"));
1152  1 assertEquals("", doc.getContent());
1153    }
1154   
 
1155  1 toggle @Test
1156    public void testAuthorAfterDocumentCopy() throws XWikiException
1157    {
1158  1 DocumentReference author = new DocumentReference("Wiki", "XWiki", "Albatross");
1159  1 this.document.setAuthorReference(author);
1160  1 XWikiDocument copy =
1161    this.document.copyDocument(this.document.getName() + " Copy", this.oldcore.getXWikiContext());
1162   
1163  1 assertEquals(author, copy.getAuthorReference());
1164    }
1165   
 
1166  1 toggle @Test
1167    public void testCreatorAfterDocumentCopy() throws XWikiException
1168    {
1169  1 DocumentReference creator = new DocumentReference("Wiki", "XWiki", "Condor");
1170  1 this.document.setCreatorReference(creator);
1171  1 XWikiDocument copy =
1172    this.document.copyDocument(this.document.getName() + " Copy", this.oldcore.getXWikiContext());
1173   
1174  1 assertEquals(creator, copy.getCreatorReference());
1175    }
1176   
 
1177  1 toggle @Test
1178    public void testCreationDateAfterDocumentCopy() throws Exception
1179    {
1180  1 Date sourceCreationDate = this.document.getCreationDate();
1181  1 Thread.sleep(1000);
1182  1 XWikiDocument copy =
1183    this.document.copyDocument(this.document.getName() + " Copy", this.oldcore.getXWikiContext());
1184   
1185  1 assertEquals(sourceCreationDate, copy.getCreationDate());
1186    }
1187   
 
1188  1 toggle @Test
1189    public void testObjectGuidsAfterDocumentCopy() throws Exception
1190    {
1191  1 assertTrue(this.document.getXObjects().size() > 0);
1192   
1193  1 List<String> originalGuids = new ArrayList<String>();
1194  1 for (Map.Entry<DocumentReference, List<BaseObject>> entry : this.document.getXObjects().entrySet()) {
1195  1 for (BaseObject baseObject : entry.getValue()) {
1196  2 originalGuids.add(baseObject.getGuid());
1197    }
1198    }
1199   
1200  1 XWikiDocument copy =
1201    this.document.copyDocument(this.document.getName() + " Copy", this.oldcore.getXWikiContext());
1202   
1203    // Verify that the cloned objects have different GUIDs
1204  1 for (Map.Entry<DocumentReference, List<BaseObject>> entry : copy.getXObjects().entrySet()) {
1205  1 for (BaseObject baseObject : entry.getValue()) {
1206  2 assertFalse("Non unique object GUID found!", originalGuids.contains(baseObject.getGuid()));
1207    }
1208    }
1209    }
1210   
 
1211  1 toggle @Test
1212    public void testRelativeObjectReferencesAfterDocumentCopy() throws Exception
1213    {
1214  1 XWikiDocument copy = this.document.copyDocument(new DocumentReference("copywiki", "copyspace", "copypage"),
1215    this.oldcore.getXWikiContext());
1216   
1217    // Verify that the XObject's XClass reference points to the target wiki and not the old wiki.
1218    // This tests the XObject cache.
1219  1 DocumentReference targetXClassReference = new DocumentReference("copywiki", DOCSPACE, DOCNAME);
1220  1 assertNotNull(copy.getXObject(targetXClassReference));
1221   
1222    // Also verify that actual XObject's reference (not from the cache).
1223  1 assertEquals(1, copy.getXObjects().size());
1224  1 BaseObject bobject = copy.getXObjects().get(copy.getXObjects().keySet().iterator().next()).get(0);
1225  1 assertEquals(new DocumentReference("copywiki", DOCSPACE, DOCNAME), bobject.getXClassReference());
1226    }
1227   
 
1228  1 toggle @Test
1229    public void testCustomMappingAfterDocumentCopy() throws Exception
1230    {
1231  1 this.document.getXClass().setCustomMapping("internal");
1232   
1233  1 XWikiDocument copy = this.document.copyDocument(new DocumentReference("copywiki", "copyspace", "copypage"),
1234    this.oldcore.getXWikiContext());
1235   
1236  1 assertEquals("", copy.getXClass().getCustomMapping());
1237    }
1238   
1239    /**
1240    * Normally the xobject vector has the Nth object on the Nth position, but in case an object gets misplaced, trying
1241    * to remove it should indeed remove that object, and no other.
1242    */
 
1243  1 toggle @Test
1244    public void testRemovingObjectWithWrongObjectVector()
1245    {
1246    // Setup: Create a document and two xobjects
1247  1 BaseObject o1 = new BaseObject();
1248  1 BaseObject o2 = new BaseObject();
1249  1 o1.setXClassReference(CLASS_REFERENCE);
1250  1 o2.setXClassReference(CLASS_REFERENCE);
1251   
1252    // Test: put the second xobject on the third position
1253    // addObject creates the object vector and configures the objects
1254    // o1 is added at position 0
1255    // o2 is added at position 1
1256  1 XWikiDocument doc = new XWikiDocument(DOCUMENT_REFERENCE);
1257  1 doc.addXObject(o1);
1258  1 doc.addXObject(o2);
1259   
1260    // Modify the o2 object's position to ensure it can still be found and removed by the removeObject method.
1261  1 assertEquals(1, o2.getNumber());
1262  1 o2.setNumber(0);
1263    // Set a field on o1 so that when comparing it with o2 they are different. This is needed so that the remove
1264    // will pick the right object to remove (since we've voluntarily set a wrong number of o2 it would pick o1
1265    // if they were equals).
1266  1 o1.addField("somefield", new StringProperty());
1267   
1268    // Call the tested method, removing o2 from position 2 which is set to null
1269  1 boolean result = doc.removeXObject(o2);
1270   
1271    // Check the correct behavior:
1272  1 assertTrue(result);
1273  1 List<BaseObject> objects = doc.getXObjects(CLASS_REFERENCE);
1274  1 assertTrue(objects.contains(o1));
1275  1 assertFalse(objects.contains(o2));
1276  1 assertNull(objects.get(1));
1277   
1278    // Second test: swap the two objects, so that the first object is in the position the second should have
1279    // Start over, re-adding the two objects
1280  1 doc = new XWikiDocument(DOCUMENT_REFERENCE);
1281  1 doc.addXObject(o1);
1282  1 doc.addXObject(o2);
1283    }
1284   
 
1285  1 toggle @Test
1286    public void testCopyDocument() throws XWikiException
1287    {
1288  1 XWikiDocument doc = new XWikiDocument();
1289  1 doc.setTitle("Some title");
1290  1 BaseObject o = new BaseObject();
1291  1 o.setXClassReference(CLASS_REFERENCE);
1292  1 doc.addXObject(o);
1293   
1294  1 XWikiDocument newDoc = doc.copyDocument("newdoc", this.oldcore.getXWikiContext());
1295  1 BaseObject newO = newDoc.getXObject(CLASS_REFERENCE);
1296   
1297  1 assertNotSame(o, newDoc.getXObject(CLASS_REFERENCE));
1298  1 assertFalse(newO.getGuid().equals(o.getGuid()));
1299    // Verify that the title is copied
1300  1 assertEquals("Some title", newDoc.getTitle());
1301    }
1302   
1303    /**
1304    * @see <a href="http://jira.xwiki.org/browse/XWIKI-6743">XWIKI-6743</a>
1305    * @see <a href="http://jira.xwiki.org/browse/XWIKI-12349">XWIKI-12349</a>
1306    */
 
1307  1 toggle @Test
1308    public void testCopyDocumentSetsTitleToNewDocNameIfPreviouslySetToDocName() throws XWikiException
1309    {
1310  1 copyDocumentAndAssertTitle(new DocumentReference("wiki1", "space1", "page1"), "page1",
1311    new DocumentReference("wiki2", "space2", "page2"), "page2");
1312   
1313  1 copyDocumentAndAssertTitle(new DocumentReference("wiki1", "space1", "WebHome"), "space1",
1314    new DocumentReference("wiki2", "space2", "page2"), "page2");
1315   
1316  1 copyDocumentAndAssertTitle(new DocumentReference("wiki1", "space1", "WebHome"), "space1",
1317    new DocumentReference("wiki2", "space2", "WebHome"), "space2");
1318    }
1319   
 
1320  3 toggle private void copyDocumentAndAssertTitle(DocumentReference oldReference, String oldTitle,
1321    DocumentReference newReference, String expectedNewTitle) throws XWikiException
1322    {
1323  3 XWikiDocument doc = new XWikiDocument(oldReference);
1324  3 doc.setTitle(oldTitle);
1325   
1326  3 XWikiDocument newDoc = doc.copyDocument(newReference, this.oldcore.getXWikiContext());
1327   
1328    // Verify that we get the expected title.
1329  3 assertEquals(expectedNewTitle, newDoc.getTitle());
1330    }
1331   
 
1332  1 toggle @Test
1333    public void testValidate() throws XWikiException, AccessDeniedException
1334    {
1335  1 this.document.setValidationScript("validationScript");
1336  1 this.baseClass.setValidationScript("validationScript");
1337   
1338  1 doReturn(new XWikiValidationInterface()
1339    {
 
1340  1 toggle @Override
1341    public boolean validateObject(BaseObject object, XWikiContext context)
1342    {
1343  1 return true;
1344    }
1345   
 
1346  1 toggle @Override
1347    public boolean validateDocument(XWikiDocument doc, XWikiContext context)
1348    {
1349  1 return true;
1350    }
1351    }).when(this.oldcore.getSpyXWiki()).parseGroovyFromPage("validationScript", this.oldcore.getXWikiContext());
1352   
1353    // With PR
1354   
1355  1 assertTrue(this.document.validate(this.oldcore.getXWikiContext()));
1356  1 assertTrue(this.baseClass.validateObject(this.baseObject, this.oldcore.getXWikiContext()));
1357   
1358    // Without PR
1359   
1360  1 doThrow(AccessDeniedException.class).when(this.oldcore.getMockContextualAuthorizationManager())
1361    .checkAccess(Right.PROGRAM, new DocumentReference("wiki", "space", "validationScript"));
1362   
1363  1 assertFalse(this.document.validate(this.oldcore.getXWikiContext()));
1364  1 assertFalse(this.baseClass.validateObject(this.baseObject, this.oldcore.getXWikiContext()));
1365    }
1366   
 
1367  1 toggle @Test
1368    public void tofromXMLDocument() throws XWikiException
1369    {
1370    // equals won't work on password fields because of http://jira.xwiki.org/browse/XWIKI-12561
1371  1 this.baseObject.removeField("passwd");
1372  1 this.baseObject2.removeField("passwd");
1373   
1374  1 Document document = this.document.toXMLDocument(this.oldcore.getXWikiContext());
1375   
1376  1 XWikiDocument newDocument = new XWikiDocument(this.document.getDocumentReference());
1377  1 newDocument.fromXML(document, false);
1378   
1379  1 assertEquals(this.document, newDocument);
1380    }
1381    }