use of org.xwiki.model.reference.WikiReference in project xwiki-platform by xwiki.
the class ScopeNotificationFilterTest method testWithTopLevelInclusiveFilters.
@Test
public void testWithTopLevelInclusiveFilters() throws Exception {
// Preferences:
//
// α: "update" event type enabled for format ALERT
//
// γ: Inclusive filter on "wikiA:SpaceB"
// ζ: Inclusive filter on "wikiA:SpaceM.DocumentN"
// Mock α
NotificationPreference preference = mock(NotificationPreference.class);
when(preference.getFormat()).thenReturn(NotificationFormat.ALERT);
Map<NotificationPreferenceProperty, Object> properties = new HashMap<>();
properties.put(NotificationPreferenceProperty.EVENT_TYPE, "update");
when(preference.getProperties()).thenReturn(properties);
// Mock γ
WikiReference wikiReference = new WikiReference("wikiA");
SpaceReference spaceReferenceB = new SpaceReference("SpaceB", new WikiReference(wikiReference));
NotificationFilterPreference prefγ = mockNotificationFilterPreference("wikiA:SpaceB", spaceReferenceB, NotificationFilterType.INCLUSIVE, null);
// Mock ζ
DocumentReference documentReference = new DocumentReference("wikiA", "SpaceM", "DocumentN");
NotificationFilterPreference prefζ = mockNotificationFilterPreference("wikiA:SpaceM.DocumentN", documentReference, NotificationFilterType.INCLUSIVE, null);
when(notificationFilterManager.getFilterPreferences(any(DocumentReference.class))).thenReturn(Sets.newSet(prefγ, prefζ));
DocumentReference user = new DocumentReference("xwiki", "XWiki", "User");
// Test 1
String result = mocker.getComponentUnderTest().filterExpression(user, preference).toString();
assertEquals("((WIKI = \"wikiA\" AND SPACE STARTS WITH \"wikiA:SpaceB\") " + "OR (WIKI = \"wikiA\" AND PAGE = \"wikiA:SpaceM.DocumentN\"))", result);
// Test with wikiA:SpaceE (filtered by γ & ζ)
Event event1 = mock(Event.class);
when(event1.getSpace()).thenReturn(new SpaceReference("SpaceE", wikiReference));
assertEquals(NotificationFilter.FilterPolicy.FILTER, mocker.getComponentUnderTest().filterEvent(event1, user, NotificationFormat.ALERT));
// Test with wikiA:SpaceB.DocumentJ (kept by γ)
Event event2 = mock(Event.class);
when(event2.getDocument()).thenReturn(new DocumentReference("wikiA", "SpaceB", "DocumentJ"));
assertEquals(NotificationFilter.FilterPolicy.NO_EFFECT, mocker.getComponentUnderTest().filterEvent(event2, user, NotificationFormat.ALERT));
// Test with wikiB:SpaceK.DocumentL (filtered by γ & ζ)
Event event3 = mock(Event.class);
when(event3.getDocument()).thenReturn(new DocumentReference("wikiB", "SpaceK", "DocumentL"));
assertEquals(NotificationFilter.FilterPolicy.FILTER, mocker.getComponentUnderTest().filterEvent(event3, user, NotificationFormat.ALERT));
// Test with wikiA:SpaceM.DocumentN (kept by ζ)
Event event4 = mock(Event.class);
when(event4.getDocument()).thenReturn(new DocumentReference("wikiA", "SpaceM", "DocumentN"));
assertEquals(NotificationFilter.FilterPolicy.NO_EFFECT, mocker.getComponentUnderTest().filterEvent(event4, user, NotificationFormat.ALERT));
}
use of org.xwiki.model.reference.WikiReference in project xwiki-platform by xwiki.
the class NotificationUserIterator method getNext.
private void getNext() {
DocumentReference classReference = new DocumentReference(wikiDescriptorManager.getCurrentWikiId(), Arrays.asList("XWiki", "Notifications", "Code"), "NotificationEmailPreferenceClass");
try {
nextUser = null;
while (!hasNext()) {
if (users.isEmpty()) {
doQuery();
if (users.isEmpty()) {
return;
}
}
while (!hasNext() && !users.isEmpty()) {
DocumentReference user = resolver.resolve(users.poll(), new WikiReference(wikiDescriptorManager.getCurrentWikiId()));
Object userInterval = documentAccessBridge.getProperty(user, classReference, "interval");
if (isDefaultInterval(userInterval) || isSameInterval(userInterval)) {
nextUser = user;
}
}
}
} catch (Exception e) {
logger.error("Fail to get next user.", e);
}
}
use of org.xwiki.model.reference.WikiReference in project xwiki-platform by xwiki.
the class DocumentInstanceOutputFilterStream method maybeSaveDocument.
private void maybeSaveDocument() throws FilterException {
XWikiDocument inputDocument = this.documentListener.getEntity();
this.documentListener.setEntity(null);
if (this.currentRevisionParameters == null) {
return;
}
XWikiContext xcontext = this.xcontextProvider.get();
try {
XWikiDocument document = xcontext.getWiki().getDocument(inputDocument.getDocumentReferenceWithLocale(), xcontext);
if (!this.documentDeleted && !document.isNew() && this.properties.isPreviousDeleted()) {
XWikiDocument originalDocument = document;
// Save current context wiki
WikiReference currentWiki = xcontext.getWikiReference();
try {
// Make sure the store is executed in the right context
xcontext.setWikiReference(document.getDocumentReference().getWikiReference());
// Put previous version in recycle bin
if (xcontext.getWiki().hasRecycleBin(xcontext)) {
xcontext.getWiki().getRecycleBinStore().saveToRecycleBin(document, xcontext.getUser(), new Date(), xcontext, true);
}
// Make sure to not generate DocumentDeletedEvent since from listener point of view it's not
xcontext.getWiki().getStore().deleteXWikiDoc(document, xcontext);
this.documentDeleted = true;
} finally {
// Restore current context wiki
xcontext.setWikiReference(currentWiki);
}
document = xcontext.getWiki().getDocument(inputDocument.getDocumentReferenceWithLocale(), xcontext);
// Remember deleted document as the actual previous version of the document (to simulate an update
// instead of a creation)
document.setOriginalDocument(originalDocument);
} else {
// Make sure to remember that the document should not be deleted anymore
this.documentDeleted = true;
}
// Remember if it's a creation or an update
boolean isnew = document.isNew();
// Safer to clone for thread safety and in case the save fail
document = document.clone();
document.loadAttachmentsContentSafe(xcontext);
document.apply(inputDocument);
// Get the version from the input document
document.setMinorEdit(inputDocument.isMinorEdit());
if (!this.properties.isAuthorPreserved()) {
if (this.properties.isAuthorSet()) {
setAuthorReference(document, this.properties.getAuthor());
} else {
setAuthorReference(document, xcontext.getUserReference());
}
document.setContentAuthorReference(document.getAuthorReference());
if (document.isNew()) {
document.setCreatorReference(document.getAuthorReference());
}
} else {
setAuthors(document, inputDocument);
}
if (this.properties.isVersionPreserved()) {
// Make sure to use metadata coming from the input document
document.setVersion(inputDocument.getVersion());
document.setDate(inputDocument.getDate());
document.setContentUpdateDate(inputDocument.getContentUpdateDate());
for (XWikiAttachment attachment : document.getAttachmentList()) {
attachment.setVersion(inputDocument.getAttachment(attachment.getFilename()).getVersion());
}
if (document.isNew()) {
document.setCreationDate(inputDocument.getCreationDate());
document.setDocumentArchive(inputDocument.getDocumentArchive());
}
// Make sure the document won't be modified by the store
document.setMetaDataDirty(false);
document.setContentDirty(false);
xcontext.getWiki().saveDocument(document, inputDocument.getComment(), inputDocument.isMinorEdit(), xcontext);
} else {
// Forget the input history to let the store do its standard job
document.setDocumentArchive((XWikiDocumentArchive) null);
xcontext.getWiki().saveDocument(document, this.properties.getSaveComment(), xcontext);
}
if (this.properties.isVerbose()) {
if (isnew) {
this.logger.info(LOG_DOCUMENT_CREATED, "Created document [{}]", document.getDocumentReferenceWithLocale());
} else {
this.logger.info(LOG_DOCUMENT_UPDATED, "Updated document [{}]", document.getDocumentReferenceWithLocale());
}
}
} catch (Exception e) {
this.logger.error(LOG_DOCUMENT_FAILSAVE, "Failed to save document [{}]", inputDocument.getDocumentReferenceWithLocale(), e);
if (this.properties.isStoppedWhenSaveFail()) {
throw new FilterException("Failed to save document", e);
}
}
}
use of org.xwiki.model.reference.WikiReference in project xwiki-platform by xwiki.
the class MockitoOldcore method before.
public void before(Class<?> testClass) throws Exception {
// Statically store the component manager in {@link Utils} to be able to access it without
// the context.
Utils.setComponentManager(getMocker());
this.context = new XWikiContext();
getXWikiContext().setWikiId("xwiki");
getXWikiContext().setMainXWiki("xwiki");
this.spyXWiki = spy(new XWiki());
getXWikiContext().setWiki(this.spyXWiki);
this.mockHibernateStore = mock(XWikiHibernateStore.class);
this.mockVersioningStore = mock(XWikiVersioningStoreInterface.class);
this.mockRightService = mock(XWikiRightService.class);
this.mockGroupService = mock(XWikiGroupService.class);
doReturn(this.mockHibernateStore).when(this.spyXWiki).getStore();
doReturn(this.mockHibernateStore).when(this.spyXWiki).getHibernateStore();
doReturn(this.mockVersioningStore).when(this.spyXWiki).getVersioningStore();
doReturn(this.mockRightService).when(this.spyXWiki).getRightService();
doReturn(this.mockGroupService).when(this.spyXWiki).getGroupService(getXWikiContext());
// We need to initialize the Component Manager so that the components can be looked up
getXWikiContext().put(ComponentManager.class.getName(), getMocker());
if (testClass.getAnnotation(AllComponents.class) != null) {
// If @AllComponents is enabled force mocking AuthorizationManager and ContextualAuthorizationManager if not
// already mocked
this.mockAuthorizationManager = getMocker().registerMockComponent(AuthorizationManager.class, false);
this.mockContextualAuthorizationManager = getMocker().registerMockComponent(ContextualAuthorizationManager.class, false);
} else {
// Make sure an AuthorizationManager and a ContextualAuthorizationManager is available
if (!getMocker().hasComponent(AuthorizationManager.class)) {
this.mockAuthorizationManager = getMocker().registerMockComponent(AuthorizationManager.class);
}
if (!getMocker().hasComponent(ContextualAuthorizationManager.class)) {
this.mockContextualAuthorizationManager = getMocker().registerMockComponent(ContextualAuthorizationManager.class);
}
}
// Make sure a default ConfigurationSource is available
if (!getMocker().hasComponent(ConfigurationSource.class)) {
this.configurationSource = getMocker().registerMemoryConfigurationSource();
}
// Make sure a "xwikicfg" ConfigurationSource is available
if (!getMocker().hasComponent(ConfigurationSource.class, XWikiCfgConfigurationSource.ROLEHINT)) {
this.xwikicfgConfigurationSource = new MockConfigurationSource();
getMocker().registerComponent(MockConfigurationSource.getDescriptor(XWikiCfgConfigurationSource.ROLEHINT), this.xwikicfgConfigurationSource);
}
// Make sure a "wiki" ConfigurationSource is available
if (!getMocker().hasComponent(ConfigurationSource.class, "wiki")) {
this.wikiConfigurationSource = new MockConfigurationSource();
getMocker().registerComponent(MockConfigurationSource.getDescriptor("wiki"), this.wikiConfigurationSource);
}
// Make sure a "space" ConfigurationSource is available
if (!getMocker().hasComponent(ConfigurationSource.class, "space")) {
this.spaceConfigurationSource = new MockConfigurationSource();
getMocker().registerComponent(MockConfigurationSource.getDescriptor("space"), this.spaceConfigurationSource);
}
// correctly with a Servlet Context.
if (getMocker().hasComponent(Environment.class) && getMocker().getInstance(Environment.class) instanceof ServletEnvironment) {
ServletEnvironment environment = getMocker().getInstance(Environment.class);
ServletContext servletContextMock = mock(ServletContext.class);
environment.setServletContext(servletContextMock);
when(servletContextMock.getAttribute("javax.servlet.context.tempdir")).thenReturn(new File(System.getProperty("java.io.tmpdir")));
File testDirectory = new File("target/test-" + new Date().getTime());
this.temporaryDirectory = new File(testDirectory, "temporary-dir");
this.permanentDirectory = new File(testDirectory, "permanent-dir");
environment.setTemporaryDirectory(this.temporaryDirectory);
environment.setPermanentDirectory(this.permanentDirectory);
}
// Initialize the Execution Context
if (this.componentManager.hasComponent(ExecutionContextManager.class)) {
ExecutionContextManager ecm = this.componentManager.getInstance(ExecutionContextManager.class);
ExecutionContext ec = new ExecutionContext();
ecm.initialize(ec);
}
// Bridge with old XWiki Context, required for old code.
Execution execution;
if (this.componentManager.hasComponent(Execution.class)) {
execution = this.componentManager.getInstance(Execution.class);
} else {
execution = this.componentManager.registerMockComponent(Execution.class);
}
ExecutionContext econtext;
if (MockUtil.isMock(execution)) {
econtext = new ExecutionContext();
when(execution.getContext()).thenReturn(econtext);
} else {
econtext = execution.getContext();
}
// Set a few standard things in the ExecutionContext
econtext.setProperty(XWikiContext.EXECUTIONCONTEXT_KEY, this.context);
this.scriptContext = (ScriptContext) econtext.getProperty(ScriptExecutionContextInitializer.SCRIPT_CONTEXT_ID);
if (this.scriptContext == null) {
this.scriptContext = new SimpleScriptContext();
econtext.setProperty(ScriptExecutionContextInitializer.SCRIPT_CONTEXT_ID, this.scriptContext);
}
if (!this.componentManager.hasComponent(ScriptContextManager.class)) {
ScriptContextManager scriptContextManager = this.componentManager.registerMockComponent(ScriptContextManager.class);
when(scriptContextManager.getCurrentScriptContext()).thenReturn(this.scriptContext);
when(scriptContextManager.getScriptContext()).thenReturn(this.scriptContext);
}
// Initialize XWikiContext provider
if (!this.componentManager.hasComponent(XWikiContext.TYPE_PROVIDER)) {
Provider<XWikiContext> xcontextProvider = this.componentManager.registerMockComponent(XWikiContext.TYPE_PROVIDER);
when(xcontextProvider.get()).thenReturn(this.context);
} else {
Provider<XWikiContext> xcontextProvider = this.componentManager.getInstance(XWikiContext.TYPE_PROVIDER);
if (MockUtil.isMock(xcontextProvider)) {
when(xcontextProvider.get()).thenReturn(this.context);
}
}
// Initialize readonly XWikiContext provider
if (!this.componentManager.hasComponent(XWikiContext.TYPE_PROVIDER, "readonly")) {
Provider<XWikiContext> xcontextProvider = this.componentManager.registerMockComponent(XWikiContext.TYPE_PROVIDER, "readonly");
when(xcontextProvider.get()).thenReturn(this.context);
} else {
Provider<XWikiContext> xcontextProvider = this.componentManager.getInstance(XWikiContext.TYPE_PROVIDER);
if (MockUtil.isMock(xcontextProvider)) {
when(xcontextProvider.get()).thenReturn(this.context);
}
}
// Initialize stub context provider
if (this.componentManager.hasComponent(XWikiStubContextProvider.class)) {
XWikiStubContextProvider stubContextProvider = this.componentManager.getInstance(XWikiStubContextProvider.class);
if (!MockUtil.isMock(stubContextProvider)) {
stubContextProvider.initialize(this.context);
}
}
// Make sure to have a mocked CoreConfiguration (even if one already exist)
if (!this.componentManager.hasComponent(CoreConfiguration.class)) {
CoreConfiguration coreConfigurationMock = this.componentManager.registerMockComponent(CoreConfiguration.class);
when(coreConfigurationMock.getDefaultDocumentSyntax()).thenReturn(Syntax.XWIKI_2_1);
} else {
CoreConfiguration coreConfiguration = this.componentManager.registerMockComponent(CoreConfiguration.class, false);
if (MockUtil.isMock(coreConfiguration)) {
when(coreConfiguration.getDefaultDocumentSyntax()).thenReturn(Syntax.XWIKI_2_1);
}
}
// Set a context ComponentManager if none exist
if (!this.componentManager.hasComponent(ComponentManager.class, "context")) {
DefaultComponentDescriptor<ComponentManager> componentManagerDescriptor = new DefaultComponentDescriptor<>();
componentManagerDescriptor.setRoleHint("context");
componentManagerDescriptor.setRoleType(ComponentManager.class);
this.componentManager.registerComponent(componentManagerDescriptor, this.componentManager);
}
// XWiki
doAnswer(new Answer<XWikiDocument>() {
@Override
public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
XWikiDocument doc = invocation.getArgument(0);
String revision = invocation.getArgument(1);
if (StringUtils.equals(revision, doc.getVersion())) {
return doc;
}
// TODO: implement version store mocking
return new XWikiDocument(doc.getDocumentReference());
}
}).when(getSpyXWiki()).getDocument(anyXWikiDocument(), any(), anyXWikiContext());
doAnswer(new Answer<XWikiDocument>() {
@Override
public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
DocumentReference target = invocation.getArgument(0);
if (target.getLocale() == null) {
target = new DocumentReference(target, Locale.ROOT);
}
XWikiDocument document = documents.get(target);
if (document == null) {
document = new XWikiDocument(target, target.getLocale());
document.setSyntax(Syntax.PLAIN_1_0);
document.setOriginalDocument(document.clone());
}
return document;
}
}).when(getSpyXWiki()).getDocument(any(DocumentReference.class), anyXWikiContext());
doAnswer(new Answer<XWikiDocument>() {
@Override
public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
XWikiDocument target = invocation.getArgument(0);
return getSpyXWiki().getDocument(target.getDocumentReferenceWithLocale(), invocation.getArgument(1));
}
}).when(getSpyXWiki()).getDocument(anyXWikiDocument(), any(XWikiContext.class));
doAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
DocumentReference target = (DocumentReference) invocation.getArguments()[0];
if (target.getLocale() == null) {
target = new DocumentReference(target, Locale.ROOT);
}
return documents.containsKey(target);
}
}).when(getSpyXWiki()).exists(any(DocumentReference.class), anyXWikiContext());
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
XWikiDocument document = invocation.getArgument(0);
String comment = invocation.getArgument(1);
boolean minorEdit = invocation.getArgument(2);
boolean isNew = document.isNew();
document.setComment(StringUtils.defaultString(comment));
document.setMinorEdit(minorEdit);
if (document.isContentDirty() || document.isMetaDataDirty()) {
document.setDate(new Date());
if (document.isContentDirty()) {
document.setContentUpdateDate(new Date());
document.setContentAuthorReference(document.getAuthorReference());
}
document.incrementVersion();
document.setContentDirty(false);
document.setMetaDataDirty(false);
}
document.setNew(false);
document.setStore(getMockStore());
XWikiDocument previousDocument = documents.get(document.getDocumentReferenceWithLocale());
if (previousDocument != null && previousDocument != document) {
for (XWikiAttachment attachment : document.getAttachmentList()) {
if (!attachment.isContentDirty()) {
attachment.setAttachment_content(previousDocument.getAttachment(attachment.getFilename()).getAttachment_content());
}
}
}
XWikiDocument originalDocument = document.getOriginalDocument();
if (originalDocument == null) {
originalDocument = spyXWiki.getDocument(document.getDocumentReferenceWithLocale(), context);
document.setOriginalDocument(originalDocument);
}
XWikiDocument savedDocument = document.clone();
documents.put(document.getDocumentReferenceWithLocale(), savedDocument);
if (isNew) {
if (notifyDocumentCreatedEvent) {
getObservationManager().notify(new DocumentCreatedEvent(document.getDocumentReference()), document, getXWikiContext());
}
} else {
if (notifyDocumentUpdatedEvent) {
getObservationManager().notify(new DocumentUpdatedEvent(document.getDocumentReference()), document, getXWikiContext());
}
}
// Set the document as it's original document
savedDocument.setOriginalDocument(savedDocument.clone());
return null;
}
}).when(getSpyXWiki()).saveDocument(anyXWikiDocument(), any(String.class), anyBoolean(), anyXWikiContext());
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
XWikiDocument document = invocation.getArgument(0);
documents.remove(document.getDocumentReferenceWithLocale());
if (notifyDocumentDeletedEvent) {
getObservationManager().notify(new DocumentDeletedEvent(document.getDocumentReference()), document, getXWikiContext());
}
return null;
}
}).when(getSpyXWiki()).deleteDocument(anyXWikiDocument(), any(Boolean.class), anyXWikiContext());
doAnswer(new Answer<BaseClass>() {
@Override
public BaseClass answer(InvocationOnMock invocation) throws Throwable {
return getSpyXWiki().getDocument((DocumentReference) invocation.getArguments()[0], invocation.getArgument(1)).getXClass();
}
}).when(getSpyXWiki()).getXClass(any(DocumentReference.class), anyXWikiContext());
doAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return getXWikiContext().getLanguage();
}
}).when(getSpyXWiki()).getLanguagePreference(anyXWikiContext());
getXWikiContext().setLocale(Locale.ENGLISH);
// XWikiStoreInterface
when(getMockStore().getTranslationList(anyXWikiDocument(), anyXWikiContext())).then(new Answer<List<String>>() {
@Override
public List<String> answer(InvocationOnMock invocation) throws Throwable {
XWikiDocument document = invocation.getArgument(0);
List<String> translations = new ArrayList<String>();
for (XWikiDocument storedDocument : documents.values()) {
Locale storedLocale = storedDocument.getLocale();
if (!storedLocale.equals(Locale.ROOT) && storedDocument.getDocumentReference().equals(document.getDocumentReference())) {
translations.add(storedLocale.toString());
}
}
return translations;
}
});
when(getMockStore().loadXWikiDoc(anyXWikiDocument(), anyXWikiContext())).then(new Answer<XWikiDocument>() {
@Override
public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
// The store is based on the contex for the wiki
DocumentReference reference = invocation.<XWikiDocument>getArgument(0).getDocumentReference();
XWikiContext xcontext = invocation.getArgument(1);
if (!xcontext.getWikiReference().equals(reference.getWikiReference())) {
reference = reference.setWikiReference(xcontext.getWikiReference());
}
return getSpyXWiki().getDocument(reference, xcontext);
}
});
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
// The store is based on the contex for the wiki
DocumentReference reference = invocation.<XWikiDocument>getArgument(0).getDocumentReferenceWithLocale();
XWikiContext xcontext = invocation.getArgument(1);
if (!xcontext.getWikiReference().equals(reference.getWikiReference())) {
reference = reference.setWikiReference(xcontext.getWikiReference());
}
documents.remove(reference);
return null;
}
}).when(getMockStore()).deleteXWikiDoc(anyXWikiDocument(), anyXWikiContext());
// Users
doAnswer(new Answer<BaseClass>() {
@Override
public BaseClass answer(InvocationOnMock invocation) throws Throwable {
XWikiContext xcontext = invocation.getArgument(0);
XWikiDocument userDocument = getSpyXWiki().getDocument(new DocumentReference(USER_CLASS, new WikiReference(xcontext.getWikiId())), xcontext);
final BaseClass userClass = userDocument.getXClass();
if (userDocument.isNew()) {
userClass.addTextField("first_name", "First Name", 30);
userClass.addTextField("last_name", "Last Name", 30);
userClass.addEmailField("email", "e-Mail", 30);
userClass.addPasswordField("password", "Password", 10);
userClass.addBooleanField("active", "Active", "active");
userClass.addTextAreaField("comment", "Comment", 40, 5);
userClass.addTextField("avatar", "Avatar", 30);
userClass.addTextField("phone", "Phone", 30);
userClass.addTextAreaField("address", "Address", 40, 3);
getSpyXWiki().saveDocument(userDocument, xcontext);
}
return userClass;
}
}).when(getSpyXWiki()).getUserClass(anyXWikiContext());
doAnswer(new Answer<BaseClass>() {
@Override
public BaseClass answer(InvocationOnMock invocation) throws Throwable {
XWikiContext xcontext = invocation.getArgument(0);
XWikiDocument groupDocument = getSpyXWiki().getDocument(new DocumentReference(GROUP_CLASS, new WikiReference(xcontext.getWikiId())), xcontext);
final BaseClass groupClass = groupDocument.getXClass();
if (groupDocument.isNew()) {
groupClass.addTextField("member", "Member", 30);
getSpyXWiki().saveDocument(groupDocument, xcontext);
}
return groupClass;
}
}).when(getSpyXWiki()).getGroupClass(anyXWikiContext());
// This allows, for example, using @ComponentList to use the real Query Manager, in integration tests.
if (!this.componentManager.hasComponent(QueryManager.class)) {
mockQueryManager();
}
when(getMockStore().getQueryManager()).then(new Answer<QueryManager>() {
@Override
public QueryManager answer(InvocationOnMock invocation) throws Throwable {
return getQueryManager();
}
});
// This allows, for example, using @ComponentList to use the real WikiDescriptorManager, in integration tests.
if (!this.componentManager.hasComponent(WikiDescriptorManager.class)) {
this.wikiDescriptorManager = getMocker().registerMockComponent(WikiDescriptorManager.class);
when(this.wikiDescriptorManager.getMainWikiId()).then(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return getXWikiContext().getMainXWiki();
}
});
when(this.wikiDescriptorManager.getCurrentWikiId()).then(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return getXWikiContext().getWikiId();
}
});
}
}
use of org.xwiki.model.reference.WikiReference in project xwiki-platform by xwiki.
the class XWikiDocumentMockitoTest method testReadFromTemplate.
/**
* Unit test for {@link XWikiDocument#readFromTemplate(DocumentReference, XWikiContext)}.
*/
@Test
public void testReadFromTemplate() throws Exception {
SpaceReference spaceReference = new SpaceReference("Space", new WikiReference("wiki"));
XWikiDocument template = new XWikiDocument(new DocumentReference("Template", spaceReference));
template.setParentReference(new EntityReference("Parent", EntityType.DOCUMENT, spaceReference));
template.setTitle("Enter title here");
template.setSyntax(Syntax.XWIKI_2_0);
template.setContent("Enter content here");
XWikiAttachment aliceAttachment = new XWikiAttachment(template, "alice.png");
aliceAttachment.setContent(new ByteArrayInputStream("alice content".getBytes()));
template.addAttachment(aliceAttachment);
XWikiAttachment bobAttachment = new XWikiAttachment(template, "bob.png");
bobAttachment.setContent(new ByteArrayInputStream("bob content".getBytes()));
template.addAttachment(bobAttachment);
XWikiContext xcontext = this.oldcore.getXWikiContext();
this.oldcore.getSpyXWiki().saveDocument(template, xcontext);
XWikiDocument target = new XWikiDocument(new DocumentReference("Page", spaceReference));
XWikiAttachment aliceModifiedAttachment = new XWikiAttachment(target, "alice.png");
aliceModifiedAttachment.setContent(new ByteArrayInputStream("alice modified content".getBytes()));
target.addAttachment(aliceModifiedAttachment);
XWikiAttachment carolAttachment = new XWikiAttachment(target, "carol.png");
carolAttachment.setContent(new ByteArrayInputStream("carol content".getBytes()));
target.addAttachment(carolAttachment);
target.readFromTemplate(template.getDocumentReference(), xcontext);
Assert.assertEquals(template.getDocumentReference(), target.getTemplateDocumentReference());
Assert.assertEquals(template.getParentReference(), target.getParentReference());
Assert.assertEquals(template.getTitle(), target.getTitle());
Assert.assertEquals(template.getSyntax(), target.getSyntax());
Assert.assertEquals(template.getContent(), target.getContent());
assertEquals(3, target.getAttachmentList().size());
assertTrue(IOUtils.contentEquals(target.getAttachment("alice.png").getContentInputStream(xcontext), aliceModifiedAttachment.getContentInputStream(xcontext)));
assertTrue(IOUtils.contentEquals(target.getAttachment("bob.png").getContentInputStream(xcontext), bobAttachment.getContentInputStream(xcontext)));
assertTrue(IOUtils.contentEquals(target.getAttachment("carol.png").getContentInputStream(xcontext), carolAttachment.getContentInputStream(xcontext)));
}
Aggregations