1. Project Clover database Sat Feb 2 2019 06:45:20 CET
  2. Package com.xpn.xwiki.doc

File XWikiDocumentMockitoTest.java

 

Code metrics

4
680
67
1
1,581
1,082
70
0.1
10.15
67
1.04

Classes

Class Line # Actions
XWikiDocumentMockitoTest 91 680 0% 70 2
0.9973368699.7%
 

Contributing tests

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