@Test
  public void endTransactionInteractsWithObjectStore() throws Exception {
    // setup
    context.ignoring(mockPersistenceSession);

    context.checking(
        new Expectations() {
          {
            final Sequence transactionOrdering = context.sequence("transactionOrdering");
            oneOf(mockObjectStore).startTransaction();
            inSequence(transactionOrdering);

            // flushed twice, once before publishing, once after
            exactly(3)
                .of(mockObjectStore)
                .execute(with(equalTo(Collections.<PersistenceCommand>emptyList())));
            inSequence(transactionOrdering);

            oneOf(mockObjectStore).endTransaction();
            inSequence(transactionOrdering);
          }
        });

    transactionManager.startTransaction();
    transactionManager.endTransaction();
  }
 private <T extends Facet> T mockFacetIgnoring(final Class<T> typeToMock) {
   final T facet = context.mock(typeToMock);
   context.checking(
       new Expectations() {
         {
           allowing(facet).facetType();
           will(returnValue(typeToMock));
           ignoring(facet);
         }
       });
   return facet;
 }
  @Test
  public void startTransactionInteractsWithObjectStore() throws Exception {
    // setup
    context.ignoring(mockPersistenceSession);

    context.checking(
        new Expectations() {
          {
            one(mockObjectStore).startTransaction();
          }
        });
    transactionManager.startTransaction();
  }
public class PropertyTest_lookupLocation {

  @Rule public JUnitRuleMockery2 context = JUnitRuleMockery2.createFor(Mode.INTERFACES_AND_CLASSES);

  @Mock private LocationLookupService mockLocationLookupService;

  private Property property;

  @Before
  public void setUp() throws Exception {
    property = new Property();
    property.locationLookupService = mockLocationLookupService;
  }

  @Test
  public void test() {
    // given
    assertThat(property.getLocation(), is(nullValue()));

    // when
    final Location location = new Location();
    context.checking(
        new Expectations() {
          {
            oneOf(mockLocationLookupService).lookup("Buckingham Palace, London");
            will(returnValue(location));
          }
        });

    property.lookupLocation("Buckingham Palace, London");

    // then
    assertThat(property.getLocation(), is(location));
  }
}
public class ObjectStorePersistedObjectsDefault_savesOidGeneratorAsMemento {

  private ObjectStorePersistedObjects persistedObjects;

  @Rule
  public JUnitRuleMockery2 context =
      JUnitRuleMockery2.createFor(JUnitRuleMockery2.Mode.INTERFACES_AND_CLASSES);

  private IdentifierGeneratorDefault.Memento mockMemento;

  @Before
  public void setUp() throws Exception {
    persistedObjects = new ObjectStorePersistedObjects();
    mockMemento = context.mock(IdentifierGeneratorDefault.Memento.class);
  }

  @Test
  public void noOidGeneratorInitially() throws Exception {
    final IdentifierGeneratorDefault.Memento oidGeneratorMemento =
        persistedObjects.getOidGeneratorMemento();
    assertThat(oidGeneratorMemento, is(nullValue()));
  }

  @Test
  public void oidGeneratorStoredOnceSaved() throws Exception {
    persistedObjects.saveOidGeneratorMemento(mockMemento);
    final IdentifierGeneratorDefault.Memento oidGeneratorMemento =
        persistedObjects.getOidGeneratorMemento();
    assertThat(oidGeneratorMemento, is(mockMemento));
  }
}
  @Test
  public void endTransactionCommitsTransactionWhenLevelDecrementsDownToZero() throws Exception {
    // setup
    context.ignoring(mockObjectStore);
    transactionManager.startTransaction();

    context.checking(
        new Expectations() {
          {
            oneOf(mockPersistenceSession).objectChangedAllDirty();
          }
        });
    assertThat(transactionManager.getTransactionLevel(), is(1));
    transactionManager.endTransaction();
    assertThat(transactionManager.getTransactionLevel(), is(0));
  }
public class NoSqlKeyCreatorTest {

  @Rule public JUnitRuleMockery2 context = JUnitRuleMockery2.createFor(Mode.INTERFACES_AND_CLASSES);

  @Mock private OidMarshaller mockOidMarshaller;
  @Mock private SpecificationLoaderSpi mockSpecificationLoader;
  @Mock private ObjectSpecification mockSpecification;

  private final RootOidDefault oid = RootOidDefault.create(ObjectSpecId.of("ERP"), "3");
  private final String oidStr = oid.enString(new OidMarshaller());

  private KeyCreatorDefault keyCreatorDefault;

  @Before
  public void setUp() throws Exception {
    keyCreatorDefault =
        new KeyCreatorDefault() {
          @Override
          protected OidMarshaller getOidMarshaller() {
            return mockOidMarshaller;
          }

          @Override
          protected SpecificationLoaderSpi getSpecificationLoader() {
            return mockSpecificationLoader;
          }
        };
  }

  @Test
  public void unmarshal() throws Exception {
    context.checking(
        new Expectations() {

          {
            one(mockOidMarshaller).unmarshal(oidStr, RootOid.class);
            will(returnValue(oid));
          }
        });
    assertEquals(oid, keyCreatorDefault.unmarshal(oidStr));
  }

