7
7
import java .util .List ;
8
8
import java .util .Map ;
9
9
import java .util .function .Consumer ;
10
+ import org .testng .TestNGException ;
10
11
import org .testng .util .Strings ;
11
12
import org .testng .xml .XmlClass ;
12
13
import org .testng .xml .XmlInclude ;
@@ -27,7 +28,8 @@ public final class Yaml {
27
28
28
29
private Yaml () {}
29
30
30
- public static XmlSuite parse (String filePath , InputStream is ) throws FileNotFoundException {
31
+ public static XmlSuite parse (String filePath , InputStream is , boolean loadClasses )
32
+ throws FileNotFoundException {
31
33
Constructor constructor = new TestNGConstructor (XmlSuite .class );
32
34
{
33
35
TypeDescription suiteDescription = new TypeDescription (XmlSuite .class );
@@ -46,6 +48,9 @@ public static XmlSuite parse(String filePath, InputStream is) throws FileNotFoun
46
48
constructor .addTypeDescription (testDescription );
47
49
}
48
50
51
+ TypeDescription xmlClassDescription = new XmlClassTypeDescriptor (loadClasses );
52
+ constructor .addTypeDescription (xmlClassDescription );
53
+
49
54
org .yaml .snakeyaml .Yaml y = new org .yaml .snakeyaml .Yaml (constructor );
50
55
if (is == null ) {
51
56
is = new FileInputStream (new File (filePath ));
@@ -347,4 +352,42 @@ public Object construct(Node node) {
347
352
}
348
353
}
349
354
}
355
+
356
+ private static class XmlClassTypeDescriptor extends TypeDescription {
357
+
358
+ private final boolean loadClasses ;
359
+
360
+ public XmlClassTypeDescriptor (boolean loadClasses ) {
361
+ super (XmlClass .class );
362
+ this .loadClasses = loadClasses ;
363
+ }
364
+
365
+ @ Override
366
+ public Object newInstance (Node node ) {
367
+ String className ;
368
+
369
+ try {
370
+ java .lang .reflect .Constructor <?> c =
371
+ XmlClass .class .getDeclaredConstructor (String .class , boolean .class );
372
+ c .setAccessible (true );
373
+ if (node instanceof MappingNode ) {
374
+ Node valueNode =
375
+ ((MappingNode ) node )
376
+ .getValue ().stream ()
377
+ .filter (
378
+ nodeTuple ->
379
+ ((ScalarNode ) nodeTuple .getKeyNode ()).getValue ().equals ("name" ))
380
+ .findFirst ()
381
+ .orElseThrow (RuntimeException ::new )
382
+ .getValueNode ();
383
+ className = ((ScalarNode ) valueNode ).getValue ();
384
+ } else {
385
+ className = ((ScalarNode ) node ).getValue ();
386
+ }
387
+ return c .newInstance (className , loadClasses );
388
+ } catch (Exception e ) {
389
+ throw new TestNGException ("Failed to instantiate class" , e );
390
+ }
391
+ }
392
+ }
350
393
}
0 commit comments