summaryrefslogtreecommitdiffstats
path: root/aspectj-attic/testing-src/AntTaskTester.java
blob: 1f032e74f87435d8eefd4eda67e3fa9b70ada951 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/* *******************************************************************
 * Copyright (c) 1999-2001 Xerox Corporation, 
 *               2002 Palo Alto Research Center, Incorporated (PARC).
 * All rights reserved. 
 * This program and the accompanying materials are made available 
 * under the terms of the Common Public License v1.0 
 * which accompanies this distribution and is available at 
 * http://www.eclipse.org/legal/cpl-v10.html 
 *  
 * Contributors: 
 *     Xerox/PARC     initial implementation 
 * ******************************************************************/


import org.apache.tools.ant.*;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;

/**
 * Provides utility methods to test ant tasks.
 */
public abstract class AntTaskTester implements BuildListener {

    public abstract String getAntFile();

    protected PrintStream out = System.out;
    protected PrintStream err = System.err;
    protected void info(Object msg) {
        out.println(" [" + msg + "]");
    }

    protected Project project;
    protected String taskname = "unset";

    protected List errors = new Vector();
    protected void throwable(Throwable t) {
        error(taskname, t);
        t.printStackTrace();
    }
    protected void error(String task, Object msg) {
        error("[" + task + "]: " + msg);
    }
    protected void error(Object msg) {
        err.println("Error: " + msg);
        errors.add(msg);
    }

    protected List wants = new Vector();
    protected void want(Object object) {
        wants.add(object);
    }
    protected List haves = new Vector();
    protected void have(Object object) {
        haves.add(object);
    }
    protected List donts = new Vector();
    protected void dont(Object object) {
        donts.add(object);
    }

    protected void clear() {
        wants = new Vector();
        haves = new Vector();
        donts = new Vector();
    }

    protected final boolean verbose = verbose();
    protected boolean verbose() { return false; }
    protected void log(String msg) {
        if (verbose) out.println("[ " + msg + " ]");
    }

    public void printSummary() {
        Iterator iter = errors.iterator();
        out.println();
        out.println("----------------------- Test Summary -----------------------");
        if (errors.size() == 0) {
            out.println("no errors");
        } else {
            out.println(errors.size() + " error" + (errors.size() > 1 ? "s" : ""));
            while (iter.hasNext()) {
                out.println(" " + iter.next());
            }
        }
        out.println("------------------------------------------------------------");
    }

    /**
     * Checks the all the assertions we wanted were achieved
     * and all those received were desired.
     */
    protected void checkAfterTask() {
        log("checking after task");
        for (Iterator i = wants.iterator(); i.hasNext();) {
            Object want = i.next();
            check(haves.contains(want),
                  "didn't see " + want + " in " + haves);
        }
        for (Iterator i = haves.iterator(); i.hasNext();) {
            Object have = i.next();
            check(wants.contains(have),
                  "shouldn't have seen " + have + " in " + wants);
        }
        for (Iterator i = donts.iterator(); i.hasNext();) {
            Object dont = i.next();
            check(!haves.contains(dont),
                  "should't have seen " + dont + " in " + haves);
        }
    }

    /**
     * Logs an error in <code>!b</code> with message <code>msg</code>.
     *
     * @param b   <code>true</code> for an error.
     * @param msg Failure message.
     */
    protected void check(boolean b, String msg) {
        if (!b) error(taskname, msg);
    }

    /**
     * Calls {@link #check(boolean,String)} with the result
     * of comparing equality of <code>o1</code> and <code>o2</code>,
     * failing with message <code>msg</code>.
     *
     * @param o1  First comparison.
     * @param o2  Other comparison.
     * @param msg Failure message.
     */
    protected void check(Object o1, Object o2, String msg) {
        if (o1 != null) {
            check(o1.equals(o2), msg);
        } else if (o2 != null) {
            check(o2.equals(o1), msg);
        } else {
            check(true, msg);
        }
    }

    /**
     * Calls {@link #runProject} with <code>args</code> and
     * the result of {@link #getAntFile}.
     *
     * @param args Arguments given on the command line.
     * @see   #runProject(String[], String)
     */
    public void runTests(String[] args) {
        runProject(args, getAntFile());
    }

    /**
     * Loads the project, collects a list of methods, and
     * passes these methods to {@link #runProject(Method[])}.
     *
     * @param args      Command line arguments.
     * @param buildFile XML file that we are giving to ANT.
     * @see #runProject(Method[])
     */
    public void runProject(String[] args, String buildFile) {
        loadProject(buildFile);
        Method[] methods = null;
        if (args == null || args.length == 0 || args[0].equals("${args}")) {
            methods = getClass().getMethods();
        } else {
            methods = new Method[args.length];
            for (int i = 0; i < args.length; i++) {
                String name = args[i];
                if (!Character.isJavaIdentifierStart(name.charAt(0)) || // todo wes: was (i)?
                    name.charAt(0) == '$') {
                    continue;
                }
                try {
                    methods[i] = getClass().getMethod(name, new Class[]{});
                } catch (NoSuchMethodException nsme) {
                    methods[i] = null;
                }
            }
        }
        runProject(methods);
    }