  @Test
  public void specification() throws Exception {
    context.checking(
        new Expectations() {
          {
            one(mockOidMarshaller).unmarshal(oidStr, TypedOid.class);
            will(returnValue(oid));
            one(mockSpecificationLoader).lookupBySpecId(oid.getObjectSpecId());
            will(returnValue(mockSpecification));
          }
        });
    final ObjectSpecification spec = keyCreatorDefault.specificationFromOidStr(oidStr);
    assertEquals(mockSpecification, spec);
  }
}
Exemple #8
0
  public static class Verify extends InvoiceItemTest {

    @Rule
    public JUnitRuleMockery2 context =
        JUnitRuleMockery2.createFor(JUnitRuleMockery2.Mode.INTERFACES_AND_CLASSES);

    @Mock Tax mockTax;

    private InvoiceItem invoiceItem;
    private LocalDate date = new LocalDate(2014, 1, 1);

    @Before
    public void setup() {
      context.checking(
          new Expectations() {
            {
              allowing(mockTax)
                  .percentageFor(with(anyOf(aNull(LocalDate.class), any(LocalDate.class))));
              will(returnValue(new BigDecimal("17.5")));
            }
          });
      invoiceItem =
          new InvoiceItem() {
            public ApplicationTenancy getApplicationTenancy() {
              return null;
            }
          };
      invoiceItem.setTax(mockTax);
    }

    @Test
    public void withLargeNetAmount() {
      invoiceItem.setNetAmount(new BigDecimal("100.00"));
      invoiceItem.verify();
      assertThat(invoiceItem.getVatAmount(), is(new BigDecimal("17.50")));
      assertThat(invoiceItem.getGrossAmount(), is(new BigDecimal("117.50")));
    }

    @Test
    public void withSmallNetAmount() {
      invoiceItem.setNetAmount(new BigDecimal("1.50"));
      invoiceItem.verify();
      assertThat(invoiceItem.getVatAmount(), is(new BigDecimal("0.26")));
      assertThat(invoiceItem.getGrossAmount(), is(new BigDecimal("1.76")));
    }

    @Test
    public void withNullTax() {
      invoiceItem.setTax(null);
      invoiceItem.setNetAmount(new BigDecimal("1.50"));
      invoiceItem.verify();
      assertThat(invoiceItem.getVatAmount(), is(new BigDecimal("0")));
      assertThat(invoiceItem.getGrossAmount(), is(new BigDecimal("1.50")));
    }
  }
  @Test
  public void endTransactionDecrementsTransactionLevel() throws Exception {
    // setup
    context.ignoring(mockObjectStore, mockPersistenceSession);
    transactionManager.startTransaction();
    transactionManager.startTransaction();

    assertThat(transactionManager.getTransactionLevel(), is(2));
    transactionManager.endTransaction();
    assertThat(transactionManager.getTransactionLevel(), is(1));
  }
  @Test
  public void unmarshal() throws Exception {
    context.checking(
        new Expectations() {

          {
            one(mockOidMarshaller).unmarshal(oidStr, RootOid.class);
            will(returnValue(oid));
          }
        });
    assertEquals(oid, keyCreatorDefault.unmarshal(oidStr));
  }
Exemple #11
0
public class DefaultClockTest {

  @Rule public JUnitRuleMockery2 context = JUnitRuleMockery2.createFor(Mode.INTERFACES_AND_CLASSES);

  private DefaultClock clock;

  @Test
  public void testGetTime() {
    clock = new DefaultClock();
    assertTrue(clock.getTime() > 0);
  }
}
  @Before
  public void setUp() throws Exception {
    org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.OFF);

    configuration = new IsisConfigurationDefault();
    servicesList = Collections.emptyList();

    oidMarshaller = new OidMarshaller();

    context.checking(
        new Expectations() {
          {
            ignoring(mockSpecificationLoader);
            ignoring(mockPersistenceSessionFactory);

            one(mockUserProfileLoader).getProfile(with(any(AuthenticationSession.class)));
            will(returnValue(new UserProfile()));

            ignoring(mockTemplateImageLoader);
            ignoring(mockAuthenticationManager);
            ignoring(mockAuthorizationManager);
          }
        });

    final ViewFactory subviewSpec =
        new ViewFactory() {
          @Override
          public View createView(final Content content, final Axes axes, final int fieldNumber) {
            return new DummyView();
          }
        };

    final IsisSessionFactoryDefault sessionFactory =
        new IsisSessionFactoryDefault(
            DeploymentType.EXPLORATION,
            configuration,
            mockTemplateImageLoader,
            mockSpecificationLoader,
            mockAuthenticationManager,
            mockAuthorizationManager,
            mockUserProfileLoader,
            mockPersistenceSessionFactory,
            servicesList,
            oidMarshaller);

    IsisContext.setConfiguration(sessionFactory.getConfiguration());
    IsisContextStatic.createRelaxedInstance(sessionFactory);
    IsisContextStatic.openSession(new ExplorationSession());

    builder = new ActionFieldBuilder(subviewSpec);
  }
 @Test
 public void specification() throws Exception {
   context.checking(
       new Expectations() {
         {
           one(mockOidMarshaller).unmarshal(oidStr, TypedOid.class);
           will(returnValue(oid));
           one(mockSpecificationLoader).lookupBySpecId(oid.getObjectSpecId());
           will(returnValue(mockSpecification));
         }
       });
   final ObjectSpecification spec = keyCreatorDefault.specificationFromOidStr(oidStr);
   assertEquals(mockSpecification, spec);
 }
 @Before
 public void setUp() throws Exception {
   context.checking(
       new Expectations() {
         {
           allowing(settings).getDatePattern();
           will(returnValue("yyyy-MM-dd"));
           allowing(settings).getDateTimePattern();
           will(returnValue("yyyy-MM-dd HH:mm"));
           allowing(settings).getDatePickerPattern();
           will(returnValue("yy-mm-dd"));
         }
       });
 }
Exemple #15
0
 @Before
 public void setup() {
   context.checking(
       new Expectations() {
         {
           allowing(mockTax)
               .percentageFor(with(anyOf(aNull(LocalDate.class), any(LocalDate.class))));
           will(returnValue(new BigDecimal("17.5")));
         }
       });
   invoiceItem =
       new InvoiceItem() {
         public ApplicationTenancy getApplicationTenancy() {
           return null;
         }
       };
   invoiceItem.setTax(mockTax);
 }
  @Test
  public void test() {
    // given
    assertThat(property.getLocation(), is(nullValue()));

    // when
    final Location location = new Location();
    context.checking(
        new Expectations() {
          {
            oneOf(mockLocationLookupService).lookup("Buckingham Palace, London");
            will(returnValue(location));
          }
        });

    property.lookupLocation("Buckingham Palace, London");

    // then
    assertThat(property.getLocation(), is(location));
  }
  @Before
  public void setUpTransactionManager() throws Exception {
    context.checking(
        new Expectations() {
          {
            allowing(mockAuthenticationSession).getUserName();
            will(returnValue("sven"));

            allowing(mockAuthenticationSession).getMessageBroker();
            will(returnValue(mockMessageBroker));
          }
        });

    transactionManager =
        new IsisTransactionManager(
            mockPersistenceSession, mockObjectStore, new ServicesInjectorDefault()) {
          @Override
          public AuthenticationSession getAuthenticationSession() {
            return mockAuthenticationSession;
          }
        };
  }
