View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *   http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.bcel;
19  
20  import static org.junit.jupiter.api.Assertions.assertEquals;
21  
22  import java.io.File;
23  import java.lang.management.ManagementFactory;
24  import java.util.ArrayList;
25  import java.util.List;
26  
27  import org.apache.bcel.classfile.AnnotationEntry;
28  import org.apache.bcel.classfile.Attribute;
29  import org.apache.bcel.classfile.ConstantUtf8;
30  import org.apache.bcel.classfile.JavaClass;
31  import org.apache.bcel.classfile.Method;
32  import org.apache.bcel.classfile.Utility;
33  import org.apache.bcel.generic.AnnotationEntryGen;
34  import org.apache.bcel.generic.ConstantPoolGen;
35  import org.apache.bcel.generic.ElementValueGen;
36  import org.apache.bcel.generic.ElementValuePairGen;
37  import org.apache.bcel.generic.ObjectType;
38  import org.apache.bcel.generic.SimpleElementValueGen;
39  import org.apache.bcel.util.ClassPath;
40  import org.apache.bcel.util.SyntheticRepository;
41  import org.apache.bcel.verifier.VerifierFactory;
42  import org.apache.commons.io.function.Uncheck;
43  
44  public abstract class AbstractTestCase {
45  
46      private static final boolean VERBOSE = false;
47  
48      protected static final String PACKAGE_BASE_NAME = AbstractTestCase.class.getPackage().getName();
49  
50      // Location of test data
51      protected static final File TESTDATA = new File("target", "testdata");
52  
53      // package base name in signature format, i.e. with '/' separators instead of '.'
54      protected static final String PACKAGE_BASE_SIG = Utility.packageToPath(PACKAGE_BASE_NAME);
55  
56      public static void clear() {
57          VerifierFactory.clear();
58          Repository.clearCache();
59          ConstantUtf8.clearCache();
60      }
61  
62      public AnnotationEntryGen createFruitAnnotationEntry(final ConstantPoolGen cp, final String aFruit, final boolean visibility) {
63          final SimpleElementValueGen evg = new SimpleElementValueGen(ElementValueGen.STRING, cp, aFruit);
64          final ElementValuePairGen nvGen = new ElementValuePairGen("fruit", evg, cp);
65          final ObjectType t = new ObjectType("SimpleStringAnnotation");
66          final List<ElementValuePairGen> elements = new ArrayList<>();
67          elements.add(nvGen);
68          return new AnnotationEntryGen(t, elements, visibility, cp);
69      }
70  
71      public SyntheticRepository createRepos(final String cpentry) {
72          return Uncheck.get(() -> {
73              try (ClassPath cp = new ClassPath("target" + File.separator + "testdata" + File.separator + cpentry + File.separator)) {
74                  return SyntheticRepository.getInstance(cp);
75              }
76          });
77      }
78  
79      /**
80       * @param name
81       * @return Path to file under the TESTDATA directory
82       */
83      protected File createTestdataFile(final String name) {
84          return new File(TESTDATA, name);
85      }
86  
87      /**
88       * Deletes a file under the TESTDATA directory
89       *
90       * @param name
91       * @return See {@link File#delete()}.
92       */
93      protected boolean delete(final String name) {
94          return new File(TESTDATA, name).delete();
95      }
96  
97      /**
98       * Deletes a directory and file under the TESTDATA directory
99       *
100      * @param dir
101      * @param name
102      * @return true if the file was deleted
103      */
104     protected boolean delete(final String dir, final String name) {
105         // The parameter is relative to the TESTDATA dir
106         final boolean b = delete(dir + File.separator + name);
107         final File testDir = new File(TESTDATA, dir);
108         final String[] files = testDir.list();
109         if (files == null || files.length == 0) {
110             if (!testDir.delete()) {
111                 System.err.println("Failed to remove: " + testDir);
112             }
113         } else {
114             System.err.println("Non-empty directory: " + testDir);
115         }
116         return b;
117     }
118 
119     protected String dumpAnnotationEntries(final AnnotationEntry[] as) {
120         final StringBuilder result = new StringBuilder();
121         result.append("[");
122         for (int i = 0; i < as.length; i++) {
123             final AnnotationEntry annotation = as[i];
124             result.append(annotation.toShortString());
125             if (i + 1 < as.length) {
126                 result.append(",");
127             }
128         }
129         result.append("]");
130         return result.toString();
131     }
132 
133     protected String dumpAnnotationEntries(final AnnotationEntryGen[] as) {
134         final StringBuilder result = new StringBuilder();
135         result.append("[");
136         for (int i = 0; i < as.length; i++) {
137             final AnnotationEntryGen annotation = as[i];
138             result.append(annotation.toShortString());
139             if (i + 1 < as.length) {
140                 result.append(",");
141             }
142         }
143         result.append("]");
144         return result.toString();
145     }
146 
147     protected Attribute findAttribute(final String name, final Attribute[] all) {
148         final List<Attribute> chosenAttrsList = new ArrayList<>();
149         for (final Attribute element : all) {
150             if (VERBOSE) {
151                 System.err.println("Attribute: " + element.getName());
152             }
153             if (element.getName().equals(name)) {
154                 chosenAttrsList.add(element);
155             }
156         }
157         assertEquals(1, chosenAttrsList.size(), "Wrong number of matches");
158         return chosenAttrsList.get(0);
159     }
160 
161     protected Attribute[] findAttribute(final String name, final JavaClass clazz) {
162         final List<Attribute> chosenAttrsList = new ArrayList<>();
163         for (final Attribute element : clazz.getAttributes()) {
164             if (VERBOSE) {
165                 System.err.println("Attribute: " + element.getName());
166             }
167             if (element.getName().equals(name)) {
168                 chosenAttrsList.add(element);
169             }
170         }
171         return chosenAttrsList.toArray(Attribute.EMPTY_ARRAY);
172     }
173 
174     /**
175      * Gets the javaagent input argument of the current running JVM.
176      *
177      * @return javaagent input argument of the current running JVM, null if not set.
178      */
179     protected String getJavaAgent() {
180         final List<String> jvmArgs = ManagementFactory.getRuntimeMXBean().getInputArguments();
181         return jvmArgs.stream().filter(arg -> arg.startsWith("-javaagent")).findFirst().orElse(null);
182     }
183 
184     protected Method getMethod(final JavaClass cl, final String methodname) {
185         for (final Method m : cl.getMethods()) {
186             if (m.getName().equals(methodname)) {
187                 return m;
188             }
189         }
190         return null;
191     }
192 
193     protected JavaClass getTestJavaClass(final String name) throws ClassNotFoundException {
194         return SyntheticRepository.getInstance().loadClass(name);
195     }
196 
197 }