001// Copyright 2006, 2007, 2008, 2010, 2011, 2012 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007// http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package org.apache.tapestry5.ioc.test;
016
017import org.apache.tapestry5.ioc.*;
018import org.apache.tapestry5.ioc.annotations.IntermediateType;
019import org.apache.tapestry5.ioc.def.*;
020import org.apache.tapestry5.ioc.services.*;
021import org.slf4j.Logger;
022
023import java.io.File;
024import java.lang.annotation.Annotation;
025import java.lang.reflect.Method;
026import java.net.URL;
027import java.util.Locale;
028
029import static java.lang.Thread.sleep;
030import static org.easymock.EasyMock.isA;
031
032/**
033 * Add factory and trainer methods for the public interfaces of Tapestry IOC.
034 *
035 * @deprecated In 5.4, with no replacement
036 */
037public class IOCTestCase extends TestBase
038{
039
040    /**
041     * Builds a Registry for the provided modules; caller should shutdown the Registry when done.
042     */
043    protected final Registry buildRegistry(Class... moduleClasses)
044    {
045        RegistryBuilder builder = new RegistryBuilder();
046
047        builder.add(moduleClasses);
048
049        return builder.build();
050    }
051
052    protected final Method findMethod(Class clazz, String methodName)
053    {
054        for (Method method : clazz.getMethods())
055        {
056            if (method.getName().equals(methodName))
057                return method;
058        }
059
060        throw new IllegalArgumentException(String.format("Class %s does not provide a method named '%s'.",
061                clazz.getName(), methodName));
062    }
063
064    protected final Method findMethod(Object subject, String methodName)
065    {
066        return findMethod(subject.getClass(), methodName);
067    }
068
069    protected final Method findMethod(String methodName)
070    {
071        return findMethod(this, methodName);
072    }
073
074    /**
075     * Combines a series of lines by forming a string with a line separator after each line.
076     */
077    protected final String join(String... lines)
078    {
079        StringBuilder result = new StringBuilder();
080
081        for (String line : lines)
082        {
083            result.append(line);
084            result.append('\n');
085        }
086
087        return result.toString();
088    }
089
090    protected final AnnotationProvider mockAnnotationProvider()
091    {
092        return newMock(AnnotationProvider.class);
093    }
094
095    @SuppressWarnings("unchecked")
096    protected final <T> Configuration<T> mockConfiguration()
097    {
098        return newMock(Configuration.class);
099    }
100
101    protected final ContributionDef mockContributionDef()
102    {
103        return newMock(ContributionDef.class);
104    }
105
106    protected final DecoratorDef mockDecoratorDef()
107    {
108        return newMock(DecoratorDef.class);
109    }
110
111    protected final DecoratorDef2 mockDecoratorDef2()
112    {
113        return newMock(DecoratorDef2.class);
114    }
115
116    protected final AdvisorDef mockAdvisorDef()
117    {
118        return newMock(AdvisorDef.class);
119    }
120
121    protected final AdvisorDef2 mockAdvisorDef2()
122    {
123        return newMock(AdvisorDef2.class);
124    }
125
126    protected final Location mockLocation()
127    {
128        return newMock(Location.class);
129    }
130
131    protected final Logger mockLogger()
132    {
133        return newMock(Logger.class);
134    }
135
136    protected final void stub_isDebugEnabled(Logger logger, boolean enabled)
137    {
138        expect(logger.isDebugEnabled()).andStubReturn(enabled);
139    }
140
141    @SuppressWarnings("unchecked")
142    protected final <K, V> MappedConfiguration<K, V> mockMappedConfiguration()
143    {
144        return newMock(MappedConfiguration.class);
145    }
146
147    protected final MessageFormatter mockMessageFormatter()
148    {
149        return newMock(MessageFormatter.class);
150    }
151
152    protected final Messages mockMessages()
153    {
154        return newMock(Messages.class);
155    }
156
157    protected final ModuleDef mockModuleDef()
158    {
159        return newMock(ModuleDef.class);
160    }
161
162    protected final ModuleDef2 mockModuleDef2()
163    {
164        return newMock(ModuleDef2.class);
165    }
166
167    protected final ObjectCreator mockObjectCreator()
168    {
169        return newMock(ObjectCreator.class);
170    }
171
172    protected final ObjectProvider mockObjectProvider()
173    {
174        return newMock(ObjectProvider.class);
175    }
176
177    @SuppressWarnings("unchecked")
178    protected final <T> OrderedConfiguration<T> mockOrderedConfiguration()
179    {
180        return newMock(OrderedConfiguration.class);
181    }
182
183    protected final Resource mockResource()
184    {
185        return newMock(Resource.class);
186    }
187
188    /**
189     * Frequently used as a placeholder for an arbitrary service (but its nice and simple).
190     */
191    protected final Runnable mockRunnable()
192    {
193        return newMock(Runnable.class);
194    }
195
196    protected final ServiceBuilderResources mockServiceBuilderResources()
197    {
198        return newMock(ServiceBuilderResources.class);
199    }
200
201    protected final ServiceDecorator mockServiceDecorator()
202    {
203        return newMock(ServiceDecorator.class);
204    }
205
206    protected final ServiceDef mockServiceDef()
207    {
208        return newMock(ServiceDef.class);
209    }
210
211    protected final ObjectLocator mockObjectLocator()
212    {
213        return newMock(ObjectLocator.class);
214    }
215
216    protected final ServiceResources mockServiceResources()
217    {
218        return newMock(ServiceResources.class);
219    }
220
221    protected final SymbolSource mockSymbolSource()
222    {
223        return newMock(SymbolSource.class);
224    }
225
226    protected final ThreadLocale mockThreadLocale()
227    {
228        return newMock(ThreadLocale.class);
229    }
230
231    protected final TypeCoercer mockTypeCoercer()
232    {
233        return newMock(TypeCoercer.class);
234    }
235
236    protected final void stub_contains(Messages messages, boolean contained)
237    {
238        expect(messages.contains(isA(String.class))).andStubReturn(contained);
239    }
240
241    protected <S, T> void train_coerce(TypeCoercer coercer, S input, Class<T> expectedType, T coercedValue)
242    {
243        expect(coercer.coerce(input, expectedType)).andReturn(coercedValue);
244    }
245
246    protected final void train_contains(Messages messages, String key, boolean result)
247    {
248        expect(messages.contains(key)).andReturn(result).atLeastOnce();
249    }
250
251    protected final void train_createInterceptor(ServiceDecorator decorator, Object coreObject, Object interceptor)
252    {
253        expect(decorator.createInterceptor(coreObject)).andReturn(interceptor);
254    }
255
256    protected final void train_createObject(ObjectCreator creator, Object service)
257    {
258        expect(creator.createObject()).andReturn(service);
259    }
260
261    protected final void train_expandSymbols(SymbolSource source, String input)
262    {
263        train_expandSymbols(source, input, input);
264    }
265
266    protected final void train_expandSymbols(SymbolSource source, String input, String expanded)
267    {
268        expect(source.expandSymbols(input)).andReturn(expanded);
269    }
270
271    protected final void train_forFile(Resource resource, String relativePath, Resource file)
272    {
273        expect(resource.forFile(relativePath)).andReturn(file);
274    }
275
276    protected final void train_forLocale(Resource base, Locale locale, Resource resource)
277    {
278        expect(base.forLocale(locale)).andReturn(resource);
279    }
280
281    /**
282     * Have to put the result before the varargs.
283     */
284    protected void train_format(MessageFormatter formatter, String result, Object... arguments)
285    {
286        expect(formatter.format(arguments)).andReturn(result);
287    }
288
289    protected final void train_get(Messages messages, String key, String message)
290    {
291        expect(messages.get(key)).andReturn(message).atLeastOnce();
292    }
293
294    protected final void train_getLocale(ThreadLocale threadLocale, Locale locale)
295    {
296        expect(threadLocale.getLocale()).andReturn(locale);
297    }
298
299    protected final void train_getLogger(LoggerSource source, String serviceId, Logger logger)
300    {
301        expect(source.getLogger(serviceId)).andReturn(logger).atLeastOnce();
302    }
303
304    protected final void train_getMessageFormatter(Messages messages, String key, MessageFormatter formatter)
305    {
306        expect(messages.getFormatter(key)).andReturn(formatter).atLeastOnce();
307    }
308
309    protected final void train_getPath(Resource r, String path)
310    {
311        expect(r.getPath()).andReturn(path).atLeastOnce();
312    }
313
314    protected final <T> void train_getService(ObjectLocator locator, Class<T> serviceInterface, T service)
315    {
316        expect(locator.getService(serviceInterface)).andReturn(service);
317    }
318
319    protected final <T> void train_getService(ObjectLocator locator, String serviceId, Class<T> serviceInterface,
320            T service)
321    {
322        expect(locator.getService(serviceId, serviceInterface)).andReturn(service);
323    }
324
325    protected final void train_getServiceId(ServiceDef def, String serviceId)
326    {
327        expect(def.getServiceId()).andReturn(serviceId).atLeastOnce();
328    }
329
330    protected final void train_getServiceId(ServiceResources resources, String serviceId)
331    {
332        expect(resources.getServiceId()).andReturn(serviceId).atLeastOnce();
333    }
334
335    protected final void train_getServiceInterface(ServiceDef def, Class serviceInterface)
336    {
337        expect(def.getServiceInterface()).andReturn(serviceInterface).atLeastOnce();
338    }
339
340    protected final void train_getServiceInterface(ServiceResources resources, Class serviceInterface)
341    {
342        expect(resources.getServiceInterface()).andReturn(serviceInterface).atLeastOnce();
343    }
344
345    protected final void train_getLogger(ServiceResources resources, Logger log)
346    {
347        expect(resources.getLogger()).andReturn(log).atLeastOnce();
348    }
349
350    protected final void train_isDebugEnabled(Logger log, boolean debugEnabled)
351    {
352        expect(log.isDebugEnabled()).andReturn(debugEnabled);
353    }
354
355    protected final void train_isTraceEnabled(Logger log, boolean traceEnabled)
356    {
357        expect(log.isTraceEnabled()).andReturn(traceEnabled);
358    }
359
360    protected final void train_matches(DecoratorDef decoratorDef, ServiceDef serviceDef, boolean matches)
361    {
362        expect(decoratorDef.matches(serviceDef)).andReturn(matches);
363    }
364
365    protected final void train_matches(AdvisorDef advisorDef, ServiceDef serviceDef, boolean matches)
366    {
367        expect(advisorDef.matches(serviceDef)).andReturn(matches);
368    }
369
370    protected final <T> void train_provide(ObjectProvider provider, Class<T> objectType,
371            AnnotationProvider annotationProvider, ObjectLocator locator, T object)
372    {
373        expect(provider.provide(objectType, annotationProvider, locator)).andReturn(object);
374    }
375
376    protected final void train_toURL(Resource resource, URL url)
377    {
378        expect(resource.toURL()).andReturn(url).atLeastOnce();
379    }
380
381    protected final <T extends Annotation> void train_getAnnotation(AnnotationProvider annotationProvider,
382            Class<T> annotationClass, T annotation)
383    {
384        expect(annotationProvider.getAnnotation(annotationClass)).andReturn(annotation);
385    }
386
387    protected final MasterObjectProvider mockMasterObjectProvider()
388    {
389        return newMock(MasterObjectProvider.class);
390    }
391
392    protected final void train_value(IntermediateType it, Class value)
393    {
394        expect(it.value()).andReturn(value);
395    }
396
397    protected final IntermediateType newIntermediateType()
398    {
399        return newMock(IntermediateType.class);
400    }
401
402    protected final PropertyAdapter mockPropertyAdapter()
403    {
404        return newMock(PropertyAdapter.class);
405    }
406
407    protected final ClassPropertyAdapter mockClassPropertyAdapter()
408    {
409        return newMock(ClassPropertyAdapter.class);
410    }
411
412    protected final PropertyAccess mockPropertyAccess()
413    {
414        return newMock(PropertyAccess.class);
415    }
416
417    protected final <T> void train_autobuild(ObjectLocator locator, Class<T> beanClass, T instance)
418    {
419        expect(locator.autobuild(beanClass)).andReturn(instance);
420    }
421
422    protected final PerthreadManager mockPerthreadManager()
423    {
424        return newMock(PerthreadManager.class);
425    }
426
427    protected final ServiceResources mockServiceResources(OperationTracker tracker)
428    {
429        ServiceResources resources = mockServiceResources();
430
431        train_getTracker(resources, tracker);
432
433        return resources;
434    }
435
436    protected final void train_getTracker(ServiceResources resources, OperationTracker tracker)
437    {
438        expect(resources.getTracker()).andReturn(tracker).atLeastOnce();
439    }
440
441    protected final ServiceBuilderResources mockServiceBuilderResources(OperationTracker tracker)
442    {
443        ServiceBuilderResources resources = mockServiceBuilderResources();
444
445        train_getTracker(resources, tracker);
446
447        return resources;
448    }
449
450    protected final void train_valueForSymbol(SymbolSource symbolSource, String symbolName, String value)
451    {
452        expect(symbolSource.valueForSymbol(symbolName)).andReturn(value).atLeastOnce();
453    }
454
455    /**
456     * Touches the file, changing the last modified time to the current time.
457     * Does not return until the last modified time for the file actually changes (how long that takes
458     * is JDK, OS and file system dependent).
459     */
460    protected final void touch(File f) throws Exception
461    {
462        long startModified = f.lastModified();
463
464        int index = 0;
465
466        while (true)
467        {
468            f.setLastModified(System.currentTimeMillis());
469
470            long newModified = f.lastModified();
471
472            if (newModified != startModified)
473                return;
474
475            // Sleep an ever increasing amount, to ensure that the filesystem
476            // catches the change to the file. The Ubuntu CI Server appears
477            // to need longer waits.
478
479            sleep(50 * (2 ^ index++));
480        }
481    }
482}