public class ObjectStoreTransactionManager_EndTransactionTest {

  @Rule public JUnitRuleMockery2 context = JUnitRuleMockery2.createFor(Mode.INTERFACES_AND_CLASSES);

  @Mock private AuthenticationSession mockAuthenticationSession;
  @Mock private PersistenceSession mockPersistenceSession;
  @Mock private MessageBroker mockMessageBroker;
  @Mock private TransactionalResource mockObjectStore;

  private IsisTransactionManager transactionManager;

  @Before
  public void setUpTransactionManager() throws Exception {
    context.checking(
        new Expectations() {
          {
            allowing(mockAuthenticationSession).getUserName();
            will(returnValue("sven"));

            allowing(mockAuthenticationSession).getMessageBroker();
            will(returnValue(mockMessageBroker));
          }
        });

    transactionManager =
        new IsisTransactionManager(
            mockPersistenceSession, mockObjectStore, new ServicesInjectorDefault()) {
          @Override
          public AuthenticationSession getAuthenticationSession() {
            return mockAuthenticationSession;
          }
        };
  }

  protected Matcher<Class<?>> anyClass() {
    return new TypeSafeMatcher<Class<?>>() {

      @Override
      public void describeTo(Description description) {
        description.appendText("any class");
      }

      @Override
      protected boolean matchesSafely(Class<?> item) {
        return true;
      }
    };
  }

  @Test
  public void endTransactionDecrementsTransactionLevel() throws Exception {
    // setup
    context.ignoring(mockObjectStore, mockPersistenceSession);
    transactionManager.startTransaction();
    transactionManager.startTransaction();

    assertThat(transactionManager.getTransactionLevel(), is(2));
    transactionManager.endTransaction();
    assertThat(transactionManager.getTransactionLevel(), is(1));
  }

  @Test
  public void endTransactionCommitsTransactionWhenLevelDecrementsDownToZero() throws Exception {
    // setup
    context.ignoring(mockObjectStore);
    transactionManager.startTransaction();

    context.checking(
        new Expectations() {
          {
            oneOf(mockPersistenceSession).objectChangedAllDirty();
          }
        });
    assertThat(transactionManager.getTransactionLevel(), is(1));
    transactionManager.endTransaction();
    assertThat(transactionManager.getTransactionLevel(), is(0));
  }

  @Test
  public void startTransactionInteractsWithObjectStore() throws Exception {
    // setup
    context.ignoring(mockPersistenceSession);

    context.checking(
        new Expectations() {
          {
            one(mockObjectStore).startTransaction();
          }
        });
    transactionManager.startTransaction();
  }

  @Test
  public void endTransactionInteractsWithObjectStore() throws Exception {
    // setup
    context.ignoring(mockPersistenceSession);

    context.checking(
        new Expectations() {
          {
            final Sequence transactionOrdering = context.sequence("transactionOrdering");
            oneOf(mockObjectStore).startTransaction();
            inSequence(transactionOrdering);

            // flushed twice, once before publishing, once after
            exactly(3)
                .of(mockObjectStore)
                .execute(with(equalTo(Collections.<PersistenceCommand>emptyList())));
            inSequence(transactionOrdering);

            oneOf(mockObjectStore).endTransaction();
            inSequence(transactionOrdering);
          }
        });

    transactionManager.startTransaction();
    transactionManager.endTransaction();
  }
}
public class ObjectAssociationAbstractTest {

  @Rule public JUnitRuleMockery2 context = JUnitRuleMockery2.createFor(Mode.INTERFACES_AND_CLASSES);

  private ObjectAssociationAbstract objectAssociation;
  private FacetedMethod facetedMethod;

  @Mock private ObjectSpecification objectSpecification;

  public static class Customer {
    private String firstName;

    public String getFirstName() {
      return firstName;
    }
  }

  @Before
  public void setup() {
    facetedMethod = FacetedMethod.createForProperty(Customer.class, "firstName");

    objectAssociation =
        new ObjectAssociationAbstract(
            facetedMethod,
            FeatureType.PROPERTY,
            objectSpecification,
            new ObjectMemberContext(DeploymentCategory.PRODUCTION, null, null, null, null, null)) {

          @Override
          public ObjectAdapter get(final ObjectAdapter fromObject) {
            return null;
          }

          @Override
          public boolean isEmpty(final ObjectAdapter adapter) {
            return false;
          }

          @Override
          public ObjectAdapter[] getChoices(final ObjectAdapter object) {
            return null;
          }

          @Override
          public ObjectAdapter getDefault(final ObjectAdapter adapter) {
            return null;
          }

          @Override
          public void toDefault(final ObjectAdapter target) {}

          @Override
          public UsabilityContext<?> createUsableInteractionContext(
              final AuthenticationSession session,
              final InteractionInvocationMethod invocationMethod,
              final ObjectAdapter target,
              Where where) {
            return null;
          }

          @Override
          public VisibilityContext<?> createVisibleInteractionContext(
              final AuthenticationSession session,
              final InteractionInvocationMethod invocationMethod,
              final ObjectAdapter targetObjectAdapter,
              Where where) {
            return null;
          }

          @Override
          public String debugData() {
            return null;
          }

          @Override
          public Instance getInstance(final ObjectAdapter adapter) {
            return null;
          }

          @Override
          public boolean containsDoOpFacet(final Class<? extends Facet> facetType) {
            return false;
          }

          @Override
          public boolean hasAutoComplete() {
            return false;
          }

          @Override
          public ObjectAdapter[] getAutoComplete(ObjectAdapter object, String searchArg) {
            return null;
          }

          @Override
          public int getAutoCompleteMinLength() {
            return 0;
          }
        };
  }

  @Test
  public void notPersistedWhenDerived() throws Exception {
    // TODO: ISIS-5, need to reinstate DerivedFacet
    final NotPersistedFacet mockFacet = mockFacetIgnoring(NotPersistedFacet.class);
    facetedMethod.addFacet(mockFacet);
    assertTrue(objectAssociation.isNotPersisted());
  }

