diff --git a/litho-it/src/test/java/com/facebook/litho/processor/integration/ProcessorIntegrationTest.java b/litho-it/src/test/java/com/facebook/litho/processor/integration/ProcessorIntegrationTest.java deleted file mode 100644 index 8af0f1ee01b..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/processor/integration/ProcessorIntegrationTest.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.processor.integration; - -import com.facebook.litho.specmodels.processor.ComponentsProcessor; -import com.facebook.litho.specmodels.processor.testing.ComponentsTestingProcessor; -import com.google.common.collect.ImmutableList; -import com.google.common.io.Resources; -import com.google.common.truth.Truth; -import com.google.testing.compile.JavaFileObjects; -import com.google.testing.compile.JavaSourceSubjectFactory; -import com.google.testing.compile.JavaSourcesSubjectFactory; -import java.io.IOException; -import javax.tools.JavaFileObject; -import javax.tools.StandardLocation; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -@RunWith(JUnit4.class) -public class ProcessorIntegrationTest { - public static String RES_PREFIX = "/processor/"; - public static String RES_PACKAGE = "com.facebook.litho.processor.integration.resources"; - - @Test - public void failsToCompileWithWrongContext() throws IOException { - final JavaFileObject javaFileObject = - JavaFileObjects.forResource( - Resources.getResource( - getClass(), RES_PREFIX + "IncorrectOnCreateLayoutArgsComponentSpec.java")); - Truth.assertAbout(JavaSourceSubjectFactory.javaSource()) - .that(javaFileObject) - .processedWith(new ComponentsProcessor()) - .failsToCompile() - .withErrorCount(1) - .withErrorContaining( - "Argument at index 0 (context) is not a valid parameter, should be one of the " - + "following: @Prop T somePropName. @TreeProp T someTreePropName. " - + "@State T someStateName. @InjectProp T someInjectPropName. @CachedValue T value, " - + "where the cached value has a corresponding @OnCalculateCachedValue method.") - .in(javaFileObject) - .onLine(28); - } - - @Test - public void compilesTestLayoutSpecWithoutError() { - final JavaFileObject javaFileObject = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "TestLayoutSpec.java")); - - final JavaFileObject testTreePropFileObject = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "TestTreeProp.java")); - - final JavaFileObject testEventFileObject = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "TestEvent.java")); - - final JavaFileObject testTagFileObject = - JavaFileObjects.forResource(Resources.getResource(getClass(), RES_PREFIX + "TestTag.java")); - - final JavaFileObject expectedOutput = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "TestLayout.java")); - - Truth.assertAbout(JavaSourcesSubjectFactory.javaSources()) - .that( - ImmutableList.of( - javaFileObject, testTreePropFileObject, testEventFileObject, testTagFileObject)) - .processedWith(new ComponentsProcessor()) - .compilesWithoutError() - .and() - .generatesFileNamed(StandardLocation.CLASS_OUTPUT, RES_PACKAGE, "TestLayout.class") - .and() - .generatesFileNamed( - StandardLocation.CLASS_OUTPUT, RES_PACKAGE, "TestLayout$TestLayoutStateContainer.class") - .and() - .generatesFileNamed(StandardLocation.CLASS_OUTPUT, RES_PACKAGE, "TestLayout$Builder.class") - .and() - .generatesFileNamed(StandardLocation.CLASS_OUTPUT, RES_PACKAGE, "TestLayoutSpec.class") - .and() - .generatesSources(expectedOutput); - } - - @Test - public void compilesTestMountSpec() { - final JavaFileObject javaFileObject = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "TestMountSpec.java")); - - final JavaFileObject testTreePropFileObject = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "TestTreeProp.java")); - - final JavaFileObject testEventFileObject = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "TestEvent.java")); - - final JavaFileObject testTagFileObject = - JavaFileObjects.forResource(Resources.getResource(getClass(), RES_PREFIX + "TestTag.java")); - - final JavaFileObject expectedOutput = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "TestMount.java")); - - Truth.assertAbout(JavaSourcesSubjectFactory.javaSources()) - .that( - ImmutableList.of( - javaFileObject, testTreePropFileObject, testEventFileObject, testTagFileObject)) - .processedWith(new ComponentsProcessor()) - .compilesWithoutError() - .and() - .generatesFileNamed(StandardLocation.CLASS_OUTPUT, RES_PACKAGE, "TestMount.class") - .and() - .generatesFileNamed( - StandardLocation.CLASS_OUTPUT, RES_PACKAGE, "TestMount$TestMountStateContainer.class") - .and() - .generatesFileNamed(StandardLocation.CLASS_OUTPUT, RES_PACKAGE, "TestMount$Builder.class") - .and() - .generatesFileNamed(StandardLocation.CLASS_OUTPUT, RES_PACKAGE, "TestMountSpec.class") - .and() - .generatesSources(expectedOutput); - } - - @Test - public void compilesBasicTestSampleSpec() { - final JavaFileObject testSpecObject = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "BasicTestSampleSpec.java")); - final JavaFileObject layoutSpecObject = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "BasicLayoutSpec.java")); - - final JavaFileObject expectedOutput = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "BasicTestSample.java")); - - Truth.assertAbout(JavaSourcesSubjectFactory.javaSources()) - .that(ImmutableList.of(testSpecObject, layoutSpecObject)) - .processedWith(new ComponentsTestingProcessor(), new ComponentsProcessor()) - .compilesWithoutError() - .and() - .generatesFileNamed(StandardLocation.CLASS_OUTPUT, RES_PACKAGE, "BasicTestSample.class") - .and() - .generatesFileNamed( - StandardLocation.CLASS_OUTPUT, RES_PACKAGE, "BasicTestSample$Matcher.class") - .and() - .generatesFileNamed( - StandardLocation.CLASS_OUTPUT, RES_PACKAGE, "BasicTestSample$Matcher$1.class") - .and() - .generatesFileNamed(StandardLocation.CLASS_OUTPUT, RES_PACKAGE, "BasicTestSampleSpec.class") - .and() - .generatesSources(expectedOutput); - } - - @Test - public void failsToCompileClassBasedTestSpec() throws IOException { - final JavaFileObject javaFileObject = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "IncorrectClassBasedTestSpec.java")); - final JavaFileObject layoutSpecObject = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "BasicLayoutSpec.java")); - - Truth.assertAbout(JavaSourcesSubjectFactory.javaSources()) - .that(ImmutableList.of(javaFileObject, layoutSpecObject)) - .processedWith(new ComponentsTestingProcessor(), new ComponentsProcessor()) - .failsToCompile() - .withErrorCount(1) - .withErrorContaining( - "Specs annotated with @TestSpecs must be interfaces and cannot be of kind CLASS.") - .in(javaFileObject) - .onLine(23); - } - - @Test - public void failsToCompileNonEmptyTestSpecInterface() throws IOException { - final JavaFileObject javaFileObject = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "IncorrectNonEmptyTestSpec.java")); - final JavaFileObject layoutSpecObject = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "BasicLayoutSpec.java")); - - Truth.assertAbout(JavaSourcesSubjectFactory.javaSources()) - .that(ImmutableList.of(javaFileObject, layoutSpecObject)) - .processedWith(new ComponentsTestingProcessor(), new ComponentsProcessor()) - .failsToCompile() - .withErrorCount(1) - .withErrorContaining( - "TestSpec interfaces must not contain any members. Please remove these function" - + " declarations: ()void test, ()java.util.List list") - .in(javaFileObject) - .onLine(24); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/processor/integration/sections/SectionsProcessorIntegrationTest.java b/litho-it/src/test/java/com/facebook/litho/processor/integration/sections/SectionsProcessorIntegrationTest.java deleted file mode 100644 index 2b67513badf..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/processor/integration/sections/SectionsProcessorIntegrationTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.processor.integration.sections; - -import com.facebook.litho.sections.specmodels.processor.SectionsComponentProcessor; -import com.google.common.collect.ImmutableList; -import com.google.common.io.Resources; -import com.google.common.truth.Truth; -import com.google.testing.compile.JavaFileObjects; -import com.google.testing.compile.JavaSourcesSubjectFactory; -import javax.tools.JavaFileObject; -import javax.tools.StandardLocation; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -@RunWith(JUnit4.class) -public class SectionsProcessorIntegrationTest { - private static final String RES_PREFIX = "/processor/sections/"; - private static final String RES_PACKAGE = - "com.facebook.litho.sections.processor.integration.resources"; - - @Ignore("T41117446") // Enable them after switching target to AndroidX - @Test - public void compilesFullGroupSectionSpecWithoutError() { - final JavaFileObject javaFileObject = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "FullGroupSectionSpec.java")); - - final JavaFileObject testEventFileObject = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "TestEvent.java")); - - final JavaFileObject testTagFileObject = - JavaFileObjects.forResource(Resources.getResource(getClass(), RES_PREFIX + "TestTag.java")); - - final JavaFileObject expectedOutput = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "FullGroupSection.java")); - - Truth.assertAbout(JavaSourcesSubjectFactory.javaSources()) - .that(ImmutableList.of(javaFileObject, testEventFileObject, testTagFileObject)) - .processedWith(new SectionsComponentProcessor()) - .compilesWithoutError() - .and() - .generatesFileNamed(StandardLocation.CLASS_OUTPUT, RES_PACKAGE, "FullGroupSection.class") - .and() - .generatesFileNamed( - StandardLocation.CLASS_OUTPUT, - RES_PACKAGE, - "FullGroupSection$FullGroupSectionStateContainer.class") - .and() - .generatesFileNamed( - StandardLocation.CLASS_OUTPUT, RES_PACKAGE, "FullGroupSection$Builder.class") - .and() - .generatesFileNamed( - StandardLocation.CLASS_OUTPUT, RES_PACKAGE, "FullGroupSectionSpec.class") - .and() - .generatesSources(expectedOutput); - } - - @Ignore("T41117446") // Enable them after switching target to AndroidX - @Test - public void compilesFullDiffSectionSpecWithoutError() { - final JavaFileObject javaFileObject = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "FullDiffSectionSpec.java")); - - final JavaFileObject testEventFileObject = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "TestEvent.java")); - - final JavaFileObject testTagFileObject = - JavaFileObjects.forResource(Resources.getResource(getClass(), RES_PREFIX + "TestTag.java")); - - final JavaFileObject expectedOutput = - JavaFileObjects.forResource( - Resources.getResource(getClass(), RES_PREFIX + "FullDiffSection.java")); - - Truth.assertAbout(JavaSourcesSubjectFactory.javaSources()) - .that(ImmutableList.of(javaFileObject, testEventFileObject, testTagFileObject)) - .processedWith(new SectionsComponentProcessor()) - .compilesWithoutError() - .and() - .generatesFileNamed(StandardLocation.CLASS_OUTPUT, RES_PACKAGE, "FullDiffSection.class") - .and() - .generatesFileNamed( - StandardLocation.CLASS_OUTPUT, - RES_PACKAGE, - "FullDiffSection$FullDiffSectionStateContainer.class") - .and() - .generatesFileNamed( - StandardLocation.CLASS_OUTPUT, RES_PACKAGE, "FullDiffSection$Builder.class") - .and() - .generatesFileNamed(StandardLocation.CLASS_OUTPUT, RES_PACKAGE, "FullDiffSectionSpec.class") - .and() - .generatesSources(expectedOutput); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/sections/specmodels/generator/GroupSectionSpecGeneratorTest.java b/litho-it/src/test/java/com/facebook/litho/sections/specmodels/generator/GroupSectionSpecGeneratorTest.java deleted file mode 100644 index a7c6bb497cb..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/sections/specmodels/generator/GroupSectionSpecGeneratorTest.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.sections.specmodels.generator; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.annotations.State; -import com.facebook.litho.sections.ChangesInfo; -import com.facebook.litho.sections.Children; -import com.facebook.litho.sections.SectionContext; -import com.facebook.litho.sections.annotations.GroupSectionSpec; -import com.facebook.litho.sections.annotations.OnCreateChildren; -import com.facebook.litho.sections.annotations.OnDataRendered; -import com.facebook.litho.sections.common.SingleComponentSection; -import com.facebook.litho.sections.specmodels.model.DelegateMethodDescriptions; -import com.facebook.litho.sections.specmodels.model.GroupSectionSpecModel; -import com.facebook.litho.sections.specmodels.processor.GroupSectionSpecModelFactory; -import com.facebook.litho.specmodels.generator.DelegateMethodGenerator; -import com.facebook.litho.specmodels.generator.TypeSpecDataHolder; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.model.SpecModel; -import com.facebook.litho.widget.Text; -import com.google.testing.compile.CompilationRule; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -@RunWith(JUnit4.class) -public class GroupSectionSpecGeneratorTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - @Mock private Messager mMessager; - - private final GroupSectionSpecModelFactory mGroupSectionSpecModelFactory = - new GroupSectionSpecModelFactory(); - - @GroupSectionSpec - static class TestGroupSectionSpec { - - @OnCreateChildren - public Children onCreateChildren(SectionContext c) { - return Children.create() - .child( - SingleComponentSection.create(c) - .component(Text.create(c).text("Single Component").build())) - .build(); - } - - @OnDataRendered - public void onDataRendered( - SectionContext c, - boolean isDataChanged, - boolean isMounted, - long uptimeMillis, - int firstVisibleIndex, - int lastVisibleIndex, - ChangesInfo changesInfo, - int globalOffset, - @Prop boolean arg0, - @State int arg1) {} - } - - private SpecModel mSpecModel; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - Elements elements = mCompilationRule.getElements(); - Types types = mCompilationRule.getTypes(); - TypeElement typeElement = - elements.getTypeElement(TestGroupSectionSpec.class.getCanonicalName()); - mSpecModel = - mGroupSectionSpecModelFactory.create( - elements, types, typeElement, mMessager, RunMode.normal(), null, null); - } - - @Test - public void testGenerateDelegates() { - final GroupSectionSpecModel groupSectionSpecModel = (GroupSectionSpecModel) mSpecModel; - final TypeSpecDataHolder dataHolder = - DelegateMethodGenerator.generateDelegates( - groupSectionSpecModel, - DelegateMethodDescriptions.getGroupSectionSpecDelegatesMap(groupSectionSpecModel), - RunMode.normal()); - - assertThat(dataHolder.getMethodSpecs()).hasSize(2); - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "@java.lang.Override\n" - + "protected com.facebook.litho.sections.Children" - + " createChildren(com.facebook.litho.sections.SectionContext c) {\n" - + " com.facebook.litho.sections.Children _result;\n" - + " _result = (com.facebook.litho.sections.Children)" - + " TestGroupSectionSpec.onCreateChildren(\n" - + " (com.facebook.litho.sections.SectionContext) c);\n" - + " return _result;\n" - + "}\n"); - assertThat(dataHolder.getMethodSpecs().get(1).toString()) - .isEqualTo( - "@java.lang.Override\n" - + "protected void dataRendered(com.facebook.litho.sections.SectionContext c," - + " boolean isDataChanged,\n" - + " boolean isMounted, long uptimeMillis, int firstVisibleIndex, int" - + " lastVisibleIndex,\n" - + " com.facebook.litho.sections.ChangesInfo changesInfo, int globalOffset) {\n" - + " TestGroupSectionSpec.onDataRendered(\n" - + " (com.facebook.litho.sections.SectionContext) c,\n" - + " (boolean) isDataChanged,\n" - + " (boolean) isMounted,\n" - + " (long) uptimeMillis,\n" - + " (int) firstVisibleIndex,\n" - + " (int) lastVisibleIndex,\n" - + " (com.facebook.litho.sections.ChangesInfo) changesInfo,\n" - + " (int) globalOffset,\n" - + " (boolean) arg0,\n" - + " (int) getStateContainerImpl(c).arg1);\n" - + "}\n"); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/sections/specmodels/processor/DiffSectionSpecModelFactoryTest.java b/litho-it/src/test/java/com/facebook/litho/sections/specmodels/processor/DiffSectionSpecModelFactoryTest.java deleted file mode 100644 index 9ea667d7fdf..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/sections/specmodels/processor/DiffSectionSpecModelFactoryTest.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.sections.specmodels.processor; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -import com.facebook.litho.Component; -import com.facebook.litho.Diff; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.sections.ChangeSet; -import com.facebook.litho.sections.SectionContext; -import com.facebook.litho.sections.annotations.DiffSectionSpec; -import com.facebook.litho.sections.annotations.OnDiff; -import com.facebook.litho.sections.specmodels.model.DiffSectionSpecModel; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.model.DependencyInjectionHelper; -import com.google.testing.compile.CompilationRule; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; - -public class DiffSectionSpecModelFactoryTest { - - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - - private final DependencyInjectionHelper mDependencyInjectionHelper = - mock(DependencyInjectionHelper.class); - - private final DiffSectionSpecModelFactory mFactory = new DiffSectionSpecModelFactory(); - - private DiffSectionSpecModel mDiffSectionSpecModel; - - @DiffSectionSpec(value = "TestDiffSectionComponentName", isPublic = false) - static class TestDiffSectionSpec { - - @OnDiff - public static void onCreateChangeSet( - SectionContext context, - ChangeSet changeSet, - @Prop Diff component, - @Prop(optional = true) Diff data) { - final Object prevData = data.getPrevious(); - final Object nextData = data.getNext(); - final Component prevComponent = component.getPrevious(); - final Component nextComponent = component.getNext(); - - if (prevComponent == null && nextComponent == null) { - return; - } - - if (prevComponent != null && nextComponent == null) { - changeSet.delete(0, prevData); - return; - } - } - } - - @Before - public void setUp() { - Elements elements = mCompilationRule.getElements(); - Types types = mCompilationRule.getTypes(); - TypeElement typeElement = - elements.getTypeElement( - DiffSectionSpecModelFactoryTest.TestDiffSectionSpec.class.getCanonicalName()); - - mDiffSectionSpecModel = - mFactory.create( - elements, - types, - typeElement, - mock(Messager.class), - RunMode.normal(), - mDependencyInjectionHelper, - null); - } - - @Test - public void create_forGroupSectionSpec_populateGenericInfo() { - DiffSectionSpecModelFactoryTestHelper.create_forDiffSectionSpec_populateGenericSpecInfo( - mDiffSectionSpecModel); - } - - @Test - public void testUpdateStateWithTransitionMethodsIsNotNull() { - assertThat(mDiffSectionSpecModel.getUpdateStateWithTransitionMethods()) - .describedAs( - "UpdateStateWithTransitionMethods cannot be null as otherwise the Litho Structure will" - + " not render") - .isNotNull(); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/sections/specmodels/processor/GroupSectionSpecModelFactoryTest.java b/litho-it/src/test/java/com/facebook/litho/sections/specmodels/processor/GroupSectionSpecModelFactoryTest.java deleted file mode 100644 index acc0dc961b2..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/sections/specmodels/processor/GroupSectionSpecModelFactoryTest.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.sections.specmodels.processor; - -import static org.mockito.Mockito.mock; - -import com.facebook.litho.ClickEvent; -import com.facebook.litho.Component; -import com.facebook.litho.annotations.Event; -import com.facebook.litho.annotations.FromTrigger; -import com.facebook.litho.annotations.OnCreateInitialState; -import com.facebook.litho.annotations.OnEvent; -import com.facebook.litho.annotations.OnTrigger; -import com.facebook.litho.annotations.OnUpdateState; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.annotations.State; -import com.facebook.litho.sections.SectionContext; -import com.facebook.litho.sections.annotations.GroupSectionSpec; -import com.facebook.litho.sections.annotations.OnBindService; -import com.facebook.litho.sections.annotations.OnCreateChildren; -import com.facebook.litho.sections.annotations.OnCreateService; -import com.facebook.litho.sections.specmodels.model.GroupSectionSpecModel; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.model.DependencyInjectionHelper; -import com.google.testing.compile.CompilationRule; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Test {@link GroupSectionSpecModelFactory} * */ -@RunWith(JUnit4.class) -public class GroupSectionSpecModelFactoryTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - - private final DependencyInjectionHelper mDependencyInjectionHelper = - mock(DependencyInjectionHelper.class); - - private final GroupSectionSpecModelFactory mFactory = new GroupSectionSpecModelFactory(); - - private GroupSectionSpecModel mGroupSectionSpecModel; - - @Event - static class TestTriggerEvent { - int testTriggerVar; - } - - @GroupSectionSpec(value = "TestGroupSectionComponentName", isPublic = false) - static class TestGroupSectionSpec { - @OnCreateInitialState - static void onCreateInitialState(@Prop int prop1, @State Integer state1) {} - - @OnUpdateState - static void onUpdateState1(Integer state1) {} - - @OnUpdateState - static void onUpdateState2(Integer state2) {} - - @OnCreateChildren - static Component onCreateChildren( - SectionContext c, @Prop int prop2, @Prop int prop3, @State Integer state1) { - return null; - } - - @OnCreateService - static String onCreateService(SectionContext c, @Prop int prop4, @State Integer state2) { - return "Test"; - } - - @OnBindService - static void onBindService(SectionContext c, String service, @Prop String prop5) {} - - @OnTrigger(TestTriggerEvent.class) - static void onTestTriggerEvent(SectionContext c, @FromTrigger int testTriggerVar) {} - - @OnEvent(ClickEvent.class) - static void onClickEvent(SectionContext c) {} - } - - @Before - public void setUp() { - Elements elements = mCompilationRule.getElements(); - Types types = mCompilationRule.getTypes(); - TypeElement typeElement = - elements.getTypeElement( - GroupSectionSpecModelFactoryTest.TestGroupSectionSpec.class.getCanonicalName()); - - mGroupSectionSpecModel = - mFactory.create( - elements, - types, - typeElement, - mock(Messager.class), - RunMode.normal(), - mDependencyInjectionHelper, - null); - } - - @Test - public void create_forGroupSectionSpec_populateGenericInfo() { - GroupSectionSpecModelFactoryTestHelper.create_forGroupSectionSpec_populateGenericSpecInfo( - mGroupSectionSpecModel, mDependencyInjectionHelper); - } - - @Test - public void create_forGroupSectionSpec_populateServiceInfo() { - GroupSectionSpecModelFactoryTestHelper.create_forGroupSectionSpec_populateServiceInfo( - mGroupSectionSpecModel); - } - - @Test - public void create_forGroupSectionSpec_populateTriggerInfo() { - GroupSectionSpecModelFactoryTestHelper.create_forGroupSectionSpec_populateTriggerInfo( - mGroupSectionSpecModel); - } - - @Test - public void create_forGroupSectionSpec_populateEventInfo() { - GroupSectionSpecModelFactoryTestHelper.create_forGroupSectionSpec_populateEventInfo( - mGroupSectionSpecModel); - } - - @Test - public void create_forGroupSectionSpec_populateUpdateStateInfo() { - GroupSectionSpecModelFactoryTestHelper.create_forGroupSectionSpec_populateUpdateStateInfo( - mGroupSectionSpecModel); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/BuilderGeneratorTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/generator/BuilderGeneratorTest.java deleted file mode 100644 index f11cdae2752..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/BuilderGeneratorTest.java +++ /dev/null @@ -1,884 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.generator; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.facebook.litho.Component; -import com.facebook.litho.ComponentContext; -import com.facebook.litho.annotations.LayoutSpec; -import com.facebook.litho.annotations.OnCreateLayout; -import com.facebook.litho.annotations.OnEvent; -import com.facebook.litho.annotations.OnUpdateState; -import com.facebook.litho.annotations.Param; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.annotations.PropDefault; -import com.facebook.litho.annotations.ResType; -import com.facebook.litho.annotations.State; -import com.facebook.litho.sections.Section; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.model.SpecModel; -import com.facebook.litho.specmodels.processor.LayoutSpecModelFactory; -import com.google.testing.compile.CompilationRule; -import java.util.LinkedList; -import java.util.List; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -/** Tests {@link BuilderGenerator} */ -@RunWith(JUnit4.class) -public class BuilderGeneratorTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - - @Mock Messager mMessager; - - private final LayoutSpecModelFactory mLayoutSpecModelFactory = new LayoutSpecModelFactory(); - - @LayoutSpec - static class TestSpec { - @PropDefault protected static boolean arg0 = true; - - @PropDefault(resType = ResType.DIMEN_SIZE, resId = 12345) - protected static float arg5; - - @OnCreateLayout - public void testDelegateMethod( - @Prop boolean arg0, - @Prop Section section, - @State int arg1, - @Param Object arg2, - @Prop(optional = true) boolean arg3, - @Prop(varArg = "name") List names, - @Prop(optional = true) float arg5) {} - - @OnEvent(Object.class) - public void testEventMethod(@Prop boolean arg0) {} - - @OnUpdateState - public void testUpdateStateMethod() {} - } - - @LayoutSpec - static class TestVarArgsWithDefaultValueSpec { - - @PropDefault static final List list = new LinkedList<>(); - - @OnCreateLayout - public static Component varArgsWithDefaultValue( - ComponentContext c, @Prop(optional = true, varArg = "item") List list) { - return null; - } - } - - @LayoutSpec - static class TestResTypeWithVarArgsSpec { - @OnCreateLayout - public void resTypeWithVarArgs( - @Prop(varArg = "size", resType = ResType.DIMEN_TEXT) List sizes) {} - } - - @LayoutSpec - static class TestDimenResTypeWithBoxFloatArgSpec { - @OnCreateLayout - public void dimenResTypeWithBoxFloatArg(@Prop(resType = ResType.DIMEN_TEXT) Float size) {} - } - - @LayoutSpec - static class TestKotlinVarArgSpec { - public static final TestKotlinVarArgSpec INSTANCE = null; - - @OnCreateLayout - public final Component onCreateLayout( - ComponentContext c, - @Prop(varArg = "number") java.util.List numbers) { - return null; - } - } - - private SpecModel mSpecModel; - private SpecModel mResTypeVarArgsSpecModel; - private SpecModel mDimenResTypeWithBoxFloatArgSpecModel; - private SpecModel mKotlinWildcardsVarArgBuildersSpecModel; - private SpecModel mVarArgsWithDefaultValueSpecModel; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - Elements elements = mCompilationRule.getElements(); - Types types = mCompilationRule.getTypes(); - - TypeElement typeElement = elements.getTypeElement(TestSpec.class.getCanonicalName()); - mSpecModel = - mLayoutSpecModelFactory.create( - elements, types, typeElement, mMessager, RunMode.normal(), null, null); - - TypeElement resWithVarArgsElement = - elements.getTypeElement(TestResTypeWithVarArgsSpec.class.getCanonicalName()); - mResTypeVarArgsSpecModel = - mLayoutSpecModelFactory.create( - elements, types, resWithVarArgsElement, mMessager, RunMode.normal(), null, null); - - TypeElement dimenResTypeWithBoxFloatArgElement = - elements.getTypeElement(TestDimenResTypeWithBoxFloatArgSpec.class.getCanonicalName()); - mDimenResTypeWithBoxFloatArgSpecModel = - mLayoutSpecModelFactory.create( - elements, - types, - dimenResTypeWithBoxFloatArgElement, - mMessager, - RunMode.normal(), - null, - null); - - TypeElement typeElementKotlinVarArgsWildcards = - elements.getTypeElement(TestKotlinVarArgSpec.class.getCanonicalName()); - mKotlinWildcardsVarArgBuildersSpecModel = - mLayoutSpecModelFactory.create( - elements, - types, - typeElementKotlinVarArgsWildcards, - mMessager, - RunMode.normal(), - null, - null); - - TypeElement typeElement1VarArgsWithDefaultValue = - elements.getTypeElement(TestVarArgsWithDefaultValueSpec.class.getCanonicalName()); - mVarArgsWithDefaultValueSpecModel = - mLayoutSpecModelFactory.create( - elements, - types, - typeElement1VarArgsWithDefaultValue, - mMessager, - RunMode.normal(), - null, - null); - } - - @Test - public void testGenerate() { - TypeSpecDataHolder dataHolder = BuilderGenerator.generate(mSpecModel); - - assertThat(dataHolder.getMethodSpecs()).hasSize(2); - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "public static Builder create(com.facebook.litho.ComponentContext context) {\n" - + " return create(context, 0, 0);\n" - + "}\n"); - assertThat(dataHolder.getMethodSpecs().get(1).toString()) - .isEqualTo( - "public static Builder create(com.facebook.litho.ComponentContext context, int" - + " defStyleAttr,\n" - + " int defStyleRes) {\n" - + " Test instance = new Test();\n" - + " return new Builder(context, defStyleAttr, defStyleRes, instance);\n" - + "}\n"); - - assertThat(dataHolder.getFieldSpecs()).hasSize(0); - assertThat(dataHolder.getTypeSpecs()).hasSize(1); - assertThat(dataHolder.getTypeSpecs().get(0).toString()) - .isEqualTo( - "@com.facebook.litho.annotations.Generated\n" - + "public static final class Builder extends" - + " com.facebook.litho.Component.Builder {\n" - + " Test mTest;\n" - + "\n" - + " com.facebook.litho.ComponentContext mContext;\n" - + "\n" - + " private final java.lang.String[] REQUIRED_PROPS_NAMES = new String[]" - + " {\"arg0\", \"section\"};\n" - + "\n" - + " private final int REQUIRED_PROPS_COUNT = 2;\n" - + "\n" - + " private final java.util.BitSet mRequired = new" - + " java.util.BitSet(REQUIRED_PROPS_COUNT);\n" - + "\n" - + " private Builder(com.facebook.litho.ComponentContext context, int defStyleAttr," - + " int defStyleRes,\n" - + " Test testRef) {\n" - + " super(context, defStyleAttr, defStyleRes, testRef);\n" - + " mTest = testRef;\n" - + " mContext = context;\n" - + " initPropDefaults();\n" - + " mRequired.clear();\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " protected void setComponent(com.facebook.litho.Component component) {\n" - + " mTest = (com.facebook.litho.specmodels.generator.BuilderGeneratorTest.Test)" - + " component;\n" - + " }\n" - + "\n" - + " void initPropDefaults() {\n" - + " this.mTest.arg5 = mResourceResolver.resolveDimenSizeRes(12345);\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"arg0\",\n" - + " required = true\n" - + " )\n" - + " @com.facebook.litho.annotations.RequiredProp(\"arg0\")\n" - + " public Builder arg0(boolean arg0) {\n" - + " this.mTest.arg0 = arg0;\n" - + " mRequired.set(0);\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"arg3\",\n" - + " required = false\n" - + " )\n" - + " public Builder arg3(boolean arg3) {\n" - + " this.mTest.arg3 = arg3;\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"arg5\",\n" - + " required = false\n" - + " )\n" - + " public Builder arg5(float arg5) {\n" - + " this.mTest.arg5 = arg5;\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"names\",\n" - + " required = false\n" - + " )\n" - + " public Builder name(java.lang.String name) {\n" - + " if (name == null) {\n" - + " return this;\n" - + " }\n" - + " if (this.mTest.names == java.util.Collections.EMPTY_LIST) {\n" - + " this.mTest.names = new java.util.ArrayList();\n" - + " }\n" - + " this.mTest.names.add(name);\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"names\",\n" - + " required = false\n" - + " )\n" - + " public Builder names(java.util.List names) {\n" - + " if (names == null) {\n" - + " return this;\n" - + " }\n" - + " if (this.mTest.names.isEmpty()) {\n" - + " this.mTest.names = names;\n" - + " } else {\n" - + " this.mTest.names.addAll(names);\n" - + " }\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"section\",\n" - + " required = true\n" - + " )\n" - + " @com.facebook.litho.annotations.RequiredProp(\"section\")\n" - + " public Builder section(com.facebook.litho.sections.Section section) {\n" - + " this.mTest.section = section;\n" - + " mRequired.set(1);\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"section\",\n" - + " required = true\n" - + " )\n" - + " @com.facebook.litho.annotations.RequiredProp(\"section\")\n" - + " public Builder section(com.facebook.litho.sections.Section.Builder" - + " sectionBuilder) {\n" - + " this.mTest.section = sectionBuilder == null ? null :" - + " sectionBuilder.build();\n" - + " mRequired.set(1);\n" - + " return this;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public Builder getThis() {\n" - + " return this;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public com.facebook.litho.specmodels.generator.BuilderGeneratorTest.Test" - + " build() {\n" - + " checkArgs(REQUIRED_PROPS_COUNT, mRequired, REQUIRED_PROPS_NAMES);\n" - + " return mTest;\n" - + " }\n" - + "}\n"); - } - - @Test - public void testResTypeWithVarArgs() { - TypeSpecDataHolder dataHolder = BuilderGenerator.generate(mResTypeVarArgsSpecModel); - assertThat(dataHolder.getTypeSpecs()).hasSize(1); - assertThat(dataHolder.getTypeSpecs().get(0).toString()) - .isEqualTo( - "@com.facebook.litho.annotations.Generated\n" - + "public static final class Builder extends" - + " com.facebook.litho.Component.Builder {\n" - + " TestResTypeWithVarArgs mTestResTypeWithVarArgs;\n" - + "\n" - + " com.facebook.litho.ComponentContext mContext;\n" - + "\n" - + " private Builder(com.facebook.litho.ComponentContext context, int defStyleAttr," - + " int defStyleRes,\n" - + " TestResTypeWithVarArgs testResTypeWithVarArgsRef) {\n" - + " super(context, defStyleAttr, defStyleRes, testResTypeWithVarArgsRef);\n" - + " mTestResTypeWithVarArgs = testResTypeWithVarArgsRef;\n" - + " mContext = context;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " protected void setComponent(com.facebook.litho.Component component) {\n" - + " mTestResTypeWithVarArgs =" - + " (com.facebook.litho.specmodels.generator.BuilderGeneratorTest.TestResTypeWithVarArgs)" - + " component;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"sizes\",\n" - + " required = false\n" - + " )\n" - + " public Builder sizePx(@androidx.annotation.Px float size) {\n" - + " if (this.mTestResTypeWithVarArgs.sizes == java.util.Collections.EMPTY_LIST)" - + " {\n" - + " this.mTestResTypeWithVarArgs.sizes = new" - + " java.util.ArrayList();\n" - + " }\n" - + " final float res = size;\n" - + " this.mTestResTypeWithVarArgs.sizes.add(res);\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"sizes\",\n" - + " required = false\n" - + " )\n" - + " public Builder sizesPx(java.util.List sizes) {\n" - + " if (sizes == null) {\n" - + " return this;\n" - + " }\n" - + " if (this.mTestResTypeWithVarArgs.sizes == java.util.Collections.EMPTY_LIST)" - + " {\n" - + " this.mTestResTypeWithVarArgs.sizes = new" - + " java.util.ArrayList();\n" - + " }\n" - + " for (int i = 0; i < sizes.size(); i++) {\n" - + " final float res = sizes.get(i);\n" - + " this.mTestResTypeWithVarArgs.sizes.add(res);\n" - + " }\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"sizes\",\n" - + " required = false\n" - + " )\n" - + " public Builder sizeDip(\n" - + " @androidx.annotation.Dimension(unit = androidx.annotation.Dimension.DP)" - + " float dip) {\n" - + " if (this.mTestResTypeWithVarArgs.sizes == java.util.Collections.EMPTY_LIST)" - + " {\n" - + " this.mTestResTypeWithVarArgs.sizes = new" - + " java.util.ArrayList();\n" - + " }\n" - + " final float res = mResourceResolver.dipsToPixels(dip);\n" - + " this.mTestResTypeWithVarArgs.sizes.add(res);\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"sizes\",\n" - + " required = false\n" - + " )\n" - + " public Builder sizesDip(java.util.List dips) {\n" - + " if (dips == null) {\n" - + " return this;\n" - + " }\n" - + " if (this.mTestResTypeWithVarArgs.sizes == java.util.Collections.EMPTY_LIST)" - + " {\n" - + " this.mTestResTypeWithVarArgs.sizes = new" - + " java.util.ArrayList();\n" - + " }\n" - + " for (int i = 0; i < dips.size(); i++) {\n" - + " final float res = mResourceResolver.dipsToPixels(dips.get(i));\n" - + " this.mTestResTypeWithVarArgs.sizes.add(res);\n" - + " }\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"sizes\",\n" - + " required = false\n" - + " )\n" - + " public Builder sizeSp(\n" - + " @androidx.annotation.Dimension(unit = androidx.annotation.Dimension.SP)" - + " float sip) {\n" - + " if (this.mTestResTypeWithVarArgs.sizes == java.util.Collections.EMPTY_LIST)" - + " {\n" - + " this.mTestResTypeWithVarArgs.sizes = new" - + " java.util.ArrayList();\n" - + " }\n" - + " final float res = mResourceResolver.sipsToPixels(sip);\n" - + " this.mTestResTypeWithVarArgs.sizes.add(res);\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"sizes\",\n" - + " required = false\n" - + " )\n" - + " public Builder sizesSp(java.util.List sips) {\n" - + " if (sips == null) {\n" - + " return this;\n" - + " }\n" - + " if (this.mTestResTypeWithVarArgs.sizes == java.util.Collections.EMPTY_LIST)" - + " {\n" - + " this.mTestResTypeWithVarArgs.sizes = new" - + " java.util.ArrayList();\n" - + " }\n" - + " for (int i = 0; i < sips.size(); i++) {\n" - + " final float res = mResourceResolver.sipsToPixels(sips.get(i));\n" - + " this.mTestResTypeWithVarArgs.sizes.add(res);\n" - + " }\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"sizes\",\n" - + " required = false\n" - + " )\n" - + " public Builder sizeRes(@androidx.annotation.DimenRes int resId) {\n" - + " if (this.mTestResTypeWithVarArgs.sizes == java.util.Collections.EMPTY_LIST)" - + " {\n" - + " this.mTestResTypeWithVarArgs.sizes = new" - + " java.util.ArrayList();\n" - + " }\n" - + " final float res = mResourceResolver.resolveDimenSizeRes(resId);\n" - + " this.mTestResTypeWithVarArgs.sizes.add(res);\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"sizes\",\n" - + " required = false\n" - + " )\n" - + " public Builder sizesRes(java.util.List resIds) {\n" - + " if (resIds == null) {\n" - + " return this;\n" - + " }\n" - + " if (this.mTestResTypeWithVarArgs.sizes == java.util.Collections.EMPTY_LIST)" - + " {\n" - + " this.mTestResTypeWithVarArgs.sizes = new" - + " java.util.ArrayList();\n" - + " }\n" - + " for (int i = 0; i < resIds.size(); i++) {\n" - + " final float res = mResourceResolver.resolveDimenSizeRes(resIds.get(i));\n" - + " this.mTestResTypeWithVarArgs.sizes.add(res);\n" - + " }\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"sizes\",\n" - + " required = false\n" - + " )\n" - + " public Builder sizeAttr(@androidx.annotation.AttrRes int attrResId,\n" - + " @androidx.annotation.DimenRes int defResId) {\n" - + " if (this.mTestResTypeWithVarArgs.sizes == java.util.Collections.EMPTY_LIST)" - + " {\n" - + " this.mTestResTypeWithVarArgs.sizes = new" - + " java.util.ArrayList();\n" - + " }\n" - + " final float res = mResourceResolver.resolveDimenSizeAttr(attrResId," - + " defResId);\n" - + " this.mTestResTypeWithVarArgs.sizes.add(res);\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"sizes\",\n" - + " required = false\n" - + " )\n" - + " public Builder sizeAttr(@androidx.annotation.AttrRes int attrResId) {\n" - + " if (this.mTestResTypeWithVarArgs.sizes == java.util.Collections.EMPTY_LIST)" - + " {\n" - + " this.mTestResTypeWithVarArgs.sizes = new" - + " java.util.ArrayList();\n" - + " }\n" - + " final float res = mResourceResolver.resolveDimenSizeAttr(attrResId, 0);\n" - + " this.mTestResTypeWithVarArgs.sizes.add(res);\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"sizes\",\n" - + " required = false\n" - + " )\n" - + " public Builder sizesAttr(java.util.List attrResIds,\n" - + " @androidx.annotation.DimenRes int defResId) {\n" - + " if (attrResIds == null) {\n" - + " return this;\n" - + " }\n" - + " if (this.mTestResTypeWithVarArgs.sizes == java.util.Collections.EMPTY_LIST)" - + " {\n" - + " this.mTestResTypeWithVarArgs.sizes = new" - + " java.util.ArrayList();\n" - + " }\n" - + " for (int i = 0; i < attrResIds.size(); i++) {\n" - + " final float res =" - + " mResourceResolver.resolveDimenSizeAttr(attrResIds.get(i), defResId);\n" - + " this.mTestResTypeWithVarArgs.sizes.add(res);\n" - + " }\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"sizes\",\n" - + " required = false\n" - + " )\n" - + " public Builder sizesAttr(java.util.List attrResIds) {\n" - + " if (attrResIds == null) {\n" - + " return this;\n" - + " }\n" - + " if (this.mTestResTypeWithVarArgs.sizes == java.util.Collections.EMPTY_LIST)" - + " {\n" - + " this.mTestResTypeWithVarArgs.sizes = new" - + " java.util.ArrayList();\n" - + " }\n" - + " for (int i = 0; i < attrResIds.size(); i++) {\n" - + " final float res =" - + " mResourceResolver.resolveDimenSizeAttr(attrResIds.get(i), 0);\n" - + " this.mTestResTypeWithVarArgs.sizes.add(res);\n" - + " }\n" - + " return this;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public Builder getThis() {\n" - + " return this;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public" - + " com.facebook.litho.specmodels.generator.BuilderGeneratorTest.TestResTypeWithVarArgs" - + " build(\n" - + " ) {\n" - + " return mTestResTypeWithVarArgs;\n" - + " }\n" - + "}\n"); - } - - @Test - public void testDimenResTypeWithBoxFloatArgSpecModel() { - TypeSpecDataHolder dataHolder = - BuilderGenerator.generate(mDimenResTypeWithBoxFloatArgSpecModel); - assertThat(dataHolder.getTypeSpecs()).hasSize(1); - assertThat(dataHolder.getTypeSpecs().get(0).toString()) - .isEqualTo( - "@com.facebook.litho.annotations.Generated\n" - + "public static final class Builder extends" - + " com.facebook.litho.Component.Builder {\n" - + " TestDimenResTypeWithBoxFloatArg mTestDimenResTypeWithBoxFloatArg;\n" - + "\n" - + " com.facebook.litho.ComponentContext mContext;\n" - + "\n" - + " private final java.lang.String[] REQUIRED_PROPS_NAMES = new String[]" - + " {\"size\"};\n" - + "\n" - + " private final int REQUIRED_PROPS_COUNT = 1;\n" - + "\n" - + " private final java.util.BitSet mRequired = new" - + " java.util.BitSet(REQUIRED_PROPS_COUNT);\n" - + "\n" - + " private Builder(com.facebook.litho.ComponentContext context, int defStyleAttr," - + " int defStyleRes,\n" - + " TestDimenResTypeWithBoxFloatArg testDimenResTypeWithBoxFloatArgRef) {\n" - + " super(context, defStyleAttr, defStyleRes," - + " testDimenResTypeWithBoxFloatArgRef);\n" - + " mTestDimenResTypeWithBoxFloatArg = testDimenResTypeWithBoxFloatArgRef;\n" - + " mContext = context;\n" - + " mRequired.clear();\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " protected void setComponent(com.facebook.litho.Component component) {\n" - + " mTestDimenResTypeWithBoxFloatArg =" - + " (com.facebook.litho.specmodels.generator.BuilderGeneratorTest.TestDimenResTypeWithBoxFloatArg)" - + " component;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"size\",\n" - + " required = true\n" - + " )\n" - + " @com.facebook.litho.annotations.RequiredProp(\"size\")\n" - + " public Builder sizePx(@androidx.annotation.Px float size) {\n" - + " this.mTestDimenResTypeWithBoxFloatArg.size = size;\n" - + " mRequired.set(0);\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"size\",\n" - + " required = true\n" - + " )\n" - + " @com.facebook.litho.annotations.RequiredProp(\"size\")\n" - + " public Builder sizeDip(\n" - + " @androidx.annotation.Dimension(unit = androidx.annotation.Dimension.DP)" - + " float dip) {\n" - + " this.mTestDimenResTypeWithBoxFloatArg.size = (float)" - + " mResourceResolver.dipsToPixels(dip);\n" - + " mRequired.set(0);\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"size\",\n" - + " required = true\n" - + " )\n" - + " @com.facebook.litho.annotations.RequiredProp(\"size\")\n" - + " public Builder sizeSp(\n" - + " @androidx.annotation.Dimension(unit = androidx.annotation.Dimension.SP)" - + " float sip) {\n" - + " this.mTestDimenResTypeWithBoxFloatArg.size = (float)" - + " mResourceResolver.sipsToPixels(sip);\n" - + " mRequired.set(0);\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"size\",\n" - + " required = true\n" - + " )\n" - + " @com.facebook.litho.annotations.RequiredProp(\"size\")\n" - + " public Builder sizeRes(@androidx.annotation.DimenRes int resId) {\n" - + " this.mTestDimenResTypeWithBoxFloatArg.size = (float)" - + " mResourceResolver.resolveDimenSizeRes(resId);\n" - + " mRequired.set(0);\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"size\",\n" - + " required = true\n" - + " )\n" - + " @com.facebook.litho.annotations.RequiredProp(\"size\")\n" - + " public Builder sizeAttr(@androidx.annotation.AttrRes int attrResId,\n" - + " @androidx.annotation.DimenRes int defResId) {\n" - + " this.mTestDimenResTypeWithBoxFloatArg.size = (float)" - + " mResourceResolver.resolveDimenSizeAttr(attrResId, defResId);\n" - + " mRequired.set(0);\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"size\",\n" - + " required = true\n" - + " )\n" - + " @com.facebook.litho.annotations.RequiredProp(\"size\")\n" - + " public Builder sizeAttr(@androidx.annotation.AttrRes int attrResId) {\n" - + " this.mTestDimenResTypeWithBoxFloatArg.size = (float)" - + " mResourceResolver.resolveDimenSizeAttr(attrResId, 0);\n" - + " mRequired.set(0);\n" - + " return this;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public Builder getThis() {\n" - + " return this;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public" - + " com.facebook.litho.specmodels.generator.BuilderGeneratorTest.TestDimenResTypeWithBoxFloatArg" - + " build(\n" - + " ) {\n" - + " checkArgs(REQUIRED_PROPS_COUNT, mRequired, REQUIRED_PROPS_NAMES);\n" - + " return mTestDimenResTypeWithBoxFloatArg;\n" - + " }\n" - + "}\n"); - } - - @Test - public void testVarArgsWithDefaultValue() { - TypeSpecDataHolder dataHolder = BuilderGenerator.generate(mVarArgsWithDefaultValueSpecModel); - assertThat(dataHolder.getTypeSpecs()).hasSize(1); - assertThat(dataHolder.getTypeSpecs().get(0).toString()) - .isEqualTo( - "@com.facebook.litho.annotations.Generated\n" - + "public static final class Builder extends" - + " com.facebook.litho.Component.Builder {\n" - + " TestVarArgsWithDefaultValue mTestVarArgsWithDefaultValue;\n" - + "\n" - + " com.facebook.litho.ComponentContext mContext;\n" - + "\n" - + " private Builder(com.facebook.litho.ComponentContext context, int defStyleAttr," - + " int defStyleRes,\n" - + " TestVarArgsWithDefaultValue testVarArgsWithDefaultValueRef) {\n" - + " super(context, defStyleAttr, defStyleRes, testVarArgsWithDefaultValueRef);\n" - + " mTestVarArgsWithDefaultValue = testVarArgsWithDefaultValueRef;\n" - + " mContext = context;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " protected void setComponent(com.facebook.litho.Component component) {\n" - + " mTestVarArgsWithDefaultValue =" - + " (com.facebook.litho.specmodels.generator.BuilderGeneratorTest.TestVarArgsWithDefaultValue)" - + " component;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"list\",\n" - + " required = false\n" - + " )\n" - + " public Builder item(java.lang.String item) {\n" - + " if (item == null) {\n" - + " return this;\n" - + " }\n" - + " if (this.mTestVarArgsWithDefaultValue.list == null ||" - + " this.mTestVarArgsWithDefaultValue.list == TestVarArgsWithDefaultValueSpec.list)" - + " {\n" - + " this.mTestVarArgsWithDefaultValue.list = new" - + " java.util.ArrayList();\n" - + " }\n" - + " this.mTestVarArgsWithDefaultValue.list.add(item);\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"list\",\n" - + " required = false\n" - + " )\n" - + " public Builder list(java.util.List list) {\n" - + " if (list == null) {\n" - + " return this;\n" - + " }\n" - + " if (this.mTestVarArgsWithDefaultValue.list == null ||" - + " this.mTestVarArgsWithDefaultValue.list.isEmpty() ||" - + " this.mTestVarArgsWithDefaultValue.list == TestVarArgsWithDefaultValueSpec.list)" - + " {\n" - + " this.mTestVarArgsWithDefaultValue.list = list;\n" - + " } else {\n" - + " this.mTestVarArgsWithDefaultValue.list.addAll(list);\n" - + " }\n" - + " return this;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public Builder getThis() {\n" - + " return this;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public" - + " com.facebook.litho.specmodels.generator.BuilderGeneratorTest.TestVarArgsWithDefaultValue" - + " build(\n" - + " ) {\n" - + " return mTestVarArgsWithDefaultValue;\n" - + " }\n" - + "}\n"); - } - - @Test - public void testKotlinVarArgWildcardsGenerate() { - TypeSpecDataHolder dataHolder = - BuilderGenerator.generate(mKotlinWildcardsVarArgBuildersSpecModel); - assertThat(dataHolder.getTypeSpecs()).hasSize(1); - assertThat(dataHolder.getTypeSpecs().get(0).toString()) - .isEqualTo( - "@com.facebook.litho.annotations.Generated\n" - + "public static final class Builder extends" - + " com.facebook.litho.Component.Builder {\n" - + " TestKotlinVarArg mTestKotlinVarArg;\n" - + "\n" - + " com.facebook.litho.ComponentContext mContext;\n" - + "\n" - + " private Builder(com.facebook.litho.ComponentContext context, int defStyleAttr," - + " int defStyleRes,\n" - + " TestKotlinVarArg testKotlinVarArgRef) {\n" - + " super(context, defStyleAttr, defStyleRes, testKotlinVarArgRef);\n" - + " mTestKotlinVarArg = testKotlinVarArgRef;\n" - + " mContext = context;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " protected void setComponent(com.facebook.litho.Component component) {\n" - + " mTestKotlinVarArg =" - + " (com.facebook.litho.specmodels.generator.BuilderGeneratorTest.TestKotlinVarArg)" - + " component;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"numbers\",\n" - + " required = false\n" - + " )\n" - + " public Builder number(java.lang.Number number) {\n" - + " if (number == null) {\n" - + " return this;\n" - + " }\n" - + " if (this.mTestKotlinVarArg.numbers == java.util.Collections.EMPTY_LIST) {\n" - + " this.mTestKotlinVarArg.numbers = new" - + " java.util.ArrayList();\n" - + " }\n" - + " this.mTestKotlinVarArg.numbers.add(number);\n" - + " return this;\n" - + " }\n" - + "\n" - + " @com.facebook.litho.annotations.PropSetter(\n" - + " value = \"numbers\",\n" - + " required = false\n" - + " )\n" - + " public Builder numbers(java.util.List numbers) {\n" - + " if (numbers == null) {\n" - + " return this;\n" - + " }\n" - + " if (this.mTestKotlinVarArg.numbers.isEmpty()) {\n" - + " this.mTestKotlinVarArg.numbers = numbers;\n" - + " } else {\n" - + " this.mTestKotlinVarArg.numbers.addAll(numbers);\n" - + " }\n" - + " return this;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public Builder getThis() {\n" - + " return this;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public" - + " com.facebook.litho.specmodels.generator.BuilderGeneratorTest.TestKotlinVarArg" - + " build() {\n" - + " return mTestKotlinVarArg;\n" - + " }\n" - + "}\n"); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/ComponentBodyGeneratorTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/generator/ComponentBodyGeneratorTest.java deleted file mode 100644 index 63ab5b35dd8..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/ComponentBodyGeneratorTest.java +++ /dev/null @@ -1,583 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.generator; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import androidx.annotation.Nullable; -import com.facebook.litho.Component; -import com.facebook.litho.ComponentContext; -import com.facebook.litho.Row; -import com.facebook.litho.annotations.LayoutSpec; -import com.facebook.litho.annotations.MountSpec; -import com.facebook.litho.annotations.OnBind; -import com.facebook.litho.annotations.OnCreateLayout; -import com.facebook.litho.annotations.OnEvent; -import com.facebook.litho.annotations.OnUpdateState; -import com.facebook.litho.annotations.OnUpdateStateWithTransition; -import com.facebook.litho.annotations.Param; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.annotations.PropDefault; -import com.facebook.litho.annotations.State; -import com.facebook.litho.annotations.TreeProp; -import com.facebook.litho.specmodels.internal.ImmutableList; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.model.ClassNames; -import com.facebook.litho.specmodels.model.EventDeclarationModel; -import com.facebook.litho.specmodels.model.LayoutSpecModel; -import com.facebook.litho.specmodels.model.PropModel; -import com.facebook.litho.specmodels.model.SpecModel; -import com.facebook.litho.specmodels.model.SpecModelUtils; -import com.facebook.litho.specmodels.model.StateParamModel; -import com.facebook.litho.specmodels.model.TypeSpec; -import com.facebook.litho.specmodels.model.TypeSpec.DeclaredTypeSpec; -import com.facebook.litho.specmodels.processor.LayoutSpecModelFactory; -import com.facebook.litho.specmodels.processor.MountSpecModelFactory; -import com.google.testing.compile.CompilationRule; -import com.squareup.javapoet.AnnotationSpec; -import com.squareup.javapoet.ClassName; -import com.squareup.javapoet.FieldSpec; -import com.squareup.javapoet.MethodSpec; -import java.util.Arrays; -import java.util.List; -import java.util.Set; -import java.util.function.Predicate; -import javax.annotation.processing.Messager; -import javax.lang.model.element.Element; -import javax.lang.model.element.Modifier; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -/** Tests {@link ComponentBodyGenerator} */ -@RunWith(JUnit4.class) -public class ComponentBodyGeneratorTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - @Mock private Messager mMessager; - - private final LayoutSpecModelFactory mLayoutSpecModelFactory = new LayoutSpecModelFactory(); - private final MountSpecModelFactory mMountSpecModelFactory = new MountSpecModelFactory(); - - @LayoutSpec - static class TestSpec { - @PropDefault protected static boolean arg0 = true; - @PropDefault protected static boolean isarg10 = true; - - @OnCreateLayout - public void testDelegateMethod( - @Prop boolean arg0, - @State int arg1, - @Param Object arg2, - @TreeProp long arg3, - @Prop @Nullable Component arg4, - @Prop List arg5, - @Prop List arg6, - @TreeProp Set> arg7, - @TreeProp Set arg8, - @Prop(varArg = "item") java.util.List arg9, - @Prop(optional = true) boolean isarg10) {} - - @OnEvent(Object.class) - public void testEventMethod( - @Prop boolean arg0, - @State int arg1, - @Param Object arg2, - @TreeProp long arg3, - @Prop @Nullable Component arg4) {} - - @OnUpdateState - public void testUpdateStateMethod() {} - } - - @MountSpec - static class MountTestSpec { - @PropDefault protected static boolean arg0 = true; - - @OnBind - public void testDelegateMethod( - @Prop boolean arg0, - @Prop @Nullable Component arg4, - @Prop List arg5, - @Prop List arg6, - @State int arg1, - @Param Object arg2, - @TreeProp long arg3, - @TreeProp Set> arg7, - @TreeProp Set arg8, - @Prop(dynamic = true) Object arg9) {} - - @OnEvent(Object.class) - public void testEventMethod( - @Prop boolean arg0, - @Prop @Nullable Component arg4, - @State int arg1, - @Param Object arg2, - @TreeProp long arg3) {} - - @OnUpdateState - public void testUpdateStateMethod() {} - } - - @LayoutSpec - static class TestWithTransitionSpec { - @PropDefault protected static boolean arg0 = true; - - @OnCreateLayout - public void testDelegateMethod( - @Prop boolean arg0, - @State int arg1, - @Param Object arg2, - @TreeProp long arg3, - @Prop List arg6, - @TreeProp Set> arg7, - @TreeProp Set arg8) {} - - @OnUpdateStateWithTransition - public void testUpdateStateWithTransitionMethod() {} - } - - @LayoutSpec - static class TestKotlinWildcardsSpec { - public static final TestKotlinWildcardsSpec INSTANCE = null; - - private static final boolean isArg1 = true; - private static final boolean arg2 = true; - - @PropDefault - public final boolean isArg1() { - return isArg1; - } - - @PropDefault - public final boolean getArg2() { - return arg2; - } - - @OnCreateLayout - public final Component onCreateLayout( - ComponentContext c, - @Prop(varArg = "number") java.util.List numbers, - @Prop(optional = true) boolean isArg1, - @Prop(optional = true) boolean arg2) { - return null; - } - } - - @LayoutSpec - static class PropsTestingComponentSpec { - - @OnCreateLayout - static Component onCreateLayout( - ComponentContext c, - @Prop int intProp, - @Prop(optional = true) int optionIntProp, - @Nullable @TreeProp String treeProp) { - return null; - } - } - - private SpecModel mSpecModelDI; - private SpecModel mMountSpecModelDI; - private SpecModel mSpecModelWithTransitionDI; - private SpecModel mKotlinWildcardsSpecModel; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - Elements elements = mCompilationRule.getElements(); - Types types = mCompilationRule.getTypes(); - TypeElement typeElement = elements.getTypeElement(TestSpec.class.getCanonicalName()); - mSpecModelDI = - mLayoutSpecModelFactory.create( - elements, types, typeElement, mMessager, RunMode.normal(), null, null); - // Here we are using the TestSpec that is declared as LayoutSpec but, because using - // the MountSpecModelFactory, is it going to be used as MountSpec anyway. - mMountSpecModelDI = - mMountSpecModelFactory.create( - elements, - types, - elements.getTypeElement(MountTestSpec.class.getCanonicalName()), - mMessager, - RunMode.normal(), - null, - null); - - TypeElement typeElementWithTransition = - elements.getTypeElement(TestWithTransitionSpec.class.getCanonicalName()); - mSpecModelWithTransitionDI = - mLayoutSpecModelFactory.create( - elements, types, typeElementWithTransition, mMessager, RunMode.normal(), null, null); - - TypeElement typeElementKotlinVarArgsWildcards = - elements.getTypeElement(TestKotlinWildcardsSpec.class.getCanonicalName()); - mKotlinWildcardsSpecModel = - mLayoutSpecModelFactory.create( - elements, - types, - typeElementKotlinVarArgsWildcards, - mMessager, - RunMode.normal(), - null, - null); - } - - @Test - public void testGenerateStateContainerImplGetter() { - assertThat( - ComponentBodyGenerator.generateStateContainerImplGetter( - mSpecModelDI, ClassNames.STATE_CONTAINER) - .toString()) - .isEqualTo( - "private com.facebook.litho.StateContainer getStateContainerImpl(\n" - + " com.facebook.litho.ComponentContext c) {\n" - + " return (com.facebook.litho.StateContainer)" - + " c.getScopedComponentInfo().getStateContainer();\n" - + "}\n"); - } - - @Test - public void testGenerateProps() { - TypeSpecDataHolder dataHolder = - ComponentBodyGenerator.generateProps(mSpecModelDI, RunMode.normal()); - assertThat(dataHolder.getFieldSpecs()).hasSize(6); - assertThat(dataHolder.getFieldSpecs().get(0).toString()) - .isEqualTo( - "@com.facebook.litho.annotations.Prop(\n" - + " resType = com.facebook.litho.annotations.ResType.NONE,\n" - + " optional = false\n" - + ")\n" - + "@com.facebook.litho.annotations.Comparable(\n" - + " type = 3\n" - + ")\n" - + "boolean arg0 = TestSpec.arg0;\n"); - assertThat(dataHolder.getFieldSpecs().get(1).toString()) - .isEqualTo( - "@androidx.annotation.Nullable\n" - + "@com.facebook.litho.annotations.Prop(\n" - + " resType = com.facebook.litho.annotations.ResType.NONE,\n" - + " optional = false\n" - + ")\n" - + "@com.facebook.litho.annotations.Comparable(\n" - + " type = 10\n" - + ")\n" - + "com.facebook.litho.Component arg4;\n"); - - assertThat(dataHolder.getFieldSpecs().get(4).toString()) - .isEqualTo( - "@com.facebook.litho.annotations.Prop(\n" - + " resType = com.facebook.litho.annotations.ResType.NONE,\n" - + " optional = true,\n" - + " varArg = \"item\"\n" - + ")\n" - + "@com.facebook.litho.annotations.Comparable(\n" - + " type = 5\n" - + ")\n" - + "java.util.List arg9 =" - + " java.util.Collections.emptyList();\n"); - assertThat(dataHolder.getFieldSpecs().get(5).toString()) - .isEqualTo( - "@com.facebook.litho.annotations.Prop(\n" - + " resType = com.facebook.litho.annotations.ResType.NONE,\n" - + " optional = true\n" - + ")\n" - + "@com.facebook.litho.annotations.Comparable(\n" - + " type = 3\n" - + ")\n" - + "boolean isarg10 = TestSpec.isarg10;\n"); - - dataHolder = ComponentBodyGenerator.generateProps(mMountSpecModelDI, RunMode.normal()); - assertThat(dataHolder.getFieldSpecs()).hasSize(6); - assertThat(dataHolder.getFieldSpecs().get(4).toString()) - .isEqualTo( - "@com.facebook.litho.annotations.Prop(\n" - + " resType = com.facebook.litho.annotations.ResType.NONE,\n" - + " optional = false\n" - + ")\n" - + "@com.facebook.litho.annotations.Comparable(\n" - + " type = 13\n" - + ")\n" - + "com.facebook.litho.DynamicValue arg9;\n"); - - assertThat(dataHolder.getFieldSpecs().get(5).toString()) - .isEqualTo("private com.facebook.litho.DynamicValue[] mDynamicProps;\n"); - } - - @Test - public void whenComponentIsGeneratedFromTest_shouldHavePublicProps() { - final Elements elements = mCompilationRule.getElements(); - final Types types = mCompilationRule.getTypes(); - final TypeElement type = - elements.getTypeElement(PropsTestingComponentSpec.class.getCanonicalName()); - final LayoutSpecModel model = - mLayoutSpecModelFactory.create( - elements, types, type, mMessager, RunMode.testing(), null, null); - final TypeSpecDataHolder holder = - ComponentBodyGenerator.generate(model, null, RunMode.testing()); - - final Predicate matcher = - annotation -> - annotation.type.equals(ClassName.get(Prop.class)) - || annotation.type.equals(ClassName.get(TreeProp.class)); - - final FieldSpec[] props = - holder.getFieldSpecs().stream() - .filter(field -> field.annotations.stream().anyMatch(matcher)) - .toArray(FieldSpec[]::new); - final MethodSpec[] getters = - holder.getMethodSpecs().stream() - .filter(method -> method.annotations.stream().anyMatch(matcher)) - .toArray(MethodSpec[]::new); - - assertThat(getters.length) - .describedAs("number of getters should be equal to the number of props") - .isEqualTo(props.length); - - Arrays.stream(getters) - .forEach(methodSpec -> assertThat(methodSpec.modifiers).contains(Modifier.PUBLIC)); - } - - @Test - public void testGeneratePropsForKotlinWildcards() { - TypeSpecDataHolder dataHolder = - ComponentBodyGenerator.generateProps(mKotlinWildcardsSpecModel, RunMode.normal()); - assertThat(dataHolder.getFieldSpecs()).hasSize(3); - assertThat(dataHolder.getFieldSpecs().get(0).toString()) - .isEqualTo( - "@com.facebook.litho.annotations.Prop(\n" - + " resType = com.facebook.litho.annotations.ResType.NONE,\n" - + " optional = true\n" - + ")\n" - + "@com.facebook.litho.annotations.Comparable(\n" - + " type = 3\n" - + ")\n" - + "boolean arg2 = TestKotlinWildcardsSpec.INSTANCE.getArg2();\n"); - assertThat(dataHolder.getFieldSpecs().get(1).toString()) - .isEqualTo( - "@com.facebook.litho.annotations.Prop(\n" - + " resType = com.facebook.litho.annotations.ResType.NONE,\n" - + " optional = true\n" - + ")\n" - + "@com.facebook.litho.annotations.Comparable(\n" - + " type = 3\n" - + ")\n" - + "boolean isArg1 = TestKotlinWildcardsSpec.INSTANCE.isArg1();\n"); - assertThat(dataHolder.getFieldSpecs().get(2).toString()) - .isEqualTo( - "@com.facebook.litho.annotations.Prop(\n" - + " resType = com.facebook.litho.annotations.ResType.NONE,\n" - + " optional = true,\n" - + " varArg = \"number\"\n" - + ")\n" - + "@com.facebook.litho.annotations.Comparable(\n" - + " type = 5\n" - + ")\n" - + "java.util.List numbers =" - + " java.util.Collections.emptyList();\n"); - } - - @Test - public void testGenerateTreeProps() { - TypeSpecDataHolder dataHolder = - ComponentBodyGenerator.generateTreeProps(mSpecModelDI, RunMode.normal()); - assertThat(dataHolder.getFieldSpecs()).hasSize(3); - assertThat(dataHolder.getFieldSpecs().get(0).toString()) - .isEqualTo( - "@com.facebook.litho.annotations.TreeProp\n" - + "@com.facebook.litho.annotations.Comparable(\n" - + " type = 3\n" - + ")\n" - + "long arg3;\n"); - } - - @Test - public void testGenerateInterStageInputs() { - TypeSpecDataHolder dataHolder = ComponentBodyGenerator.generateInterStageInputs(mSpecModelDI); - assertThat(dataHolder.getFieldSpecs()).hasSize(0); - } - - @Test - public void testGenerateEventDeclarations() { - SpecModel specModel = mock(SpecModel.class); - when(specModel.getEventDeclarations()) - .thenReturn( - ImmutableList.of( - new EventDeclarationModel( - ClassName.OBJECT, ClassName.OBJECT, ImmutableList.of(), null))); - - TypeSpecDataHolder dataHolder = ComponentBodyGenerator.generateEventHandlers(specModel); - assertThat(dataHolder.getFieldSpecs()).hasSize(1); - assertThat(dataHolder.getFieldSpecs().get(0).toString()) - .isEqualTo( - "@androidx.annotation.Nullable\n" - + "com.facebook.litho.EventHandler objectHandler;\n"); - } - - @Test - public void testGenerateIsEquivalentMethod() { - assertThat( - ComponentBodyGenerator.generateIsEquivalentPropsMethod( - mMountSpecModelDI, RunMode.normal()) - .toString()) - .isEqualTo( - "@java.lang.Override\n" - + "public boolean isEquivalentProps(com.facebook.litho.Component other,\n" - + " boolean shouldCompareCommonProps) {\n" - + " if (this == other) {\n" - + " return true;\n" - + " }\n" - + " if (other == null || getClass() != other.getClass()) {\n" - + " return false;\n" - + " }\n" - + " MountTest mountTestRef = (MountTest) other;\n" - + " if (arg0 != mountTestRef.arg0) {\n" - + " return false;\n" - + " }\n" - + " if (arg4 != null ? !arg4.isEquivalentTo(mountTestRef.arg4," - + " shouldCompareCommonProps) : mountTestRef.arg4 != null) {\n" - + " return false;\n" - + " }\n" - + " if (arg5 != null) {\n" - + " if (mountTestRef.arg5 == null || arg5.size() != mountTestRef.arg5.size())" - + " {\n" - + " return false;\n" - + " }\n" - + " java.util.Iterator _e1_1 = arg5.iterator();\n" - + " java.util.Iterator _e2_1 =" - + " mountTestRef.arg5.iterator();\n" - + " while (_e1_1.hasNext() && _e2_1.hasNext()) {\n" - + " if (!_e1_1.next().isEquivalentTo(_e2_1.next())) {\n" - + " return false;\n" - + " }\n" - + " }\n" - + " } else if (mountTestRef.arg5 != null) {\n" - + " return false;\n" - + " }\n" - + " if (arg6 != null ? !arg6.equals(mountTestRef.arg6) : mountTestRef.arg6 !=" - + " null) {\n" - + " return false;\n" - + " }\n" - + " if (arg9 != null ? !arg9.equals(mountTestRef.arg9) : mountTestRef.arg9 !=" - + " null) {\n" - + " return false;\n" - + " }\n" - + " return true;\n" - + "}\n"); - } - - @Test - public void testGetDynamicProps() { - TypeSpecDataHolder dataHolder = ComponentBodyGenerator.generateGetDynamicProps(mSpecModelDI); - assertThat(dataHolder.getMethodSpecs()).isEmpty(); - - dataHolder = ComponentBodyGenerator.generateGetDynamicProps(mMountSpecModelDI); - assertThat(dataHolder.getMethodSpecs()).hasSize(1); - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "@java.lang.Override\n" - + "protected com.facebook.litho.DynamicValue[] getDynamicProps() {\n" - + " return mDynamicProps;\n" - + "}\n"); - } - - @Test - public void testGenerateStateParamImplAccessor() { - StateParamModel stateParamModel = mock(StateParamModel.class); - when(stateParamModel.getName()).thenReturn("stateParam"); - assertThat( - ComponentBodyGenerator.getImplAccessor( - "testMethod", mSpecModelDI, stateParamModel, "c")) - .isEqualTo("getStateContainerImpl(c).stateParam"); - } - - @Test - public void testGeneratePropParamImplAccessor() { - PropModel propModel = mock(PropModel.class); - when(propModel.getName()).thenReturn("propParam"); - assertThat(ComponentBodyGenerator.getImplAccessor("testMethod", mSpecModelDI, propModel, "c")) - .isEqualTo("propParam"); - } - - @Test - public void testCalculateLevelOfComponentInCollections() { - Elements elements = mCompilationRule.getElements(); - TypeElement typeElement = elements.getTypeElement(CollectionObject.class.getCanonicalName()); - List fields = typeElement.getEnclosedElements(); - TypeSpec arg0 = SpecModelUtils.generateTypeSpec(fields.get(0).asType()); - TypeSpec arg1 = SpecModelUtils.generateTypeSpec(fields.get(1).asType()); - TypeSpec arg2 = SpecModelUtils.generateTypeSpec(fields.get(2).asType()); - - assertThat(arg0.getClass()).isEqualTo(DeclaredTypeSpec.class); - assertThat(arg1.getClass()).isEqualTo(DeclaredTypeSpec.class); - assertThat(arg2.getClass()).isEqualTo(DeclaredTypeSpec.class); - assertThat( - ComponentBodyGenerator.calculateLevelOfComponentInCollections((DeclaredTypeSpec) arg0)) - .isEqualTo(1); - assertThat( - ComponentBodyGenerator.calculateLevelOfComponentInCollections((DeclaredTypeSpec) arg1)) - .isEqualTo(2); - assertThat( - ComponentBodyGenerator.calculateLevelOfComponentInCollections((DeclaredTypeSpec) arg2)) - .isEqualTo(0); - } - - @Test - public void testGenerateMakeShallowCopyWithStateUpdate() { - TypeSpecDataHolder typeSpecDataHolder = - ComponentBodyGenerator.generateMakeShallowCopy(mSpecModelDI, true); - assertThat(typeSpecDataHolder.getMethodSpecs().size()).isEqualTo(1); - - assertThat(typeSpecDataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "@java.lang.Override\n" - + "public Test makeShallowCopy() {\n" - + " Test component = (Test) super.makeShallowCopy();\n" - + " component.arg4 = component.arg4 != null ? component.arg4.makeShallowCopy() :" - + " null;\n" - + " return component;\n" - + "}\n"); - } - - @Test - public void testGenerateMakeShallowCopyWithOnlyStateUpdateWithTransition() { - TypeSpecDataHolder typeSpecDataHolder = - ComponentBodyGenerator.generateMakeShallowCopy(mSpecModelWithTransitionDI, true); - assertThat(typeSpecDataHolder.getMethodSpecs().size()).isEqualTo(1); - - assertThat(typeSpecDataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "@java.lang.Override\n" - + "public TestWithTransition makeShallowCopy() {\n" - + " TestWithTransition component = (TestWithTransition) super.makeShallowCopy();\n" - + " return component;\n" - + "}\n"); - } - - private static class CollectionObject { - List arg0; - List> arg1; - Set>> arg2; - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/DynamicPropsEquivalenceGeneratorTest.kt b/litho-it/src/test/java/com/facebook/litho/specmodels/generator/DynamicPropsEquivalenceGeneratorTest.kt deleted file mode 100644 index e0dfe1051a1..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/DynamicPropsEquivalenceGeneratorTest.kt +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.generator - -import com.facebook.litho.annotations.MountSpec -import com.facebook.litho.annotations.OnBind -import com.facebook.litho.annotations.Prop -import com.facebook.litho.specmodels.internal.RunMode -import com.facebook.litho.specmodels.processor.MountSpecModelFactory -import com.google.testing.compile.CompilationRule -import org.assertj.core.api.Assertions.assertThat -import org.junit.Rule -import org.junit.Test -import org.junit.runner.RunWith -import org.junit.runners.JUnit4 - -@MountSpec -object MountTestSpec { - @OnBind - fun onBind( - @Prop(dynamic = true) intArg: Int, - @Prop(dynamic = true) longArg: Long, - @Prop(dynamic = true) floatArg: Float, - @Prop(dynamic = true) doubleArg: Double, - @Prop(dynamic = true) objectArg: Any? - ) = Unit -} - -@RunWith(JUnit4::class) -class DynamicPropsEquivalenceGeneratorTest { - - @Rule @JvmField val compilationRule = CompilationRule() - - @Test - fun `test dynamic prop equivalency checks only compare refs`() { - val mountSpecModel = - MountSpecModelFactory() - .create( - compilationRule.elements, - compilationRule.types, - compilationRule.elements.getTypeElement(MountTestSpec::class.java.canonicalName), - null, - RunMode.normal(), - null, - null) - - val generatedIsEquivalentMethod = - ComponentBodyGenerator.generateIsEquivalentPropsMethod(mountSpecModel, RunMode.normal()) - .toString() - - assertThat(generatedIsEquivalentMethod) - .isEqualTo( - """ - @java.lang.Override - public boolean isEquivalentProps(com.facebook.litho.Component other, - boolean shouldCompareCommonProps) { - if (this == other) { - return true; - } - if (other == null || getClass() != other.getClass()) { - return false; - } - MountTest mountTestRef = (MountTest) other; - if (doubleArg != null ? !doubleArg.equals(mountTestRef.doubleArg) : mountTestRef.doubleArg != null) { - return false; - } - if (floatArg != null ? !floatArg.equals(mountTestRef.floatArg) : mountTestRef.floatArg != null) { - return false; - } - if (intArg != null ? !intArg.equals(mountTestRef.intArg) : mountTestRef.intArg != null) { - return false; - } - if (longArg != null ? !longArg.equals(mountTestRef.longArg) : mountTestRef.longArg != null) { - return false; - } - if (objectArg != null ? !objectArg.equals(mountTestRef.objectArg) : mountTestRef.objectArg != null) { - return false; - } - return true; - } - - """ - .trimIndent()) - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/EventGeneratorTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/generator/EventGeneratorTest.java deleted file mode 100644 index b5fe67d8d8e..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/EventGeneratorTest.java +++ /dev/null @@ -1,765 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.generator; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import androidx.annotation.Nullable; -import com.facebook.litho.ComponentContext; -import com.facebook.litho.annotations.Event; -import com.facebook.litho.annotations.EventHandlerRebindMode; -import com.facebook.litho.annotations.FromEvent; -import com.facebook.litho.annotations.LayoutSpec; -import com.facebook.litho.annotations.OnEvent; -import com.facebook.litho.annotations.Param; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.annotations.PropDefault; -import com.facebook.litho.annotations.State; -import com.facebook.litho.specmodels.internal.ImmutableList; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.model.ClassNames; -import com.facebook.litho.specmodels.model.EventDeclarationModel; -import com.facebook.litho.specmodels.model.EventMethod; -import com.facebook.litho.specmodels.model.FieldModel; -import com.facebook.litho.specmodels.model.MethodParamModel; -import com.facebook.litho.specmodels.model.SimpleMethodParamModel; -import com.facebook.litho.specmodels.model.SpecMethodModel; -import com.facebook.litho.specmodels.model.SpecModel; -import com.facebook.litho.specmodels.model.TypeSpec; -import com.facebook.litho.specmodels.processor.LayoutSpecModelFactory; -import com.google.testing.compile.CompilationRule; -import com.squareup.javapoet.ClassName; -import com.squareup.javapoet.FieldSpec; -import com.squareup.javapoet.MethodSpec; -import com.squareup.javapoet.ParameterizedTypeName; -import com.squareup.javapoet.TypeName; -import com.squareup.javapoet.TypeVariableName; -import java.lang.annotation.Annotation; -import java.util.List; -import java.util.Set; -import javax.annotation.processing.Messager; -import javax.lang.model.element.Modifier; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests {@link EventGenerator} */ -@RunWith(JUnit4.class) -public class EventGeneratorTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - - private final LayoutSpecModelFactory mLayoutSpecModelFactory = new LayoutSpecModelFactory(); - - @LayoutSpec - static class TestSpec { - @PropDefault protected static final boolean arg0 = true; - - @OnEvent(Object.class) - public static void testEventMethod1( - ComponentContext c, - @Prop boolean arg0, - @State int arg1, - @Param Object arg2, - @Param T arg3, - @FromEvent long arg4, - @Param @Nullable T arg6) {} - - @OnEvent(Object.class) - public static void testEventMethod2( - ComponentContext c, - @Prop boolean arg0, - @State int arg1, - @State(canUpdateLazily = true) long arg5) {} - } - - @LayoutSpec(events = {CustomEvent.class}) - static class CustomEventTestSpec {} - - @Event - static class CustomEvent { - public Object nonnullObject; - public @Nullable Object nullableObject; - } - - private SpecModel mSpecModel; - private SpecModel mCustomEventSpecModel; - private final SpecModel mMockSpecModel = mock(SpecModel.class); - - @Before - public void setUp() { - Elements elements = mCompilationRule.getElements(); - Types types = mCompilationRule.getTypes(); - TypeElement typeElement = elements.getTypeElement(TestSpec.class.getCanonicalName()); - mSpecModel = - mLayoutSpecModelFactory.create( - elements, types, typeElement, mock(Messager.class), RunMode.normal(), null, null); - mCustomEventSpecModel = - mLayoutSpecModelFactory.create( - elements, - types, - elements.getTypeElement(CustomEventTestSpec.class.getCanonicalName()), - mock(Messager.class), - RunMode.normal(), - null, - null); - - EventDeclarationModel eventDeclarationModel = - new EventDeclarationModel( - ClassName.OBJECT, - ClassName.OBJECT, - ImmutableList.of( - new FieldModel( - FieldSpec.builder(TypeName.INT, "field1", Modifier.PUBLIC).build(), - new Object()), - new FieldModel( - FieldSpec.builder(TypeName.INT, "field2", Modifier.PUBLIC).build(), - new Object())), - new Object()); - when(mMockSpecModel.getEventDeclarations()).thenReturn(ImmutableList.of(eventDeclarationModel)); - when(mMockSpecModel.getContextClass()).thenReturn(ClassNames.COMPONENT_CONTEXT); - when(mMockSpecModel.getComponentName()).thenReturn("Test"); - when(mMockSpecModel.getScopeMethodName()).thenReturn("getComponentScope"); - when(mMockSpecModel.getTypeVariables()).thenReturn(ImmutableList.of()); - } - - @Test - public void testGenerateEventMethods() { - TypeSpecDataHolder dataHolder = EventGenerator.generateEventMethods(mSpecModel); - - assertThat(dataHolder.getMethodSpecs()).hasSize(2); - - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "private void testEventMethod1(\n" - + " com.facebook.litho.HasEventDispatcher _abstract," - + " com.facebook.litho.ComponentContext c,\n" - + " java.lang.Object arg2, T arg3, @androidx.annotation.Nullable T arg6) {\n" - + " Test _ref = (Test) _abstract;\n" - + " TestStateContainer _state = getStateContainerImpl(c);\n" - + " TestSpec.testEventMethod1(\n" - + " c,\n" - + " (boolean) _ref.arg0,\n" - + " (int) _state.arg1,\n" - + " arg2,\n" - + " arg3,\n" - + " (long) _ref.arg4,\n" - + " arg6);\n" - + "}\n"); - - assertThat(dataHolder.getMethodSpecs().get(1).toString()) - .isEqualTo( - "private void testEventMethod2(com.facebook.litho.HasEventDispatcher _abstract,\n" - + " com.facebook.litho.ComponentContext c) {\n" - + " Test _ref = (Test) _abstract;\n" - + " TestStateContainer _state = getStateContainerWithLazyStateUpdatesApplied(c," - + " _ref);\n" - + " TestSpec.testEventMethod2(\n" - + " c,\n" - + " (boolean) _ref.arg0,\n" - + " (int) _state.arg1,\n" - + " (long) _state.arg5);\n" - + "}\n"); - } - - @Test - public void testGenerateEventHandlerFactories() { - TypeSpecDataHolder dataHolder = EventGenerator.generateEventHandlerFactories(mSpecModel); - - assertThat(dataHolder.getMethodSpecs()).hasSize(2); - - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "public static " - + " com.facebook.litho.EventHandler testEventMethod1(\n" - + " com.facebook.litho.ComponentContext c, java.lang.Object arg2, T arg3,\n" - + " @androidx.annotation.Nullable T arg6) {\n" - + " return newEventHandler(Test.class, \"Test\", c, -1400079064, new Object[] {\n" - + " arg2,\n" - + " arg3,\n" - + " arg6,\n" - + " }, com.facebook.litho.annotations.EventHandlerRebindMode.REBIND);\n" - + "}\n"); - - assertThat(dataHolder.getMethodSpecs().get(1).toString()) - .isEqualTo( - "public static com.facebook.litho.EventHandler testEventMethod2(\n" - + " com.facebook.litho.ComponentContext c) {\n" - + " return newEventHandler(Test.class, \"Test\", c, -1400079063, null," - + " com.facebook.litho.annotations.EventHandlerRebindMode.REBIND);\n" - + "}\n"); - } - - @Test - public void testGenerateDispatchOnEvent() { - assertThat(EventGenerator.generateDispatchOnEventImpl(mSpecModel).toString()) - .isEqualTo( - "@java.lang.Override\n" - + "protected java.lang.Object dispatchOnEventImpl(final" - + " com.facebook.litho.EventHandler eventHandler,\n" - + " final java.lang.Object eventState) {\n" - + " int id = eventHandler.id;\n" - + " switch (id) {\n" - + " // testEventMethod1\n" - + " case -1400079064: {\n" - + " java.lang.Object _event = (java.lang.Object) eventState;\n" - + " testEventMethod1(\n" - + " eventHandler.dispatchInfo.hasEventDispatcher,\n" - + " (com.facebook.litho.ComponentContext)" - + " eventHandler.dispatchInfo.componentContext,\n" - + " (java.lang.Object) eventHandler.params[0],\n" - + " (java.lang.CharSequence) eventHandler.params[1],\n" - + " (java.lang.CharSequence) eventHandler.params[2]);\n" - + " return null;\n" - + " }\n" - + " // testEventMethod2\n" - + " case -1400079063: {\n" - + " java.lang.Object _event = (java.lang.Object) eventState;\n" - + " testEventMethod2(\n" - + " eventHandler.dispatchInfo.hasEventDispatcher,\n" - + " (com.facebook.litho.ComponentContext)" - + " eventHandler.dispatchInfo.componentContext);\n" - + " return null;\n" - + " }\n" - + " // __internalOnErrorHandler\n" - + " case -1048037474: {\n" - + " dispatchErrorEvent((com.facebook.litho.ComponentContext)" - + " eventHandler.dispatchInfo.componentContext, (com.facebook.litho.ErrorEvent)" - + " eventState);\n" - + " return null;\n" - + " }\n" - + " default:\n" - + " return null;\n" - + " }\n" - + "}\n"); - } - - @Test - public void testGetEventHandlerMethods() { - TypeSpecDataHolder dataHolder = EventGenerator.generateGetEventHandlerMethods(mMockSpecModel); - - assertThat(dataHolder.getMethodSpecs()).hasSize(1); - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "@androidx.annotation.Nullable\n" - + "public static com.facebook.litho.EventHandler" - + " getObjectHandler(\n" - + " com.facebook.litho.ComponentContext context) {\n" - + " if (context.getComponentScope() == null) {\n" - + " return null;\n" - + " }\n" - + " return ((Test) context.getComponentScope()).objectHandler;\n" - + "}\n"); - } - - @Test - public void testGenerateEventDispatchers() { - TypeSpecDataHolder dataHolder = EventGenerator.generateEventDispatchers(mMockSpecModel); - - assertThat(dataHolder.getMethodSpecs()).hasSize(1); - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "static java.lang.Object dispatchObject(com.facebook.litho.EventHandler _eventHandler," - + " int field1,\n" - + " int field2) {\n" - + " final java.lang.Object _eventState = new java.lang.Object();\n" - + " _eventState.field1 = field1;\n" - + " _eventState.field2 = field2;\n" - + " return (java.lang.Object) _eventHandler.dispatchEvent(_eventState);\n" - + "}\n"); - } - - @Test - public void testGenerateEventDispatchersIgnoresGenericTypesInFields() { - FieldModel fieldWithTypeArguments = - new FieldModel( - FieldSpec.builder( - ParameterizedTypeName.get(List.class, String.class), "field1", Modifier.PUBLIC) - .build(), - new Object()); - - EventDeclarationModel eventDeclarationModel = - new EventDeclarationModel( - ClassName.OBJECT, - ClassName.OBJECT, - ImmutableList.of(fieldWithTypeArguments), - new Object()); - when(mMockSpecModel.getEventDeclarations()).thenReturn(ImmutableList.of(eventDeclarationModel)); - - TypeSpecDataHolder dataHolder = EventGenerator.generateEventDispatchers(mMockSpecModel); - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "static java.lang.Object dispatchObject(com.facebook.litho.EventHandler" - + " _eventHandler,\n" - + " java.util.List field1) {\n" - + " final java.lang.Object _eventState = new java.lang.Object();\n" - + " _eventState.field1 = field1;\n" - + " return (java.lang.Object) _eventHandler.dispatchEvent(_eventState);\n" - + "}\n"); - } - - @Test - public void - whenEventDispatcherIsGeneratedFromCustomEventTest_EventFieldAnnotationsArePassedToParams() { - final TypeSpecDataHolder holder = - EventGenerator.generateEventDispatchers(mCustomEventSpecModel); - final MethodSpec[] methodSpecs = - holder.getMethodSpecs().stream() - .filter(method -> method.name.equals("dispatchCustomEvent")) - .toArray(MethodSpec[]::new); - - assertThat(methodSpecs.length) - .describedAs("we should have exact one dispatch method for CustomEvent") - .isEqualTo(1); - assertThat(methodSpecs[0].toString()) - .isEqualTo( - "static void dispatchCustomEvent(com.facebook.litho.EventHandler _eventHandler,\n" - + " java.lang.Object nonnullObject, @androidx.annotation.Nullable" - + " java.lang.Object nullableObject) {\n" - + " final com.facebook.litho.specmodels.generator.EventGeneratorTest.CustomEvent" - + " _eventState = new" - + " com.facebook.litho.specmodels.generator.EventGeneratorTest.CustomEvent();\n" - + " _eventState.nonnullObject = nonnullObject;\n" - + " _eventState.nullableObject = nullableObject;\n" - + " _eventHandler.dispatchEvent(_eventState);\n" - + "}\n"); - } - - @Test - public void whenEventHandlerWithGenericTypedVariables_shouldGenerateTypedEventHandlerFactory() { - final TypeVariableName typeM = TypeVariableName.get("M"); - final TypeVariableName typeN = TypeVariableName.get("N"); - final ParameterizedTypeName eventClass = - ParameterizedTypeName.get(ClassName.bestGuess("EventClass"), typeM, typeN); - - EventDeclarationModel eventModel = - new EventDeclarationModel( - eventClass, - ClassName.VOID, - ImmutableList.of( - new FieldModel( - FieldSpec.builder(typeM, "field1", Modifier.PUBLIC).build(), new Object()), - new FieldModel( - FieldSpec.builder(typeN, "field2", Modifier.PUBLIC).build(), new Object())), - new Object()); - - ImmutableList params = - ImmutableList.of( - new SimpleMethodParamModel( - new TypeSpec(ClassNames.COMPONENT_CONTEXT), - "c", - ImmutableList.of(), - ImmutableList.of(), - new Object()), - new SimpleMethodParamModel( - new TypeSpec(ClassName.bestGuess("FirstType")), - "field1", - ImmutableList.of((Annotation) () -> FromEvent.class), - ImmutableList.of(), - new Object()), - new SimpleMethodParamModel( - new TypeSpec(ClassName.bestGuess("SecondType")), - "field2", - ImmutableList.of((Annotation) () -> FromEvent.class), - ImmutableList.of(), - new Object())); - - SpecMethodModel handlerModel = - new SpecMethodModel<>( - ImmutableList.of(), - ImmutableList.of(), - "onEvent", - new TypeSpec(ClassName.VOID), - ImmutableList.of(), - params, - new Object(), - new EventMethod(EventHandlerRebindMode.REBIND), - eventModel); - - MethodSpec method = - EventGenerator.generateEventHandlerFactory( - handlerModel, ClassNames.COMPONENT_CONTEXT, "TestComponent"); - - assertThat(method.typeVariables).hasSize(2); - TypeVariableName T0 = method.typeVariables.get(0); - TypeVariableName T1 = method.typeVariables.get(1); - - assertThat(T0.bounds.get(0)).isEqualTo(ClassName.bestGuess("FirstType")); - assertThat(T1.bounds.get(0)).isEqualTo(ClassName.bestGuess("SecondType")); - - assertThat(method.returnType).isInstanceOf(ParameterizedTypeName.class); - - ParameterizedTypeName returnType = ((ParameterizedTypeName) method.returnType); - assertThat(returnType.typeArguments.get(0)).isInstanceOf(ParameterizedTypeName.class); - - ParameterizedTypeName returnEventType = (ParameterizedTypeName) returnType.typeArguments.get(0); - assertThat(returnEventType.rawType).isEqualTo(eventClass.rawType); - assertThat(returnEventType.typeArguments).hasSize(2); - - assertThat(returnEventType.typeArguments.get(0)).isInstanceOf(TypeVariableName.class); - assertThat(returnEventType.typeArguments.get(1)).isInstanceOf(TypeVariableName.class); - - assertThat(method.toString()) - .isEqualTo( - "public static " - + " com.facebook.litho.EventHandler> onEvent(\n" - + " com.facebook.litho.ComponentContext c) {\n" - + " return newEventHandler(TestComponent.class, \"TestComponent\", c, -1349761029," - + " null, com.facebook.litho.annotations.EventHandlerRebindMode.REBIND);\n" - + "}\n"); - } - - @Test - public void whenEventHandlerWithSameGenericOnTwoFields_shouldGenerateTypedEventHandlerFactory() { - final TypeVariableName typeM = TypeVariableName.get("M"); - final ParameterizedTypeName eventClass = - ParameterizedTypeName.get(ClassName.bestGuess("EventClass"), typeM); - - EventDeclarationModel eventModel = - new EventDeclarationModel( - eventClass, - ClassName.VOID, - ImmutableList.of( - new FieldModel( - FieldSpec.builder(typeM, "field1", Modifier.PUBLIC).build(), new Object()), - new FieldModel( - FieldSpec.builder(typeM, "field2", Modifier.PUBLIC).build(), new Object())), - new Object()); - - ImmutableList params = - ImmutableList.of( - new SimpleMethodParamModel( - new TypeSpec(ClassNames.COMPONENT_CONTEXT), - "c", - ImmutableList.of(), - ImmutableList.of(), - new Object()), - new SimpleMethodParamModel( - new TypeSpec(ClassName.bestGuess("FirstType")), - "field1", - ImmutableList.of((Annotation) () -> FromEvent.class), - ImmutableList.of(), - new Object()), - new SimpleMethodParamModel( - new TypeSpec(ClassName.bestGuess("FirstType")), - "field2", - ImmutableList.of((Annotation) () -> FromEvent.class), - ImmutableList.of(), - new Object())); - - SpecMethodModel handlerModel = - new SpecMethodModel<>( - ImmutableList.of(), - ImmutableList.of(), - "onEvent", - new TypeSpec(ClassName.VOID), - ImmutableList.of(), - params, - new Object(), - new EventMethod(EventHandlerRebindMode.REBIND), - eventModel); - - MethodSpec method = - EventGenerator.generateEventHandlerFactory( - handlerModel, ClassNames.COMPONENT_CONTEXT, "TestComponent"); - - assertThat(method.typeVariables).hasSize(1); - TypeVariableName T0 = method.typeVariables.get(0); - - assertThat(T0.bounds.get(0)).isEqualTo(ClassName.bestGuess("FirstType")); - - assertThat(method.returnType).isInstanceOf(ParameterizedTypeName.class); - - ParameterizedTypeName returnType = ((ParameterizedTypeName) method.returnType); - assertThat(returnType.typeArguments.get(0)).isInstanceOf(ParameterizedTypeName.class); - - ParameterizedTypeName returnEventType = (ParameterizedTypeName) returnType.typeArguments.get(0); - assertThat(returnEventType.rawType).isEqualTo(eventClass.rawType); - assertThat(returnEventType.typeArguments).hasSize(1); - - assertThat(returnEventType.typeArguments.get(0)).isInstanceOf(TypeVariableName.class); - - assertThat(method.toString()) - .isEqualTo( - "public static com.facebook.litho.EventHandler>" - + " onEvent(\n" - + " com.facebook.litho.ComponentContext c) {\n" - + " return newEventHandler(TestComponent.class, \"TestComponent\", c, -1349761029," - + " null, com.facebook.litho.annotations.EventHandlerRebindMode.REBIND);\n" - + "}\n"); - } - - @Test - public void whenEventHandlerNoGenericTypedVariables_shouldGenerateTypedEventHandlerFactory() { - final TypeVariableName typeM = TypeVariableName.get("M"); - final TypeVariableName typeN = TypeVariableName.get("N"); - final ParameterizedTypeName eventClass = - ParameterizedTypeName.get(ClassName.bestGuess("EventClass"), typeM, typeN); - - EventDeclarationModel eventModel = - new EventDeclarationModel( - eventClass, - ClassName.VOID, - ImmutableList.of( - new FieldModel( - FieldSpec.builder(typeM, "field1", Modifier.PUBLIC).build(), new Object()), - new FieldModel( - FieldSpec.builder(typeN, "field2", Modifier.PUBLIC).build(), new Object())), - new Object()); - - ImmutableList params = - ImmutableList.of( - new SimpleMethodParamModel( - new TypeSpec(ClassNames.COMPONENT_CONTEXT), - "c", - ImmutableList.of(), - ImmutableList.of(), - new Object())); - - SpecMethodModel handlerModel = - new SpecMethodModel<>( - ImmutableList.of(), - ImmutableList.of(), - "onEvent", - new TypeSpec(ClassName.VOID), - ImmutableList.of(), - params, - new Object(), - new EventMethod(EventHandlerRebindMode.REBIND), - eventModel); - - MethodSpec method = - EventGenerator.generateEventHandlerFactory( - handlerModel, ClassNames.COMPONENT_CONTEXT, "TestComponent"); - - assertThat(method.typeVariables).hasSize(2); - TypeVariableName T0 = method.typeVariables.get(0); - TypeVariableName T1 = method.typeVariables.get(1); - - assertThat(T0.bounds).hasSize(0); - assertThat(T1.bounds).hasSize(0); - - assertThat(method.returnType).isInstanceOf(ParameterizedTypeName.class); - - ParameterizedTypeName returnType = ((ParameterizedTypeName) method.returnType); - assertThat(returnType.typeArguments.get(0)).isInstanceOf(ParameterizedTypeName.class); - - ParameterizedTypeName returnEventType = (ParameterizedTypeName) returnType.typeArguments.get(0); - assertThat(returnEventType.rawType).isEqualTo(eventClass.rawType); - assertThat(returnEventType.typeArguments).hasSize(2); - - assertThat(returnEventType.typeArguments.get(0)).isInstanceOf(TypeVariableName.class); - assertThat(returnEventType.typeArguments.get(1)).isInstanceOf(TypeVariableName.class); - - assertThat(method.toString()) - .isEqualTo( - "public static com.facebook.litho.EventHandler> onEvent(\n" - + " com.facebook.litho.ComponentContext c) {\n" - + " return newEventHandler(TestComponent.class, \"TestComponent\", c, -1349761029," - + " null, com.facebook.litho.annotations.EventHandlerRebindMode.REBIND);\n" - + "}\n"); - } - - @Test - public void whenEventHandlerWithNamedTypedVariables_shouldGenerateTypedEventHandlerFactory() { - final TypeVariableName typeM = TypeVariableName.get("M"); - final TypeVariableName typeN = TypeVariableName.get("N"); - final ParameterizedTypeName eventClass = - ParameterizedTypeName.get(ClassName.bestGuess("EventClass"), typeM, typeN); - - EventDeclarationModel eventModel = - new EventDeclarationModel( - eventClass, - ClassName.VOID, - ImmutableList.of( - new FieldModel( - FieldSpec.builder(typeM, "field1", Modifier.PUBLIC).build(), new Object()), - new FieldModel( - FieldSpec.builder(typeN, "field2", Modifier.PUBLIC).build(), new Object()), - new FieldModel( - FieldSpec.builder(typeM, "field3", Modifier.PUBLIC).build(), new Object())), - new Object()); - - final TypeVariableName paramTypeName = TypeVariableName.get("P", Set.class); - final TypeVariableName firstTypeName = - TypeVariableName.get("F", ClassName.bestGuess("FirstType")); - final TypeVariableName secondTypeName = - TypeVariableName.get("S", ClassName.bestGuess("SecondType")); - final ImmutableList types = - ImmutableList.of(TypeVariableName.get("T"), paramTypeName, firstTypeName, secondTypeName); - - ImmutableList params = - ImmutableList.of( - new SimpleMethodParamModel( - new TypeSpec(ClassNames.COMPONENT_CONTEXT), - "c", - ImmutableList.of(), - ImmutableList.of(), - new Object()), - new SimpleMethodParamModel( - new TypeSpec(firstTypeName), - "field1", - ImmutableList.of((Annotation) () -> FromEvent.class), - ImmutableList.of(), - new Object()), - new SimpleMethodParamModel( - new TypeSpec(firstTypeName), - "field3", - ImmutableList.of((Annotation) () -> FromEvent.class), - ImmutableList.of(), - new Object()), - new SimpleMethodParamModel( - new TypeSpec(secondTypeName), - "field2", - ImmutableList.of((Annotation) () -> FromEvent.class), - ImmutableList.of(), - new Object()), - new SimpleMethodParamModel( - new TypeSpec(paramTypeName), - "param1", - ImmutableList.of((Annotation) () -> Param.class), - ImmutableList.of(), - new Object())); - - SpecMethodModel handlerModel = - new SpecMethodModel<>( - ImmutableList.of(), - ImmutableList.of(), - "onEvent", - new TypeSpec(ClassName.VOID), - types, - params, - new Object(), - new EventMethod(EventHandlerRebindMode.REBIND), - eventModel); - - MethodSpec method = - EventGenerator.generateEventHandlerFactory( - handlerModel, ClassNames.COMPONENT_CONTEXT, "TestComponent"); - - assertThat(method.typeVariables).hasSize(4); - TypeVariableName T = method.typeVariables.get(0); - TypeVariableName P = method.typeVariables.get(1); - TypeVariableName F = method.typeVariables.get(2); - TypeVariableName S = method.typeVariables.get(3); - - assertThat(F.bounds.get(0)).isEqualTo(ClassName.bestGuess("FirstType")); - assertThat(S.bounds.get(0)).isEqualTo(ClassName.bestGuess("SecondType")); - assertThat(P.bounds.get(0)).isEqualTo(ClassName.get(Set.class)); - - assertThat(method.returnType).isInstanceOf(ParameterizedTypeName.class); - - ParameterizedTypeName returnType = ((ParameterizedTypeName) method.returnType); - assertThat(returnType.typeArguments.get(0)).isInstanceOf(ParameterizedTypeName.class); - - ParameterizedTypeName returnEventType = (ParameterizedTypeName) returnType.typeArguments.get(0); - assertThat(returnEventType.rawType).isEqualTo(eventClass.rawType); - assertThat(returnEventType.typeArguments).hasSize(2); - - assertThat(returnEventType.typeArguments.get(0)).isInstanceOf(TypeVariableName.class); - assertThat(returnEventType.typeArguments.get(1)).isInstanceOf(TypeVariableName.class); - - assertThat(method.toString()) - .isEqualTo( - "public static " - + " com.facebook.litho.EventHandler> onEvent(\n" - + " com.facebook.litho.ComponentContext c, P param1) {\n" - + " return newEventHandler(TestComponent.class, \"TestComponent\", c, -1349761029," - + " new Object[] {\n" - + " param1,\n" - + " }, com.facebook.litho.annotations.EventHandlerRebindMode.REBIND);\n" - + "}\n"); - } - - @Test - public void whenEventHandlerWithPrimitiveTypedVariables_shouldGenerateTypedEventHandlerFactory() { - final TypeVariableName typeM = TypeVariableName.get("M"); - final ParameterizedTypeName eventClass = - ParameterizedTypeName.get(ClassName.bestGuess("EventClass"), typeM); - - EventDeclarationModel eventModel = - new EventDeclarationModel( - eventClass, - ClassName.VOID, - ImmutableList.of( - new FieldModel( - FieldSpec.builder(typeM, "field1", Modifier.PUBLIC).build(), new Object())), - new Object()); - - ImmutableList params = - ImmutableList.of( - new SimpleMethodParamModel( - new TypeSpec(ClassNames.COMPONENT_CONTEXT), - "c", - ImmutableList.of(), - ImmutableList.of(), - new Object()), - new SimpleMethodParamModel( - new TypeSpec(TypeName.INT), - "field1", - ImmutableList.of((Annotation) () -> FromEvent.class), - ImmutableList.of(), - new Object())); - - SpecMethodModel handlerModel = - new SpecMethodModel<>( - ImmutableList.of(), - ImmutableList.of(), - "onEvent", - new TypeSpec(ClassName.VOID), - ImmutableList.of(), - params, - new Object(), - new EventMethod(EventHandlerRebindMode.REBIND), - eventModel); - - MethodSpec method = - EventGenerator.generateEventHandlerFactory( - handlerModel, ClassNames.COMPONENT_CONTEXT, "TestComponent"); - - assertThat(method.typeVariables).hasSize(1); - TypeVariableName T0 = method.typeVariables.get(0); - - assertThat(T0.bounds).hasSize(1); - - assertThat(method.returnType).isInstanceOf(ParameterizedTypeName.class); - - ParameterizedTypeName returnType = ((ParameterizedTypeName) method.returnType); - assertThat(returnType.typeArguments.get(0)).isInstanceOf(ParameterizedTypeName.class); - - ParameterizedTypeName returnEventType = (ParameterizedTypeName) returnType.typeArguments.get(0); - assertThat(returnEventType.rawType).isEqualTo(eventClass.rawType); - assertThat(returnEventType.typeArguments).hasSize(1); - - assertThat(returnEventType.typeArguments.get(0)).isInstanceOf(TypeVariableName.class); - - assertThat(method.toString()) - .isEqualTo( - "public static " - + " com.facebook.litho.EventHandler> onEvent(\n" - + " com.facebook.litho.ComponentContext c) {\n" - + " return newEventHandler(TestComponent.class, \"TestComponent\", c, -1349761029," - + " null, com.facebook.litho.annotations.EventHandlerRebindMode.REBIND);\n" - + "}\n"); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/InterStagePropsGeneratorTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/generator/InterStagePropsGeneratorTest.java deleted file mode 100644 index 412d6e5cae9..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/InterStagePropsGeneratorTest.java +++ /dev/null @@ -1,286 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.generator; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import androidx.annotation.UiThread; -import com.facebook.litho.ComponentContext; -import com.facebook.litho.ComponentLayout; -import com.facebook.litho.LithoView; -import com.facebook.litho.Output; -import com.facebook.litho.Size; -import com.facebook.litho.annotations.FromMeasure; -import com.facebook.litho.annotations.FromPrepare; -import com.facebook.litho.annotations.MountSpec; -import com.facebook.litho.annotations.OnBind; -import com.facebook.litho.annotations.OnMeasure; -import com.facebook.litho.annotations.OnPrepare; -import com.facebook.litho.specmodels.internal.ImmutableList; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.model.ClassNames; -import com.facebook.litho.specmodels.model.DelegateMethodDescriptions; -import com.facebook.litho.specmodels.model.InterStageInputParamModel; -import com.facebook.litho.specmodels.model.MethodParamModelFactory; -import com.facebook.litho.specmodels.model.SpecModel; -import com.facebook.litho.specmodels.processor.MountSpecModelFactory; -import com.google.testing.compile.CompilationRule; -import com.squareup.javapoet.ClassName; -import com.squareup.javapoet.MethodSpec; -import com.squareup.javapoet.TypeSpec; -import java.util.ArrayList; -import java.util.List; -import javax.annotation.processing.Messager; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -@RunWith(JUnit4.class) -public class InterStagePropsGeneratorTest { - public @Rule CompilationRule mCompilationRule = new CompilationRule(); - private @Mock Messager mMessager; - - private SpecModel mInterstagePropsMountSpecModel; - private final MountSpecModelFactory mMountSpecModelFactory = new MountSpecModelFactory(); - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - - Elements elements = mCompilationRule.getElements(); - Types types = mCompilationRule.getTypes(); - - mInterstagePropsMountSpecModel = - spy( - mMountSpecModelFactory.create( - elements, - types, - elements.getTypeElement(MountTestSpec.class.getCanonicalName()), - mMessager, - RunMode.normal(), - null, - null)); - - InterStageInputParamModel props = - new InterStageInputParamModel( - MethodParamModelFactory.createSimpleMethodParamModel( - new com.facebook.litho.specmodels.model.TypeSpec(ClassNames.STRING), - "stringOutput", - new Object())); - - when(mInterstagePropsMountSpecModel.getInterStageInputs()).thenReturn(ImmutableList.of(props)); - } - - @Test - public void test_interStageProps_containerClassName() { - assertThat( - InterStagePropsContainerGenerator.getInterStagePropsContainerClassName( - mInterstagePropsMountSpecModel)) - .isEqualTo("MountTestInterStagePropsContainer"); - } - - @Test - public void test_generate_container_impl() { - final TypeSpec container = - InterStagePropsContainerGenerator.generate(mInterstagePropsMountSpecModel); - - assertThat(container.toString()) - .isEqualTo( - "@com.facebook.litho.annotations.Generated\n" - + "static class MountTestInterStagePropsContainer implements" - + " com.facebook.litho.InterStagePropsContainer {\n" - + " java.lang.String stringOutput;\n" - + "}\n"); - } - - @Test - public void test_generate_getAndCreate_container() { - final TypeSpecDataHolder holder = - ComponentBodyGenerator.generate(mInterstagePropsMountSpecModel, null, RunMode.testing()); - final List methodNames = new ArrayList<>(); - for (MethodSpec methodSpec : holder.getMethodSpecs()) { - methodNames.add(methodSpec.name); - } - - assertThat(methodNames.contains("createPrepareInterStagePropsContainer")).isTrue(); - assertThat(methodNames.contains("getPrepareInterStagePropsContainerImpl")).isTrue(); - } - - @Test - public void test_create_container() { - MethodSpec methodSpec = - ComponentBodyGenerator.generateInterStagePropsContainerCreator( - ClassName.bestGuess( - InterStagePropsContainerGenerator.getInterStagePropsContainerClassName( - mInterstagePropsMountSpecModel))); - - assertThat(methodSpec.toString()) - .isEqualTo( - "@java.lang.Override\n" - + "protected MountTestInterStagePropsContainer createInterStagePropsContainer() {\n" - + " return new MountTestInterStagePropsContainer();\n" - + "}\n"); - } - - @Test - public void test_get_container_impl() { - MethodSpec methodSpec = - ComponentBodyGenerator.generateInterstagePropsContainerImplGetter( - mInterstagePropsMountSpecModel, - ClassName.bestGuess( - InterStagePropsContainerGenerator.getInterStagePropsContainerClassName( - mInterstagePropsMountSpecModel))); - - assertThat(methodSpec.toString()) - .isEqualTo( - "private MountTestInterStagePropsContainer getInterStagePropsContainerImpl(\n" - + " com.facebook.litho.ComponentContext c,\n" - + " com.facebook.litho.InterStagePropsContainer interStageProps) {\n" - + " return (MountTestInterStagePropsContainer)" - + " super.getInterStagePropsContainer(c, interStageProps);\n" - + "}\n"); - } - - @Test - public void test_makeShallowCopy_clear() { - final TypeSpecDataHolder holder = - ComponentBodyGenerator.generateMakeShallowCopy(mInterstagePropsMountSpecModel, false); - assertThat(holder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "@java.lang.Override\n" - + "public MountTest makeShallowCopy() {\n" - + " MountTest component = (MountTest) super.makeShallowCopy();\n" - + " return component;\n" - + "}\n"); - } - - @Test - public void test_usages() { - TypeSpecDataHolder holder = - DelegateMethodGenerator.generateDelegates( - mInterstagePropsMountSpecModel, - DelegateMethodDescriptions.MOUNT_SPEC_DELEGATE_METHODS_MAP, - RunMode.testing()); - - assertThat(holder.getMethodSpecs()).hasSize(4); - - MethodSpec onPrepareMethod = null; - MethodSpec onBindMethod = null; - MethodSpec onMeasureMethod = null; - - for (int i = 0, size = holder.getMethodSpecs().size(); i < size; i++) { - final MethodSpec methodSpec = holder.getMethodSpecs().get(i); - if (methodSpec.name.equals("onPrepare")) { - onPrepareMethod = methodSpec; - } - - if (methodSpec.name.equals("onMeasure")) { - onMeasureMethod = methodSpec; - } - - if (methodSpec.name.equals("onBind")) { - onBindMethod = methodSpec; - } - } - - assertThat(onPrepareMethod).isNotNull(); - assertThat(onMeasureMethod).isNotNull(); - assertThat(onBindMethod).isNotNull(); - - assertThat(onPrepareMethod.toString()) - .isEqualTo( - "@java.lang.Override\n" - + "protected void onPrepare(com.facebook.litho.ComponentContext c) {\n" - + " com.facebook.litho.Output colorTmp = new Output<>();\n" - + " MountTestSpec.onPrepare(\n" - + " (com.facebook.litho.ComponentContext) c,\n" - + " (com.facebook.litho.Output) colorTmp);\n" - + " getPrepareInterStagePropsContainerImpl(c).color = colorTmp.get();\n" - + "}\n"); - - assertThat(onMeasureMethod.toString()) - .isEqualTo( - "@java.lang.Override\n" - + "protected void onMeasure(com.facebook.litho.ComponentContext c,\n" - + " com.facebook.litho.ComponentLayout layout, int widthSpec, int heightSpec,\n" - + " com.facebook.litho.Size size, com.facebook.litho.InterStagePropsContainer" - + " _5) {\n" - + " com.facebook.litho.InterStagePropsContainer _interStageProps = _5;\n" - + " com.facebook.litho.Output stringOutputTmp = new" - + " Output<>();\n" - + " MountTestSpec.onMeasure(\n" - + " (com.facebook.litho.ComponentContext) c,\n" - + " (com.facebook.litho.ComponentLayout) layout,\n" - + " (int) widthSpec,\n" - + " (int) heightSpec,\n" - + " (com.facebook.litho.Size) size,\n" - + " (com.facebook.litho.Output) stringOutputTmp);\n" - + " getInterStagePropsContainerImpl(c, _interStageProps).stringOutput =" - + " stringOutputTmp.get();\n" - + "}\n"); - - assertThat(onBindMethod.toString()) - .isEqualTo( - "@java.lang.Override\n" - + "protected void onBind(com.facebook.litho.ComponentContext c, java.lang.Object" - + " lithoView,\n" - + " com.facebook.litho.InterStagePropsContainer _2) {\n" - + " com.facebook.litho.InterStagePropsContainer _interStageProps = _2;\n" - + " com.facebook.litho.Output stringOutputTmp = new" - + " Output<>();\n" - + " MountTestSpec.onBind(\n" - + " (com.facebook.litho.ComponentContext) c,\n" - + " (com.facebook.litho.LithoView) lithoView,\n" - + " (java.lang.Integer) getPrepareInterStagePropsContainerImpl(c).color,\n" - + " (com.facebook.litho.Output) stringOutputTmp);\n" - + " getInterStagePropsContainerImpl(c, _interStageProps).stringOutput =" - + " stringOutputTmp.get();\n" - + "}\n"); - } - - @MountSpec - static class MountTestSpec { - - @OnPrepare - static void onPrepare(ComponentContext c, Output color) {} - - @OnMeasure - static void onMeasure( - ComponentContext c, - ComponentLayout layout, - int widthSpec, - int heightSpec, - Size size, - Output stringOutput) {} - - @UiThread - @OnBind - static void onBind( - ComponentContext c, - LithoView lithoView, - @FromPrepare Integer color, - @FromMeasure Output stringOutput) {} - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/SimpleNameDelegateGeneratorTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/generator/SimpleNameDelegateGeneratorTest.java deleted file mode 100644 index 764a7e2e723..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/SimpleNameDelegateGeneratorTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.generator; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -import com.facebook.litho.Component; -import com.facebook.litho.annotations.LayoutSpec; -import com.facebook.litho.annotations.OnCreateLayout; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.model.LayoutSpecModel; -import com.facebook.litho.specmodels.processor.LayoutSpecModelFactory; -import com.google.testing.compile.CompilationRule; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests {@link SimpleNameDelegateGenerator} */ -@RunWith(JUnit4.class) -public class SimpleNameDelegateGeneratorTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - - private final LayoutSpecModelFactory mLayoutSpecModelFactory = new LayoutSpecModelFactory(); - - @LayoutSpec - private static class TestWithoutDelegateSpec { - - @OnCreateLayout - public void onCreateLayout(@Prop boolean arg0, @Prop Component delegate) {} - } - - @LayoutSpec(simpleNameDelegate = "delegate") - private static class TestWithDelegateSpec { - - @OnCreateLayout - public void onCreateLayout(@Prop boolean arg0, @Prop Component delegate) {} - } - - private LayoutSpecModel getSpecModel(Class specClass) { - Elements elements = mCompilationRule.getElements(); - Types types = mCompilationRule.getTypes(); - TypeElement typeElement = elements.getTypeElement(specClass.getCanonicalName()); - - return mLayoutSpecModelFactory.create( - elements, types, typeElement, mock(Messager.class), RunMode.normal(), null, null); - } - - @Test - public void testGenerateWithoutDelegate() { - TypeSpecDataHolder dataHolder = - SimpleNameDelegateGenerator.generate(getSpecModel(TestWithoutDelegateSpec.class)); - - assertThat(dataHolder.getMethodSpecs()).hasSize(0); - } - - @Test - public void testGenerateWithDelegate() { - TypeSpecDataHolder dataHolder = - SimpleNameDelegateGenerator.generate(getSpecModel(TestWithDelegateSpec.class)); - - assertThat(dataHolder.getMethodSpecs()).hasSize(1); - - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "@java.lang.Override\n" - + "protected com.facebook.litho.Component getSimpleNameDelegate() {\n" - + " return delegate;\n" - + "}\n"); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/StateContainerGeneratorTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/generator/StateContainerGeneratorTest.java deleted file mode 100644 index 72033e983b6..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/StateContainerGeneratorTest.java +++ /dev/null @@ -1,423 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.generator; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.facebook.litho.StateValue; -import com.facebook.litho.Transition; -import com.facebook.litho.animation.AnimatedProperties; -import com.facebook.litho.annotations.LayoutSpec; -import com.facebook.litho.annotations.OnCreateLayout; -import com.facebook.litho.annotations.OnUpdateState; -import com.facebook.litho.annotations.OnUpdateStateWithTransition; -import com.facebook.litho.annotations.Param; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.annotations.State; -import com.facebook.litho.annotations.TreeProp; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.model.SpecModel; -import com.facebook.litho.specmodels.processor.LayoutSpecModelFactory; -import com.google.testing.compile.CompilationRule; -import java.util.List; -import java.util.function.Function; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -/** Tests {@link StateContainerGenerator} */ -@RunWith(JUnit4.class) -public class StateContainerGeneratorTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - @Mock private Messager mMessager; - - private final LayoutSpecModelFactory mLayoutSpecModelFactory = new LayoutSpecModelFactory(); - - private SpecModel mSpecModelWithState; - private SpecModel mSpecModelWithStateWithTransition; - private SpecModel mSpecModelWithBothMethods; - private SpecModel mSpecModelWithSameGenericMultipleTimes; - private SpecModel mSpecModelWithMultipleGenerics; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - final Elements elements = mCompilationRule.getElements(); - final Types types = mCompilationRule.getTypes(); - - final TypeElement typeElementWithState = - elements.getTypeElement(TestWithStateSpec.class.getCanonicalName()); - mSpecModelWithState = - mLayoutSpecModelFactory.create( - elements, types, typeElementWithState, mMessager, RunMode.normal(), null, null); - - final TypeElement typeElementWithTransition = - elements.getTypeElement(TestWithStateWithTransitionSpec.class.getCanonicalName()); - mSpecModelWithStateWithTransition = - mLayoutSpecModelFactory.create( - elements, types, typeElementWithTransition, mMessager, RunMode.normal(), null, null); - - final TypeElement typeElementWithBothMethods = - elements.getTypeElement(TestWithBothMethodsSpec.class.getCanonicalName()); - mSpecModelWithBothMethods = - mLayoutSpecModelFactory.create( - elements, types, typeElementWithBothMethods, mMessager, RunMode.normal(), null, null); - - final TypeElement typeElementWithSameGenericMultipleTimes = - elements.getTypeElement(TestWithSameGenericMultipleTimesSpec.class.getCanonicalName()); - mSpecModelWithSameGenericMultipleTimes = - mLayoutSpecModelFactory.create( - elements, - types, - typeElementWithSameGenericMultipleTimes, - mMessager, - RunMode.normal(), - null, - null); - - final TypeElement typeElementWithMultipleGenerics = - elements.getTypeElement(TestWithMultipleGenericsSpec.class.getCanonicalName()); - mSpecModelWithMultipleGenerics = - mLayoutSpecModelFactory.create( - elements, - types, - typeElementWithMultipleGenerics, - mMessager, - RunMode.normal(), - null, - null); - } - - @Test - public void testGetStateContainerClassName() { - assertThat(StateContainerGenerator.getStateContainerClassName(mSpecModelWithState)) - .isEqualTo("TestWithStateStateContainer"); - } - - @Test - public void testGenerateStateContainerImpl() { - assertThat(StateContainerGenerator.generate(mSpecModelWithState, RunMode.normal()).toString()) - .isEqualTo( - "@androidx.annotation.VisibleForTesting(\n" - + " otherwise = 2\n" - + ")\n" - + "@com.facebook.litho.annotations.Generated\n" - + "static class TestWithStateStateContainer" - + " extends com.facebook.litho.StateContainer {\n" - + " @com.facebook.litho.annotations.State\n" - + " @com.facebook.litho.annotations.Comparable(\n" - + " type = 3\n" - + " )\n" - + " int arg1;\n" - + "\n" - + " @com.facebook.litho.annotations.State\n" - + " @com.facebook.litho.annotations.Comparable(\n" - + " type = 3\n" - + " )\n" - + " boolean arg4;\n" - + "\n" - + " @java.lang.Override\n" - + " public void applyStateUpdate(com.facebook.litho.StateContainer.StateUpdate" - + " stateUpdate) {\n" - + " com.facebook.litho.StateValue arg1;\n" - + " com.facebook.litho.StateValue arg4;\n" - + "\n" - + " final java.lang.Object[] params = stateUpdate.params;\n" - + " switch (stateUpdate.type) {\n" - + " case 0:\n" - + " TestWithStateSpec.testUpdateState();\n" - + " break;\n" - + "\n" - + " case -2147483648:\n" - + " this.arg4 = (boolean) params[0];\n" - + " break;\n" - + " }\n" - + " }\n" - + "}\n"); - } - - @Test - public void testGenerateStateContainerWithTransitionImpl() { - assertThat( - StateContainerGenerator.generate(mSpecModelWithStateWithTransition, RunMode.normal()) - .toString()) - .isEqualTo( - "@androidx.annotation.VisibleForTesting(\n" - + " otherwise = 2\n" - + ")\n" - + "@com.facebook.litho.annotations.Generated\n" - + "static class TestWithStateWithTransitionStateContainer extends com.facebook.litho.StateContainer implements" - + " com.facebook.litho.SpecGeneratedComponent.TransitionContainer {\n" - + " @com.facebook.litho.annotations.State\n" - + " @com.facebook.litho.annotations.Comparable(\n" - + " type = 3\n" - + " )\n" - + " int arg1;\n" - + "\n" - + " @com.facebook.litho.annotations.State\n" - + " @com.facebook.litho.annotations.Comparable(\n" - + " type = 3\n" - + " )\n" - + " boolean arg4;\n" - + "\n" - + " @java.lang.Override\n" - + " public com.facebook.litho.Transition applyStateUpdateWithTransition(\n" - + " com.facebook.litho.StateContainer.StateUpdate stateUpdate) {\n" - + " com.facebook.litho.StateValue arg1;\n" - + " com.facebook.litho.StateValue arg4;\n" - + "\n" - + " final java.lang.Object[] params = stateUpdate.params;\n" - + " com.facebook.litho.Transition _transition = null;\n" - + " switch (stateUpdate.type) {\n" - + " case 0:\n" - + " _transition =" - + " TestWithStateWithTransitionSpec.testUpdateStateWithTransition();\n" - + " break;\n" - + "\n" - + " case -2147483648:\n" - + " this.arg4 = (boolean) params[0];\n" - + " break;\n" - + " }\n" - + " return _transition;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public void applyStateUpdate(com.facebook.litho.StateContainer.StateUpdate" - + " stateUpdate) {\n" - + " if (applyStateUpdateWithTransition(stateUpdate) != null) {\n" - + " throw new UnsupportedOperationException();\n" - + " }\n" - + " }\n" - + "}\n"); - } - - @Test - public void testGenerateStateContainerWithBothMethodsImpl() { - assertThat( - StateContainerGenerator.generate(mSpecModelWithBothMethods, RunMode.normal()) - .toString()) - .isEqualTo( - "@androidx.annotation.VisibleForTesting(\n" - + " otherwise = 2\n" - + ")\n" - + "@com.facebook.litho.annotations.Generated\n" - + "static class TestWithBothMethodsStateContainer" - + " extends com.facebook.litho.StateContainer implements" - + " com.facebook.litho.SpecGeneratedComponent.TransitionContainer {\n" - + " @com.facebook.litho.annotations.State\n" - + " @com.facebook.litho.annotations.Comparable(\n" - + " type = 3\n" - + " )\n" - + " int arg1;\n" - + "\n" - + " @com.facebook.litho.annotations.State\n" - + " @com.facebook.litho.annotations.Comparable(\n" - + " type = 3\n" - + " )\n" - + " boolean arg4;\n" - + "\n" - + " @java.lang.Override\n" - + " public com.facebook.litho.Transition applyStateUpdateWithTransition(\n" - + " com.facebook.litho.StateContainer.StateUpdate stateUpdate) {\n" - + " com.facebook.litho.StateValue arg1;\n" - + " com.facebook.litho.StateValue arg4;\n" - + "\n" - + " final java.lang.Object[] params = stateUpdate.params;\n" - + " com.facebook.litho.Transition _transition = null;\n" - + " switch (stateUpdate.type) {\n" - + " case 0:\n" - + " TestWithBothMethodsSpec.testUpdateState();\n" - + " break;\n" - + "\n" - + " case 1:\n" - + " _transition = TestWithBothMethodsSpec.testUpdateStateWithTransition();\n" - + " break;\n" - + "\n" - + " case -2147483648:\n" - + " this.arg4 = (boolean) params[0];\n" - + " break;\n" - + " }\n" - + " return _transition;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public void applyStateUpdate(com.facebook.litho.StateContainer.StateUpdate" - + " stateUpdate) {\n" - + " if (applyStateUpdateWithTransition(stateUpdate) != null) {\n" - + " throw new UnsupportedOperationException();\n" - + " }\n" - + " }\n" - + "}\n"); - } - - @Test - public void testGenerateStateContainerWithSameGenericMultipleTimesImpl() { - assertThat( - StateContainerGenerator.generate( - mSpecModelWithSameGenericMultipleTimes, RunMode.normal()) - .toString()) - .isEqualTo( - "@androidx.annotation.VisibleForTesting(\n" - + " otherwise = 2\n" - + ")\n" - + "@com.facebook.litho.annotations.Generated\n" - + "static class TestWithSameGenericMultipleTimesStateContainer extends" - + " com.facebook.litho.StateContainer {\n" - + " @com.facebook.litho.annotations.State\n" - + " @com.facebook.litho.annotations.Comparable(\n" - + " type = 5\n" - + " )\n" - + " java.util.List values;\n" - + "\n" - + " @java.lang.Override\n" - + " public void applyStateUpdate(com.facebook.litho.StateContainer.StateUpdate" - + " stateUpdate) {\n" - + " com.facebook.litho.StateValue> values;\n" - + "\n" - + " final java.lang.Object[] params = stateUpdate.params;\n" - + " switch (stateUpdate.type) {\n" - + " case 0:\n" - + " values = new com.facebook.litho.StateValue>();\n" - + " values.set(this.values);\n" - + " TestWithSameGenericMultipleTimesSpec.updateValues(values," - + " (java.util.List) params[0]);\n" - + " this.values = values.get();\n" - + " break;\n" - + " }\n" - + " }\n" - + "}\n"); - } - - @Test - public void testGenerateStateContainerWithMultipleGenericsImpl() { - assertThat( - StateContainerGenerator.generate(mSpecModelWithMultipleGenerics, RunMode.normal()) - .toString()) - .isEqualTo( - "@androidx.annotation.VisibleForTesting(\n" - + " otherwise = 2\n" - + ")\n" - + "@com.facebook.litho.annotations.Generated\n" - + "static class TestWithMultipleGenericsStateContainer extends" - + " com.facebook.litho.StateContainer {\n" - + " @com.facebook.litho.annotations.State\n" - + " @com.facebook.litho.annotations.Comparable(\n" - + " type = 13\n" - + " )\n" - + " java.util.function.Function functions;\n" - + "\n" - + " @java.lang.Override\n" - + " public void applyStateUpdate(com.facebook.litho.StateContainer.StateUpdate" - + " stateUpdate) {\n" - + " com.facebook.litho.StateValue>" - + " functions;\n" - + "\n" - + " final java.lang.Object[] params = stateUpdate.params;\n" - + " switch (stateUpdate.type) {\n" - + " case 0:\n" - + " functions = new" - + " com.facebook.litho.StateValue>();\n" - + " functions.set(this.functions);\n" - + " TestWithMultipleGenericsSpec.updateValues(functions," - + " (java.util.function.Function) params[0]);\n" - + " this.functions = functions.get();\n" - + " break;\n" - + " }\n" - + " }\n" - + "}\n"); - } - - @LayoutSpec - private static class TestWithStateSpec { - @OnCreateLayout - public void onCreateLayout( - @Prop boolean arg0, - @State int arg1, - @Param Object arg2, - @TreeProp long arg3, - @State(canUpdateLazily = true) boolean arg4) {} - - @OnUpdateState - void testUpdateState() {} - } - - @LayoutSpec - private static class TestWithStateWithTransitionSpec { - @OnCreateLayout - public void onCreateLayout( - @Prop boolean arg0, - @State int arg1, - @Param Object arg2, - @TreeProp long arg3, - @State(canUpdateLazily = true) boolean arg4) {} - - @OnUpdateStateWithTransition - Transition testUpdateStateWithTransition() { - return null; - } - } - - @LayoutSpec - private static class TestWithBothMethodsSpec { - @OnCreateLayout - public void onCreateLayout( - @Prop boolean arg0, - @State int arg1, - @Param Object arg2, - @TreeProp long arg3, - @State(canUpdateLazily = true) boolean arg4) {} - - @OnUpdateState - void testUpdateState() {} - - @OnUpdateStateWithTransition - Transition testUpdateStateWithTransition() { - return Transition.create(Transition.TransitionKeyType.GLOBAL, "key") - .animate(AnimatedProperties.X); - } - } - - @LayoutSpec - private static class TestWithSameGenericMultipleTimesSpec { - - @OnCreateLayout - static void onCreateLayout(@State List values) {} - - @OnUpdateState - static void updateValues(StateValue> values, @Param List foos) {} - } - - @LayoutSpec - private static class TestWithMultipleGenericsSpec { - - @OnCreateLayout - static void onCreateLayout(@State Function functions) {} - - @OnUpdateState - static void updateValues( - StateValue> functions, @Param Function foos) {} - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/StateGeneratorTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/generator/StateGeneratorTest.java deleted file mode 100644 index 26f7b1f1abe..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/StateGeneratorTest.java +++ /dev/null @@ -1,515 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.generator; - -import static com.facebook.litho.specmodels.generator.StateGenerator.STATE_UPDATE_PREFIX; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -import androidx.annotation.Nullable; -import com.facebook.litho.StateValue; -import com.facebook.litho.Transition; -import com.facebook.litho.animation.AnimatedProperties; -import com.facebook.litho.annotations.LayoutSpec; -import com.facebook.litho.annotations.OnCreateInitialState; -import com.facebook.litho.annotations.OnCreateLayout; -import com.facebook.litho.annotations.OnEvent; -import com.facebook.litho.annotations.OnUpdateState; -import com.facebook.litho.annotations.OnUpdateStateWithTransition; -import com.facebook.litho.annotations.Param; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.annotations.State; -import com.facebook.litho.annotations.TreeProp; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.model.SpecModel; -import com.facebook.litho.specmodels.processor.LayoutSpecModelFactory; -import com.google.testing.compile.CompilationRule; -import java.util.List; -import java.util.function.Function; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests {@link StateGenerator} */ -@RunWith(JUnit4.class) -public class StateGeneratorTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - - private final LayoutSpecModelFactory mLayoutSpecModelFactory = new LayoutSpecModelFactory(); - - @LayoutSpec - private static class TestWithStateSpec { - @OnCreateLayout - public void onCreateLayout( - @Prop boolean arg0, - @State int arg1, - @Param Object arg2, - @TreeProp long arg3, - @State(canUpdateLazily = true) boolean arg4) {} - - @OnEvent(Object.class) - public void testEventMethod2(@Prop boolean arg0, @State int arg1) {} - - @OnUpdateState - void updateCurrentState(@Param Object nonnullObject, @Param @Nullable Object nulalbleObject) {} - } - - @LayoutSpec - private static class TestWithoutStateSpec { - - @OnCreateLayout - public void onCreateLayout() {} - } - - @LayoutSpec - private static class TestWithStateWithTransitionSpec { - @OnCreateLayout - public void onCreateLayout( - @Prop boolean arg0, - @State int arg1, - @Param Object arg2, - @TreeProp long arg3, - @State(canUpdateLazily = true) boolean arg4) {} - - @OnEvent(Object.class) - public void testEventMethod2(@Prop boolean arg0, @State int arg1) {} - - @OnUpdateStateWithTransition - void updateCurrentState() {} - } - - @LayoutSpec - private static class TestWithBothStatesSpec { - @OnCreateLayout - public void onCreateLayout( - @Prop boolean arg0, - @State int arg1, - @Param Object arg2, - @TreeProp long arg3, - @State(canUpdateLazily = true) boolean arg4) {} - - @OnEvent(Object.class) - public void testEventMethod2(@Prop boolean arg0, @State int arg1) {} - - @OnUpdateState - void updateCurrentState() {} - - @OnUpdateStateWithTransition - Transition updateCurrentStateWithTransition() { - return Transition.create(Transition.TransitionKeyType.GLOBAL, "key") - .animate(AnimatedProperties.X); - } - } - - @LayoutSpec - private static class TestWithLazyGeneric { - @OnCreateLayout - public void onCreateLayout(@State(canUpdateLazily = true) T arg0) {} - - @OnUpdateState - void updateCurrentState() {} - } - - @LayoutSpec - private static class TestWithLazyMethodGeneric { - @OnCreateLayout - public void onCreateLayout(@Prop int arg0) {} - - @OnCreateInitialState - static void onCreateInitialState(@State(canUpdateLazily = true) T arg1) {} - } - - @LayoutSpec - private static class TestWithLazyMethodGenericNullable { - @OnCreateLayout - public void onCreateLayout(@Prop int arg0) {} - - @OnCreateInitialState - static void onCreateInitialState(@State(canUpdateLazily = true) @Nullable T arg1) {} - } - - @LayoutSpec - private static class TestWithSameGenericMultipleTimes { - - @OnCreateLayout - static void onCreateLayout(@State List values) {} - - @OnUpdateState - static void updateValues(StateValue> values, @Param List foos) {} - } - - @LayoutSpec - private static class TestWithMultipleGenerics { - - @OnCreateLayout - static void onCreateLayout(@State Function functions) {} - - @OnUpdateState - static void updateValues( - StateValue> functions, @Param Function foos) {} - } - - private SpecModel mSpecModelWithState; - private SpecModel mSpecModelWithoutState; - private SpecModel mSpecModelWithStateWithTransition; - private SpecModel mSpecModelWithBothStates; - private SpecModel mSpecModelWithLazyGeneric; - private SpecModel mSpecModelWithLazyMethodGeneric; - private SpecModel mSpecModelWithLazyMethodGenericNullable; - private SpecModel mSpecWithSameGenericMultipleTimes; - private SpecModel mSpecWithMultipleGenerics; - - @Before - public void setUp() { - Elements elements = mCompilationRule.getElements(); - Types types = mCompilationRule.getTypes(); - TypeElement typeElementWithState = - elements.getTypeElement(TestWithStateSpec.class.getCanonicalName()); - mSpecModelWithState = - mLayoutSpecModelFactory.create( - elements, - types, - typeElementWithState, - mock(Messager.class), - RunMode.normal(), - null, - null); - TypeElement typeElementWithoutState = - elements.getTypeElement(TestWithoutStateSpec.class.getCanonicalName()); - mSpecModelWithoutState = - mLayoutSpecModelFactory.create( - elements, - types, - typeElementWithoutState, - mock(Messager.class), - RunMode.normal(), - null, - null); - - TypeElement typeElementWithStateWithTransition = - elements.getTypeElement(TestWithStateWithTransitionSpec.class.getCanonicalName()); - mSpecModelWithStateWithTransition = - mLayoutSpecModelFactory.create( - elements, - types, - typeElementWithStateWithTransition, - mock(Messager.class), - RunMode.normal(), - null, - null); - - TypeElement typeElementWithBothStates = - elements.getTypeElement(TestWithBothStatesSpec.class.getCanonicalName()); - mSpecModelWithBothStates = - mLayoutSpecModelFactory.create( - elements, - types, - typeElementWithBothStates, - mock(Messager.class), - RunMode.normal(), - null, - null); - - final TypeElement typeElementWithLazyGeneric = - elements.getTypeElement(TestWithLazyGeneric.class.getCanonicalName()); - mSpecModelWithLazyGeneric = - mLayoutSpecModelFactory.create( - elements, - types, - typeElementWithLazyGeneric, - mock(Messager.class), - RunMode.normal(), - null, - null); - - final TypeElement typeElementWithLazyMethodGeneric = - elements.getTypeElement(TestWithLazyMethodGeneric.class.getCanonicalName()); - mSpecModelWithLazyMethodGeneric = - mLayoutSpecModelFactory.create( - elements, - types, - typeElementWithLazyMethodGeneric, - mock(Messager.class), - RunMode.normal(), - null, - null); - - final TypeElement typeElementWithLazyMethodGenericNullable = - elements.getTypeElement(TestWithLazyMethodGenericNullable.class.getCanonicalName()); - mSpecModelWithLazyMethodGenericNullable = - mLayoutSpecModelFactory.create( - elements, - types, - typeElementWithLazyMethodGenericNullable, - mock(Messager.class), - RunMode.normal(), - null, - null); - - final TypeElement typeElementWithSameGenericMultipleTimes = - elements.getTypeElement(TestWithSameGenericMultipleTimes.class.getCanonicalName()); - mSpecWithSameGenericMultipleTimes = - mLayoutSpecModelFactory.create( - elements, - types, - typeElementWithSameGenericMultipleTimes, - mock(Messager.class), - RunMode.normal(), - null, - null); - - final TypeElement typeElementWithMultipleGenerics = - elements.getTypeElement(TestWithMultipleGenerics.class.getCanonicalName()); - mSpecWithMultipleGenerics = - mLayoutSpecModelFactory.create( - elements, - types, - typeElementWithMultipleGenerics, - mock(Messager.class), - RunMode.normal(), - null, - null); - } - - @Test - public void testGenerateHasState() { - TypeSpecDataHolder dataHolder = StateGenerator.generateHasState(mSpecModelWithState); - - assertThat(dataHolder.getMethodSpecs()).hasSize(1); - - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "@java.lang.Override\n" - + "protected boolean hasState() {\n" - + " return true;\n" - + "}\n"); - } - - @Test - public void testDoNotGenerateState() { - TypeSpecDataHolder dataHolder = StateGenerator.generateHasState(mSpecModelWithoutState); - - assertThat(dataHolder.getMethodSpecs()).isEmpty(); - } - - @Test - public void testDoNotGenerateTransferState() { - TypeSpecDataHolder dataHolder = StateGenerator.generateTransferState(mSpecModelWithoutState); - - assertThat(dataHolder.getMethodSpecs()).isEmpty(); - } - - @Test - public void testGenerateStateContainerWithLazyStateUpdatesApplied_noLazyState() { - TypeSpecDataHolder dataHolder = - StateGenerator.generateGetStateContainerWithLazyStateUpdatesApplied(mSpecModelWithoutState); - - assertThat(dataHolder.getMethodSpecs()).isEmpty(); - } - - @Test - public void testGenerateStateContainerWithLazyStateUpdatesApplied_withLazyState() { - TypeSpecDataHolder dataHolder = - StateGenerator.generateGetStateContainerWithLazyStateUpdatesApplied(mSpecModelWithState); - - assertThat(dataHolder.getMethodSpecs()).hasSize(1); - - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "private TestWithStateStateContainer getStateContainerWithLazyStateUpdatesApplied(\n" - + " com.facebook.litho.ComponentContext c,\n" - + " com.facebook.litho.specmodels.generator.StateGeneratorTest.TestWithState" - + " component) {\n" - + " TestWithStateStateContainer _stateContainer = (TestWithStateStateContainer)" - + " getStateContainerImpl(c);\n" - + " return (TestWithStateStateContainer)" - + " c.applyLazyStateUpdatesForContainer(_stateContainer);\n" - + "}\n"); - } - - @Test - public void testGenerateOnStateUpdateMethods() { - TypeSpecDataHolder dataHolder = - StateGenerator.generateOnStateUpdateMethods(mSpecModelWithState); - - assertThat(dataHolder.getMethodSpecs()).hasSize(3); - - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "protected static void updateCurrentState(com.facebook.litho.ComponentContext c,\n" - + " java.lang.Object nonnullObject, @androidx.annotation.Nullable" - + " java.lang.Object nulalbleObject) {\n" - + " com.facebook.litho.Component _component = c.getComponentScope();\n" - + " if (_component == null) {\n" - + " return;\n" - + " }\n" - + " com.facebook.litho.StateContainer.StateUpdate _stateUpdate = new" - + " com.facebook.litho.StateContainer.StateUpdate(0, nonnullObject," - + " nulalbleObject);\n" - + " c.updateStateAsync(_stateUpdate, \"" - + STATE_UPDATE_PREFIX - + "TestWithState.updateCurrentState\");\n" - + "}\n"); - - assertThat(dataHolder.getMethodSpecs().get(1).toString()) - .isEqualTo( - "protected static void updateCurrentStateAsync(com.facebook.litho.ComponentContext c,\n" - + " java.lang.Object nonnullObject, @androidx.annotation.Nullable" - + " java.lang.Object nulalbleObject) {\n" - + " com.facebook.litho.Component _component = c.getComponentScope();\n" - + " if (_component == null) {\n" - + " return;\n" - + " }\n" - + " com.facebook.litho.StateContainer.StateUpdate _stateUpdate = new" - + " com.facebook.litho.StateContainer.StateUpdate(0, nonnullObject," - + " nulalbleObject);\n" - + " c.updateStateAsync(_stateUpdate, \"" - + STATE_UPDATE_PREFIX - + "TestWithState.updateCurrentState\");\n" - + "}\n"); - - assertThat(dataHolder.getMethodSpecs().get(2).toString()) - .isEqualTo( - "protected static void updateCurrentStateSync(com.facebook.litho.ComponentContext c,\n" - + " java.lang.Object nonnullObject, @androidx.annotation.Nullable" - + " java.lang.Object nulalbleObject) {\n" - + " com.facebook.litho.Component _component = c.getComponentScope();\n" - + " if (_component == null) {\n" - + " return;\n" - + " }\n" - + " com.facebook.litho.StateContainer.StateUpdate _stateUpdate = new" - + " com.facebook.litho.StateContainer.StateUpdate(0, nonnullObject," - + " nulalbleObject);\n" - + " c.updateStateSync(_stateUpdate, \"" - + STATE_UPDATE_PREFIX - + "TestWithState.updateCurrentState\");\n" - + "}\n"); - } - - @Test - public void testGenerateOnStateUpdateWithTransitionMethods() { - TypeSpecDataHolder dataHolder = - StateGenerator.generateOnStateUpdateMethods(mSpecModelWithStateWithTransition); - - assertThat(dataHolder.getMethodSpecs()).hasSize(1); - - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "protected static void" - + " updateCurrentStateWithTransition(com.facebook.litho.ComponentContext c) {\n" - + " com.facebook.litho.Component _component = c.getComponentScope();\n" - + " if (_component == null) {\n" - + " return;\n" - + " }\n" - + " com.facebook.litho.StateContainer.StateUpdate _stateUpdate = new" - + " com.facebook.litho.StateContainer.StateUpdate(0);\n" - + " c.updateStateWithTransition(_stateUpdate, \"" - + STATE_UPDATE_PREFIX - + "TestWithStateWithTransition.updateCurrentState\");\n" - + "}\n"); - } - - @Test - public void testGenerateLazyStateUpdateMethods() { - TypeSpecDataHolder dataHolder = - StateGenerator.generateLazyStateUpdateMethods(mSpecModelWithState); - - assertThat(dataHolder.getMethodSpecs()).hasSize(1); - - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "protected static void lazyUpdateArg4(com.facebook.litho.ComponentContext c,\n" - + " final boolean lazyUpdateValue) {\n" - + " com.facebook.litho.Component _component = c.getComponentScope();\n" - + " if (_component == null) {\n" - + " return;\n" - + " }\n" - + " com.facebook.litho.StateContainer.StateUpdate _stateUpdate = new" - + " com.facebook.litho.StateContainer.StateUpdate(-2147483648, lazyUpdateValue);\n" - + " c.updateStateLazy(_stateUpdate);\n" - + "}\n"); - } - - @Test - public void testGenerateLazyStateUpdateMethodsForGenerics() { - TypeSpecDataHolder dataHolder = - StateGenerator.generateLazyStateUpdateMethods(mSpecModelWithLazyGeneric); - - assertThat(dataHolder.getMethodSpecs()).hasSize(1); - - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "protected static void lazyUpdateArg0(\n" - + " com.facebook.litho.ComponentContext c, final T lazyUpdateValue) {\n" - + " com.facebook.litho.Component _component = c.getComponentScope();\n" - + " if (_component == null) {\n" - + " return;\n" - + " }\n" - + " com.facebook.litho.StateContainer.StateUpdate _stateUpdate = new" - + " com.facebook.litho.StateContainer.StateUpdate(-2147483648, lazyUpdateValue);\n" - + " c.updateStateLazy(_stateUpdate);\n" - + "}\n"); - } - - @Test - public void testGenerateLazyStateUpdateMethodsForGenericMethod() { - TypeSpecDataHolder dataHolder = - StateGenerator.generateLazyStateUpdateMethods(mSpecModelWithLazyMethodGeneric); - - assertThat(dataHolder.getMethodSpecs()).hasSize(1); - - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "protected static void lazyUpdateArg1(com.facebook.litho.ComponentContext c,\n" - + " final T lazyUpdateValue) {\n" - + " com.facebook.litho.Component _component = c.getComponentScope();\n" - + " if (_component == null) {\n" - + " return;\n" - + " }\n" - + " com.facebook.litho.StateContainer.StateUpdate _stateUpdate = new" - + " com.facebook.litho.StateContainer.StateUpdate(-2147483648, lazyUpdateValue);\n" - + " c.updateStateLazy(_stateUpdate);\n" - + "}\n"); - } - - @Test - public void testGenerateLazyStateUpdateMethodsForGenericMethodNullable() { - TypeSpecDataHolder dataHolder = - StateGenerator.generateLazyStateUpdateMethods(mSpecModelWithLazyMethodGenericNullable); - - assertThat(dataHolder.getMethodSpecs()).hasSize(1); - - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "protected static void lazyUpdateArg1(com.facebook.litho.ComponentContext c,\n" - + " @androidx.annotation.Nullable final T lazyUpdateValue) {\n" - + " com.facebook.litho.Component _component = c.getComponentScope();\n" - + " if (_component == null) {\n" - + " return;\n" - + " }\n" - + " com.facebook.litho.StateContainer.StateUpdate _stateUpdate = new" - + " com.facebook.litho.StateContainer.StateUpdate(-2147483648, lazyUpdateValue);\n" - + " c.updateStateLazy(_stateUpdate);\n" - + "}\n"); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/TriggerGeneratorTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/generator/TriggerGeneratorTest.java deleted file mode 100644 index 7972c93738a..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/TriggerGeneratorTest.java +++ /dev/null @@ -1,410 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.generator; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -import androidx.annotation.Nullable; -import com.facebook.litho.ComponentContext; -import com.facebook.litho.annotations.Event; -import com.facebook.litho.annotations.FromTrigger; -import com.facebook.litho.annotations.LayoutSpec; -import com.facebook.litho.annotations.OnTrigger; -import com.facebook.litho.annotations.Param; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.annotations.PropDefault; -import com.facebook.litho.annotations.State; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.model.SpecModel; -import com.facebook.litho.specmodels.processor.LayoutSpecModelFactory; -import com.google.testing.compile.CompilationRule; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests {@link TriggerGenerator} */ -@RunWith(JUnit4.class) -public class TriggerGeneratorTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - - private final LayoutSpecModelFactory mLayoutSpecModelFactory = new LayoutSpecModelFactory(); - - @LayoutSpec - static class TestSpec { - @PropDefault protected static final boolean arg0 = true; - - @OnTrigger(TestEvent.class) - public Object testTriggerMethod1( - ComponentContext c, - @Prop boolean arg0, - @State int arg1, - @Param Object arg2, - @Param @Nullable T arg3, - @FromTrigger long arg4, - @FromTrigger @Nullable T arg5) { - - return null; - } - - @OnTrigger(Object.class) - public void testTriggerMethod2(ComponentContext c, @Prop boolean arg0, @State int arg1) {} - } - - @Event(returnType = Object.class) - static class TestEvent { - public long arg4; - } - - private SpecModel mSpecModel; - - @Before - public void setUp() { - Elements elements = mCompilationRule.getElements(); - Types types = mCompilationRule.getTypes(); - TypeElement typeElement = elements.getTypeElement(TestSpec.class.getCanonicalName()); - mSpecModel = - mLayoutSpecModelFactory.create( - elements, types, typeElement, mock(Messager.class), RunMode.normal(), null, null); - } - - @Test - public void testGenerateAcceptTriggerEvent() { - assertThat(TriggerGenerator.generateAcceptTriggerEventImpl(mSpecModel).toString()) - .isEqualTo( - "@java.lang.Override\n" - + "protected java.lang.Object acceptTriggerEventImpl(\n" - + " final com.facebook.litho.EventTrigger eventTrigger, final java.lang.Object" - + " eventState,\n" - + " final java.lang.Object[] params) {\n" - + " int id = eventTrigger.getId();\n" - + " switch(id) {\n" - + " case -773082596: {\n" - + " com.facebook.litho.specmodels.generator.TriggerGeneratorTest.TestEvent" - + " _event =" - + " (com.facebook.litho.specmodels.generator.TriggerGeneratorTest.TestEvent)" - + " eventState;\n" - + " return testTriggerMethod1(\n" - + " (com.facebook.litho.ComponentContext)" - + " eventTrigger.getComponentContext(),\n" - + " eventTrigger.getTriggerTarget(),\n" - + " (java.lang.Object) params[0],\n" - + " (T) params[1],\n" - + " _event.arg4,\n" - + " _event.arg5);\n" - + " }\n" - + " case 969727739: {\n" - + " java.lang.Object _event = (java.lang.Object) eventState;\n" - + " testTriggerMethod2(\n" - + " (com.facebook.litho.ComponentContext)" - + " eventTrigger.getComponentContext(),\n" - + " eventTrigger.getTriggerTarget());\n" - + " return null;\n" - + " }\n" - + " default:\n" - + " return null;\n" - + " }\n" - + "}\n"); - } - - @Test - public void testGenerateOnTriggerMethods() { - TypeSpecDataHolder dataHolder = TriggerGenerator.generateOnTriggerMethodDelegates(mSpecModel); - - assertThat(dataHolder.getMethodSpecs()).hasSize(2); - - String result = dataHolder.getMethodSpecs().get(0).toString(); - System.out.println(result); - assertThat(result) - .isEqualTo( - "private java.lang.Object testTriggerMethod1(com.facebook.litho.ComponentContext c,\n" - + " com.facebook.litho.EventTriggerTarget _abstract, java.lang.Object arg2,\n" - + " @androidx.annotation.Nullable T arg3, long arg4," - + " @androidx.annotation.Nullable T arg5) {\n" - + " Test _ref = (Test) _abstract;\n" - + " java.lang.Object _result = (java.lang.Object) TestSpec.testTriggerMethod1(\n" - + " c,\n" - + " (boolean) _ref.arg0,\n" - + " (int) _ref.getStateContainerImpl(c).arg1,\n" - + " arg2,\n" - + " arg3,\n" - + " arg4,\n" - + " arg5);\n" - + " return _result;\n" - + "}\n"); - - String result2 = dataHolder.getMethodSpecs().get(1).toString(); - System.out.println(result2); - assertThat(result2) - .isEqualTo( - "private void testTriggerMethod2(com.facebook.litho.ComponentContext c,\n" - + " com.facebook.litho.EventTriggerTarget _abstract) {\n" - + " Test _ref = (Test) _abstract;\n" - + " TestSpec.testTriggerMethod2(\n" - + " c,\n" - + " (boolean) _ref.arg0,\n" - + " (int) _ref.getStateContainerImpl(c).arg1);\n" - + "}\n"); - } - - @Test - public void testGenerateStaticTriggerMethod() { - TypeSpecDataHolder dataHolder = TriggerGenerator.generateStaticTriggerMethods(mSpecModel); - - assertThat(dataHolder.getMethodSpecs()).hasSize(8); - - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "/**\n" - + " * This will send the testTriggerMethod1 trigger to the component with the given" - + " handle.\n" - + " * For more information about using triggers, see" - + " https://fblitho.com/docs/trigger-events\n" - + " */\n" - + "public static java.lang.Object" - + " testTriggerMethod1(\n" - + " com.facebook.litho.ComponentContext c, com.facebook.litho.Handle handle," - + " java.lang.Object arg2,\n" - + " @androidx.annotation.Nullable T arg3, long arg4," - + " @androidx.annotation.Nullable T arg5) {\n" - + " int methodId = -773082596;\n" - + " com.facebook.litho.EventTrigger trigger = getEventTrigger(c, methodId," - + " handle);\n" - + " if (trigger == null) {\n" - + " return null;\n" - + " }\n" - + " com.facebook.litho.specmodels.generator.TriggerGeneratorTest.TestEvent" - + " _eventState = new" - + " com.facebook.litho.specmodels.generator.TriggerGeneratorTest.TestEvent();\n" - + " _eventState.arg4 = arg4;\n" - + " _eventState.arg5 = arg5;\n" - + " return (java.lang.Object) trigger.dispatchOnTrigger(_eventState, new Object[]" - + " {\n" - + " arg2,\n" - + " arg3,\n" - + " });\n" - + "}\n"); - - assertThat(dataHolder.getMethodSpecs().get(1).toString()) - .isEqualTo( - "/**\n" - + " * @deprecated Use {@link #testTriggerMethod1(ComponentContext, Handle)}" - + " instead.\n" - + " */\n" - + "@java.lang.Deprecated\n" - + "public static java.lang.Object" - + " testTriggerMethod1(\n" - + " com.facebook.litho.ComponentContext c, java.lang.String key," - + " java.lang.Object arg2,\n" - + " @androidx.annotation.Nullable T arg3, long arg4," - + " @androidx.annotation.Nullable T arg5) {\n" - + " int methodId = -773082596;\n" - + " com.facebook.litho.EventTrigger trigger = getEventTrigger(c, methodId, key);\n" - + " if (trigger == null) {\n" - + " return null;\n" - + " }\n" - + " com.facebook.litho.specmodels.generator.TriggerGeneratorTest.TestEvent" - + " _eventState = new" - + " com.facebook.litho.specmodels.generator.TriggerGeneratorTest.TestEvent();\n" - + " _eventState.arg4 = arg4;\n" - + " _eventState.arg5 = arg5;\n" - + " return (java.lang.Object) trigger.dispatchOnTrigger(_eventState, new Object[]" - + " {\n" - + " arg2,\n" - + " arg3,\n" - + " });\n" - + "}\n"); - - assertThat(dataHolder.getMethodSpecs().get(2).toString()) - .isEqualTo( - "/**\n" - + " * @deprecated Use {@link #testTriggerMethod1(ComponentContext, Handle)}" - + " instead.\n" - + " */\n" - + "@java.lang.Deprecated\n" - + "public static java.lang.Object" - + " testTriggerMethod1(\n" - + " com.facebook.litho.EventTrigger trigger, java.lang.Object arg2,\n" - + " @androidx.annotation.Nullable T arg3, long arg4," - + " @androidx.annotation.Nullable T arg5) {\n" - + " com.facebook.litho.specmodels.generator.TriggerGeneratorTest.TestEvent" - + " _eventState = new" - + " com.facebook.litho.specmodels.generator.TriggerGeneratorTest.TestEvent();\n" - + " _eventState.arg4 = arg4;\n" - + " _eventState.arg5 = arg5;\n" - + " return (java.lang.Object) trigger.dispatchOnTrigger(_eventState, new Object[]" - + " {\n" - + " arg2,\n" - + " arg3,\n" - + " });\n" - + "}\n"); - - assertThat(dataHolder.getMethodSpecs().get(3).toString()) - .isEqualTo( - "/**\n" - + " * @deprecated Use {@link #testTriggerMethod1(ComponentContext, Handle)}" - + " instead.\n" - + " */\n" - + "@java.lang.Deprecated\n" - + "static java.lang.Object testTriggerMethod1(\n" - + " com.facebook.litho.ComponentContext c, java.lang.Object arg2,\n" - + " @androidx.annotation.Nullable T arg3, long arg4," - + " @androidx.annotation.Nullable T arg5) {\n" - + " Test component = (Test) c.getComponentScope();\n" - + " return component.testTriggerMethod1(\n" - + " c,\n" - + " (com.facebook.litho.EventTriggerTarget) component,\n" - + " arg2,\n" - + " arg3,\n" - + " arg4,\n" - + " arg5);\n" - + "}\n"); - - assertThat(dataHolder.getMethodSpecs().get(4).toString()) - .isEqualTo( - "/**\n" - + " * This will send the testTriggerMethod2 trigger to the component with the given" - + " handle.\n" - + " * For more information about using triggers, see" - + " https://fblitho.com/docs/trigger-events\n" - + " */\n" - + "public static void testTriggerMethod2(com.facebook.litho.ComponentContext c,\n" - + " com.facebook.litho.Handle handle) {\n" - + " int methodId = 969727739;\n" - + " com.facebook.litho.EventTrigger trigger = getEventTrigger(c, methodId," - + " handle);\n" - + " if (trigger == null) {\n" - + " return;\n" - + " }\n" - + " java.lang.Object _eventState = new java.lang.Object();\n" - + " trigger.dispatchOnTrigger(_eventState, new Object[] {\n" - + " });\n" - + "}\n"); - - assertThat(dataHolder.getMethodSpecs().get(5).toString()) - .isEqualTo( - "/**\n" - + " * @deprecated Use {@link #testTriggerMethod2(ComponentContext, Handle)}" - + " instead.\n" - + " */\n" - + "@java.lang.Deprecated\n" - + "public static void testTriggerMethod2(com.facebook.litho.ComponentContext c," - + " java.lang.String key) {\n" - + " int methodId = 969727739;\n" - + " com.facebook.litho.EventTrigger trigger = getEventTrigger(c, methodId, key);\n" - + " if (trigger == null) {\n" - + " return;\n" - + " }\n" - + " java.lang.Object _eventState = new java.lang.Object();\n" - + " trigger.dispatchOnTrigger(_eventState, new Object[] {\n" - + " });\n" - + "}\n"); - - assertThat(dataHolder.getMethodSpecs().get(6).toString()) - .isEqualTo( - "/**\n" - + " * @deprecated Use {@link #testTriggerMethod2(ComponentContext, Handle)}" - + " instead.\n" - + " */\n" - + "@java.lang.Deprecated\n" - + "public static void testTriggerMethod2(com.facebook.litho.EventTrigger trigger)" - + " {\n" - + " java.lang.Object _eventState = new java.lang.Object();\n" - + " trigger.dispatchOnTrigger(_eventState, new Object[] {\n" - + " });\n" - + "}\n"); - - assertThat(dataHolder.getMethodSpecs().get(7).toString()) - .isEqualTo( - "/**\n" - + " * @deprecated Use {@link #testTriggerMethod2(ComponentContext, Handle)}" - + " instead.\n" - + " */\n" - + "@java.lang.Deprecated\n" - + "static void testTriggerMethod2(com.facebook.litho.ComponentContext c) {\n" - + " Test component = (Test) c.getComponentScope();\n" - + " component.testTriggerMethod2(\n" - + " c,\n" - + " (com.facebook.litho.EventTriggerTarget) component);\n" - + "}\n"); - } - - @Test - public void testGenerateStaticGetTriggerMethods() { - TypeSpecDataHolder dataHolder = TriggerGenerator.generateStaticGetTriggerMethods(mSpecModel); - - assertThat(dataHolder.getMethodSpecs()).hasSize(4); - - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "private static" - + " com.facebook.litho.EventTrigger" - + " createTestTriggerMethod1Trigger(\n" - + " com.facebook.litho.ComponentContext c, com.facebook.litho.Component" - + " component) {\n" - + " int methodId = -773082596;\n" - + " return newEventTrigger(c, component, methodId);\n" - + "}\n"); - - assertThat(dataHolder.getMethodSpecs().get(1).toString()) - .isEqualTo( - "/**\n" - + " * @deprecated Do not use this method to get a EventTrigger to use later." - + " Instead give the component a Handle and use {@link" - + " #testTriggerMethod1(ComponentContext, Handle)}.\n" - + " */\n" - + "@java.lang.Deprecated\n" - + "public static" - + " com.facebook.litho.EventTrigger" - + " testTriggerMethod1Trigger(\n" - + " com.facebook.litho.ComponentContext c, java.lang.String key) {\n" - + " int methodId = -773082596;\n" - + " return newEventTrigger(c, key, methodId);\n" - + "}\n"); - - assertThat(dataHolder.getMethodSpecs().get(2).toString()) - .isEqualTo( - "private static com.facebook.litho.EventTrigger" - + " createTestTriggerMethod2Trigger(\n" - + " com.facebook.litho.ComponentContext c, com.facebook.litho.Component" - + " component) {\n" - + " int methodId = 969727739;\n" - + " return newEventTrigger(c, component, methodId);\n" - + "}\n"); - - assertThat(dataHolder.getMethodSpecs().get(3).toString()) - .isEqualTo( - "/**\n" - + " * @deprecated Do not use this method to get a EventTrigger to use later." - + " Instead give the component a Handle and use {@link" - + " #testTriggerMethod2(ComponentContext, Handle)}.\n" - + " */\n" - + "@java.lang.Deprecated\n" - + "public static com.facebook.litho.EventTrigger" - + " testTriggerMethod2Trigger(\n" - + " com.facebook.litho.ComponentContext c, java.lang.String key) {\n" - + " int methodId = 969727739;\n" - + " return newEventTrigger(c, key, methodId);\n" - + "}\n"); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/WorkingRangeGeneratorTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/generator/WorkingRangeGeneratorTest.java deleted file mode 100644 index d0b99ba4d0e..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/generator/WorkingRangeGeneratorTest.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.generator; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -import com.facebook.litho.ComponentContext; -import com.facebook.litho.annotations.LayoutSpec; -import com.facebook.litho.annotations.OnEnteredRange; -import com.facebook.litho.annotations.OnExitedRange; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.annotations.PropDefault; -import com.facebook.litho.annotations.State; -import com.facebook.litho.annotations.TreeProp; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.model.SpecModel; -import com.facebook.litho.specmodels.processor.LayoutSpecModelFactory; -import com.google.testing.compile.CompilationRule; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -@RunWith(JUnit4.class) -public class WorkingRangeGeneratorTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - - private final LayoutSpecModelFactory mLayoutSpecModelFactory = new LayoutSpecModelFactory(); - - @LayoutSpec - static class TestSpec { - @PropDefault protected static final boolean arg0 = true; - - @OnEnteredRange(name = "enter") - public void testEnteredRangeMethod(ComponentContext c, @Prop boolean arg0, @State int arg1) {} - - @OnExitedRange(name = "exit") - public void testExitedRangeMethod(ComponentContext c, @Prop T arg2, @TreeProp int arg3) {} - - @OnEnteredRange(name = "prefetch") - public void testEnteredPrefetchMethod( - ComponentContext c, @Prop boolean arg0, @State int arg1) {} - - @OnExitedRange(name = "prefetch") - public void testExitedPrefetchMethod(ComponentContext c, @Prop T arg2, @TreeProp int arg3) {} - } - - private SpecModel mSpecModel; - - @Before - public void setUp() { - Elements elements = mCompilationRule.getElements(); - Types types = mCompilationRule.getTypes(); - TypeElement typeElement = - elements.getTypeElement(WorkingRangeGeneratorTest.TestSpec.class.getCanonicalName()); - mSpecModel = - mLayoutSpecModelFactory.create( - elements, types, typeElement, mock(Messager.class), RunMode.normal(), null, null); - } - - @Test - public void testGenerateDispatchOnEnteredRange() { - assertThat(WorkingRangeGenerator.generateDispatchOnEnteredRangeMethod(mSpecModel).toString()) - .isEqualTo( - "@java.lang.Override\n" - + "public void dispatchOnEnteredRange(com.facebook.litho.ComponentContext c," - + " java.lang.String name,\n" - + " com.facebook.litho.InterStagePropsContainer interStageProps) {\n" - + " switch (name) {\n" - + " case \"enter\": {\n" - + " testEnteredRangeMethod(c, interStageProps);\n" - + " return;\n" - + " }\n" - + " case \"prefetch\": {\n" - + " testEnteredPrefetchMethod(c, interStageProps);\n" - + " return;\n" - + " }\n" - + " }\n" - + "}\n"); - } - - @Test - public void testGenerateDispatchOnExitedRange() { - assertThat(WorkingRangeGenerator.generateDispatchOnExitedRangeMethod(mSpecModel).toString()) - .isEqualTo( - "@java.lang.Override\n" - + "public void dispatchOnExitedRange(com.facebook.litho.ComponentContext c," - + " java.lang.String name,\n" - + " com.facebook.litho.InterStagePropsContainer interStageProps) {\n" - + " switch (name) {\n" - + " case \"exit\": {\n" - + " testExitedRangeMethod(c, interStageProps);\n" - + " return;\n" - + " }\n" - + " case \"prefetch\": {\n" - + " testExitedPrefetchMethod(c, interStageProps);\n" - + " return;\n" - + " }\n" - + " }\n" - + "}\n"); - } - - @Test - public void testGenerateWorkingRangeMethodDelegates() { - TypeSpecDataHolder dataHolder = - WorkingRangeGenerator.generateWorkingRangeMethodDelegates(mSpecModel); - - assertThat(dataHolder.getMethodSpecs()).hasSize(4); - - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "private void testEnteredRangeMethod(com.facebook.litho.ComponentContext c,\n" - + " com.facebook.litho.InterStagePropsContainer interStageProps) {\n" - + " TestSpec.testEnteredRangeMethod(\n" - + " (com.facebook.litho.ComponentContext) c,\n" - + " (boolean) arg0,\n" - + " (int) getStateContainerImpl(c).arg1);\n" - + "}\n"); - - assertThat(dataHolder.getMethodSpecs().get(1).toString()) - .isEqualTo( - "private void testExitedRangeMethod(com.facebook.litho.ComponentContext c,\n" - + " com.facebook.litho.InterStagePropsContainer interStageProps) {\n" - + " TestSpec.testExitedRangeMethod(\n" - + " (com.facebook.litho.ComponentContext) c,\n" - + " (T) arg2,\n" - + " (int) (c.getParentTreeProp(int.class)));\n" - + "}\n"); - - assertThat(dataHolder.getMethodSpecs().get(2).toString()) - .isEqualTo( - "private void testEnteredPrefetchMethod(com.facebook.litho.ComponentContext c,\n" - + " com.facebook.litho.InterStagePropsContainer interStageProps) {\n" - + " TestSpec.testEnteredPrefetchMethod(\n" - + " (com.facebook.litho.ComponentContext) c,\n" - + " (boolean) arg0,\n" - + " (int) getStateContainerImpl(c).arg1);\n" - + "}\n"); - - assertThat(dataHolder.getMethodSpecs().get(3).toString()) - .isEqualTo( - "private void testExitedPrefetchMethod(com.facebook.litho.ComponentContext c,\n" - + " com.facebook.litho.InterStagePropsContainer interStageProps) {\n" - + " TestSpec.testExitedPrefetchMethod(\n" - + " (com.facebook.litho.ComponentContext) c,\n" - + " (T) arg2,\n" - + " (int) (c.getParentTreeProp(int.class)));\n" - + "}\n"); - } - - @Test - public void testGenerateStaticRegisterMethods() { - TypeSpecDataHolder dataHolder = WorkingRangeGenerator.generateStaticRegisterMethods(mSpecModel); - - assertThat(dataHolder.getMethodSpecs()).hasSize(3); - - assertThat(dataHolder.getMethodSpecs().get(0).toString()) - .isEqualTo( - "static void registerEnterWorkingRange(com.facebook.litho.ComponentContext c,\n" - + " com.facebook.litho.WorkingRange workingRange) {\n" - + " if (workingRange == null) {\n" - + " return;\n" - + " }\n" - + " com.facebook.litho.Component component = c.getComponentScope();\n" - + " registerWorkingRange(c, \"enter\", workingRange, component," - + " c.getGlobalKey());\n" - + "}\n"); - - assertThat(dataHolder.getMethodSpecs().get(1).toString()) - .isEqualTo( - "static void registerExitWorkingRange(com.facebook.litho.ComponentContext c,\n" - + " com.facebook.litho.WorkingRange workingRange) {\n" - + " if (workingRange == null) {\n" - + " return;\n" - + " }\n" - + " com.facebook.litho.Component component = c.getComponentScope();\n" - + " registerWorkingRange(c, \"exit\", workingRange, component," - + " c.getGlobalKey());\n" - + "}\n"); - - assertThat(dataHolder.getMethodSpecs().get(2).toString()) - .isEqualTo( - "static void registerPrefetchWorkingRange(com.facebook.litho.ComponentContext c,\n" - + " com.facebook.litho.WorkingRange workingRange) {\n" - + " if (workingRange == null) {\n" - + " return;\n" - + " }\n" - + " com.facebook.litho.Component component = c.getComponentScope();\n" - + " registerWorkingRange(c, \"prefetch\", workingRange, component," - + " c.getGlobalKey());\n" - + "}\n"); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/model/CachedValueGeneratorTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/model/CachedValueGeneratorTest.java deleted file mode 100644 index f0ed2a7ce50..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/model/CachedValueGeneratorTest.java +++ /dev/null @@ -1,923 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.model; - -import static org.assertj.core.api.Assertions.assertThat; - -import androidx.annotation.Nullable; -import com.facebook.litho.Component; -import com.facebook.litho.ComponentContext; -import com.facebook.litho.Row; -import com.facebook.litho.annotations.LayoutSpec; -import com.facebook.litho.annotations.OnCalculateCachedValue; -import com.facebook.litho.annotations.OnCreateLayout; -import com.facebook.litho.annotations.OnEvent; -import com.facebook.litho.annotations.OnUpdateState; -import com.facebook.litho.annotations.Param; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.annotations.State; -import com.facebook.litho.annotations.TreeProp; -import com.facebook.litho.specmodels.generator.CachedValueGenerator; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.processor.LayoutSpecModelFactory; -import com.google.testing.compile.CompilationRule; -import java.util.List; -import java.util.Set; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -/** Tests {@link CachedValueGenerator} */ -@RunWith(JUnit4.class) -public class CachedValueGeneratorTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - @Mock private Messager mMessager; - - private final LayoutSpecModelFactory mLayoutSpecModelFactory = new LayoutSpecModelFactory(); - - private SpecModel mLayoutSpecModel; - - @LayoutSpec - static class CachedValueTestSpec { - - @OnCalculateCachedValue(name = "expensiveValue") - static String onCreateExpensiveValue() { - return "ABC"; - } - - @OnCalculateCachedValue(name = "expensiveValueWithContext") - static String onCreateExpensiveValueWithContext(ComponentContext context) { - return "ABC"; - } - - @OnCalculateCachedValue(name = "moreExpensiveValue") - static String onCreateMoreExpensiveValue(@Prop boolean arg0, @State int arg1) { - return "DEF"; - } - - @OnCalculateCachedValue(name = "moreExpensiveValueWithContext") - static String onCreateMoreExpensiveValueWithContext( - @Prop boolean arg0, @State int arg1, ComponentContext context) { - return "DEF"; - } - - @OnCalculateCachedValue(name = "expensiveValueWithGeneric") - static String onCreateExpensiveValueWithGeneric(@Prop E genericArg) { - return "GHI"; - } - - @OnCalculateCachedValue(name = "expensiveValueWithMoreGenerics") - static String onCreateExpensiveValueWithMoreGenerics( - @Prop E genericArg, @Prop E genericArg2) { - return "JKL"; - } - - @OnCalculateCachedValue(name = "expensiveValueWithMoreGenericsAndContext") - static String onCreateExpensiveValueWithMoreGenericsAndContext( - ComponentContext context, @Prop E genericArg, @Prop E genericArg2) { - return "JKL"; - } - - @OnCalculateCachedValue(name = "expensiveValueWithTreeProp") - static String onCreateExpensiveValueWithTreeProp(@Prop boolean arg0, @TreeProp long arg6) { - return "MNO"; - } - - @OnCreateLayout - public void testDelegateMethod( - @Prop boolean arg0, - @Prop @Nullable Component arg1, - @Prop List arg2, - @Prop List arg3, - @Prop E genericArg, - @State int arg4, - @Param Object arg5, - @TreeProp long arg6, - @TreeProp Set> arg7, - @TreeProp Set arg8) {} - - @OnEvent(Object.class) - public void testEventMethod( - @Prop boolean arg0, - @Prop @Nullable Component arg1, - @State int arg2, - @Param Object arg3, - @TreeProp long arg4) {} - - @OnUpdateState - public void testUpdateStateMethod() {} - } - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - Elements elements = mCompilationRule.getElements(); - Types types = mCompilationRule.getTypes(); - TypeElement typeElement = - elements.getTypeElement( - CachedValueGeneratorTest.CachedValueTestSpec.class.getCanonicalName()); - mLayoutSpecModel = - mLayoutSpecModelFactory.create( - elements, types, typeElement, mMessager, RunMode.normal(), null, null); - } - - @Test - public void testGenerateInputsClassNoParam() { - final List> models = - SpecModelUtils.getMethodModelsWithAnnotation( - mLayoutSpecModel, OnCalculateCachedValue.class); - final SpecMethodModel specMethodModel = - models.stream() - .filter(m -> m.name.toString().equals("onCreateExpensiveValue")) - .findFirst() - .get(); - final String expensiveValueInputsClass = - CachedValueGenerator.createInputsClass( - CachedValueGenerator.getCachedValueInputs(specMethodModel), - "expensiveValue", - RunMode.normal()) - .toString(); - assertThat(expensiveValueInputsClass) - .isEqualTo( - "@com.facebook.litho.annotations.Generated\n" - + "private static class ExpensiveValueInputs {\n" - + " private final String globalKey;\n" - + "\n" - + " ExpensiveValueInputs(String globalKey) {\n" - + " this.globalKey = globalKey;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public int hashCode() {\n" - + " return com.facebook.litho.CommonUtils.hash(globalKey, getClass());\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public boolean equals(java.lang.Object other) {\n" - + " if (this == other) {\n" - + " return true;\n" - + " }\n" - + " if (other == null || !(other instanceof ExpensiveValueInputs)) {\n" - + " return false;\n" - + " }\n" - + " ExpensiveValueInputs cachedValueInputs = (ExpensiveValueInputs) other;\n" - + " if (!com.facebook.rendercore.utils.EquivalenceUtils.equals(globalKey," - + " cachedValueInputs.globalKey)) {\n" - + " return false;\n" - + " }\n" - + " return true;\n" - + " }\n" - + "}\n"); - } - - @Test - public void testGenerateGetterNoParam() { - final List> models = - SpecModelUtils.getMethodModelsWithAnnotation( - mLayoutSpecModel, OnCalculateCachedValue.class); - final SpecMethodModel specMethodModel = - models.stream() - .filter(m -> m.name.toString().equals("onCreateExpensiveValue")) - .findFirst() - .get(); - final String expensiveValueMethod = - CachedValueGenerator.createGetterMethod( - mLayoutSpecModel, - specMethodModel, - CachedValueGenerator.getCachedValueInputs(specMethodModel), - "expensiveValue", - 0) - .toString(); - assertThat(expensiveValueMethod) - .isEqualTo( - "private java.lang.String getExpensiveValue(com.facebook.litho.ComponentContext c) {\n" - + " String globalKey = c.getGlobalKey();\n" - + " final ExpensiveValueInputs inputs = new ExpensiveValueInputs(globalKey);\n" - + " java.lang.String expensiveValue = (java.lang.String)" - + " c.getCachedValue(globalKey, 0, inputs);\n" - + " if (expensiveValue == null) {\n" - + " expensiveValue = CachedValueTestSpec.onCreateExpensiveValue();\n" - + " c.putCachedValue(globalKey, 0, inputs, expensiveValue);\n" - + " }\n" - + " return expensiveValue;\n" - + "}\n"); - } - - @Test - public void testGenerateInputsClassWithContextParam() { - final List> models = - SpecModelUtils.getMethodModelsWithAnnotation( - mLayoutSpecModel, OnCalculateCachedValue.class); - final SpecMethodModel specMethodModel = - models.stream() - .filter(m -> m.name.toString().equals("onCreateExpensiveValueWithContext")) - .findFirst() - .get(); - final String expensiveValueInputsClass = - CachedValueGenerator.createInputsClass( - CachedValueGenerator.getCachedValueInputs(specMethodModel), - "expensiveValueWithContext", - RunMode.normal()) - .toString(); - assertThat(expensiveValueInputsClass) - .isEqualTo( - "@com.facebook.litho.annotations.Generated\n" - + "private static class ExpensiveValueWithContextInputs {\n" - + " private final String globalKey;\n" - + "\n" - + " ExpensiveValueWithContextInputs(String globalKey) {\n" - + " this.globalKey = globalKey;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public int hashCode() {\n" - + " return com.facebook.litho.CommonUtils.hash(globalKey, getClass());\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public boolean equals(java.lang.Object other) {\n" - + " if (this == other) {\n" - + " return true;\n" - + " }\n" - + " if (other == null || !(other instanceof ExpensiveValueWithContextInputs))" - + " {\n" - + " return false;\n" - + " }\n" - + " ExpensiveValueWithContextInputs cachedValueInputs =" - + " (ExpensiveValueWithContextInputs) other;\n" - + " if (!com.facebook.rendercore.utils.EquivalenceUtils.equals(globalKey," - + " cachedValueInputs.globalKey)) {\n" - + " return false;\n" - + " }\n" - + " return true;\n" - + " }\n" - + "}\n"); - } - - @Test - public void testGenerateGetterWithContextParam() { - final List> models = - SpecModelUtils.getMethodModelsWithAnnotation( - mLayoutSpecModel, OnCalculateCachedValue.class); - final SpecMethodModel specMethodModel = - models.stream() - .filter(m -> m.name.toString().equals("onCreateExpensiveValueWithContext")) - .findFirst() - .get(); - - final String expensiveValue = - CachedValueGenerator.createGetterMethod( - mLayoutSpecModel, - specMethodModel, - CachedValueGenerator.getCachedValueInputs(specMethodModel), - "expensiveValueWithContext", - 1) - .toString(); - assertThat(expensiveValue) - .isEqualTo( - "private java.lang.String" - + " getExpensiveValueWithContext(com.facebook.litho.ComponentContext c) {\n" - + " String globalKey = c.getGlobalKey();\n" - + " final ExpensiveValueWithContextInputs inputs = new" - + " ExpensiveValueWithContextInputs(globalKey);\n" - + " java.lang.String expensiveValueWithContext = (java.lang.String)" - + " c.getCachedValue(globalKey, 1, inputs);\n" - + " if (expensiveValueWithContext == null) {\n" - + " expensiveValueWithContext =" - + " CachedValueTestSpec.onCreateExpensiveValueWithContext(c);\n" - + " c.putCachedValue(globalKey, 1, inputs, expensiveValueWithContext);\n" - + " }\n" - + " return expensiveValueWithContext;\n" - + "}\n"); - } - - @Test - public void testGenerateInputsClassGenericParam() { - final List> models = - SpecModelUtils.getMethodModelsWithAnnotation( - mLayoutSpecModel, OnCalculateCachedValue.class); - final SpecMethodModel specMethodModel = - models.stream() - .filter(m -> m.name.toString().equals("onCreateExpensiveValueWithGeneric")) - .findFirst() - .get(); - final String inputsClassWithGenericParam = - CachedValueGenerator.createInputsClass( - CachedValueGenerator.getCachedValueInputs(specMethodModel), - "expensiveValueWithGeneric", - RunMode.normal()) - .toString(); - assertThat(inputsClassWithGenericParam) - .isEqualTo( - "@com.facebook.litho.annotations.Generated\n" - + "private static class ExpensiveValueWithGenericInputs {\n" - + " private final String globalKey;\n" - + "\n" - + " private final E genericArg;\n" - + "\n" - + " ExpensiveValueWithGenericInputs(String globalKey, E genericArg) {\n" - + " this.globalKey = globalKey;\n" - + " this.genericArg = genericArg;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public int hashCode() {\n" - + " return com.facebook.litho.CommonUtils.hash(globalKey, genericArg," - + " getClass());\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public boolean equals(java.lang.Object other) {\n" - + " if (this == other) {\n" - + " return true;\n" - + " }\n" - + " if (other == null || !(other instanceof ExpensiveValueWithGenericInputs))" - + " {\n" - + " return false;\n" - + " }\n" - + " ExpensiveValueWithGenericInputs cachedValueInputs =" - + " (ExpensiveValueWithGenericInputs) other;\n" - + " if (!com.facebook.rendercore.utils.EquivalenceUtils.equals(globalKey," - + " cachedValueInputs.globalKey)) {\n" - + " return false;\n" - + " }\n" - + " if (genericArg != null ? !genericArg.equals(cachedValueInputs.genericArg) :" - + " cachedValueInputs.genericArg != null) {\n" - + " return false;\n" - + " }\n" - + " return true;\n" - + " }\n" - + "}\n"); - } - - @Test - public void testGenerateGetterGenericParam() { - final List> models = - SpecModelUtils.getMethodModelsWithAnnotation( - mLayoutSpecModel, OnCalculateCachedValue.class); - final SpecMethodModel specMethodModel = - models.stream() - .filter(m -> m.name.toString().equals("onCreateExpensiveValueWithGeneric")) - .findFirst() - .get(); - final String valueWithGeneric = - CachedValueGenerator.createGetterMethod( - mLayoutSpecModel, - specMethodModel, - CachedValueGenerator.getCachedValueInputs(specMethodModel), - "expensiveValueWithGeneric", - 4) - .toString(); - assertThat(valueWithGeneric) - .isEqualTo( - "private java.lang.String" - + " getExpensiveValueWithGeneric(com.facebook.litho.ComponentContext c) {\n" - + " String globalKey = c.getGlobalKey();\n" - + " final ExpensiveValueWithGenericInputs inputs = new" - + " ExpensiveValueWithGenericInputs(globalKey,genericArg);\n" - + " java.lang.String expensiveValueWithGeneric = (java.lang.String)" - + " c.getCachedValue(globalKey, 4, inputs);\n" - + " if (expensiveValueWithGeneric == null) {\n" - + " expensiveValueWithGeneric =" - + " CachedValueTestSpec.onCreateExpensiveValueWithGeneric(genericArg);\n" - + " c.putCachedValue(globalKey, 4, inputs, expensiveValueWithGeneric);\n" - + " }\n" - + " return expensiveValueWithGeneric;\n" - + "}\n"); - } - - @Test - public void testGenerateInputsClassMultipleGenericsParams() { - final List> models = - SpecModelUtils.getMethodModelsWithAnnotation( - mLayoutSpecModel, OnCalculateCachedValue.class); - final SpecMethodModel specMethodModel = - models.stream() - .filter(m -> m.name.toString().equals("onCreateExpensiveValueWithMoreGenerics")) - .findFirst() - .get(); - final String inputsClassWithGenericParam = - CachedValueGenerator.createInputsClass( - CachedValueGenerator.getCachedValueInputs(specMethodModel), - "expensiveValueWithMoreGenerics", - RunMode.normal()) - .toString(); - assertThat(inputsClassWithGenericParam) - .isEqualTo( - "@com.facebook.litho.annotations.Generated\n" - + "private static class ExpensiveValueWithMoreGenericsInputs {\n" - + " private final String globalKey;\n" - + "\n" - + " private final E genericArg;\n" - + "\n" - + " private final E genericArg2;\n" - + "\n" - + " ExpensiveValueWithMoreGenericsInputs(String globalKey, E genericArg, E" - + " genericArg2) {\n" - + " this.globalKey = globalKey;\n" - + " this.genericArg = genericArg;\n" - + " this.genericArg2 = genericArg2;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public int hashCode() {\n" - + " return com.facebook.litho.CommonUtils.hash(globalKey, genericArg," - + " genericArg2, getClass());\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public boolean equals(java.lang.Object other) {\n" - + " if (this == other) {\n" - + " return true;\n" - + " }\n" - + " if (other == null || !(other instanceof" - + " ExpensiveValueWithMoreGenericsInputs)) {\n" - + " return false;\n" - + " }\n" - + " ExpensiveValueWithMoreGenericsInputs cachedValueInputs =" - + " (ExpensiveValueWithMoreGenericsInputs) other;\n" - + " if (!com.facebook.rendercore.utils.EquivalenceUtils.equals(globalKey," - + " cachedValueInputs.globalKey)) {\n" - + " return false;\n" - + " }\n" - + " if (genericArg != null ? !genericArg.equals(cachedValueInputs.genericArg) :" - + " cachedValueInputs.genericArg != null) {\n" - + " return false;\n" - + " }\n" - + " if (genericArg2 != null ? !genericArg2.equals(cachedValueInputs.genericArg2)" - + " : cachedValueInputs.genericArg2 != null) {\n" - + " return false;\n" - + " }\n" - + " return true;\n" - + " }\n" - + "}\n"); - } - - @Test - public void testGenerateGetterMultipleGenericsParams() { - final List> models = - SpecModelUtils.getMethodModelsWithAnnotation( - mLayoutSpecModel, OnCalculateCachedValue.class); - final SpecMethodModel specMethodModel = - models.stream() - .filter(m -> m.name.toString().equals("onCreateExpensiveValueWithMoreGenerics")) - .findFirst() - .get(); - final String valueWithMoreGenerics = - CachedValueGenerator.createGetterMethod( - mLayoutSpecModel, - specMethodModel, - CachedValueGenerator.getCachedValueInputs(specMethodModel), - "expensiveValueWithMoreGenerics", - 5) - .toString(); - assertThat(valueWithMoreGenerics) - .isEqualTo( - "private java.lang.String" - + " getExpensiveValueWithMoreGenerics(com.facebook.litho.ComponentContext c) {\n" - + " String globalKey = c.getGlobalKey();\n" - + " final ExpensiveValueWithMoreGenericsInputs inputs = new" - + " ExpensiveValueWithMoreGenericsInputs(globalKey,genericArg,genericArg2);\n" - + " java.lang.String expensiveValueWithMoreGenerics = (java.lang.String)" - + " c.getCachedValue(globalKey, 5, inputs);\n" - + " if (expensiveValueWithMoreGenerics == null) {\n" - + " expensiveValueWithMoreGenerics =" - + " CachedValueTestSpec.onCreateExpensiveValueWithMoreGenerics(genericArg,genericArg2);\n" - + " c.putCachedValue(globalKey, 5, inputs, expensiveValueWithMoreGenerics);\n" - + " }\n" - + " return expensiveValueWithMoreGenerics;\n" - + "}\n"); - } - - @Test - public void testGenerateInputsClassMultipleGenericsParamsAndContext() { - final List> models = - SpecModelUtils.getMethodModelsWithAnnotation( - mLayoutSpecModel, OnCalculateCachedValue.class); - final SpecMethodModel specMethodModel = - models.stream() - .filter( - m -> m.name.toString().equals("onCreateExpensiveValueWithMoreGenericsAndContext")) - .findFirst() - .get(); - final String inputsClassWithGenericParam = - CachedValueGenerator.createInputsClass( - CachedValueGenerator.getCachedValueInputs(specMethodModel), - "expensiveValueWithMoreGenericsAndContext", - RunMode.normal()) - .toString(); - assertThat(inputsClassWithGenericParam) - .isEqualTo( - "@com.facebook.litho.annotations.Generated\n" - + "private static class ExpensiveValueWithMoreGenericsAndContextInputs {\n" - + " private final String globalKey;\n" - + "\n" - + " private final E genericArg;\n" - + "\n" - + " private final E genericArg2;\n" - + "\n" - + " ExpensiveValueWithMoreGenericsAndContextInputs(String globalKey, E genericArg," - + " E genericArg2) {\n" - + " this.globalKey = globalKey;\n" - + " this.genericArg = genericArg;\n" - + " this.genericArg2 = genericArg2;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public int hashCode() {\n" - + " return com.facebook.litho.CommonUtils.hash(globalKey, genericArg," - + " genericArg2, getClass());\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public boolean equals(java.lang.Object other) {\n" - + " if (this == other) {\n" - + " return true;\n" - + " }\n" - + " if (other == null || !(other instanceof" - + " ExpensiveValueWithMoreGenericsAndContextInputs)) {\n" - + " return false;\n" - + " }\n" - + " ExpensiveValueWithMoreGenericsAndContextInputs cachedValueInputs =" - + " (ExpensiveValueWithMoreGenericsAndContextInputs) other;\n" - + " if (!com.facebook.rendercore.utils.EquivalenceUtils.equals(globalKey," - + " cachedValueInputs.globalKey)) {\n" - + " return false;\n" - + " }\n" - + " if (genericArg != null ? !genericArg.equals(cachedValueInputs.genericArg) :" - + " cachedValueInputs.genericArg != null) {\n" - + " return false;\n" - + " }\n" - + " if (genericArg2 != null ? !genericArg2.equals(cachedValueInputs.genericArg2)" - + " : cachedValueInputs.genericArg2 != null) {\n" - + " return false;\n" - + " }\n" - + " return true;\n" - + " }\n" - + "}\n"); - } - - @Test - public void testGenerateGetterMultipleGenericsParamsAndContext() { - final List> models = - SpecModelUtils.getMethodModelsWithAnnotation( - mLayoutSpecModel, OnCalculateCachedValue.class); - final SpecMethodModel specMethodModel = - models.stream() - .filter( - m -> m.name.toString().equals("onCreateExpensiveValueWithMoreGenericsAndContext")) - .findFirst() - .get(); - final String valueWithMoreGenericsAndContext = - CachedValueGenerator.createGetterMethod( - mLayoutSpecModel, - specMethodModel, - CachedValueGenerator.getCachedValueInputs(specMethodModel), - "expensiveValueWithMoreGenericsAndContext", - 6) - .toString(); - assertThat(valueWithMoreGenericsAndContext) - .isEqualTo( - "private java.lang.String getExpensiveValueWithMoreGenericsAndContext(\n" - + " com.facebook.litho.ComponentContext c) {\n" - + " String globalKey = c.getGlobalKey();\n" - + " final ExpensiveValueWithMoreGenericsAndContextInputs inputs = new" - + " ExpensiveValueWithMoreGenericsAndContextInputs(globalKey,genericArg,genericArg2);\n" - + " java.lang.String expensiveValueWithMoreGenericsAndContext = (java.lang.String)" - + " c.getCachedValue(globalKey, 6, inputs);\n" - + " if (expensiveValueWithMoreGenericsAndContext == null) {\n" - + " expensiveValueWithMoreGenericsAndContext =" - + " CachedValueTestSpec.onCreateExpensiveValueWithMoreGenericsAndContext(c,genericArg,genericArg2);\n" - + " c.putCachedValue(globalKey, 6, inputs," - + " expensiveValueWithMoreGenericsAndContext);\n" - + " }\n" - + " return expensiveValueWithMoreGenericsAndContext;\n" - + "}\n"); - } - - @Test - public void testGenerateInputsClassWithParam() { - final List> models = - SpecModelUtils.getMethodModelsWithAnnotation( - mLayoutSpecModel, OnCalculateCachedValue.class); - final SpecMethodModel specMethodModel = - models.stream() - .filter(m -> m.name.toString().equals("onCreateMoreExpensiveValue")) - .findFirst() - .get(); - final String expensiveValueInputsClass = - CachedValueGenerator.createInputsClass( - CachedValueGenerator.getCachedValueInputs(specMethodModel), - "moreExpensiveValue", - RunMode.normal()) - .toString(); - assertThat(expensiveValueInputsClass) - .isEqualTo( - "@com.facebook.litho.annotations.Generated\n" - + "private static class MoreExpensiveValueInputs {\n" - + " private final String globalKey;\n" - + "\n" - + " private final boolean arg0;\n" - + "\n" - + " private final int arg1;\n" - + "\n" - + " MoreExpensiveValueInputs(String globalKey, boolean arg0, int arg1) {\n" - + " this.globalKey = globalKey;\n" - + " this.arg0 = arg0;\n" - + " this.arg1 = arg1;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public int hashCode() {\n" - + " return com.facebook.litho.CommonUtils.hash(globalKey, arg0, arg1," - + " getClass());\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public boolean equals(java.lang.Object other) {\n" - + " if (this == other) {\n" - + " return true;\n" - + " }\n" - + " if (other == null || !(other instanceof MoreExpensiveValueInputs)) {\n" - + " return false;\n" - + " }\n" - + " MoreExpensiveValueInputs cachedValueInputs = (MoreExpensiveValueInputs)" - + " other;\n" - + " if (!com.facebook.rendercore.utils.EquivalenceUtils.equals(globalKey," - + " cachedValueInputs.globalKey)) {\n" - + " return false;\n" - + " }\n" - + " if (arg0 != cachedValueInputs.arg0) {\n" - + " return false;\n" - + " }\n" - + " if (arg1 != cachedValueInputs.arg1) {\n" - + " return false;\n" - + " }\n" - + " return true;\n" - + " }\n" - + "}\n"); - } - - @Test - public void testGenerateGetterWithParam() { - final List> models = - SpecModelUtils.getMethodModelsWithAnnotation( - mLayoutSpecModel, OnCalculateCachedValue.class); - final SpecMethodModel specMethodModel = - models.stream() - .filter(m -> m.name.toString().equals("onCreateMoreExpensiveValue")) - .findFirst() - .get(); - final String moreExpensiveValue = - CachedValueGenerator.createGetterMethod( - mLayoutSpecModel, - specMethodModel, - CachedValueGenerator.getCachedValueInputs(specMethodModel), - "moreExpensiveValue", - 2) - .toString(); - assertThat(moreExpensiveValue) - .isEqualTo( - "private java.lang.String getMoreExpensiveValue(com.facebook.litho.ComponentContext c)" - + " {\n" - + " String globalKey = c.getGlobalKey();\n" - + " final MoreExpensiveValueInputs inputs = new" - + " MoreExpensiveValueInputs(globalKey,arg0,getStateContainerImpl(c).arg1);\n" - + " java.lang.String moreExpensiveValue = (java.lang.String)" - + " c.getCachedValue(globalKey, 2, inputs);\n" - + " if (moreExpensiveValue == null) {\n" - + " moreExpensiveValue =" - + " CachedValueTestSpec.onCreateMoreExpensiveValue(arg0,getStateContainerImpl(c).arg1);\n" - + " c.putCachedValue(globalKey, 2, inputs, moreExpensiveValue);\n" - + " }\n" - + " return moreExpensiveValue;\n" - + "}\n"); - } - - @Test - public void testGenerateInputsClassWithParamAndContext() { - final List> models = - SpecModelUtils.getMethodModelsWithAnnotation( - mLayoutSpecModel, OnCalculateCachedValue.class); - final SpecMethodModel specMethodModel = - models.stream() - .filter(m -> m.name.toString().equals("onCreateMoreExpensiveValueWithContext")) - .findFirst() - .get(); - final String expensiveValueInputsClass = - CachedValueGenerator.createInputsClass( - CachedValueGenerator.getCachedValueInputs(specMethodModel), - "moreExpensiveValueWithContext", - RunMode.normal()) - .toString(); - assertThat(expensiveValueInputsClass) - .isEqualTo( - "@com.facebook.litho.annotations.Generated\n" - + "private static class MoreExpensiveValueWithContextInputs {\n" - + " private final String globalKey;\n" - + "\n" - + " private final boolean arg0;\n" - + "\n" - + " private final int arg1;\n" - + "\n" - + " MoreExpensiveValueWithContextInputs(String globalKey, boolean arg0, int arg1)" - + " {\n" - + " this.globalKey = globalKey;\n" - + " this.arg0 = arg0;\n" - + " this.arg1 = arg1;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public int hashCode() {\n" - + " return com.facebook.litho.CommonUtils.hash(globalKey, arg0, arg1," - + " getClass());\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public boolean equals(java.lang.Object other) {\n" - + " if (this == other) {\n" - + " return true;\n" - + " }\n" - + " if (other == null || !(other instanceof" - + " MoreExpensiveValueWithContextInputs)) {\n" - + " return false;\n" - + " }\n" - + " MoreExpensiveValueWithContextInputs cachedValueInputs =" - + " (MoreExpensiveValueWithContextInputs) other;\n" - + " if (!com.facebook.rendercore.utils.EquivalenceUtils.equals(globalKey," - + " cachedValueInputs.globalKey)) {\n" - + " return false;\n" - + " }\n" - + " if (arg0 != cachedValueInputs.arg0) {\n" - + " return false;\n" - + " }\n" - + " if (arg1 != cachedValueInputs.arg1) {\n" - + " return false;\n" - + " }\n" - + " return true;\n" - + " }\n" - + "}\n"); - } - - @Test - public void testGenerateGetterWithParamAndContext() { - final List> models = - SpecModelUtils.getMethodModelsWithAnnotation( - mLayoutSpecModel, OnCalculateCachedValue.class); - final SpecMethodModel specMethodModel = - models.stream() - .filter(m -> m.name.toString().equals("onCreateMoreExpensiveValueWithContext")) - .findFirst() - .get(); - final String moreExpensiveValueWithContext = - CachedValueGenerator.createGetterMethod( - mLayoutSpecModel, - specMethodModel, - CachedValueGenerator.getCachedValueInputs(specMethodModel), - "moreExpensiveValueWithContext", - 3) - .toString(); - assertThat(moreExpensiveValueWithContext) - .isEqualTo( - "private java.lang.String" - + " getMoreExpensiveValueWithContext(com.facebook.litho.ComponentContext c) {\n" - + " String globalKey = c.getGlobalKey();\n" - + " final MoreExpensiveValueWithContextInputs inputs = new" - + " MoreExpensiveValueWithContextInputs(globalKey,arg0,getStateContainerImpl(c).arg1);\n" - + " java.lang.String moreExpensiveValueWithContext = (java.lang.String)" - + " c.getCachedValue(globalKey, 3, inputs);\n" - + " if (moreExpensiveValueWithContext == null) {\n" - + " moreExpensiveValueWithContext =" - + " CachedValueTestSpec.onCreateMoreExpensiveValueWithContext(arg0,getStateContainerImpl(c).arg1,c);\n" - + " c.putCachedValue(globalKey, 3, inputs, moreExpensiveValueWithContext);\n" - + " }\n" - + " return moreExpensiveValueWithContext;\n" - + "}\n"); - } - - @Test - public void testGenerateInputsClassWithTreeProp() { - final List> models = - SpecModelUtils.getMethodModelsWithAnnotation( - mLayoutSpecModel, OnCalculateCachedValue.class); - final SpecMethodModel specMethodModel = - models.stream() - .filter(m -> m.name.toString().equals("onCreateExpensiveValueWithTreeProp")) - .findFirst() - .get(); - final String expensiveValueInputsClass = - CachedValueGenerator.createInputsClass( - CachedValueGenerator.getCachedValueInputs(specMethodModel), - "expensiveValueWithTreeProp", - RunMode.normal()) - .toString(); - assertThat(expensiveValueInputsClass) - .isEqualTo( - "@com.facebook.litho.annotations.Generated\n" - + "private static class ExpensiveValueWithTreePropInputs {\n" - + " private final String globalKey;\n" - + "\n" - + " private final boolean arg0;\n" - + "\n" - + " private final long arg6;\n" - + "\n" - + " ExpensiveValueWithTreePropInputs(String globalKey, boolean arg0, long arg6)" - + " {\n" - + " this.globalKey = globalKey;\n" - + " this.arg0 = arg0;\n" - + " this.arg6 = arg6;\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public int hashCode() {\n" - + " return com.facebook.litho.CommonUtils.hash(globalKey, arg0, arg6," - + " getClass());\n" - + " }\n" - + "\n" - + " @java.lang.Override\n" - + " public boolean equals(java.lang.Object other) {\n" - + " if (this == other) {\n" - + " return true;\n" - + " }\n" - + " if (other == null || !(other instanceof ExpensiveValueWithTreePropInputs))" - + " {\n" - + " return false;\n" - + " }\n" - + " ExpensiveValueWithTreePropInputs cachedValueInputs =" - + " (ExpensiveValueWithTreePropInputs) other;\n" - + " if (!com.facebook.rendercore.utils.EquivalenceUtils.equals(globalKey," - + " cachedValueInputs.globalKey)) {\n" - + " return false;\n" - + " }\n" - + " if (arg0 != cachedValueInputs.arg0) {\n" - + " return false;\n" - + " }\n" - + " if (arg6 != cachedValueInputs.arg6) {\n" - + " return false;\n" - + " }\n" - + " return true;\n" - + " }\n" - + "}\n"); - } - - @Test - public void testGenerateGetterWithTreeProp() { - final List> models = - SpecModelUtils.getMethodModelsWithAnnotation( - mLayoutSpecModel, OnCalculateCachedValue.class); - final SpecMethodModel specMethodModel = - models.stream() - .filter(m -> m.name.toString().equals("onCreateExpensiveValueWithTreeProp")) - .findFirst() - .get(); - final String expensiveValueWithTreeProp = - CachedValueGenerator.createGetterMethod( - mLayoutSpecModel, - specMethodModel, - CachedValueGenerator.getCachedValueInputs(specMethodModel), - "expensiveValueWithTreeProp", - 7) - .toString(); - assertThat(expensiveValueWithTreeProp) - .isEqualTo( - "private java.lang.String" - + " getExpensiveValueWithTreeProp(com.facebook.litho.ComponentContext c) {\n" - + " String globalKey = c.getGlobalKey();\n" - + " final ExpensiveValueWithTreePropInputs inputs = new" - + " ExpensiveValueWithTreePropInputs(globalKey,arg0,(c.getParentTreeProp(long.class)));\n" - + " java.lang.String expensiveValueWithTreeProp = (java.lang.String)" - + " c.getCachedValue(globalKey, 7, inputs);\n" - + " if (expensiveValueWithTreeProp == null) {\n" - + " expensiveValueWithTreeProp =" - + " CachedValueTestSpec.onCreateExpensiveValueWithTreeProp(arg0,(c.getParentTreeProp(long.class)));\n" - + " c.putCachedValue(globalKey, 7, inputs, expensiveValueWithTreeProp);\n" - + " }\n" - + " return expensiveValueWithTreeProp;\n" - + "}\n"); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/model/DifferentlyTypedDuplicatePropValidationTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/model/DifferentlyTypedDuplicatePropValidationTest.java deleted file mode 100644 index f5871731076..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/model/DifferentlyTypedDuplicatePropValidationTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.model; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -import com.facebook.litho.ComponentContext; -import com.facebook.litho.annotations.Event; -import com.facebook.litho.annotations.LayoutSpec; -import com.facebook.litho.annotations.OnCreateLayout; -import com.facebook.litho.annotations.OnEvent; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.processor.LayoutSpecModelFactory; -import com.google.testing.compile.CompilationRule; -import java.util.List; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -@RunWith(JUnit4.class) -public class DifferentlyTypedDuplicatePropValidationTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - private final LayoutSpecModelFactory mFactory = new LayoutSpecModelFactory(); - - interface Drawable {} - - @Event(returnType = boolean.class) - public static class TestEvent { - public boolean testValue; - } - - @LayoutSpec - public static class DupeLayoutSpec { - - @OnCreateLayout - static void OnCreateLayout(ComponentContext c, @Prop String prop1) {} - - // Note that prop1 here has the same name but a different type. - @OnEvent(TestEvent.class) - static void onEvent(@Prop StringBuffer prop1) {} - } - - @Test - public void testDuplicatePropValidationError() { - final Elements elements = mCompilationRule.getElements(); - final Types types = mCompilationRule.getTypes(); - final TypeElement typeElement = - elements.getTypeElement(DupeLayoutSpec.class.getCanonicalName()); - final LayoutSpecModel layoutSpecModel = - mFactory.create( - elements, types, typeElement, mock(Messager.class), RunMode.normal(), null, null); - - final List specModelValidationErrors = - SpecModelValidation.validateLayoutSpecModel(layoutSpecModel, RunMode.normal()); - - assertThat(specModelValidationErrors) - .extracting("message") - .contains( - "The prop prop1 is defined differently in different methods. " - + "Ensure that each instance of this prop is declared in the same way " - + "(this means having the same type, resType and values for isOptional, " - + "isCommonProp and overrideCommonPropBehavior)."); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/model/ErrorEventHandlerGeneratorTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/model/ErrorEventHandlerGeneratorTest.java deleted file mode 100644 index ef9b6a4622d..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/model/ErrorEventHandlerGeneratorTest.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.model; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.facebook.litho.ComponentContext; -import com.facebook.litho.ErrorEvent; -import com.facebook.litho.annotations.FromEvent; -import com.facebook.litho.annotations.LayoutSpec; -import com.facebook.litho.annotations.OnError; -import com.facebook.litho.annotations.OnEvent; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.processor.LayoutSpecModelFactory; -import com.google.testing.compile.CompilationRule; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -/** Tests {@link ErrorEventHandlerGenerator}. */ -@RunWith(JUnit4.class) -public class ErrorEventHandlerGeneratorTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - - private final LayoutSpecModelFactory mLayoutSpecModelFactory = new LayoutSpecModelFactory(); - @Mock Messager mMessager; - - @LayoutSpec - static class TestSpec { - @OnError - public void testErrorHandler(ComponentContext c, Exception e) {} - } - - @LayoutSpec - static class ManualErrorHandlerSpec { - @OnEvent(ErrorEvent.class) - static void __internalOnErrorHandler(ComponentContext c, @FromEvent Exception exception) {} - } - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testHasOnErrorDelegate() { - final Elements elements = mCompilationRule.getElements(); - final TypeElement typeElement = elements.getTypeElement(TestSpec.class.getCanonicalName()); - final Types types = mCompilationRule.getTypes(); - final LayoutSpecModel specModel = - mLayoutSpecModelFactory.create( - elements, types, typeElement, mMessager, RunMode.normal(), null, null); - - assertThat(ErrorEventHandlerGenerator.hasOnErrorDelegateMethod(specModel.getDelegateMethods())) - .isTrue(); - } - - @Test - public void testManualErrorHandlerGeneration() { - final Elements elements = mCompilationRule.getElements(); - final TypeElement typeElement = - elements.getTypeElement(ManualErrorHandlerSpec.class.getCanonicalName()); - final Types types = mCompilationRule.getTypes(); - final LayoutSpecModel specModel = - mLayoutSpecModelFactory.create( - elements, types, typeElement, mMessager, RunMode.normal(), null, null); - - assertThat(ErrorEventHandlerGenerator.hasOnErrorDelegateMethod(specModel.getDelegateMethods())) - .isFalse(); - - // This verifies that the synthetic model matches the one defined here, i.e. that we - // internally generate the method we expect. - final SpecMethodModel generatedErrorEventMethod = - ErrorEventHandlerGenerator.generateErrorEventHandlerDefinition(); - final SpecMethodModel localErrorEventMethod = - specModel.getEventMethods().get(0); - - // These are properties that we can reliably generate as opposed to those which may - // differ in their runtime representation. - assertThat(generatedErrorEventMethod) - .isEqualToComparingOnlyGivenFields( - localErrorEventMethod, - "annotations", - "modifiers", - "returnTypeSpec", - "returnType", - "typeVariables"); - - assertThat(generatedErrorEventMethod.name).hasToString(localErrorEventMethod.name.toString()); - assertThat(generatedErrorEventMethod.typeModel.name) - .hasToString(localErrorEventMethod.typeModel.name.toString()); - - assertThat(generatedErrorEventMethod.typeModel.fields).hasSize(2); - // The Represented object refers to a javax model which we can't obtain here. - for (int i = 0; i < generatedErrorEventMethod.typeModel.fields.size(); i++) { - assertThat(generatedErrorEventMethod.typeModel.fields.get(i)) - .isEqualToIgnoringGivenFields( - localErrorEventMethod.typeModel.fields.get(i), "representedObject"); - } - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/model/SpecMethodModelUtilsTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/model/SpecMethodModelUtilsTest.java deleted file mode 100644 index 995531c2620..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/model/SpecMethodModelUtilsTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.model; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -import com.facebook.litho.annotations.FromEvent; -import com.facebook.litho.annotations.LayoutSpec; -import com.facebook.litho.annotations.OnEvent; -import com.facebook.litho.annotations.Param; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.annotations.State; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.processor.LayoutSpecModelFactory; -import com.google.testing.compile.CompilationRule; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests {@link SpecMethodModelUtils} */ -@RunWith(JUnit4.class) -public class SpecMethodModelUtilsTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - private final LayoutSpecModelFactory mLayoutSpecModelFactory = new LayoutSpecModelFactory(); - - @LayoutSpec - static class TestSpec { - - @OnEvent(Object.class) - public void noStateEventMethod(@Prop boolean arg0) {} - - @OnEvent(Object.class) - public void hasOnlyNormalStateEventMethod( - @Prop boolean arg0, @State int arg1, @Param Object arg2, @FromEvent long arg3) {} - - @OnEvent(Object.class) - public void hasLazyStateEventMethod( - @Prop boolean arg0, @State int arg1, @State(canUpdateLazily = true) long arg4) {} - } - - private SpecModel mSpecModel; - - @Before - public void setUp() { - Elements elements = mCompilationRule.getElements(); - Types types = mCompilationRule.getTypes(); - TypeElement typeElement = elements.getTypeElement(TestSpec.class.getCanonicalName()); - mSpecModel = - mLayoutSpecModelFactory.create( - elements, types, typeElement, mock(Messager.class), RunMode.normal(), null, null); - } - - @Test - public void testHasLazyStateParams() { - SpecMethodModel noStateEventMethod = mSpecModel.getEventMethods().get(0); - assertThat(noStateEventMethod.name.toString()).isEqualTo("noStateEventMethod"); - assertThat(SpecMethodModelUtils.hasLazyStateParams(noStateEventMethod)).isFalse(); - - SpecMethodModel hasOnlyNormalStateEventMethod = mSpecModel.getEventMethods().get(1); - assertThat(hasOnlyNormalStateEventMethod.name.toString()) - .isEqualTo("hasOnlyNormalStateEventMethod"); - assertThat(SpecMethodModelUtils.hasLazyStateParams(hasOnlyNormalStateEventMethod)).isFalse(); - - SpecMethodModel hasLazyStateEventMethod = mSpecModel.getEventMethods().get(2); - assertThat(hasLazyStateEventMethod.name.toString()).isEqualTo("hasLazyStateEventMethod"); - assertThat(SpecMethodModelUtils.hasLazyStateParams(hasLazyStateEventMethod)).isTrue(); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/model/TreePropValidationTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/model/TreePropValidationTest.java deleted file mode 100644 index 4f35cfc36e5..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/model/TreePropValidationTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.model; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -import com.facebook.litho.Column; -import com.facebook.litho.Component; -import com.facebook.litho.ComponentContext; -import com.facebook.litho.annotations.LayoutSpec; -import com.facebook.litho.annotations.OnCreateLayout; -import com.facebook.litho.annotations.OnCreateTreeProp; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.processor.LayoutSpecModelFactory; -import com.google.common.collect.Iterables; -import com.google.testing.compile.CompilationRule; -import java.util.List; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests {@link TreePropValidation} */ -@RunWith(JUnit4.class) -public class TreePropValidationTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - - @LayoutSpec - static class TestSpec { - - @OnCreateLayout - public static Component onCreateLayout(ComponentContext c) { - return Column.create(c).build(); - } - - @OnCreateTreeProp - public static void treePropReturningVoid(ComponentContext c, @Prop int myProp) {} - - @OnCreateTreeProp - public static TestTreeProp treePropWithoutContextArg(@Prop TestTreeProp myProp) { - return myProp; - } - } - - static class TestTreeProp {} - - @Test - public void testOnCreateTreePropMethod() { - Elements elements = mCompilationRule.getElements(); - Types types = mCompilationRule.getTypes(); - TypeElement typeElement = elements.getTypeElement(TestSpec.class.getCanonicalName()); - LayoutSpecModel specModel = - new LayoutSpecModelFactory() - .create( - elements, types, typeElement, mock(Messager.class), RunMode.normal(), null, null); - - SpecMethodModel methodReturningVoid = - Iterables.find( - specModel.getDelegateMethods(), - delegateMethod -> delegateMethod.name.toString().equals("treePropReturningVoid")); - SpecMethodModel methodWithoutContextArg = - Iterables.find( - specModel.getDelegateMethods(), - delegateMethod -> delegateMethod.name.toString().equals("treePropWithoutContextArg")); - - List validationErrors = TreePropValidation.validate(specModel); - assertThat(validationErrors).hasSize(2); - - assertThat(validationErrors.get(0).element).isEqualTo(methodReturningVoid.representedObject); - assertThat(validationErrors.get(0).message) - .isEqualTo("@OnCreateTreeProp methods cannot return void."); - - assertThat(validationErrors.get(1).element) - .isEqualTo(methodWithoutContextArg.representedObject); - assertThat(validationErrors.get(1).message) - .isEqualTo( - "The first argument of an @OnCreateTreeProp method should be " - + "com.facebook.litho.ComponentContext."); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/DelegateMethodExtractorTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/processor/DelegateMethodExtractorTest.java deleted file mode 100644 index f0c68301e84..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/DelegateMethodExtractorTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.processor; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -import com.facebook.litho.annotations.Event; -import com.facebook.litho.annotations.OnCreateLayout; -import com.facebook.litho.annotations.OnCreateLayoutWithSizeSpec; -import com.facebook.litho.annotations.OnEvent; -import com.facebook.litho.annotations.OnUpdateState; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.annotations.State; -import com.facebook.litho.specmodels.internal.ImmutableList; -import com.facebook.litho.specmodels.model.DelegateMethod; -import com.facebook.litho.specmodels.model.DelegateMethodDescriptions; -import com.facebook.litho.specmodels.model.SpecMethodModel; -import com.google.testing.compile.CompilationRule; -import java.lang.annotation.Annotation; -import java.util.ArrayList; -import java.util.List; -import javax.annotation.processing.Messager; -import javax.lang.model.element.Modifier; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests {@link DelegateMethodExtractor} */ -@RunWith(JUnit4.class) -public class DelegateMethodExtractorTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - - static class TestClass { - - @OnCreateLayout - public void testMethod( - @Prop boolean testProp, @State int testState, @Event Object testPermittedAnnotation) { - // Don't do anything. - } - - @OnEvent(Object.class) - public void ignored() {} - - @OnUpdateState - public void alsoIgnored() {} - } - - static class TestClassWithSizeSpec { - @OnCreateLayoutWithSizeSpec - public void testMethod( - int h, - int w, - @Prop boolean testProp, - @State int testState, - @Event Object testPermittedAnnotation) { - // Don't do anything. - } - } - - @Test - public void testMethodExtraction() { - Elements elements = mCompilationRule.getElements(); - TypeElement typeElement = elements.getTypeElement(TestClass.class.getCanonicalName()); - - List> permittedParamAnnotations = new ArrayList<>(); - permittedParamAnnotations.add(Event.class); - - ImmutableList> delegateMethods = - DelegateMethodExtractor.getDelegateMethods( - typeElement, - new ArrayList<>(DelegateMethodDescriptions.LAYOUT_SPEC_DELEGATE_METHODS_MAP.keySet()), - permittedParamAnnotations, - ImmutableList.>of(), - ImmutableList.>of(), - mock(Messager.class)); - - DelegateMethodExtractorTestHelper.assertDelegateMethodExtraction(delegateMethods); - } - - @Test - public void testMethodExtraction_WithOnCreateLayoutWithSizeSpec_shouldFindMethod() { - Elements elements = mCompilationRule.getElements(); - TypeElement typeElement = - elements.getTypeElement(TestClassWithSizeSpec.class.getCanonicalName()); - - List> permittedParamAnnotations = new ArrayList<>(); - permittedParamAnnotations.add(Event.class); - - ImmutableList> delegateMethods = - DelegateMethodExtractor.getDelegateMethods( - typeElement, - new ArrayList<>(DelegateMethodDescriptions.LAYOUT_SPEC_DELEGATE_METHODS_MAP.keySet()), - permittedParamAnnotations, - ImmutableList.>of(), - ImmutableList.>of(), - mock(Messager.class)); - - assertThat(delegateMethods.size()).isEqualTo(1); - - SpecMethodModel delegateMethod = delegateMethods.iterator().next(); - assertThat(delegateMethod.annotations.size()).isEqualTo(1); - assertThat(delegateMethod.modifiers.size()).isEqualTo(1); - - assertThat(delegateMethod.modifiers).contains(Modifier.PUBLIC); - assertThat(delegateMethod.name.toString()).isEqualTo("testMethod"); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/DuplicatePropValidationTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/processor/DuplicatePropValidationTest.java deleted file mode 100644 index 45df1a04d7a..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/DuplicatePropValidationTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.processor; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -import com.facebook.litho.ComponentContext; -import com.facebook.litho.annotations.MountSpec; -import com.facebook.litho.annotations.OnCreateMountContent; -import com.facebook.litho.annotations.OnMount; -import com.facebook.litho.annotations.OnPrepare; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.model.MountSpecModel; -import com.facebook.litho.specmodels.model.SpecModelValidation; -import com.facebook.litho.specmodels.model.SpecModelValidationError; -import com.google.testing.compile.CompilationRule; -import java.util.List; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -@RunWith(JUnit4.class) -public class DuplicatePropValidationTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - private final MountSpecModelFactory mFactory = new MountSpecModelFactory(); - - interface Drawable {} - - @MountSpec - public static class DupeMountSpec { - - @OnPrepare - static void onPrepare(ComponentContext c, @Prop(optional = true) String prop1) {} - - @OnMount - static void onMount( - ComponentContext c, Drawable drawable, @Prop String prop1, @Prop int prop2) {} - - @OnCreateMountContent - static Drawable onCreateMountContent(ComponentContext c) { - return null; - } - } - - @Test - public void testDuplicatePropValidationError() { - final Elements elements = mCompilationRule.getElements(); - final Types types = mCompilationRule.getTypes(); - final TypeElement typeElement = elements.getTypeElement(DupeMountSpec.class.getCanonicalName()); - final MountSpecModel mountSpecModel = - mFactory.create( - elements, types, typeElement, mock(Messager.class), RunMode.normal(), null, null); - - final List specModelValidationErrors = - SpecModelValidation.validateMountSpecModel(mountSpecModel, RunMode.normal()); - - assertThat(specModelValidationErrors) - .extracting("message") - .contains( - "The prop prop1 is defined differently in different methods. " - + "Ensure that each instance of this prop is declared in the same way " - + "(this means having the same type, resType and values for isOptional, " - + "isCommonProp and overrideCommonPropBehavior)."); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/EventMethodExtractorTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/processor/EventMethodExtractorTest.java deleted file mode 100644 index 7b61e3ff255..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/EventMethodExtractorTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.processor; - -import static org.mockito.Mockito.mock; - -import com.facebook.litho.annotations.Event; -import com.facebook.litho.annotations.OnCreateLayout; -import com.facebook.litho.annotations.OnEvent; -import com.facebook.litho.annotations.OnUpdateState; -import com.facebook.litho.annotations.Param; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.annotations.State; -import com.facebook.litho.specmodels.internal.ImmutableList; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.model.EventDeclarationModel; -import com.facebook.litho.specmodels.model.EventMethod; -import com.facebook.litho.specmodels.model.SpecMethodModel; -import com.google.testing.compile.CompilationRule; -import java.lang.annotation.Annotation; -import java.util.ArrayList; -import java.util.List; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests {@link EventMethodExtractor} */ -@RunWith(JUnit4.class) -public class EventMethodExtractorTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - - static class TestClass { - - @OnCreateLayout - public void ignored() {} - - @OnEvent(Object.class) - public void testMethod( - @Prop boolean testProp, - @State int testState, - @Param Object testPermittedAnnotation, - @Event Object testNotPermittedAnnotation, - T testTypeVariable) { - // Don't do anything. - } - - @OnUpdateState - public void alsoIgnored() {} - } - - @Test - public void testMethodExtraction() { - Elements elements = mCompilationRule.getElements(); - TypeElement typeElement = elements.getTypeElement(TestClass.class.getCanonicalName()); - - List> permittedParamAnnotations = new ArrayList<>(); - - ImmutableList> methods = - EventMethodExtractor.getOnEventMethods( - elements, - typeElement, - permittedParamAnnotations, - ImmutableList.of(), - mock(Messager.class), - RunMode.normal()); - - EventMethodExtractorTestHelper.assertMethodExtraction(methods); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/LayoutSpecModelFactoryTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/processor/LayoutSpecModelFactoryTest.java deleted file mode 100644 index cddd4d34821..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/LayoutSpecModelFactoryTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.processor; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -import com.facebook.litho.Component; -import com.facebook.litho.ComponentContext; -import com.facebook.litho.annotations.LayoutSpec; -import com.facebook.litho.annotations.OnAttached; -import com.facebook.litho.annotations.OnCreateInitialState; -import com.facebook.litho.annotations.OnCreateLayout; -import com.facebook.litho.annotations.OnDetached; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.annotations.State; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.model.DependencyInjectionHelper; -import com.facebook.litho.specmodels.model.LayoutSpecModel; -import com.google.testing.compile.CompilationRule; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests {@link LayoutSpecModelFactory} */ -@RunWith(JUnit4.class) -public class LayoutSpecModelFactoryTest { - private static final String TEST_QUALIFIED_SPEC_NAME = - "com.facebook.litho.specmodels.processor.LayoutSpecModelFactoryTest.TestLayoutSpec"; - private static final String TEST_QUALIFIED_COMPONENT_NAME = - "com.facebook.litho.specmodels.processor.LayoutSpecModelFactoryTest.TestLayoutComponentName"; - - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - - private final LayoutSpecModelFactory mFactory = new LayoutSpecModelFactory(); - private final DependencyInjectionHelper mDependencyInjectionHelper = - mock(DependencyInjectionHelper.class); - - private LayoutSpecModel mLayoutSpecModel; - - @Before - public void setUp() { - Elements elements = mCompilationRule.getElements(); - Types types = mCompilationRule.getTypes(); - TypeElement typeElement = - elements.getTypeElement(LayoutSpecModelFactoryTest.TestLayoutSpec.class.getCanonicalName()); - - mLayoutSpecModel = - mFactory.create( - elements, - types, - typeElement, - mock(Messager.class), - RunMode.normal(), - mDependencyInjectionHelper, - null); - } - - @Test - public void create_forLayoutSpec_populateGenericSpecInfo() { - // can't move to helper, because PsiLayoutSpecModelFactoryTest doesn't support qualified names - assertThat(mLayoutSpecModel.getSpecTypeName().toString()).isEqualTo(TEST_QUALIFIED_SPEC_NAME); - assertThat(mLayoutSpecModel.getComponentTypeName().toString()) - .isEqualTo(TEST_QUALIFIED_COMPONENT_NAME); - LayoutSpecModelFactoryTestHelper.create_forLayoutSpec_populateGenericSpecInfo( - mLayoutSpecModel, mDependencyInjectionHelper); - } - - @Test - public void create_forLayoutSpec_populateOnAttachInfo() { - LayoutSpecModelFactoryTestHelper.create_forLayoutSpec_populateOnAttachInfo(mLayoutSpecModel); - } - - @Test - public void create_forLayoutSpec_populateOnDetachInfo() { - LayoutSpecModelFactoryTestHelper.create_forLayoutSpec_populateOnDetachInfo(mLayoutSpecModel); - } - - @LayoutSpec(value = "TestLayoutComponentName") - static class TestLayoutSpec { - - @OnCreateInitialState - static void createInitialState(@Prop int prop1) {} - - @OnCreateLayout - static Component onCreateLayout(ComponentContext c, @Prop int prop2) { - return null; - } - - @OnAttached - static void onAttached(ComponentContext c, @Prop Object prop3, @State Object state1) {} - - @OnDetached - static void onDetached(ComponentContext c, @Prop Object prop4, @State Object state2) {} - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/MethodExtractorUtilsTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/processor/MethodExtractorUtilsTest.java deleted file mode 100644 index ab80281dfff..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/MethodExtractorUtilsTest.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.processor; - -import static com.facebook.litho.specmodels.processor.MethodExtractorUtils.getMethodParams; -import static com.facebook.litho.specmodels.processor.MethodExtractorUtils.getTypeVariables; -import static com.facebook.litho.specmodels.processor.MethodExtractorUtilsTestHelper.assertOnAttachedHasInfoForAllParams; -import static com.facebook.litho.specmodels.processor.MethodExtractorUtilsTestHelper.assertOnAttachedHasNoTypeVars; -import static com.facebook.litho.specmodels.processor.MethodExtractorUtilsTestHelper.assertOnDetachedHasInfoForAllTypeVars; -import static com.facebook.litho.specmodels.processor.MethodExtractorUtilsTestHelper.assertOnDetachedHasNoParams; -import static org.mockito.Mockito.mock; - -import com.facebook.litho.ComponentContext; -import com.facebook.litho.annotations.Prop; -import com.google.testing.compile.CompilationRule; -import java.util.Collections; -import java.util.List; -import javax.annotation.processing.Messager; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.ElementFilter; -import javax.lang.model.util.Elements; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; - -public class MethodExtractorUtilsTest { - @Rule public final CompilationRule mCompilationRule = new CompilationRule(); - List methods; - - @Before - public void setUp() { - final Elements elements = mCompilationRule.getElements(); - final TypeElement typeElement = - elements.getTypeElement(MethodExtractorUtilsTest.TestClass.class.getCanonicalName()); - methods = ElementFilter.methodsIn(typeElement.getEnclosedElements()); - } - - @Test - public void getMethodParams_forMethodWithNoParams_returnsEmptyList() { - assertOnDetachedHasNoParams( - getMethodParams( - methods.get(1), - mock(Messager.class), - Collections.emptyList(), - Collections.emptyList(), - Collections.emptyList(), - Collections.emptyList())); - } - - @Test - public void getMethodParams_forMethodwithParams_returnsInfoForAllParams() { - assertOnAttachedHasInfoForAllParams( - getMethodParams( - methods.get(0), - mock(Messager.class), - Collections.singletonList(Prop.class), - Collections.emptyList(), - Collections.emptyList(), - Collections.emptyList())); - } - - @Test - public void getTypeVariables_forMethodWithNoTypeVars_returnsEmptyList() { - assertOnAttachedHasNoTypeVars(getTypeVariables(methods.get(0))); - } - - @Test - public void getTypeVariables_forMethodWithTypeVars_returnsInfoForAllTypeVars() { - assertOnDetachedHasInfoForAllTypeVars(getTypeVariables(methods.get(1))); - } - - static class TestClass { - static void onAttached(ComponentContext c, int num, @Prop Object prop) {} - - static void onDetached() {} - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/MountSpecModelFactoryTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/processor/MountSpecModelFactoryTest.java deleted file mode 100644 index 2038a14aeac..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/MountSpecModelFactoryTest.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.processor; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -import com.facebook.litho.ComponentContext; -import com.facebook.litho.StateValue; -import com.facebook.litho.Transition; -import com.facebook.litho.annotations.Event; -import com.facebook.litho.annotations.FromMeasure; -import com.facebook.litho.annotations.FromTrigger; -import com.facebook.litho.annotations.MountSpec; -import com.facebook.litho.annotations.MountingType; -import com.facebook.litho.annotations.OnAttached; -import com.facebook.litho.annotations.OnBindDynamicValue; -import com.facebook.litho.annotations.OnBoundsDefined; -import com.facebook.litho.annotations.OnCreateInitialState; -import com.facebook.litho.annotations.OnCreateMountContent; -import com.facebook.litho.annotations.OnCreateTreeProp; -import com.facebook.litho.annotations.OnDetached; -import com.facebook.litho.annotations.OnMount; -import com.facebook.litho.annotations.OnTrigger; -import com.facebook.litho.annotations.OnUnmount; -import com.facebook.litho.annotations.OnUpdateStateWithTransition; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.annotations.ShouldAlwaysRemeasure; -import com.facebook.litho.annotations.State; -import com.facebook.litho.annotations.TreeProp; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.model.DependencyInjectionHelper; -import com.facebook.litho.specmodels.model.MountSpecModel; -import com.google.testing.compile.CompilationRule; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests {@link MountSpecModelFactory} */ -@RunWith(JUnit4.class) -public class MountSpecModelFactoryTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - - private final DependencyInjectionHelper mDependencyInjectionHelper = - mock(DependencyInjectionHelper.class); - - private final MountSpecModelFactory mFactory = new MountSpecModelFactory(); - - private MountSpecModel mMountSpecModel; - - static class TestTreeProp { - - private final long mValue; - - public TestTreeProp(long value) { - mValue = value; - } - - public long getValue() { - return mValue; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - TestTreeProp other = (TestTreeProp) obj; - return other.getValue() == mValue; - } - - @Override - public int hashCode() { - return (int) mValue; - } - } - - @Event(returnType = String.class) - static class TestTriggerEvent { - int integer; - } - - static class ColorDrawable {} - ; - - static class Context {} - ; - - @MountSpec( - value = "TestMountComponentName", - isPublic = false, - isPureRender = true, - events = {TestTriggerEvent.class}) - static class TestMountSpecWithExplicitMountType { - - @OnCreateMountContent(mountingType = MountingType.DRAWABLE) - static ColorDrawable onCreateMountContent(Context context) { - return new ColorDrawable(); - } - - @OnCreateInitialState - static void createInitialState(@Prop int prop1) {} - - @OnCreateTreeProp - static TestTreeProp onCreateFeedPrefetcherProp(@Prop long prop2) { - return new TestTreeProp(prop2); - } - - @OnBoundsDefined - static void onBoundsDefined( - @Prop Object prop3, @Prop char[] prop4, @FromMeasure Long measureOutput) {} - - @OnMount - static void onMount( - @Prop(optional = true) boolean prop5, - @State(canUpdateLazily = true) long state1, - @State S state2, - @TreeProp TestTreeProp treeProp) {} - - @OnUnmount - static void onUnmount() {} - - @OnTrigger(TestTriggerEvent.class) - static String testTrigger(@Prop Object prop6, @FromTrigger int integer) { - return ""; - } - - @ShouldAlwaysRemeasure - static boolean shouldAlwaysRemeasure(@Prop boolean prop7) { - return prop7; - } - - @OnAttached - static void onAttached(ComponentContext c, @Prop Object prop8, @State Object state3) {} - - @OnDetached - static void onDetached(ComponentContext c, @Prop Object prop9, @State Object state4) {} - - @OnBindDynamicValue - static void onBindDynamicValue(ColorDrawable colorDrawable, @Prop(dynamic = true) int prop10) {} - - @OnUpdateStateWithTransition - static Transition onUpdateStateWithTransition(StateValue stateValue) { - return null; - } - } - - @Before - public void setUp() { - Elements elements = mCompilationRule.getElements(); - Types types = mCompilationRule.getTypes(); - TypeElement typeElement = - elements.getTypeElement( - MountSpecModelFactoryTest.TestMountSpecWithExplicitMountType.class.getCanonicalName()); - - mMountSpecModel = - mFactory.create( - elements, - types, - typeElement, - mock(Messager.class), - RunMode.normal(), - mDependencyInjectionHelper, - null); - } - - @Test - public void create_forMountSpecWithExplicitMountType_populateGenericSpecInfo() { - // can't move to helper, because PsiMountSpecModelFactoryTest doesn't support qualified names - assertThat(mMountSpecModel.getSpecTypeName().toString()) - .isEqualTo( - "com.facebook.litho.specmodels.processor.MountSpecModelFactoryTest.TestMountSpecWithExplicitMountType"); - assertThat(mMountSpecModel.getComponentTypeName().toString()) - .isEqualTo( - "com.facebook.litho.specmodels.processor.MountSpecModelFactoryTest." - + "TestMountComponentName"); - - MountSpecModelFactoryTestHelper - .create_forMountSpecWithExplicitMountType_populateGenericSpecInfo( - mMountSpecModel, mDependencyInjectionHelper); - } - - @Test - public void create_forMountSpecWithExplicitMountType_populateOnAttachInfo() { - MountSpecModelFactoryTestHelper.create_forMountSpecWithExplicitMountType_populateOnAttachInfo( - mMountSpecModel); - } - - @Test - public void create_forMountSpecWithExplicitMountType_populateOnDetachInfo() { - MountSpecModelFactoryTestHelper.create_forMountSpecWithExplicitMountType_populateOnDetachInfo( - mMountSpecModel); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/PropNameInterStageStoreTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/processor/PropNameInterStageStoreTest.java deleted file mode 100644 index 8d960c2485f..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/PropNameInterStageStoreTest.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.processor; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.facebook.litho.annotations.ResType; -import com.facebook.litho.specmodels.internal.ImmutableList; -import com.facebook.litho.specmodels.model.InjectPropModel; -import com.facebook.litho.specmodels.model.PropModel; -import com.facebook.litho.testing.specmodels.MockMethodParamModel; -import com.facebook.litho.testing.specmodels.MockSpecModel; -import com.squareup.javapoet.ClassName; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.Optional; -import javax.annotation.processing.Filer; -import javax.tools.FileObject; -import javax.tools.JavaFileManager; -import javax.tools.StandardLocation; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Answers; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -/** Tests {@link PropNameInterStageStore} */ -@RunWith(JUnit4.class) -public class PropNameInterStageStoreTest { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - Filer mFiler; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testLoad() throws IOException { - final PropNameInterStageStore store = new PropNameInterStageStore(mFiler); - - final FileObject fileObject = makeFileObjectForString("arg0\narg1\n"); - when(mFiler.getResource((JavaFileManager.Location) any(), anyString(), anyString())) - .thenReturn(fileObject); - - final Optional> strings = - store.loadNames(new MockName("com.example.MyComponentSpec")); - assertThat(strings.isPresent()).isTrue(); - assertThat(strings.get()).containsExactly("arg0", "arg1"); - - verify(mFiler) - .getResource( - StandardLocation.CLASS_PATH, - "", - "_STRIPPED_RESOURCES/litho/com.example.MyComponentSpec.props"); - } - - @Test - public void testSave() throws IOException { - final PropNameInterStageStore store = new PropNameInterStageStore(mFiler); - - final MockSpecModel specModel = - MockSpecModel.newBuilder() - .rawProps(ImmutableList.of(makePropModel("param0"), makePropModel("param1"))) - .rawInjectProps(ImmutableList.of(makeInjectPropModel("injectParam0"))) - .specTypeName(ClassName.get(MyTestSpec.class)) - .build(); - store.saveNames(specModel); - - verify(mFiler) - .createResource( - StandardLocation.CLASS_OUTPUT, - "", - "_STRIPPED_RESOURCES/litho/com.facebook.litho.specmodels.processor.PropNameInterStageStoreTest.MyTestSpec.props"); - - // Not checking the actually written values here because Java IO is a horrible mess. - } - - public static class MyTestSpec {} - - static FileObject makeFileObjectForString(String value) throws IOException { - final ByteArrayInputStream inputStream = new ByteArrayInputStream(value.getBytes()); - final FileObject file = mock(FileObject.class); - when(file.openInputStream()).thenReturn(inputStream); - return file; - } - - static PropModel makePropModel(String name) { - return new PropModel( - MockMethodParamModel.newBuilder().name(name).build(), - false, - false, - false, - false, - ResType.BOOL, - ""); - } - - private InjectPropModel makeInjectPropModel(String name) { - return new InjectPropModel(MockMethodParamModel.newBuilder().name(name).build()); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/TagExtractorTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/processor/TagExtractorTest.java deleted file mode 100644 index 78d6f9e7fe4..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/TagExtractorTest.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.processor; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.facebook.litho.annotations.LayoutSpec; -import com.facebook.litho.specmodels.internal.ImmutableList; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.model.TagModel; -import com.google.testing.compile.CompilationRule; -import com.squareup.javapoet.ClassName; -import java.util.EnumSet; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests {@link TagExtractor} */ -@RunWith(JUnit4.class) -public class TagExtractorTest { - - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - private ImmutableList mTagModels; - private ImmutableList mTagModelsInAbiMode; - - interface EmptyInterface {} - - interface NonEmptyInterface { - void method(); - } - - interface ExtendedInterface extends NonEmptyInterface {} - - @LayoutSpec - static class TestClass implements EmptyInterface, NonEmptyInterface, ExtendedInterface { - - @Override - public void method() {} - } - - @Before - public void setUp() { - Elements elements = mCompilationRule.getElements(); - Types types = mCompilationRule.getTypes(); - - mTagModels = - TagExtractor.extractTagsFromSpecClass( - types, elements.getTypeElement(TestClass.class.getCanonicalName()), RunMode.normal()); - - mTagModelsInAbiMode = - TagExtractor.extractTagsFromSpecClass( - types, - elements.getTypeElement(TestClass.class.getCanonicalName()), - EnumSet.of(RunMode.ABI)); - } - - @Test - public void testExtractsAllTags() { - assertThat(mTagModels).hasSize(3); - assertThat(mTagModelsInAbiMode).hasSize(3); - } - - @Test - public void testValidExtraction() { - TagModel emptyInterface = mTagModels.get(0); - assertThat(emptyInterface.name) - .isEqualTo( - ClassName.bestGuess( - "com.facebook.litho.specmodels.processor.TagExtractorTest.EmptyInterface")); - assertThat(emptyInterface.hasMethods).isFalse(); - assertThat(emptyInterface.hasSupertype).isFalse(); - } - - @Test - public void testValidExtractionInAbiMode() { - TagModel emptyInterface = mTagModelsInAbiMode.get(0); - assertThat(emptyInterface.name) - .isEqualTo( - ClassName.bestGuess( - "com.facebook.litho.specmodels.processor.TagExtractorTest.EmptyInterface")); - assertThat(emptyInterface.hasMethods).isFalse(); - assertThat(emptyInterface.hasSupertype).isFalse(); - } - - @Test - public void testNonEmptyTag() { - TagModel nonEmptyInterface = mTagModels.get(1); - assertThat(nonEmptyInterface.name) - .isEqualTo( - ClassName.bestGuess( - "com.facebook.litho.specmodels.processor.TagExtractorTest.NonEmptyInterface")); - assertThat(nonEmptyInterface.hasMethods).isTrue(); - } - - @Test - public void testNonEmptyTagInAbiMode() { - TagModel nonEmptyInterface = mTagModelsInAbiMode.get(1); - assertThat(nonEmptyInterface.name) - .isEqualTo( - ClassName.bestGuess( - "com.facebook.litho.specmodels.processor.TagExtractorTest.NonEmptyInterface")); - assertThat(nonEmptyInterface.hasMethods).isFalse(); - } - - @Test - public void testTagWithExtend() { - TagModel extendedInterface = mTagModels.get(2); - assertThat(extendedInterface.name) - .isEqualTo( - ClassName.bestGuess( - "com.facebook.litho.specmodels.processor.TagExtractorTest.ExtendedInterface")); - assertThat(extendedInterface.hasSupertype).isTrue(); - } - - @Test - public void testTagWithExtendInAbiMode() { - TagModel extendedInterface = mTagModelsInAbiMode.get(2); - assertThat(extendedInterface.name) - .isEqualTo( - ClassName.bestGuess( - "com.facebook.litho.specmodels.processor.TagExtractorTest.ExtendedInterface")); - assertThat(extendedInterface.hasSupertype).isFalse(); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/TestTargetExtractorTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/processor/TestTargetExtractorTest.java deleted file mode 100644 index 01ea21e8a5b..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/TestTargetExtractorTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.processor; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.facebook.litho.Component; -import com.facebook.litho.ComponentContext; -import com.facebook.litho.annotations.LayoutSpec; -import com.facebook.litho.annotations.OnCreateLayout; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.annotations.TestSpec; -import com.google.testing.compile.CompilationRule; -import javax.lang.model.element.TypeElement; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -@RunWith(JUnit4.class) -public class TestTargetExtractorTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - - @LayoutSpec - static class MyLayoutSpec { - @OnCreateLayout - public Component onCreateLayout(ComponentContext c, @Prop String s) { - return null; - } - } - - @TestSpec(MyLayoutSpec.class) - interface TestMyLayoutSpec {} - - @Test - public void testExtraction() { - final TypeElement typeElement = - mCompilationRule.getElements().getTypeElement(TestMyLayoutSpec.class.getCanonicalName()); - - final TypeElement testSpecValue = TestTargetExtractor.getTestSpecValue(typeElement); - assertThat(testSpecValue) - .isNotNull() - .hasToString( - "com.facebook.litho.specmodels.processor.TestTargetExtractorTest.MyLayoutSpec"); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/TriggerMethodExtractorTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/processor/TriggerMethodExtractorTest.java deleted file mode 100644 index ebd956a8cc5..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/TriggerMethodExtractorTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.processor; - -import static org.mockito.Mockito.mock; - -import com.facebook.litho.annotations.Event; -import com.facebook.litho.annotations.FromTrigger; -import com.facebook.litho.annotations.OnCreateLayout; -import com.facebook.litho.annotations.OnTrigger; -import com.facebook.litho.annotations.OnUpdateState; -import com.facebook.litho.annotations.Param; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.annotations.State; -import com.facebook.litho.specmodels.internal.ImmutableList; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.model.EventDeclarationModel; -import com.facebook.litho.specmodels.model.EventMethod; -import com.facebook.litho.specmodels.model.SpecMethodModel; -import com.google.testing.compile.CompilationRule; -import com.squareup.javapoet.ClassName; -import java.lang.annotation.Annotation; -import java.util.ArrayList; -import java.util.List; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests {@link TriggerMethodExtractor} */ -@RunWith(JUnit4.class) -public class TriggerMethodExtractorTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - - static class TestClass { - - @OnCreateLayout - public void ignored() {} - - @OnTrigger(TestEvent.class) - public void testMethod( - @Prop boolean testProp, - @State int testState, - @Param Object testPermittedAnnotation, - @FromTrigger long arg4) { - // Don't do anything. - } - - @OnUpdateState - public void alsoIgnored() {} - } - - @Event(returnType = Object.class) - static class TestEvent { - public long arg4; - } - - @Test - public void testMethodExtraction() { - Elements elements = mCompilationRule.getElements(); - TypeElement typeElement = elements.getTypeElement(TestClass.class.getCanonicalName()); - - List> permittedParamAnnotations = new ArrayList<>(); - - ImmutableList> methods = - TriggerMethodExtractor.getOnTriggerMethods( - elements, - typeElement, - permittedParamAnnotations, - ImmutableList.of(), - mock(Messager.class), - RunMode.normal()); - - ClassName eventClassName = - ClassName.bestGuess( - "com.facebook.litho.specmodels.processor.TriggerMethodExtractorTest.TestEvent"); - - TriggerMethodExtractorTestHelper.assertMethodExtraction(methods, eventClassName); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/UpdateStateMethodExtractorTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/processor/UpdateStateMethodExtractorTest.java deleted file mode 100644 index 7324a0f879a..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/UpdateStateMethodExtractorTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.processor; - -import static org.mockito.Mockito.mock; - -import com.facebook.litho.annotations.OnCreateLayout; -import com.facebook.litho.annotations.OnEvent; -import com.facebook.litho.annotations.OnUpdateState; -import com.facebook.litho.annotations.Param; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.annotations.State; -import com.facebook.litho.specmodels.internal.ImmutableList; -import com.facebook.litho.specmodels.model.SpecMethodModel; -import com.facebook.litho.specmodels.model.UpdateStateMethod; -import com.google.testing.compile.CompilationRule; -import java.lang.annotation.Annotation; -import java.util.ArrayList; -import java.util.List; -import javax.annotation.processing.Messager; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests {@link UpdateStateMethodExtractor} */ -@RunWith(JUnit4.class) -public class UpdateStateMethodExtractorTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - - static class TestClass { - - @OnCreateLayout - public void ignored() {} - - @OnEvent(Object.class) - public void alsoIgnored() {} - - @OnUpdateState - public void testMethod( - @Prop boolean testProp, @State int testState, @Param Object testPermittedAnnotation) { - // Don't do anything. - } - } - - @Test - public void testMethodExtraction() { - Elements elements = mCompilationRule.getElements(); - TypeElement typeElement = elements.getTypeElement(TestClass.class.getCanonicalName()); - - List> permittedParamAnnotations = new ArrayList<>(); - - ImmutableList> methods = - UpdateStateMethodExtractor.getOnUpdateStateMethods( - typeElement, permittedParamAnnotations, ImmutableList.of(), mock(Messager.class)); - - UpdateStateMethodExtractorTestHelper.assertMethodExtraction(methods); - } -} diff --git a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/testing/TestLayoutSpecModelFactoryTest.java b/litho-it/src/test/java/com/facebook/litho/specmodels/processor/testing/TestLayoutSpecModelFactoryTest.java deleted file mode 100644 index a24eb92b18c..00000000000 --- a/litho-it/src/test/java/com/facebook/litho/specmodels/processor/testing/TestLayoutSpecModelFactoryTest.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.facebook.litho.specmodels.processor.testing; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.data.Index.atIndex; -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import com.facebook.litho.Component; -import com.facebook.litho.ComponentContext; -import com.facebook.litho.Row; -import com.facebook.litho.annotations.LayoutSpec; -import com.facebook.litho.annotations.OnCreateLayout; -import com.facebook.litho.annotations.Prop; -import com.facebook.litho.annotations.ResType; -import com.facebook.litho.annotations.TestSpec; -import com.facebook.litho.specmodels.internal.ImmutableList; -import com.facebook.litho.specmodels.internal.RunMode; -import com.facebook.litho.specmodels.model.PropModel; -import com.facebook.litho.specmodels.model.testing.TestSpecGenerator; -import com.facebook.litho.specmodels.model.testing.TestSpecModel; -import com.facebook.litho.specmodels.processor.InterStageStore; -import com.facebook.litho.specmodels.processor.PropNameInterStageStore; -import com.google.testing.compile.CompilationRule; -import java.util.Optional; -import javax.annotation.processing.Filer; -import javax.annotation.processing.Messager; -import javax.lang.model.element.Name; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -/** Tests {@link TestSpecModelFactory} for an enclosed {@link LayoutSpec}. */ -@RunWith(JUnit4.class) -public class TestLayoutSpecModelFactoryTest { - @Rule public CompilationRule mCompilationRule = new CompilationRule(); - - private Elements mElements; - private Types mTypes; - private TypeElement mTypeElement; - @Mock private Messager mMessager; - - @LayoutSpec - static class MyLayoutSpec { - @OnCreateLayout - public static Component onCreateLayout( - ComponentContext c, - @Prop String s, - @Prop Component child, - @Prop(resType = ResType.DIMEN_SIZE) float size, - @Prop(optional = true) int i) { - return Row.create(c).build(); - } - } - - @TestSpec(MyLayoutSpec.class) - interface TestMyLayoutSpec {} - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - mElements = mCompilationRule.getElements(); - mTypes = mCompilationRule.getTypes(); - mTypeElement = mElements.getTypeElement(TestMyLayoutSpec.class.getCanonicalName()); - } - - @Test - public void testCreate() { - final TestSpecModelFactory factory = new TestSpecModelFactory(); - final TestSpecModel layoutSpecModel = - factory.create(mElements, mTypes, mTypeElement, mMessager, RunMode.normal(), null, null); - - assertThat(layoutSpecModel.getSpecName()).isEqualTo("TestMyLayoutSpec"); - assertThat(layoutSpecModel.getComponentName()).isEqualTo("TestMyLayout"); - assertThat(layoutSpecModel.getSpecTypeName().toString()) - .isEqualTo( - "com.facebook.litho.specmodels.processor.testing.TestLayoutSpecModelFactoryTest.TestMyLayoutSpec"); - assertThat(layoutSpecModel.getComponentTypeName().toString()) - .isEqualTo( - "com.facebook.litho.specmodels.processor.testing.TestLayoutSpecModelFactoryTest.TestMyLayout"); - - assertThat(layoutSpecModel.getProps().stream().map(PropModel::getName).toArray()) - .hasSize(4) - .contains("child", atIndex(0)) - .contains("i", atIndex(1)) - .contains("s", atIndex(2)) - .contains("size", atIndex(3)); - } - - @Test - public void testCreateWithCachedProps() { - final TestSpecModelFactory factory = new TestSpecModelFactory(); - final Filer mockFiler = mock(Filer.class, RETURNS_DEEP_STUBS); - final InterStageStore interStageStore = - new InterStageStore() { - @Override - public PropNameInterStageStore getPropNameInterStageStore() { - return new PropNameInterStageStore(mockFiler) { - @Override - public Optional> loadNames(Name qualifiedName) { - return Optional.of(ImmutableList.of("a", "b", "c", "d")); - } - }; - } - }; - - final TestSpecModel layoutSpecModel = - factory.create( - mElements, mTypes, mTypeElement, mMessager, RunMode.normal(), null, interStageStore); - - assertThat(layoutSpecModel.getSpecName()).isEqualTo("TestMyLayoutSpec"); - assertThat(layoutSpecModel.getComponentName()).isEqualTo("TestMyLayout"); - assertThat(layoutSpecModel.getSpecTypeName().toString()) - .isEqualTo( - "com.facebook.litho.specmodels.processor.testing.TestLayoutSpecModelFactoryTest.TestMyLayoutSpec"); - assertThat(layoutSpecModel.getComponentTypeName().toString()) - .isEqualTo( - "com.facebook.litho.specmodels.processor.testing.TestLayoutSpecModelFactoryTest.TestMyLayout"); - - assertThat(layoutSpecModel.getProps().stream().map(PropModel::getName).toArray()) - .hasSize(4) - .contains("a", atIndex(0)) - .contains("b", atIndex(1)) - .contains("c", atIndex(2)) - .contains("d", atIndex(3)); - } - - @Test - public void testDelegation() { - final TestSpecGenerator specGenerator = mock(TestSpecGenerator.class); - final TestSpecModelFactory factory = new TestSpecModelFactory(specGenerator); - - final TestSpecModel layoutSpecModel = - factory.create(mElements, mTypes, mTypeElement, mMessager, RunMode.normal(), null, null); - layoutSpecModel.generate(RunMode.normal()); - - verify(specGenerator).generate(layoutSpecModel); - } -}