    /**
     * Execute the targets whose name matches those found in <code>methods</code>.
     *
     * @param methods List of methods to execute.
     */
    protected final void runProject(Method[] methods) {
        if (methods == null || methods.length < 1) {
            return;
        }
        for (int i = 0; i < methods.length; i++) {
            Method method = methods[i];
            if (method == null) {
                error("a method is null!");
                continue;
            }
            taskname = method.getName();
            if (taskname.startsWith("test")) {
                info("test task: " + taskname);
                try {
                    method.invoke(this, new Object[]{});
                    beforeTasks();
                    execute(taskname);
                    afterTasks();
                } catch (Throwable t) {
                    throwable(t);
                } finally {
                    info("done task: " + taskname);
                }
            } else if (taskname.startsWith("fail")) {
                info("fail task: " + taskname);
                try {
                    beforeTasks();
                    want(taskname + "-error");
                    execute(taskname);
                    afterTasks();
                } catch (Throwable t) {
                    if (t instanceof BuildException) {
                        have(taskname + "-error");
                        try {
                            method.invoke(this, new Object[]{t});
                        } catch (Throwable tt) {
                            throwable(tt);
                        }
                    } else {
                        throwable(t);
                    }
                } finally {
                    info("done task: " + taskname);
                }
            }
        }
        printSummary();
    }

    /**
     * Called before every task.
     */
    private final void beforeTasks() {
        clear();
        beforeMethod();
        beforeEveryTask();
    }

    /**
     * Called after every task.
     */
    private final void afterTasks() {
        afterMethod();
        afterEveryTask();
        checkAfterTask();
    }    

    /**
     * Invokes the method with prefix <code>prefix</code>.
     *
     * @param prefix Prefix of the method to execute.
     */
    private final void taskMethod(String prefix) {
        String name = prefix + Character.toUpperCase(taskname.charAt(0)) +
            taskname.substring(1);
        try {
            Method method = getClass().getDeclaredMethod(name, new Class[]{});
            if (method != null) {
                method.invoke(this, new Object[]{});
            }
        } catch (Throwable t) {
        }
    }

    /**
     * Executes the method with prefix <code>after</code>.
     */
    private final void afterMethod() {
        taskMethod("after");
    }

    /**
     * Executes the method with prefix <code>before</code>.
     */
    private final void beforeMethod() {
        taskMethod("before");
    }

    /**
     * Override this to do some work before every task.
     */
    protected void beforeEveryTask() {}

    /**
     * Override this for initialization -- called at
     * the end of {@link #loadProject}.
     */
    protected void init() {}

    /**
     * Override this to do some work after every task.
     */
    protected void afterEveryTask() {}

    protected void setProperties(Map map, boolean user) {
        Iterator iter = map.keySet().iterator();
        while (iter.hasNext()) {
            Object key = iter.next();
            Object val = map.get(key);
            String keyString = key + "";
            String valString = val + "";
            if (user) {
                project.setUserProperty(keyString, valString);
            } else {
                project.setProperty(keyString, valString);
            }
        }
    }

    protected void setProperties() {
        setProperties(getProperties(), false);
    }

    protected void setUserProperties() {
        setProperties(getUserProperties(), true);
    }

    /**
     * Override this to provide user properties -- default to
     * an empty <code>HashMap</code>.
     *
     * @return Empty <code>HashMap</code>.
     */
    protected Map getUserProperties() {
        return new HashMap();
    }

    /**
     * Override this to provide system properties -- default to
     * an empty <code>HashMap</code>.
     *
     * @return Empty <code>HashMap</code>.
     */
    protected Map getProperties() {
        return new HashMap();
    }

    /**
     * Loads the project with file name <code>buildFile</code>.
     *
     * @param buildFile Name of the XML file to load.
     */
    public void loadProject(String buildFile) {
        project = new Project();
        project.init();
        project.setUserProperty("ant.file", new File(buildFile).getAbsolutePath() );
        setProperties();
        setUserProperties();
        project.addBuildListener(this);
        ProjectHelper.configureProject(project, new File(buildFile));
        init();
    }

    public void execute(String targetName) {
        try { 
            project.executeTarget(targetName);
        } finally { 
        }
    }

    private static class StringBufferOutputStream extends OutputStream {
        private StringBuffer buf;
        public StringBufferOutputStream(StringBuffer buf) {
            this.buf = buf;
        }
        public void write(int c) { 
            buf.append((char)c);
        }
    }

    public boolean verbosity(BuildEvent event) {
        int[] verbosities = verbosities();
        int priority = event.getPriority();
        for (int i = 0; i < verbosities.length; i++) {
            if (priority == verbosities[i]) return true;
        }
        return false;
    }

    public int[] verbosities() {
        return new int[] { /*Project.MSG_VERBOSE,*/ Project.MSG_INFO, Project.MSG_WARN, project.MSG_ERR };
    }

    // BuildListener
    public void buildFinished(BuildEvent event) {
    }
    public void buildStarted(BuildEvent event) {
    }
    public void messageLogged(BuildEvent event) {
        if (verbosity(event)) {
            out.println(event.getMessage());
        }
    }
    public void targetFinished(BuildEvent event) {
    }
    public void targetStarted(BuildEvent event) {
    }
    public void taskFinished(BuildEvent event) {
    }
    public void taskStarted(BuildEvent event) {
    }
}