  @Test
  public void notPersistedWhenFlaggedAsNotPersisted() throws Exception {
    final NotPersistedFacet mockFacet = mockFacetIgnoring(NotPersistedFacet.class);
    facetedMethod.addFacet(mockFacet);
    assertTrue(objectAssociation.isNotPersisted());
  }

  @Test
  public void persisted() throws Exception {
    assertFalse(objectAssociation.isNotPersisted());
  }

  @Test
  public void notHidden() throws Exception {
    assertFalse(objectAssociation.isAlwaysHidden());
  }

  @Test
  public void optional() throws Exception {
    assertFalse(objectAssociation.isMandatory());
  }

  @Test
  public void mandatory() throws Exception {
    final MandatoryFacet mockFacet = mockFacetIgnoring(MandatoryFacet.class);
    facetedMethod.addFacet(mockFacet);
    assertTrue(objectAssociation.isMandatory());
  }

  @Test
  public void hasNoChoices() throws Exception {
    assertFalse(objectAssociation.hasChoices());
  }

  @Test
  public void hasChoices() throws Exception {
    final PropertyChoicesFacet mockFacet = mockFacetIgnoring(PropertyChoicesFacet.class);
    facetedMethod.addFacet(mockFacet);
    assertTrue(objectAssociation.hasChoices());
  }

  private <T extends Facet> T mockFacetIgnoring(final Class<T> typeToMock) {
    final T facet = context.mock(typeToMock);
    context.checking(
        new Expectations() {
          {
            allowing(facet).facetType();
            will(returnValue(typeToMock));
            ignoring(facet);
          }
        });
    return facet;
  }
}
public class ActionFieldBuilderTest {

  @Rule public JUnitRuleMockery2 context = JUnitRuleMockery2.createFor(Mode.INTERFACES_AND_CLASSES);

  @Mock protected TemplateImageLoader mockTemplateImageLoader;
  @Mock protected SpecificationLoaderSpi mockSpecificationLoader;
  @Mock protected PersistenceSessionFactory mockPersistenceSessionFactory;
  @Mock private UserProfileLoader mockUserProfileLoader;
  @Mock protected AuthenticationManager mockAuthenticationManager;
  @Mock protected AuthorizationManager mockAuthorizationManager;

  private IsisConfiguration configuration;
  private List<Object> servicesList;
  private OidMarshaller oidMarshaller;

  private ActionFieldBuilder builder;

  @Before
  public void setUp() throws Exception {
    org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.OFF);

    configuration = new IsisConfigurationDefault();
    servicesList = Collections.emptyList();

    oidMarshaller = new OidMarshaller();

    context.checking(
        new Expectations() {
          {
            ignoring(mockSpecificationLoader);
            ignoring(mockPersistenceSessionFactory);

            one(mockUserProfileLoader).getProfile(with(any(AuthenticationSession.class)));
            will(returnValue(new UserProfile()));

            ignoring(mockTemplateImageLoader);
            ignoring(mockAuthenticationManager);
            ignoring(mockAuthorizationManager);
          }
        });

    final ViewFactory subviewSpec =
        new ViewFactory() {
          @Override
          public View createView(final Content content, final Axes axes, final int fieldNumber) {
            return new DummyView();
          }
        };

    final IsisSessionFactoryDefault sessionFactory =
        new IsisSessionFactoryDefault(
            DeploymentType.EXPLORATION,
            configuration,
            mockTemplateImageLoader,
            mockSpecificationLoader,
            mockAuthenticationManager,
            mockAuthorizationManager,
            mockUserProfileLoader,
            mockPersistenceSessionFactory,
            servicesList,
            oidMarshaller);

    IsisContext.setConfiguration(sessionFactory.getConfiguration());
    IsisContextStatic.createRelaxedInstance(sessionFactory);
    IsisContextStatic.openSession(new ExplorationSession());

    builder = new ActionFieldBuilder(subviewSpec);
  }

  @After
  public void tearDown() {
    IsisContext.closeSession();
  }

  @Test
  public void testUpdateBuild() {
    final MockControl control = MockControl.createControl(View.class);
    final View view = (View) control.getMock();

    control.expectAndDefaultReturn(view.getView(), view);
    control.expectAndDefaultReturn(view.getContent(), null);

    /*
     * DummyView[] views = new DummyView[2]; views[1] = new DummyView();
     * views[1].setupContent(new ObjectParameter("name", null, null, false,
     * 1, actionContent)); view.setupSubviews(views);
     */

    control.replay();

    // builder.build(view);

    control.verify();
  }

  /*
   * // TODO fails on server as cant load X11 for Text class public void
   * xxxtestNewBuild() { view.setupSubviews(new View[0]);
   *
   * view.addAction("add TextView0 null");
   * view.addAction("add MockView1/LabelBorder"); view.addAction("add
   * MockView2/LabelBorder");
   *
   * builder.build(view);
   *
   * view.verify(); } public void
   * xxxtestUpdateBuildWhereParameterHasChangedFromNullToAnObject() {
   * DummyView[] views = new DummyView[2]; views[1] = new DummyView();
   * ObjectParameter objectParameter = new ObjectParameter("name", null, null,
   * false, 1, actionContent); views[1].setupContent(objectParameter);
   * view.setupSubviews(views);
   *
   * actionContent.setParameter(0, new DummyObjectAdapter());
   *
   * view.addAction("replace MockView1 with MockView2/LabelBorder");
   *
   * builder.build(view);
   *
   * view.verify(); }
   *
   * public void
   * xxxtestUpdateBuildWhereParameterHasChangedFromAnObjectToNull() {
   * DummyView[] views = new DummyView[2]; views[1] = new DummyView();
   * ObjectParameter objectParameter = new ObjectParameter("name", new
   * DummyObjectAdapter(), null, false, 1, actionContent);
   * views[1].setupContent(objectParameter); view.setupSubviews(views);
   *
   * objectParameter.setObject(null);
   *
   * view.addAction("replace MockView1 with MockView2/LabelBorder");
   *
   * builder.build(view);
   *
   * view.verify(); }
   *
   * public void
   * xxxtestUpdateBuildWhereParameterHasChangedFromOneObjectToAnother() {
   * DummyView[] views = new DummyView[2]; views[1] = new DummyView();
   * ObjectParameter objectParameter = new ObjectParameter("name", new
   * DummyObjectAdapter(), null, false, 1, actionContent);
   * views[1].setupContent(objectParameter); view.setupSubviews(views);
   *
   * objectParameter.setObject(new DummyObjectAdapter());
   *
   * view.addAction("replace MockView1 with MockView2/LabelBorder");
   *
   * builder.build(view);
   *
   * view.verify(); }
   *
   * public void xxtestUpdateBuildWhereParameterObjectSetButToSameObject() {
   * DummyView[] views = new DummyView[2]; views[1] = new DummyView();
   * DummyObjectAdapter dummyObjectAdapter = new DummyObjectAdapter();
   * ObjectParameter objectParameter = new ObjectParameter("name",
   * dummyObjectAdapter, null, false, 1, actionContent);
   * views[1].setupContent(objectParameter); view.setupSubviews(views);
   *
   * actionContent.setParameter(0, dummyObjectAdapter); //
   * objectParameter.setObject(dummyObjectAdapter);
   *
   * builder.build(view);
   *
   * view.verify(); } }
   *
   * class MockActionHelper extends ActionHelper {
   *
   * protected MockActionHelper( ObjectAdapter target, Action action, String[]
   * labels, ObjectAdapter[] parameters, ObjectSpecification[] parameterTypes,
   * boolean[] required) { super(target, action, labels, parameters,
   * parameterTypes, required); }
   */
}
public class ApplicationFeatureViewModelTest {

