From c0857b1ca877588adb280d7c21ad5638fa7d6404 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Lars=C3=A9n?= Date: Sat, 9 Jul 2022 16:40:11 +0200 Subject: [PATCH] fix: Enable creation of packages with repeated simple names in qualified name (#4770) --- .../reflect/declaration/CtPackageImpl.java | 8 +---- .../reflect/factory/PackageFactoryTest.java | 31 +++++++++++++++++++ 2 files changed, 32 insertions(+), 7 deletions(-) create mode 100644 src/test/java/spoon/reflect/factory/PackageFactoryTest.java diff --git a/src/main/java/spoon/support/reflect/declaration/CtPackageImpl.java b/src/main/java/spoon/support/reflect/declaration/CtPackageImpl.java index c73b39c09a2..aae74c3977d 100644 --- a/src/main/java/spoon/support/reflect/declaration/CtPackageImpl.java +++ b/src/main/java/spoon/support/reflect/declaration/CtPackageImpl.java @@ -45,13 +45,7 @@ protected CtRole getRole() { @Override public CtPackage put(String simpleName, CtPackage pack) { - if (pack == null) { - return null; - } - // they are the same - if (CtPackageImpl.this.getQualifiedName().equals(pack.getQualifiedName())) { - addAllTypes(pack, CtPackageImpl.this); - addAllPackages(pack, CtPackageImpl.this); + if (pack == null || pack == CtPackageImpl.this) { return null; } diff --git a/src/test/java/spoon/reflect/factory/PackageFactoryTest.java b/src/test/java/spoon/reflect/factory/PackageFactoryTest.java new file mode 100644 index 00000000000..13cb1897fa1 --- /dev/null +++ b/src/test/java/spoon/reflect/factory/PackageFactoryTest.java @@ -0,0 +1,31 @@ +package spoon.reflect.factory; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.sameInstance; +import static org.hamcrest.MatcherAssert.assertThat; + +import spoon.Launcher; +import spoon.reflect.declaration.CtPackage; +import spoon.test.GitHubIssue; + +class PackageFactoryTest { + + @GitHubIssue(issueNumber = 4764, fixed = true) + void getOrCreate_returnsNestedPackageStructure_whenQualifiedNameRepeatsSimpleName() { + // contract: A qualified name that is simply repetitions of a single simple name results in the expected + // nested package structure + + PackageFactory factory = new Launcher().getFactory().Package(); + String topLevelPackageName = "spoon"; + String nestedPackageName = topLevelPackageName + "." + topLevelPackageName; + + CtPackage packageWithDuplicatedSimpleNames = factory.getOrCreate(nestedPackageName); + CtPackage topLevelPackage = factory.get(topLevelPackageName); + + assertThat(topLevelPackage.getQualifiedName(), equalTo(topLevelPackageName)); + assertThat(packageWithDuplicatedSimpleNames.getQualifiedName(), equalTo(nestedPackageName)); + + assertThat(topLevelPackage.getPackage(topLevelPackageName), sameInstance(packageWithDuplicatedSimpleNames)); + assertThat(packageWithDuplicatedSimpleNames.getParent(), sameInstance(topLevelPackage)); + } +} \ No newline at end of file