  @Rule
  public JUnitRuleMockery2 context =
      JUnitRuleMockery2.createFor(JUnitRuleMockery2.Mode.INTERFACES_AND_CLASSES);

  ApplicationFeatureViewModel applicationFeatureViewModel;

  @Mock ApplicationFeatureRepository mockApplicationFeatureRepository;

  @Mock DomainObjectContainer mockContainer;

  public static class ViewModelRoundtrip extends ApplicationFeatureViewModelTest {

    @Test
    public void whenPackage() throws Exception {
      ApplicationPackage applicationPackage =
          new ApplicationPackage(ApplicationFeatureId.newPackage("com.mycompany"));

      final String str = applicationPackage.viewModelMemento();
      final ApplicationFeatureViewModel applicationFeatureVM2 = new ApplicationPackage();
      applicationFeatureVM2.viewModelInit(str);

      assertThat(applicationFeatureVM2.getType(), CoreMatchers.is(ApplicationFeatureType.PACKAGE));
      assertThat(applicationFeatureVM2.getPackageName(), is("com.mycompany"));
      assertThat(applicationFeatureVM2.getClassName(), is(nullValue()));
      assertThat(applicationFeatureVM2.getMemberName(), is(nullValue()));
    }

    @Test
    public void whenClass() throws Exception {
      ApplicationClass applicationClass =
          new ApplicationClass(ApplicationFeatureId.newClass("com.mycompany.Bar"));

      final String str = applicationClass.viewModelMemento();
      final ApplicationFeatureViewModel applicationFeatureVM2 = new ApplicationClass();
      applicationFeatureVM2.viewModelInit(str);

      assertThat(applicationFeatureVM2.getType(), is(ApplicationFeatureType.CLASS));
      assertThat(applicationFeatureVM2.getPackageName(), is("com.mycompany"));
      assertThat(applicationFeatureVM2.getClassName(), is("Bar"));
      assertThat(applicationFeatureVM2.getMemberName(), is(nullValue()));
    }

    @Test
    public void whenMember() throws Exception {
      ApplicationClassProperty applicationClassProperty =
          new ApplicationClassProperty(ApplicationFeatureId.newMember("com.mycompany.Bar", "foo"));

      final String str = applicationClassProperty.viewModelMemento();
      final ApplicationFeatureViewModel applicationFeatureVM2 = new ApplicationClassProperty();
      applicationFeatureVM2.viewModelInit(str);

      assertThat(applicationFeatureVM2.getType(), is(ApplicationFeatureType.MEMBER));
      assertThat(applicationFeatureVM2.getPackageName(), is("com.mycompany"));
      assertThat(applicationFeatureVM2.getClassName(), is("Bar"));
      assertThat(applicationFeatureVM2.getMemberName(), is("foo"));
    }
  }

  public static class Title extends ApplicationFeatureViewModelTest {

    @Test
    public void happyCase() throws Exception {

      applicationFeatureViewModel =
          new ApplicationFeatureViewModel(
              ApplicationFeatureId.newMember("com.mycompany.Bar#foo")) {};
      assertThat(applicationFeatureViewModel.title(), is("com.mycompany.Bar#foo"));
    }
  }

  public static class IconName extends ApplicationFeatureViewModelTest {

    @Test
    public void happyCase() throws Exception {

      applicationFeatureViewModel = new ApplicationFeatureViewModel() {};
      assertThat(applicationFeatureViewModel.iconName(), is("applicationFeature"));
    }
  }

  public static class PrivateConstructors {

    @Test
    public void forFunctions() throws Exception {
      new PrivateConstructorTester(ApplicationFeatureViewModel.Functions.class).exercise();
    }
  }

  public abstract static class ValueTypeContractTest
      extends ValueTypeContractTestAbstract<ApplicationFeatureViewModel> {

    static ApplicationFeatureViewModel pkg(ApplicationFeatureId applicationFeatureId) {
      return new ApplicationPackage(applicationFeatureId);
    }

    static ApplicationFeatureViewModel cls(ApplicationFeatureId applicationFeatureId) {
      return new ApplicationClass(applicationFeatureId);
    }

    static ApplicationFeatureViewModel prop(ApplicationFeatureId applicationFeatureId) {
      return new ApplicationClassProperty(applicationFeatureId);
    }

    static ApplicationFeatureViewModel coll(ApplicationFeatureId applicationFeatureId) {
      return new ApplicationClassCollection(applicationFeatureId);
    }

    static ApplicationFeatureViewModel act(ApplicationFeatureId applicationFeatureId) {
      return new ApplicationClassAction(applicationFeatureId);
    }

    public static class PackageFeatures extends ValueTypeContractTest {

      @Override
      protected List<ApplicationFeatureViewModel> getObjectsWithSameValue() {
        return Arrays.asList(
            pkg(ApplicationFeatureId.newPackage("com.mycompany")),
            pkg(ApplicationFeatureId.newPackage("com.mycompany")));
      }

      @Override
      protected List<ApplicationFeatureViewModel> getObjectsWithDifferentValue() {
        return Arrays.asList(
            pkg(ApplicationFeatureId.newPackage("com.mycompany2")),
            cls(ApplicationFeatureId.newClass("com.mycompany.Foo")),
            prop(ApplicationFeatureId.newMember("com.mycompany.Foo#bar")));
      }
    }

    public static class ClassFeatures extends ValueTypeContractTest {

      @Override
      protected List<ApplicationFeatureViewModel> getObjectsWithSameValue() {
        return Arrays.asList(
            cls(ApplicationFeatureId.newClass("com.mycompany.Foo")),
            cls(ApplicationFeatureId.newClass("com.mycompany.Foo")));
      }

      @Override
      protected List<ApplicationFeatureViewModel> getObjectsWithDifferentValue() {
        return Arrays.asList(
            pkg(ApplicationFeatureId.newPackage("com.mycompany")),
            cls(ApplicationFeatureId.newClass("com.mycompany.Foo2")),
            act(ApplicationFeatureId.newMember("com.mycompany.Foo#bar")));
      }
    }

    public static class PropertyFeatures extends ValueTypeContractTest {

      @Override
      protected List<ApplicationFeatureViewModel> getObjectsWithSameValue() {
        return Arrays.asList(
            prop(ApplicationFeatureId.newMember("com.mycompany.Foo#bar")),
            prop(ApplicationFeatureId.newMember("com.mycompany.Foo#bar")));
      }

      @Override
      protected List<ApplicationFeatureViewModel> getObjectsWithDifferentValue() {
        return Arrays.asList(
            pkg(ApplicationFeatureId.newPackage("com.mycompany")),
            cls(ApplicationFeatureId.newClass("com.mycompany.Foo")),
            prop(ApplicationFeatureId.newMember("com.mycompany.Foo#bar2")));
      }
    }
  }

  public static class GetContents extends ApplicationFeatureViewModelTest {

    @Test
    public void givenPackage_whenAddPackageAndClass() throws Exception {

      // given
      final ApplicationFeatureId applicationFeatureId =
          ApplicationFeatureId.newPackage("com.mycompany");
      final ApplicationFeatureId packageFeatureId =
          ApplicationFeatureId.newPackage("com.mycompany.flob");
      final ApplicationFeatureId classFeatureId =
          ApplicationFeatureId.newClass("com.mycompany.Bar");

      final ApplicationFeature applicationFeature = new ApplicationFeature(applicationFeatureId);

      applicationFeature.addToContents(packageFeatureId);
      applicationFeature.addToContents(classFeatureId);

      ApplicationPackage applicationFeatureVM = new ApplicationPackage(applicationFeatureId);
      applicationFeatureVM.applicationFeatureRepository = mockApplicationFeatureRepository;
      applicationFeatureVM.container = mockContainer;

      // then
      context.checking(
          new Expectations() {
            {
              allowing(mockApplicationFeatureRepository).findFeature(applicationFeatureId);
              will(returnValue(applicationFeature));

              oneOf(mockContainer)
                  .newViewModelInstance(
                      ApplicationPackage.class, packageFeatureId.asEncodedString());
              will(returnValue(new ApplicationPackage()));

              oneOf(mockContainer)
                  .newViewModelInstance(ApplicationClass.class, classFeatureId.asEncodedString());
              will(returnValue(new ApplicationClass()));
            }
          });

      // when
      final List<ApplicationFeatureViewModel> contents = applicationFeatureVM.getContents();

      // then
      assertThat(contents.size(), is(2));
    }
  }

  public static class GetProperties extends ApplicationFeatureViewModelTest {

    @Test
    public void givenClass_whenAddMember() throws Exception {

      // given
      final ApplicationFeatureId classId = ApplicationFeatureId.newClass("com.mycompany.Bar");
      final ApplicationFeatureId propertyId =
          ApplicationFeatureId.newMember("com.mycompany.Bar", "foo");
      final ApplicationFeatureId actionId =
          ApplicationFeatureId.newMember("com.mycompany.Bar", "boz");

      final ApplicationFeature classFeature = new ApplicationFeature(classId);
      final ApplicationFeature propertyFeature = new ApplicationFeature(propertyId);
      propertyFeature.setMemberType(ApplicationMemberType.PROPERTY);
      final ApplicationFeature actionFeature = new ApplicationFeature(actionId);
      actionFeature.setMemberType(ApplicationMemberType.ACTION);

      classFeature.addToMembers(propertyId, ApplicationMemberType.PROPERTY);
      classFeature.addToMembers(actionId, ApplicationMemberType.ACTION);

      ApplicationClass applicationClass = new ApplicationClass(classId);
      applicationClass.applicationFeatureRepository = mockApplicationFeatureRepository;
      applicationClass.container = mockContainer;

      // then
      context.checking(
          new Expectations() {
            {
              allowing(mockApplicationFeatureRepository).findFeature(classId);
              will(returnValue(classFeature));

              allowing(mockApplicationFeatureRepository).findFeature(propertyId);
              will(returnValue(propertyFeature));

              allowing(mockApplicationFeatureRepository).findFeature(actionId);
              will(returnValue(actionFeature));

              oneOf(mockContainer)
                  .newViewModelInstance(
                      ApplicationClassProperty.class, propertyId.asEncodedString());
              will(returnValue(new ApplicationClassProperty(propertyId)));

              oneOf(mockContainer)
                  .newViewModelInstance(ApplicationClassAction.class, actionId.asEncodedString());
              will(returnValue(new ApplicationClassAction(actionId)));
            }
          });

      // when
      final List<ApplicationClassProperty> properties = applicationClass.getProperties();

      // then
      assertThat(properties.size(), is(1));

      // when
      final List<ApplicationClassAction> actions = applicationClass.getActions();

      // then
      assertThat(actions.size(), is(1));
    }
  }

  public static class GetFullyQualifiedClassName extends ApplicationFeatureViewModelTest {

    @Test
    public void happyCase() throws Exception {

      applicationFeatureViewModel =
          new ApplicationFeatureViewModel(
              ApplicationFeatureId.newMember("com.mycompany.Bar#foo")) {};
      assertThat(applicationFeatureViewModel.getFullyQualifiedName(), is("com.mycompany.Bar#foo"));
    }
  }

  public static class GetType extends ApplicationFeatureViewModelTest {

    @Test
    public void whenPackage() throws Exception {
      applicationFeatureViewModel =
          new ApplicationFeatureViewModel(ApplicationFeatureId.newPackage("com.mycompany")) {};
      assertThat(applicationFeatureViewModel.getType(), is(ApplicationFeatureType.PACKAGE));
    }

    @Test
    public void whenClass() throws Exception {
      applicationFeatureViewModel =
          new ApplicationFeatureViewModel(ApplicationFeatureId.newClass("com.mycompany.Bar")) {};
      assertThat(applicationFeatureViewModel.getType(), is(ApplicationFeatureType.CLASS));
    }

    @Test
    public void whenMember() throws Exception {
      applicationFeatureViewModel =
          new ApplicationFeatureViewModel(
              ApplicationFeatureId.newMember("com.mycompany.Bar#foo")) {};
      assertThat(applicationFeatureViewModel.getType(), is(ApplicationFeatureType.MEMBER));
    }
  }

  public static class HideClassName extends ApplicationFeatureViewModelTest {

    @Test
    public void whenPackage() throws Exception {
      applicationFeatureViewModel =
          new ApplicationFeatureViewModel(ApplicationFeatureId.newPackage("com.mycompany")) {};
      assertThat(applicationFeatureViewModel.hideClassName(), is(true));
    }

    @Test
    public void whenClass() throws Exception {
      applicationFeatureViewModel =
          new ApplicationFeatureViewModel(ApplicationFeatureId.newClass("com.mycompany.Bar")) {};
      assertThat(applicationFeatureViewModel.hideClassName(), is(false));
    }

    @Test
    public void whenMember() throws Exception {
      applicationFeatureViewModel =
          new ApplicationFeatureViewModel(
              ApplicationFeatureId.newMember("com.mycompany.Bar#foo")) {};
      assertThat(applicationFeatureViewModel.hideClassName(), is(false));
    }
  }

  public static class HideMemberName extends ApplicationFeatureViewModelTest {

    @Test
    public void whenPackage() throws Exception {
      applicationFeatureViewModel =
          new ApplicationFeatureViewModel(ApplicationFeatureId.newPackage("com.mycompany")) {};
      assertThat(applicationFeatureViewModel.hideMemberName(), is(true));
    }

    @Test
    public void whenClass() throws Exception {
      applicationFeatureViewModel =
          new ApplicationFeatureViewModel(ApplicationFeatureId.newClass("com.mycompany.Bar")) {};
      assertThat(applicationFeatureViewModel.hideMemberName(), is(true));
    }

    @Test
    public void whenMember() throws Exception {
      applicationFeatureViewModel =
          new ApplicationFeatureViewModel(
              ApplicationFeatureId.newMember("com.mycompany.Bar#foo")) {};
      assertThat(applicationFeatureViewModel.hideMemberName(), is(false));
    }
  }

  public static class GetContributed extends ApplicationFeatureViewModelTest {

    public static class PropertyImpl extends GetContributed {

      @Mock ApplicationFeature mockApplicationFeature;

      @Test
      public void delegatesToUnderlyingFeature() throws Exception {
        // given
        final ApplicationFeatureId featureId =
            ApplicationFeatureId.newMember("com.mycompany.Bar#foo");
        applicationFeatureViewModel = new ApplicationFeatureViewModel(featureId) {};
        applicationFeatureViewModel.applicationFeatureRepository = mockApplicationFeatureRepository;

        // then
        context.checking(
            new Expectations() {
              {
                oneOf(mockApplicationFeatureRepository).findFeature(featureId);
                will(returnValue(mockApplicationFeature));

                oneOf(mockApplicationFeature).isContributed();
                will(returnValue(true));
              }
            });

        // when
        assertThat(applicationFeatureViewModel.isContributed(), is(true));
      }
    }

    public static class Hide extends GetContributed {

      @Test
      public void whenPackage() throws Exception {
        applicationFeatureViewModel =
            new ApplicationFeatureViewModel(ApplicationFeatureId.newPackage("com.mycompany")) {};
        assertThat(applicationFeatureViewModel.hideContributed(), is(true));
      }

      @Test
      public void whenClass() throws Exception {
        applicationFeatureViewModel =
            new ApplicationFeatureViewModel(ApplicationFeatureId.newClass("com.mycompany.Bar")) {};
        assertThat(applicationFeatureViewModel.hideContributed(), is(true));
      }

      @Test
      public void whenMember() throws Exception {
        applicationFeatureViewModel =
            new ApplicationFeatureViewModel(
                ApplicationFeatureId.newMember("com.mycompany.Bar#foo")) {};
        assertThat(applicationFeatureViewModel.hideContributed(), is(false));
      }
    }
  }

  public static class Parent extends ApplicationFeatureViewModelTest {

    @Mock ApplicationFeature mockApplicationFeature;
    private ApplicationFeatureViewModel parent;

    @Before
    public void setUp() throws Exception {
      applicationFeatureViewModel = new ApplicationFeatureViewModel() {};
      applicationFeatureViewModel.applicationFeatureRepository = mockApplicationFeatureRepository;
      applicationFeatureViewModel.container = mockContainer;

      parent = new ApplicationFeatureViewModel() {};
    }

    @Test
    public void whenPackage() throws Exception {

      // given
      final ApplicationFeatureId featureId = ApplicationFeatureId.newPackage("com.mycompany");
      final ApplicationFeatureId parentId = ApplicationFeatureId.newPackage("com");
      applicationFeatureViewModel.setFeatureId(featureId);

      // then
      context.checking(
          new Expectations() {
            {
              allowing(mockApplicationFeatureRepository).findFeature(parentId);
              will(returnValue(mockApplicationFeature));

              oneOf(mockContainer)
                  .newViewModelInstance(ApplicationPackage.class, parentId.asEncodedString());
              will(returnValue(parent));
            }
          });

      // when
      assertThat(applicationFeatureViewModel.getParent(), is(parent));
    }

    @Test
    public void whenPackageTopLevel() throws Exception {

      // given
      final ApplicationFeatureId featureId = ApplicationFeatureId.newPackage("com");
      applicationFeatureViewModel.setFeatureId(featureId);

      // then
      context.checking(
          new Expectations() {
            {
              never(mockApplicationFeatureRepository);

              never(mockContainer);
            }
          });

      // when
      assertThat(applicationFeatureViewModel.getParent(), is(nullValue()));
    }

    // should this instead fail-fast, given that the parent should always exist if the child does?
    @Test
    public void whenParentNonExistent() throws Exception {

      // given
      final ApplicationFeatureId featureId = ApplicationFeatureId.newPackage("com.mycompany");
      final ApplicationFeatureId parentId = ApplicationFeatureId.newPackage("com");
      applicationFeatureViewModel.setFeatureId(featureId);

      // then
      context.checking(
          new Expectations() {
            {
              allowing(mockApplicationFeatureRepository).findFeature(parentId);
              will(returnValue(null));

              never(mockContainer);
            }
          });

      // when
      assertThat(applicationFeatureViewModel.getParent(), is(nullValue()));
    }

    @Test
    public void whenClass() throws Exception {

      // given
      final ApplicationFeatureId featureId = ApplicationFeatureId.newClass("com.mycompany.Bar");
      final ApplicationFeatureId parentId = ApplicationFeatureId.newPackage("com.mycompany");
      applicationFeatureViewModel.setFeatureId(featureId);

      // then
      context.checking(
          new Expectations() {
            {
              allowing(mockApplicationFeatureRepository).findFeature(with(equalTo(parentId)));
              will(returnValue(mockApplicationFeature));

              oneOf(mockContainer)
                  .newViewModelInstance(ApplicationPackage.class, parentId.asEncodedString());
              will(returnValue(parent));
            }
          });

      // when
      assertThat(applicationFeatureViewModel.getParent(), is(parent));
    }

    @Test
    public void whenMember() throws Exception {
      // given
      final ApplicationFeatureId featureId =
          ApplicationFeatureId.newMember("com.mycompany.Bar#foo");
      final ApplicationFeatureId parentId = ApplicationFeatureId.newClass("com.mycompany.Bar");
      applicationFeatureViewModel.setFeatureId(featureId);

      // then
      context.checking(
          new Expectations() {
            {
              allowing(mockApplicationFeatureRepository).findFeature(parentId);
              will(returnValue(mockApplicationFeature));

              oneOf(mockContainer)
                  .newViewModelInstance(ApplicationClass.class, parentId.asEncodedString());
              will(returnValue(parent));
            }
          });

      // when
      assertThat(applicationFeatureViewModel.getParent(), is(parent));
    }
  }

  public static class GetPermissions extends ApplicationFeatureViewModelTest {

    @Mock ApplicationPermissionRepository mockApplicationPermissionRepository;

    @Test
    public void delegatesToUnderlyingRepo() throws Exception {
      // given
      final ApplicationFeatureId featureId =
          ApplicationFeatureId.newMember("com.mycompany.Bar#foo");
      applicationFeatureViewModel = new ApplicationFeatureViewModel(featureId) {};
      applicationFeatureViewModel.applicationPermissionRepository =
          mockApplicationPermissionRepository;

      // then
      final List<ApplicationPermission> result = Lists.newArrayList();
      context.checking(
          new Expectations() {
            {
              oneOf(mockApplicationPermissionRepository).findByFeatureCached(featureId);
              will(returnValue(result));
            }
          });

      // when
      assertThat(applicationFeatureViewModel.getPermissions(), is(result));
    }
  }
}
 @Before
 public void setUp() throws Exception {
   persistedObjects = new ObjectStorePersistedObjects();
   mockMemento = context.mock(IdentifierGeneratorDefault.Memento.class);
 }
public class DateConverterForJodaLocalDateTimeTest {

  @Rule public JUnitRuleMockery2 context = JUnitRuleMockery2.createFor(Mode.INTERFACES_AND_CLASSES);

  @Mock private WicketViewerSettings settings;

  @Before
  public void setUp() throws Exception {
    context.checking(
        new Expectations() {
          {
            allowing(settings).getDatePattern();
            will(returnValue("yyyy-MM-dd"));
            allowing(settings).getDateTimePattern();
            will(returnValue("yyyy-MM-dd HH:mm"));
            allowing(settings).getDatePickerPattern();
            will(returnValue("yy-mm-dd"));
          }
        });
  }

  @Test
  public void roundtripWhenParsingDateFormat() {
    final DateConverterForJodaLocalDateTime converter =
        new DateConverterForJodaLocalDateTime(settings, 0);
    final LocalDateTime dt = converter.convertToObject("2013-05-11", null);
    assertThat(dt, is(new LocalDateTime(2013, 05, 11, 0, 0)));

    final String str = converter.convertToString(dt, null);
    assertThat(str, is("2013-05-11 00:00"));
  }

  @Test
  public void roundtripWhenParsingDateTimeFormat() {
    final DateConverterForJodaLocalDateTime converter =
        new DateConverterForJodaLocalDateTime(settings, 0);
    final LocalDateTime dt = converter.convertToObject("2013-05-11 00:00", null);
    assertThat(dt, is(new LocalDateTime(2013, 05, 11, 0, 0)));

    final String str = converter.convertToString(dt, null);
    assertThat(str, is("2013-05-11 00:00"));
  }

  @Test
  public void roundtripWhenParsingDateFormatWithAdjustBy() {
    final DateConverterForJodaLocalDateTime converter =
        new DateConverterForJodaLocalDateTime(settings, -1);
    final LocalDateTime dt = converter.convertToObject("2013-05-11", null);
    assertThat(dt, is(new LocalDateTime(2013, 05, 12, 0, 0)));

    final String str = converter.convertToString(dt, null);
    assertThat(str, is("2013-05-11 00:00"));
  }

  @Test
  public void roundtripWhenParsingDateTimeFormatWithAdjustBy() {
    final DateConverterForJodaLocalDateTime converter =
        new DateConverterForJodaLocalDateTime(settings, -1);
    final LocalDateTime dt = converter.convertToObject("2013-05-11 00:00", null);
    assertThat(dt, is(new LocalDateTime(2013, 05, 12, 0, 0)));

    final String str = converter.convertToString(dt, null);
    assertThat(str, is("2013-05-11 00:00"));
  }
}