src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
BasicController { @RequestMapping(value = "parameters", method = RequestMethod.GET) public ModelAndView getParameterPageView(final Locale locale) { JSONObject json = new JSONObject(ImmutableMap.of("form.id", parameterService.getParameterId().toString())); Map<String, String> arguments = ImmutableMap.of("context", json.toString()); return crudService.prepareView(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.VIEW_PARAMETERS, arguments, locale); } @RequestMapping(value = "parameters", method = RequestMethod.GET) ModelAndView getParameterPageView(final Locale locale); }
@Test public void shouldPrepareViewForParameters() throws Exception { Map<String, String> arguments = ImmutableMap.of("context", "{\"form.id\":\"13\"}"); ModelAndView expectedMav = mock(ModelAndView.class); CrudService crudController = mock(CrudService.class); given( crudController.prepareView(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.VIEW_PARAMETERS, arguments, Locale.ENGLISH)).willReturn(expectedMav); ParameterService parameterService = mock(ParameterService.class); given(parameterService.getParameterId()).willReturn(13L); BasicController basicController = new BasicController(); setField(basicController, "crudService", crudController); setField(basicController, "parameterService", parameterService); ModelAndView mav = basicController.getParameterPageView(Locale.ENGLISH); assertEquals(expectedMav, mav); }
ProductDetailsHooks { public void disableProductFormForExternalItems(final ViewDefinitionState state) { FormComponent productForm = (FormComponent) state.getComponentByReference(L_FORM); FieldComponent entityTypeField = (FieldComponent) state.getComponentByReference(ProductFields.ENTITY_TYPE); FieldComponent parentField = (FieldComponent) state.getComponentByReference(ProductFields.PARENT); LookupComponent assortmentLookup = (LookupComponent) state.getComponentByReference(ProductFields.ASSORTMENT); Long productId = productForm.getEntityId(); if (productId == null) { productForm.setFormEnabled(true); return; } Entity product = dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_PRODUCT).get(productId); if (product == null) { return; } String externalNumber = product.getStringField(ProductFields.EXTERNAL_NUMBER); if (StringUtils.isEmpty(externalNumber)) { productForm.setFormEnabled(true); } else { productForm.setFormEnabled(false); entityTypeField.setEnabled(true); parentField.setEnabled(true); assortmentLookup.setEnabled(true); } } void generateProductNumber(final ViewDefinitionState view); void fillUnit(final ViewDefinitionState view); void disableUnitFromWhenFormIsSaved(final ViewDefinitionState view); void disableProductFormForExternalItems(final ViewDefinitionState state); void updateRibbonState(final ViewDefinitionState view); }
@Test public void shouldDisabledFormWhenExternalNumberIsNotNull() throws Exception { Long productId = 1L; given(view.getComponentByReference(L_FORM)).willReturn(productForm); given(view.getComponentByReference(ProductFields.PARENT)).willReturn(parentField); given(view.getComponentByReference(ProductFields.ENTITY_TYPE)).willReturn(entityTypeField); given(view.getComponentByReference(ProductFields.ASSORTMENT)).willReturn(assortmentLookup); given(productForm.getEntityId()).willReturn(L_ID); given(dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_PRODUCT)).willReturn(productDD); given(productDD.get(productId)).willReturn(product); given(product.getStringField(ProductFields.EXTERNAL_NUMBER)).willReturn(L_EXTERNAL_NUMBER); productDetailsHooks.disableProductFormForExternalItems(view); verify(productForm).setFormEnabled(false); verify(entityTypeField).setEnabled(true); verify(parentField).setEnabled(true); } @Test public void shouldntDisabledFormWhenExternalNumberIsNull() throws Exception { Long productId = 1L; given(view.getComponentByReference(L_FORM)).willReturn(productForm); given(view.getComponentByReference(ProductFields.PARENT)).willReturn(parentField); given(view.getComponentByReference(ProductFields.ENTITY_TYPE)).willReturn(entityTypeField); given(productForm.getEntityId()).willReturn(L_ID); given(dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_PRODUCT)).willReturn(productDD); given(productDD.get(productId)).willReturn(product); given(product.getStringField(ProductFields.EXTERNAL_NUMBER)).willReturn(null); productDetailsHooks.disableProductFormForExternalItems(view); verify(productForm).setFormEnabled(true); }
ProductDetailsHooks { public void fillUnit(final ViewDefinitionState view) { FormComponent productForm = (FormComponent) view.getComponentByReference(L_FORM); FieldComponent unitField = (FieldComponent) view.getComponentByReference(UNIT); if ((productForm.getEntityId() == null) && (unitField.getFieldValue() == null)) { unitField.setFieldValue(unitService.getDefaultUnitFromSystemParameters()); unitField.requestComponentUpdateState(); } } void generateProductNumber(final ViewDefinitionState view); void fillUnit(final ViewDefinitionState view); void disableUnitFromWhenFormIsSaved(final ViewDefinitionState view); void disableProductFormForExternalItems(final ViewDefinitionState state); void updateRibbonState(final ViewDefinitionState view); }
@Test public void shouldntFillUnitIfFormIsSaved() { given(view.getComponentByReference(L_FORM)).willReturn(productForm); given(view.getComponentByReference(UNIT)).willReturn(unitField); given(productForm.getEntityId()).willReturn(L_ID); productDetailsHooks.fillUnit(view); verify(unitField, never()).setFieldValue(Mockito.anyString()); } @Test public void shouldFillUnitIfFormIsntSaved() { given(view.getComponentByReference(L_FORM)).willReturn(productForm); given(view.getComponentByReference(UNIT)).willReturn(unitField); given(productForm.getEntityId()).willReturn(null); given(unitField.getFieldValue()).willReturn(null); given(unitService.getDefaultUnitFromSystemParameters()).willReturn(L_SZT); productDetailsHooks.fillUnit(view); verify(unitField).setFieldValue(L_SZT); }
WorkPlansListView { public List<Entity> getSelectedWorkPlans() { return workPlansGrid.getSelectedEntities(); } WorkPlansListView(final WindowComponent window, final RibbonActionItem deleteButton, final GridComponent workPlansGrid); static WorkPlansListView from(final ViewDefinitionState view); void setUpDeleteButton(final boolean isEnabled, final String message); List<Entity> getSelectedWorkPlans(); @Override boolean equals(final Object obj); @Override int hashCode(); }
@Test public final void shouldGetSelectedEntities() { List<Entity> entities = ImmutableList.of(mockEntity(), mockEntity(), mockEntity(), mockEntity()); given(workPlansGrid.getSelectedEntities()).willReturn(entities); List<Entity> result = workPlansListView.getSelectedWorkPlans(); assertEquals(entities, result); }
UnitConversionItemValidatorsB { public boolean validateUnitOnConversionWithProduct(final DataDefinition dataDefinition, final Entity unitConversionItem) { final Entity product = unitConversionItem.getBelongsToField(UnitConversionItemFieldsB.PRODUCT); final String unitFrom = unitConversionItem.getStringField(UnitConversionItemFields.UNIT_FROM); if (product == null || product.getStringField(ProductFields.UNIT).equals(unitFrom)) { return true; } final String errorMsg = "basic.product.validateError.unitFrom.doesNotMatchUnitConversionItem"; unitConversionItem.addError(dataDefinition.getField(UnitConversionItemFields.UNIT_FROM), errorMsg); return false; } boolean validateUnitOnConversionWithProduct(final DataDefinition dataDefinition, final Entity unitConversionItem); }
@Test public void sholudReturnTrueIfProductIsNull() { given(unitConversionItem.getBelongsToField(UnitConversionItemFieldsB.PRODUCT)).willReturn(null); boolean result = unitConversionItemValidatorsB.validateUnitOnConversionWithProduct(dataDefinition, unitConversionItem); assertTrue(result); } @Test public void sholudReturnTrueIfProductUnitIsEqualFieldUnit() { stubConversionSourceUnit(SOME_UNIT); stubProductUnit(SOME_UNIT); boolean result = unitConversionItemValidatorsB.validateUnitOnConversionWithProduct(dataDefinition, unitConversionItem); assertTrue(result); verify(unitConversionItem, Mockito.never()).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); } @Test public void sholudReturnErrorIfProductUnitIsNotEqualFieldUnit() { stubConversionSourceUnit(SOME_UNIT); stubProductUnit("otherNotEqualSzt"); boolean result = unitConversionItemValidatorsB.validateUnitOnConversionWithProduct(dataDefinition, unitConversionItem); assertFalse(result); verify(unitConversionItem).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); }
ProductHooks { public void clearFamilyFromProductWhenTypeIsChanged(final DataDefinition productDD, final Entity product) { if (product.getId() == null) { return; } String entityType = product.getStringField(ENTITY_TYPE); Entity productFromDB = product.getDataDefinition().get(product.getId()); if (entityType.equals(PARTICULAR_PRODUCT.getStringValue()) && !entityType.equals(productFromDB.getStringField(ENTITY_TYPE))) { deleteProductFamily(productFromDB); } } void generateNodeNumber(final DataDefinition productDD, final Entity product); void updateNodeNumber(final DataDefinition productDD, final Entity product); void clearFamilyFromProductWhenTypeIsChanged(final DataDefinition productDD, final Entity product); boolean checkIfNotBelongsToSameFamily(final DataDefinition productDD, final Entity product); boolean checkIfParentIsFamily(final DataDefinition productDD, final Entity product); void clearFieldsOnCopy(final DataDefinition dataDefinition, final Entity product); void clearExternalIdOnCopy(final DataDefinition dataDefinition, final Entity entity); void calculateConversionIfUnitChanged(final DataDefinition productDD, final Entity product); void calculateConversionOnCreate(final DataDefinition productDD, final Entity product); boolean validateAdditionalUnit(final DataDefinition productDD, final Entity product); boolean validateCodeUniqueness(final DataDefinition productDD, final Entity product); }
@Test public void shouldReturnWhenEntityIdIsNull() throws Exception { when(entity.getId()).thenReturn(null); productHooks.clearFamilyFromProductWhenTypeIsChanged(dataDefinition, entity); } @Test public void shouldReturnWhenSavingEntityIsFamily() throws Exception { Long entityId = 1L; when(entity.getId()).thenReturn(entityId); when(entity.getStringField(ProductFields.ENTITY_TYPE)).thenReturn("02productsFamily"); when(entity.getDataDefinition()).thenReturn(dataDefinition); when(dataDefinition.get(entityId)).thenReturn(product); productHooks.clearFamilyFromProductWhenTypeIsChanged(dataDefinition, entity); } @Test public void shouldDeleteFamilyFromProductsWhenEntityTypeIsChanged() throws Exception { Long entityId = 1L; when(entity.getId()).thenReturn(entityId); when(entity.getStringField(ProductFields.ENTITY_TYPE)).thenReturn("01particularProduct"); when(dataDefinition.get(entityId)).thenReturn(product); when(product.getStringField(ProductFields.ENTITY_TYPE)).thenReturn("02productsFamily"); searchProductLikeParent(product); EntityList products = mockEntityListIterator(asList(prod1, prod2)); when(searchCriteria.list()).thenReturn(result); when(result.getEntities()).thenReturn(products); productHooks.clearFamilyFromProductWhenTypeIsChanged(dataDefinition, entity); Assert.assertEquals(null, prod1.getBelongsToField("parent")); Assert.assertEquals(null, prod2.getBelongsToField("parent")); }
ProductHooks { public void clearExternalIdOnCopy(final DataDefinition dataDefinition, final Entity entity) { if (entity == null) { return; } entity.setField("externalNumber", null); } void generateNodeNumber(final DataDefinition productDD, final Entity product); void updateNodeNumber(final DataDefinition productDD, final Entity product); void clearFamilyFromProductWhenTypeIsChanged(final DataDefinition productDD, final Entity product); boolean checkIfNotBelongsToSameFamily(final DataDefinition productDD, final Entity product); boolean checkIfParentIsFamily(final DataDefinition productDD, final Entity product); void clearFieldsOnCopy(final DataDefinition dataDefinition, final Entity product); void clearExternalIdOnCopy(final DataDefinition dataDefinition, final Entity entity); void calculateConversionIfUnitChanged(final DataDefinition productDD, final Entity product); void calculateConversionOnCreate(final DataDefinition productDD, final Entity product); boolean validateAdditionalUnit(final DataDefinition productDD, final Entity product); boolean validateCodeUniqueness(final DataDefinition productDD, final Entity product); }
@Test public void shouldClearExternalIdOnCopy() throws Exception { productHooks.clearExternalIdOnCopy(dataDefinition, entity); Mockito.verify(entity).setField("externalNumber", null); }
ExchangeRatesNbpServiceImpl implements ExchangeRatesNbpService { @Override public Map<String, BigDecimal> parse(InputStream inputStream, NbpProperties nbpProperties) { Map<String, BigDecimal> exRates = new HashMap<>(); try { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLStreamReader sr = inputFactory.createXMLStreamReader(inputStream); sr.nextTag(); sr.nextTag(); String currencyCode = ""; BigDecimal exRate = null; BigDecimal factor = BigDecimal.ONE; String exchangeRateField = nbpProperties.fieldName(); while (sr.hasNext()) { if (sr.getEventType() == XMLStreamConstants.END_DOCUMENT) { sr.close(); } if (sr.isStartElement()) { String s = sr.getLocalName(); if (s.equals("przelicznik")) { factor = new BigDecimal(sr.getElementText().replace(',', '.')); } else if (s.equals("kod_waluty")) { currencyCode = sr.getElementText(); } else if (s.equals(exchangeRateField)) { exRate = new BigDecimal(sr.getElementText().replace(',', '.')); } if (exRate != null) { exRates.put(currencyCode, exRate.divide(factor, RoundingMode.HALF_UP)); exRate = null; } } sr.next(); } } catch (XMLStreamException e) { throw new RuntimeException(e); } finally { closeStream(inputStream); } return exRates; } @Override Map<String, BigDecimal> get(NbpProperties nbpProperties); @Override Map<String, BigDecimal> parse(InputStream inputStream, NbpProperties nbpProperties); }
@Test public void shouldParseCorrectlyGivenExampleDocument() throws Exception { Map<String, BigDecimal> map = service.parse(inputStream, ExchangeRatesNbpService.NbpProperties.LAST_C); assertTrue(map.containsKey("USD")); assertTrue(map.containsKey("CAD")); assertTrue(map.containsKey("AUD")); assertTrue(map.containsValue(new BigDecimal("0.3076"))); assertTrue(map.containsValue(new BigDecimal("2.8927"))); assertTrue(map.containsValue(new BigDecimal("2.8732"))); } @Test public void shouldParseAlwaysCloseInputStream() throws Exception { InputStream inputStreamSpied = spy(inputStream); service.parse(inputStreamSpied, ExchangeRatesNbpService.NbpProperties.LAST_C); verify(inputStreamSpied, atLeastOnce()).close(); }
ProductValidators { public boolean checkEanUniqueness(final DataDefinition productDD, final FieldDefinition eanFieldDefinition, final Entity product, final Object eanOldValue, final Object eanNewValue) { String ean = (String) eanNewValue; if (StringUtils.isEmpty(ean) || ObjectUtils.equals(eanOldValue, ean)) { return true; } if (productWithEanAlreadyExists(productDD, ean)) { product.addError(eanFieldDefinition, "smartView.validate.field.error.duplicated"); return false; } return true; } boolean checkEanUniqueness(final DataDefinition productDD, final FieldDefinition eanFieldDefinition, final Entity product, final Object eanOldValue, final Object eanNewValue); }
@Test public final void shouldCheckEanUniquenessJustReturnTrueIfNewEanIsEmpty() { String oldVal = "123456"; String newVal = ""; boolean isValid = productValidators.checkEanUniqueness(dataDefinition, fieldDefinition, entity, oldVal, newVal); assertTrue(isValid); verify(entity, never()).addError(any(FieldDefinition.class), anyString()); } @Test public final void shouldCheckEanUniquenessJustReturnTrueIfNewEanIsNull() { String oldVal = "123456"; String newVal = null; boolean isValid = productValidators.checkEanUniqueness(dataDefinition, fieldDefinition, entity, oldVal, newVal); assertTrue(isValid); verify(entity, never()).addError(any(FieldDefinition.class), anyString()); } @Test public final void shouldCheckEanUniquenessReturnTrueIfThereIsNoExistingProductsWithGivenId() { String oldVal = "123456"; String newVal = "654321"; ArgumentCaptor<SearchCriterion> criterionCaptor = ArgumentCaptor.forClass(SearchCriterion.class); stubSearchCriteriaWith(null); boolean isValid = productValidators.checkEanUniqueness(dataDefinition, fieldDefinition, entity, oldVal, newVal); assertTrue(isValid); verify(entity, never()).addError(any(FieldDefinition.class), anyString()); verify(scb).add(criterionCaptor.capture()); assertEquals(SearchRestrictions.eq(ProductFields.EAN, newVal), criterionCaptor.getValue()); } @Test public final void shouldCheckEanUniquenessReturnFalsAndMarkFieldAsInvalidIfProductsWithGivenIdExists() { String oldVal = "123456"; String newVal = "654321"; ArgumentCaptor<SearchCriterion> criterionCaptor = ArgumentCaptor.forClass(SearchCriterion.class); Entity resultEntity = mock(Entity.class); stubSearchCriteriaWith(resultEntity); boolean isValid = productValidators.checkEanUniqueness(dataDefinition, fieldDefinition, entity, oldVal, newVal); assertFalse(isValid); verify(entity).addError(fieldDefinition, "smartView.validate.field.error.duplicated"); verify(scb).add(criterionCaptor.capture()); assertEquals(SearchRestrictions.eq(ProductFields.EAN, newVal), criterionCaptor.getValue()); }
WorkPlansListView { public void setUpDeleteButton(final boolean isEnabled, final String message) { deleteButton.setEnabled(isEnabled); deleteButton.setMessage(message); deleteButton.requestUpdate(true); window.requestRibbonRender(); } WorkPlansListView(final WindowComponent window, final RibbonActionItem deleteButton, final GridComponent workPlansGrid); static WorkPlansListView from(final ViewDefinitionState view); void setUpDeleteButton(final boolean isEnabled, final String message); List<Entity> getSelectedWorkPlans(); @Override boolean equals(final Object obj); @Override int hashCode(); }
@Test public final void shouldSetUpDeleteButton() { boolean isEnabled = true; String message = "some arbitrary mesage"; workPlansListView.setUpDeleteButton(isEnabled, message); verify(deleteButton).setEnabled(isEnabled); verify(deleteButton).setMessage(message); verify(deleteButton).requestUpdate(true); verify(windowComponent).requestRibbonRender(); }
CompanyService { public Long getCompanyId() { if (getCompany() == null) { return null; } else { return getCompany().getId(); } } Long getCompanyId(); @Transactional Entity getCompany(); @Transactional Entity getCompany(final Long companyId); final Boolean isCompanyOwner(final Entity company); void disabledGridWhenCompanyIsOwner(final ViewDefinitionState view, final String... references); void disableButton(final ViewDefinitionState view, final String ribbonGroupName, final String ribbonActionItemName, final boolean isEnabled, final String message); }
@Test public void shouldReturnExistingCompanyEntityId() throws Exception { Entity company = Mockito.mock(Entity.class); given(company.getId()).willReturn(13L); given(parameterService.getParameter()).willReturn(parameter); given(parameter.getBelongsToField(ParameterFields.COMPANY)).willReturn(company); Long id = companyService.getCompanyId(); assertEquals(Long.valueOf(13L), id); }
CompanyService { @Transactional public Entity getCompany() { Entity parameter = parameterService.getParameter(); return parameter.getBelongsToField(ParameterFields.COMPANY); } Long getCompanyId(); @Transactional Entity getCompany(); @Transactional Entity getCompany(final Long companyId); final Boolean isCompanyOwner(final Entity company); void disabledGridWhenCompanyIsOwner(final ViewDefinitionState view, final String... references); void disableButton(final ViewDefinitionState view, final String ribbonGroupName, final String ribbonActionItemName, final boolean isEnabled, final String message); }
@Test public void shouldReturnExistingCompanyEntity() throws Exception { given(parameterService.getParameter()).willReturn(parameter); given(parameter.getBelongsToField(ParameterFields.COMPANY)).willReturn(company); given(company.isValid()).willReturn(true); Entity existingcompany = companyService.getCompany(); assertEquals(company, existingcompany); }
Shift { public Optional<DateRange> findWorkTimeAt(final Date date) { if (timetableExceptions.hasFreeTimeAt(date)) { return Optional.absent(); } DateTime dateTime = new DateTime(date); Optional<TimeRange> maybeTimeRangeFromPlan = findWorkTimeAt(dateTime.getDayOfWeek(), dateTime.toLocalTime()); for (TimeRange timeRangeFromPlan : maybeTimeRangeFromPlan.asSet()) { return Optional.of(buildDateRangeFrom(timeRangeFromPlan, date)); } return timetableExceptions.findDateRangeFor(TimetableExceptionType.WORK_TIME, date); } Shift(final Entity shiftEntity); Shift(final Entity shiftEntity, final DateTime day); Shift(final Entity shiftEntity, final DateTime day, final boolean checkWorking); boolean worksAt(final int dayOfWeek, final LocalTime time); boolean worksAt(final int dayOfWeek); boolean worksAt(final LocalDate localDate); boolean worksAt(final DateTime dateTime); @Deprecated boolean worksAt(final Date date); Optional<DateRange> findWorkTimeAt(final Date date); Optional<TimeRange> findWorkTimeAt(final int dayOfWeek, final LocalTime time); Optional<TimeRange> findWorkTimeAt(final int dayOfWeek); List<TimeRange> findWorkTimeAt(final LocalDate localDate); Entity getEntity(); Long getId(); DateTime getShiftStartDate(); void setShiftStartDate(DateTime shiftStartDate); DateTime getShiftEndDate(); void setShiftEndDate(DateTime shiftEndDate); @Override int hashCode(); @Override boolean equals(final Object obj); }
@Test public final void shouldReturnWorkingHoursForDay() { String hours = "6:00-12:00, 21:30-2:30"; given(shiftEntity.getStringField(ShiftFields.MONDAY_HOURS)).willReturn(hours); given(shiftEntity.getBooleanField(ShiftFields.MONDAY_WORKING)).willReturn(true); LocalDate mondayDate = new LocalDate(2013, 9, 2); Shift shift = new Shift(shiftEntity); List<TimeRange> timeRanges = shift.findWorkTimeAt(mondayDate); List<TimeRange> expectedTimeRanges = ImmutableList.of(new TimeRange(new LocalTime(6, 0), new LocalTime(12, 0)), new TimeRange(new LocalTime(21, 30), new LocalTime(2, 30))); assertEquals(expectedTimeRanges, timeRanges); }
WorkingHours implements Comparable<WorkingHours> { public Set<TimeRange> getTimeRanges() { return Collections.unmodifiableSet(hours); } WorkingHours(final String hourRanges); boolean isEmpty(); boolean contains(final LocalTime time); Optional<TimeRange> findRangeFor(final LocalTime time); Set<TimeRange> getTimeRanges(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override int compareTo(final WorkingHours other); }
@Test public final void shouldBuildWorkingHoursFromSingleTimeRangeWithTwoDigitsHour() { String timeRangeString = "09:00-17:00"; WorkingHours workingHours = new WorkingHours(timeRangeString); assertEquals(1, workingHours.getTimeRanges().size()); TimeRange timeRange = workingHours.getTimeRanges().iterator().next(); assertEquals(new LocalTime(9, 0, 0), timeRange.getFrom()); assertEquals(new LocalTime(17, 0, 0), timeRange.getTo()); } @Test public final void shouldBuildWorkingHoursFromSingleTimeRangeWithOneDigitsHour() { String timeRangeString = "9:00-17:00"; WorkingHours workingHours = new WorkingHours(timeRangeString); assertEquals(1, workingHours.getTimeRanges().size()); TimeRange timeRange = workingHours.getTimeRanges().iterator().next(); assertEquals(new LocalTime(9, 0, 0), timeRange.getFrom()); assertEquals(new LocalTime(17, 0, 0), timeRange.getTo()); }
ProductsFamiliesTreeService { public List<Entity> getHierarchyProductsTree(final Entity product) { List<Entity> tree = new ArrayList<Entity>(); addProduct(tree, product); generateTree(product, tree); return tree; } List<Entity> getHierarchyProductsTree(final Entity product); }
@Test public void shouldReturnTreeWithoutChildrenWhenDoesnotExists() throws Exception { EntityList emptyList = mockEntityList(new LinkedList<Entity>()); when(productDsk.getHasManyField(PRODUCT_FAMILY_CHILDRENS)).thenReturn(emptyList); List<Entity> tree = productsFamiliesTreeService.getHierarchyProductsTree(productDsk); assertEquals(1, tree.size()); assertEquals(productDsk, tree.get(0)); } @Test public void shouldReturnTreeWithTwoLevel() throws Exception { List<Entity> tree = productsFamiliesTreeService.getHierarchyProductsTree(productDsk); assertEquals(4, tree.size()); assertEquals(productDsk3, tree.get(2)); assertEquals(productDsk2, tree.get(3)); } @Test public void shouldReturnTreeWithOneLevel() throws Exception { EntityList emptyList = mockEntityList(new LinkedList<Entity>()); when(productDsk1.getHasManyField(PRODUCT_FAMILY_CHILDRENS)).thenReturn(emptyList); List<Entity> tree = productsFamiliesTreeService.getHierarchyProductsTree(productDsk); assertEquals(3, tree.size()); assertEquals(productDsk2, tree.get(2)); }
ProductCatalogNumbersServiceImpl implements ProductCatalogNumbersService { @Override public Entity getProductCatalogNumber(final Entity product, final Entity supplier) { return dataDefinitionService .get(ProductCatalogNumbersConstants.PLUGIN_IDENTIFIER, ProductCatalogNumbersConstants.MODEL_PRODUCT_CATALOG_NUMBERS).find() .add(SearchRestrictions.belongsTo(PRODUCT, product)).add(SearchRestrictions.belongsTo(COMPANY, supplier)) .setMaxResults(1).uniqueResult(); } @Override Entity getProductCatalogNumber(final Entity product, final Entity supplier); }
@Test public void shouldReturnNullWhenGetProductCatalogNumber() { given(productCatalogNumbersDD.find()).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.add(Mockito.any(SearchCriterion.class))).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.setMaxResults(1)).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.uniqueResult()).willReturn(null); Entity result = productCatalogNumbersService.getProductCatalogNumber(null, null); assertEquals(null, result); } @Test public void shouldReturnProductCatalogNumberWhenFetProductCatalogNumber() { given(productCatalogNumbersDD.find()).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.add(Mockito.any(SearchCriterion.class))).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.setMaxResults(1)).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.uniqueResult()).willReturn(productCatalogNumbers); Entity result = productCatalogNumbersService.getProductCatalogNumber(product, supplier); assertEquals(productCatalogNumbers, result); }
ProductService { public boolean checkIfProductEntityTypeIsCorrect(final Entity product, final ProductFamilyElementType entityType) { return entityType.getStringValue().equals(product.getStringField(ENTITY_TYPE)); } Entity find(final SearchProjection projection, final SearchCriterion criteria, final SearchOrder order); List<Entity> findAll(final SearchProjection projection, final SearchCriterion criteria, final SearchOrder order); boolean checkIfProductEntityTypeIsCorrect(final Entity product, final ProductFamilyElementType entityType); void conversionForProductUnit(final Entity product); BigDecimal convertQuantityFromProductUnit(final Entity product, final BigDecimal quantity, final String targetUnit); boolean hasUnitChangedOnUpdate(final Entity product); void getDefaultConversions(final ViewDefinitionState view, final ComponentState state, final String[] args); void getDefaultConversionsForGrid(final ViewDefinitionState view, final ComponentState state, final String[] args); boolean checkIfSubstituteIsNotRemoved(final DataDefinition substituteComponentDD, final Entity substituteComponent); boolean checkSubstituteComponentUniqueness(final DataDefinition substituteComponentDD, final Entity substituteComponent); boolean checkIfProductIsNotRemoved(final DataDefinition substituteDD, final Entity substitute); void fillUnit(final DataDefinition productDD, final Entity product); }
@Test public void shouldReturnTrueWhenCheckIfProductEntityTypeIsCorrect() throws Exception { given(product.getStringField(ENTITY_TYPE)).willReturn(PARTICULAR_PRODUCT.getStringValue()); boolean result = productService.checkIfProductEntityTypeIsCorrect(product, PARTICULAR_PRODUCT); assertTrue(result); } @Test public void shouldReturnFalseWhenCheckIfProductEntityTypeIsCorrect() throws Exception { given(product.getStringField(ENTITY_TYPE)).willReturn(PARTICULAR_PRODUCT.getStringValue()); boolean result = productService.checkIfProductEntityTypeIsCorrect(product, PRODUCTS_FAMILY); assertFalse(result); }
ProductService { public boolean checkIfProductIsNotRemoved(final DataDefinition substituteDD, final Entity substitute) { Entity product = substitute.getBelongsToField(SubstituteFields.PRODUCT); if (product == null || product.getId() == null) { return true; } Entity productEntity = dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_PRODUCT).get( product.getId()); if (productEntity == null) { substitute.addGlobalError("smartView.message.belongsToNotFound"); substitute.setField(SubstituteFields.PRODUCT, null); return false; } return true; } Entity find(final SearchProjection projection, final SearchCriterion criteria, final SearchOrder order); List<Entity> findAll(final SearchProjection projection, final SearchCriterion criteria, final SearchOrder order); boolean checkIfProductEntityTypeIsCorrect(final Entity product, final ProductFamilyElementType entityType); void conversionForProductUnit(final Entity product); BigDecimal convertQuantityFromProductUnit(final Entity product, final BigDecimal quantity, final String targetUnit); boolean hasUnitChangedOnUpdate(final Entity product); void getDefaultConversions(final ViewDefinitionState view, final ComponentState state, final String[] args); void getDefaultConversionsForGrid(final ViewDefinitionState view, final ComponentState state, final String[] args); boolean checkIfSubstituteIsNotRemoved(final DataDefinition substituteComponentDD, final Entity substituteComponent); boolean checkSubstituteComponentUniqueness(final DataDefinition substituteComponentDD, final Entity substituteComponent); boolean checkIfProductIsNotRemoved(final DataDefinition substituteDD, final Entity substitute); void fillUnit(final DataDefinition productDD, final Entity product); }
@Test public void shouldReturnTrueWhenProductIsNotRemoved() throws Exception { boolean result = productService.checkIfProductIsNotRemoved(productDD, product); assertTrue(result); } @Test public void shouldReturnFalseWhenEntityDoesnotExists() throws Exception { DataDefinition productDD = Mockito.mock(DataDefinition.class); Long productId = 1L; given(substitute.getBelongsToField(SubstituteFields.PRODUCT)).willReturn(product); given(dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_PRODUCT)).willReturn(productDD); given(product.getId()).willReturn(productId); given(productDD.get(productId)).willReturn(null); boolean result = productService.checkIfProductIsNotRemoved(substituteDD, substitute); assertFalse(result); } @Test public void shouldReturnTrueWhenProductExists() throws Exception { DataDefinition productDD = Mockito.mock(DataDefinition.class); Long productId = 1L; given(substitute.getBelongsToField(SubstituteFields.PRODUCT)).willReturn(product); given(dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_PRODUCT)).willReturn(productDD); given(product.getId()).willReturn(productId); given(productDD.get(productId)).willReturn(product); boolean result = productService.checkIfProductIsNotRemoved(substituteDD, substitute); assertTrue(result); }
ProductService { public boolean checkIfSubstituteIsNotRemoved(final DataDefinition substituteComponentDD, final Entity substituteComponent) { Entity substitute = substituteComponent.getBelongsToField(SubstituteComponentFields.SUBSTITUTE); if (substitute == null || substitute.getId() == null) { return true; } Entity substituteEntity = dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_SUBSTITUTE) .get(substitute.getId()); if (substituteEntity == null) { substituteComponent.addGlobalError("smartView.message.belongsToNotFound"); substituteComponent.setField(SubstituteComponentFields.SUBSTITUTE, null); return false; } else { return true; } } Entity find(final SearchProjection projection, final SearchCriterion criteria, final SearchOrder order); List<Entity> findAll(final SearchProjection projection, final SearchCriterion criteria, final SearchOrder order); boolean checkIfProductEntityTypeIsCorrect(final Entity product, final ProductFamilyElementType entityType); void conversionForProductUnit(final Entity product); BigDecimal convertQuantityFromProductUnit(final Entity product, final BigDecimal quantity, final String targetUnit); boolean hasUnitChangedOnUpdate(final Entity product); void getDefaultConversions(final ViewDefinitionState view, final ComponentState state, final String[] args); void getDefaultConversionsForGrid(final ViewDefinitionState view, final ComponentState state, final String[] args); boolean checkIfSubstituteIsNotRemoved(final DataDefinition substituteComponentDD, final Entity substituteComponent); boolean checkSubstituteComponentUniqueness(final DataDefinition substituteComponentDD, final Entity substituteComponent); boolean checkIfProductIsNotRemoved(final DataDefinition substituteDD, final Entity substitute); void fillUnit(final DataDefinition productDD, final Entity product); }
@Test public void shouldReturnFalseWhenSubstituteDoesnotExists() throws Exception { DataDefinition substituteDD = Mockito.mock(DataDefinition.class); Long substituteId = 1L; given(substituteComponent.getBelongsToField(SubstituteComponentFields.SUBSTITUTE)).willReturn(substitute); given(dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_SUBSTITUTE)).willReturn( substituteDD); given(substitute.getId()).willReturn(substituteId); given(substituteDD.get(substituteId)).willReturn(null); boolean result = productService.checkIfSubstituteIsNotRemoved(substituteComponentDD, substituteComponent); assertFalse(result); } @Test public void shouldReturnTrueWhenEntityDoesnotHaveBTSubstitute() throws Exception { boolean result = productService.checkIfSubstituteIsNotRemoved(substituteComponentDD, substituteComponent); assertTrue(result); } @Test public void shouldReturnTrueWhenSubstitueExists() throws Exception { DataDefinition substituteDD = Mockito.mock(DataDefinition.class); Long substituteId = 1L; given(substituteComponent.getBelongsToField(SubstituteComponentFields.SUBSTITUTE)).willReturn(substitute); given(dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_SUBSTITUTE)).willReturn( substituteDD); given(substitute.getId()).willReturn(substituteId); given(substituteDD.get(substituteId)).willReturn(substitute); boolean result = productService.checkIfSubstituteIsNotRemoved(substituteComponentDD, substituteComponent); assertTrue(result); }
ProductService { public void fillUnit(final DataDefinition productDD, final Entity product) { if (product.getField(UNIT) == null) { product.setField(UNIT, unitService.getDefaultUnitFromSystemParameters()); } } Entity find(final SearchProjection projection, final SearchCriterion criteria, final SearchOrder order); List<Entity> findAll(final SearchProjection projection, final SearchCriterion criteria, final SearchOrder order); boolean checkIfProductEntityTypeIsCorrect(final Entity product, final ProductFamilyElementType entityType); void conversionForProductUnit(final Entity product); BigDecimal convertQuantityFromProductUnit(final Entity product, final BigDecimal quantity, final String targetUnit); boolean hasUnitChangedOnUpdate(final Entity product); void getDefaultConversions(final ViewDefinitionState view, final ComponentState state, final String[] args); void getDefaultConversionsForGrid(final ViewDefinitionState view, final ComponentState state, final String[] args); boolean checkIfSubstituteIsNotRemoved(final DataDefinition substituteComponentDD, final Entity substituteComponent); boolean checkSubstituteComponentUniqueness(final DataDefinition substituteComponentDD, final Entity substituteComponent); boolean checkIfProductIsNotRemoved(final DataDefinition substituteDD, final Entity substitute); void fillUnit(final DataDefinition productDD, final Entity product); }
@Test public void shouldntFillUnitIfUnitIsntNull() { Entity product = mock(Entity.class); DataDefinition productDD = mock(DataDefinition.class); given(product.getField(UNIT)).willReturn(L_SZT); productService.fillUnit(productDD, product); verify(product, never()).setField(Mockito.anyString(), Mockito.anyString()); } @Test public void shouldFillUnitIfUnitIsNull() { Entity product = mock(Entity.class); DataDefinition productDD = mock(DataDefinition.class); given(product.getField(UNIT)).willReturn(null); given(unitService.getDefaultUnitFromSystemParameters()).willReturn(L_SZT); productService.fillUnit(productDD, product); verify(product).setField(UNIT, L_SZT); }
TechnologyOperationComponentHooksOTFO { public void changeDescriptionInOperationalTasksWhenChanged(final DataDefinition technologyOperationComponentDD, final Entity technologyOperationComponent) { Long technologyOperationComponentId = technologyOperationComponent.getId(); if (technologyOperationComponentId == null) { return; } Entity technologyOperationComponentFromDB = technologyOperationComponentDD.get(technologyOperationComponentId); String comment = (technologyOperationComponent.getStringField(TechnologyOperationComponentFields.COMMENT) == null) ? "" : technologyOperationComponent.getStringField(TechnologyOperationComponentFields.COMMENT); String technologyOperationComponentComment = (technologyOperationComponentFromDB .getStringField(TechnologyOperationComponentFields.COMMENT) == null) ? "" : technologyOperationComponentFromDB .getStringField(TechnologyOperationComponentFields.COMMENT); if (!comment.equals(technologyOperationComponentComment)) { changedDescriptionInOperationalTasks(technologyOperationComponent); } } void changeDescriptionInOperationalTasksWhenChanged(final DataDefinition technologyOperationComponentDD, final Entity technologyOperationComponent); }
@Test public void shouldReturnWhenEntityIdIsNull() throws Exception { Long technologyOperationComponentId = null; String comment = "comment"; given(technologyOperationComponent.getId()).willReturn(technologyOperationComponentId); technologyOperationComponentHooksOTFO.changeDescriptionInOperationalTasksWhenChanged(technologyOperationComponentDD, technologyOperationComponent); Mockito.verify(operationalTask, Mockito.never()).setField(OperationalTaskFields.DESCRIPTION, comment); Mockito.verify(operationalTaskDD, Mockito.never()).save(operationalTask); } @Test public void shouldReturnWhenTechnologyOperationComponentCommentIsTheSame() throws Exception { Long technologyOperationComponentId = 1L; String comment = "comment"; String technologyOperationComponentComment = "comment"; given(technologyOperationComponent.getId()).willReturn(technologyOperationComponentId); given(technologyOperationComponentDD.get(technologyOperationComponentId)).willReturn(technologyOperationComponentFromDB); given(technologyOperationComponent.getStringField(TechnologyOperationComponentFields.COMMENT)).willReturn(comment); given(technologyOperationComponentFromDB.getStringField(TechnologyOperationComponentFields.COMMENT)).willReturn( technologyOperationComponentComment); technologyOperationComponentHooksOTFO.changeDescriptionInOperationalTasksWhenChanged(technologyOperationComponentDD, technologyOperationComponent); Mockito.verify(operationalTask, Mockito.never()).setField(OperationalTaskFields.DESCRIPTION, comment); Mockito.verify(operationalTaskDD, Mockito.never()).save(operationalTask); } @Ignore @Test public void shouldChangeOperationalTasksDescriptionWhenTechnologyOperationComponentCommentWasChanged() throws Exception { Long technologyOperationComponentId = 1L; String comment = "comment"; String technologyOperationComponentComment = "comment2"; given(technologyOperationComponent.getId()).willReturn(technologyOperationComponentId); given(technologyOperationComponentDD.get(technologyOperationComponentId)).willReturn(technologyOperationComponentFromDB); given(technologyOperationComponent.getStringField(TechnologyOperationComponentFields.COMMENT)).willReturn(comment); given(technologyOperationComponentFromDB.getStringField(TechnologyOperationComponentFields.COMMENT)).willReturn( technologyOperationComponentComment); EntityList techOperCompOperationalTasks = mockEntityList(Lists.newArrayList(techOperCompOperationalTask)); given( operationalTasksForOrdersService .getTechOperCompOperationalTasksForTechnologyOperationComponent(technologyOperationComponent)) .willReturn(techOperCompOperationalTasks); technologyOperationComponentHooksOTFO.changeDescriptionInOperationalTasksWhenChanged(technologyOperationComponentDD, technologyOperationComponent); Mockito.verify(operationalTask).setField(OperationalTaskFields.DESCRIPTION, comment); Mockito.verify(operationalTaskDD).save(operationalTask); }
OperationHooksOTFO { public void changedNameInOperationalTasksWhenChanged(final DataDefinition operationDD, final Entity operation) { Long operationId = operation.getId(); if (operationId == null) { return; } Entity operationFromDB = operationDD.get(operationId); String name = operation.getStringField(OperationFields.NAME); String operationName = operationFromDB.getStringField(OperationFields.NAME); if (!name.equals(operationName)) { changedNameInOperationalTasks(operation); } } void changedNameInOperationalTasksWhenChanged(final DataDefinition operationDD, final Entity operation); }
@Test public void shouldReturnIfEntityIdIsNull() throws Exception { Long operationId = null; String name = "name"; given(operation.getId()).willReturn(operationId); operationHooksOTFO.changedNameInOperationalTasksWhenChanged(operationDD, operation); Mockito.verify(operationalTask, Mockito.never()).setField(OperationalTaskFields.NAME, name); Mockito.verify(operationalTaskDD, Mockito.never()).save(operationalTask); } @Test public void shouldReturnWhenEntityNameIsTheSame() throws Exception { Long operationId = 1L; String name = "name"; String operationName = "name"; given(operation.getId()).willReturn(operationId); given(operationDD.get(operationId)).willReturn(operationFromDB); given(operation.getStringField(OperationFields.NAME)).willReturn(name); given(operationFromDB.getStringField(OperationFields.NAME)).willReturn(operationName); operationHooksOTFO.changedNameInOperationalTasksWhenChanged(operationDD, operation); Mockito.verify(operationalTask, Mockito.never()).setField(OperationalTaskFields.NAME, name); Mockito.verify(operationalTaskDD, Mockito.never()).save(operationalTask); } @Ignore @Test public void shouldChangeOperationalTaskNameWhenOperationNameWasChanged() throws Exception { Long operationId = 1L; String name = "name"; String operationName = "name2"; given(operation.getId()).willReturn(operationId); given(operationDD.get(operationId)).willReturn(operationFromDB); given(operation.getStringField(OperationFields.NAME)).willReturn(name); given(operationFromDB.getStringField(OperationFields.NAME)).willReturn(operationName); EntityList technologyOperationComponents = mockEntityList(Lists.newArrayList(technologyOperationComponent)); given(operationalTasksForOrdersService.getTechnologyOperationComponentsForOperation(operation)).willReturn( technologyOperationComponents); operationHooksOTFO.changedNameInOperationalTasksWhenChanged(operationDD, operation); Mockito.verify(operationalTask).setField(OperationalTaskFields.NAME, name); Mockito.verify(operationalTaskDD).save(operationalTask); }
OperationalTaskDetailsHooksOTFO { public void disableFieldsWhenOrderTypeIsSelected(final ViewDefinitionState view) { FieldComponent typeTaskField = (FieldComponent) view.getComponentByReference(OperationalTaskFields.TYPE_TASK); String typeTask = (String) typeTaskField.getFieldValue(); List<String> referenceBasicFields = Lists.newArrayList(OperationalTaskFields.NAME, OperationalTaskFields.PRODUCTION_LINE, OperationalTaskFields.DESCRIPTION); List<String> extendFields = Lists.newArrayList(OperationalTaskFieldsOTFO.ORDER, OperationalTaskFieldsOTFO.TECHNOLOGY_OPERATION_COMPONENT); if (operationalTasksForOrdersService.isOperationalTaskTypeTaskOtherCase(typeTask)) { changedStateField(view, referenceBasicFields, true); changedStateField(view, extendFields, false); clearFieldValue(view, extendFields); } else { changedStateField(view, referenceBasicFields, false); changedStateField(view, extendFields, true); } } void disableFieldsWhenOrderTypeIsSelected(final ViewDefinitionState view); void disableButtons(final ViewDefinitionState view); void setTechnology(final ViewDefinitionState view); void setTechnologyOperationComponent(final ViewDefinitionState view); }
@Test public void shouldDisabledFieldWhenTypeForOrderIsSelected() throws Exception { String typeTask = OperationalTaskTypeTaskOTFO.EXECUTION_OPERATION_IN_ORDER.getStringValue(); given(typeTaskField.getFieldValue()).willReturn(typeTask); given(operationalTasksForOrdersService.isOperationalTaskTypeTaskOtherCase(typeTask)).willReturn(false); operationalTaskDetailsHooksOTFO.disableFieldsWhenOrderTypeIsSelected(view); Mockito.verify(nameField).setEnabled(false); Mockito.verify(descriptionField).setEnabled(false); Mockito.verify(productionLineField).setEnabled(false); Mockito.verify(orderField).setEnabled(true); Mockito.verify(technologyOperationComponentField).setEnabled(true); } @Test public void shouldEnabledFieldWhenTypeOtherCaseIsSelected() throws Exception { String typeTask = OperationalTaskTypeTask.OTHER_CASE.getStringValue(); given(typeTaskField.getFieldValue()).willReturn(typeTask); given(operationalTasksForOrdersService.isOperationalTaskTypeTaskOtherCase(typeTask)).willReturn(true); operationalTaskDetailsHooksOTFO.disableFieldsWhenOrderTypeIsSelected(view); Mockito.verify(nameField).setEnabled(true); Mockito.verify(descriptionField).setEnabled(true); Mockito.verify(productionLineField).setEnabled(true); Mockito.verify(orderField).setEnabled(false); Mockito.verify(technologyOperationComponentField).setEnabled(false); }
OrderHooksOTFO { public void changedProductionLineInOperationalTasksWhenChanged(final DataDefinition orderDD, final Entity order) { Long orderId = order.getId(); if (orderId == null) { return; } Entity orderFromDB = orderDD.get(orderId); Entity productionLine = order.getBelongsToField(OrderFields.PRODUCTION_LINE); Entity orderProductionLine = orderFromDB.getBelongsToField(OrderFields.PRODUCTION_LINE); if ((productionLine == null) || (orderProductionLine == null)) { return; } else { if (!orderProductionLine.getId().equals(productionLine.getId())) { changedProductionLineInOperationalTasks(orderFromDB, productionLine); } } } void changedProductionLineInOperationalTasksWhenChanged(final DataDefinition orderDD, final Entity order); }
@Test public void shouldReturnWhenEntityIdIsNull() throws Exception { Long orderId = null; given(order.getId()).willReturn(orderId); orderHooksOTFO.changedProductionLineInOperationalTasksWhenChanged(orderDD, order); } @Test public void shouldReturnWhenProductionLineIsTheSame() throws Exception { Long orderId = 1L; Long productionLineId = 1L; given(order.getId()).willReturn(orderId); given(orderDD.get(orderId)).willReturn(orderFromDB); given(order.getBelongsToField(OrderFields.PRODUCTION_LINE)).willReturn(productionLine); given(orderFromDB.getBelongsToField(OrderFields.PRODUCTION_LINE)).willReturn(productionLine); given(productionLine.getId()).willReturn(productionLineId); orderHooksOTFO.changedProductionLineInOperationalTasksWhenChanged(orderDD, order); Mockito.verify(operationalTask, Mockito.never()).setField(OrderFields.PRODUCTION_LINE, null); Mockito.verify(operationalTaskDD, Mockito.never()).save(operationalTask); } @Test public void shouldReturneWhenProductionLineIsNull() throws Exception { Long orderId = 1L; Long productionLineId = 1L; given(order.getId()).willReturn(orderId); given(orderDD.get(orderId)).willReturn(orderFromDB); given(order.getBelongsToField(OrderFields.PRODUCTION_LINE)).willReturn(productionLine); given(orderFromDB.getBelongsToField(OrderFields.PRODUCTION_LINE)).willReturn(null); given(productionLine.getId()).willReturn(productionLineId); orderHooksOTFO.changedProductionLineInOperationalTasksWhenChanged(orderDD, order); Mockito.verify(operationalTask, Mockito.never()).setField(OrderFields.PRODUCTION_LINE, productionLine); Mockito.verify(operationalTaskDD, Mockito.never()).save(operationalTask); } @Ignore @Test public void shouldChangeProductionLineWhenProductionLineWasChanged() throws Exception { Long orderId = 1L; Long productionLineId = 1L; Long orderProductionLineId = 2L; given(order.getId()).willReturn(orderId); given(orderDD.get(orderId)).willReturn(orderFromDB); given(order.getBelongsToField(OrderFields.PRODUCTION_LINE)).willReturn(productionLine); given(orderFromDB.getBelongsToField(OrderFields.PRODUCTION_LINE)).willReturn(orderProductionLine); given(productionLine.getId()).willReturn(productionLineId); given(orderProductionLine.getId()).willReturn(orderProductionLineId); EntityList operationalTasks = mockEntityList(Lists.newArrayList(operationalTask)); given(operationalTasksForOrdersService.getOperationalTasksForOrder(order)).willReturn(operationalTasks); orderHooksOTFO.changedProductionLineInOperationalTasksWhenChanged(orderDD, order); Mockito.verify(operationalTask).setField(OrderFields.PRODUCTION_LINE, productionLine); Mockito.verify(operationalTaskDD).save(operationalTask); }
ProductCatalogNumbersHooks { public boolean checkIfExistsCatalogNumberWithNumberAndCompany(final DataDefinition dataDefinition, final Entity entity) { SearchCriteriaBuilder criteria = dataDefinitionService .get(ProductCatalogNumbersConstants.PLUGIN_IDENTIFIER, ProductCatalogNumbersConstants.MODEL_PRODUCT_CATALOG_NUMBERS).find() .add(SearchRestrictions.eq(CATALOG_NUMBER, entity.getStringField(CATALOG_NUMBER))) .add(SearchRestrictions.belongsTo(COMPANY, entity.getBelongsToField(COMPANY))); if (entity.getId() != null) { criteria.add(SearchRestrictions.ne("id", entity.getId())); } List<Entity> catalogsNumbers = criteria.list().getEntities(); if (catalogsNumbers.isEmpty()) { return true; } else { entity.addGlobalError("productCatalogNumbers.productCatalogNumber.validationError.alreadyExistsCatalogNumerForCompany"); return false; } } boolean checkIfExistsCatalogNumberWithProductAndCompany(final DataDefinition dataDefinition, final Entity entity); boolean checkIfExistsCatalogNumberWithNumberAndCompany(final DataDefinition dataDefinition, final Entity entity); }
@Test public void shouldReturnTrueWhenEntityWithGivenNumberAndCompanyDoesnotExistsInDB() throws Exception { SearchCriterion criterion1 = SearchRestrictions.eq(CATALOG_NUMBER, entity.getStringField(CATALOG_NUMBER)); SearchCriterion criterion2 = SearchRestrictions.belongsTo(ProductCatalogNumberFields.COMPANY, company); given(entity.getId()).willReturn(null); given(criteria.add(criterion1)).willReturn(criteria); given(criteria.add(criterion2)).willReturn(criteria); given(criteria.list()).willReturn(searchResult); given(searchResult.getEntities()).willReturn(productCatalogNumbers); given(productCatalogNumbers.isEmpty()).willReturn(true); boolean result = productCatalogNumbersHooks.checkIfExistsCatalogNumberWithNumberAndCompany(dataDefinition, entity); Assert.assertTrue(result); } @Test public void shouldReturnFalseWhenEntityWithGivenNumberAndCompanyDoesExistsInDB() throws Exception { SearchCriterion criterion1 = SearchRestrictions.eq(CATALOG_NUMBER, entity.getStringField(CATALOG_NUMBER)); SearchCriterion criterion2 = SearchRestrictions.belongsTo(ProductCatalogNumberFields.COMPANY, company); given(entity.getId()).willReturn(null); given(criteria.add(criterion1)).willReturn(criteria); given(criteria.add(criterion2)).willReturn(criteria); given(criteria.list()).willReturn(searchResult); given(searchResult.getEntities()).willReturn(productCatalogNumbers); given(productCatalogNumbers.isEmpty()).willReturn(false); boolean result = productCatalogNumbersHooks.checkIfExistsCatalogNumberWithNumberAndCompany(dataDefinition, entity); Assert.assertFalse(result); Mockito.verify(entity).addGlobalError( "productCatalogNumbers.productCatalogNumber.validationError.alreadyExistsCatalogNumerForCompany"); }
OperationDurationDetailsInOrderDetailsHooksOTFO { public void disableCreateButton(final ViewDefinitionState view) { WindowComponent window = (WindowComponent) view.getComponentByReference(L_WINDOW); RibbonGroup operationalTasks = window.getRibbon().getGroupByName(L_OPERATIONAL_TASKS); RibbonActionItem createOperationalTasks = operationalTasks.getItemByName(L_CREATE_OPERATIONAL_TASKS); if (isGenerated(view) && orderHasTechnologyAndCorrectState(view)) { createOperationalTasks.setEnabled(true); } else { createOperationalTasks.setEnabled(false); } createOperationalTasks.requestUpdate(true); } void disableCreateButton(final ViewDefinitionState view); }
@Test public void shouldEnableButtonWhenIsGeneratedAndOrderStateIsAccepted() throws Exception { String generatedEndDate = "01-02-2012"; given(generatedEndDateField.getFieldValue()).willReturn(generatedEndDate); given(order.getStringField(OrderFields.STATE)).willReturn(OrderStateStringValues.ACCEPTED); given(order.getBelongsToField(OrderFields.TECHNOLOGY)).willReturn(technology); operationDurationDetailsInOrderDetailsHooksOTFO.disableCreateButton(view); Mockito.verify(createOperationalTasks).setEnabled(true); } @Test public void shouldDisableButtonWhenIsNotGeneratedAndOrderStateIsInProgress() throws Exception { String generatedEndDate = ""; given(generatedEndDateField.getFieldValue()).willReturn(generatedEndDate); given(order.getStringField(OrderFields.STATE)).willReturn(OrderStateStringValues.IN_PROGRESS); given(order.getBelongsToField(OrderFields.TECHNOLOGY)).willReturn(technology); operationDurationDetailsInOrderDetailsHooksOTFO.disableCreateButton(view); Mockito.verify(createOperationalTasks).setEnabled(false); } @Test public void shouldDisableButtonWhenIsNotGeneratedAndOrderStateIsIncorrect() throws Exception { String generatedEndDate = ""; given(generatedEndDateField.getFieldValue()).willReturn(generatedEndDate); given(order.getStringField(OrderFields.STATE)).willReturn(OrderStateStringValues.ABANDONED); given(order.getBelongsToField(OrderFields.TECHNOLOGY)).willReturn(technology); operationDurationDetailsInOrderDetailsHooksOTFO.disableCreateButton(view); Mockito.verify(createOperationalTasks).setEnabled(false); } @Test public void shouldDisableFieldWhenIsGeneratedAndOrderStateIsIncorrect() throws Exception { String generatedEndDate = "01-02-2012"; given(generatedEndDateField.getFieldValue()).willReturn(generatedEndDate); given(order.getStringField(OrderFields.STATE)).willReturn(OrderStateStringValues.DECLINED); given(order.getBelongsToField(OrderFields.TECHNOLOGY)).willReturn(technology); operationDurationDetailsInOrderDetailsHooksOTFO.disableCreateButton(view); Mockito.verify(createOperationalTasks).setEnabled(false); }
OperationalTaskValidatorsOTFO { public boolean validatesWith(final DataDefinition operationalTaskDD, final Entity operationalTask) { return checkIfOrderHasTechnology(operationalTaskDD, operationalTask); } boolean validatesWith(final DataDefinition operationalTaskDD, final Entity operationalTask); }
@Test public void shouldReturnTrueWhenOrderIsNotSave() throws Exception { given(operationalTask.getBelongsToField(OperationalTaskFieldsOTFO.ORDER)).willReturn(null); boolean result = operationalTaskValidatorsOTFO.validatesWith(operationalTaskDD, operationalTask); Assert.assertTrue(result); } @Test public void shouldReturnFalseWhenOrderDoesNotHaveTechnology() throws Exception { given(operationalTask.getBelongsToField(OperationalTaskFieldsOTFO.ORDER)).willReturn(order); given(order.getBelongsToField(OrderFields.TECHNOLOGY)).willReturn(null); boolean result = operationalTaskValidatorsOTFO.validatesWith(operationalTaskDD, operationalTask); Assert.assertFalse(result); Mockito.verify(operationalTask).addError(operationalTaskDD.getField(OperationalTaskFieldsOTFO.ORDER), "operationalTasks.operationalTask.order.error.technologyIsNull"); } @Test public void shouldReturnTrueWhenOrderHaveTechnology() throws Exception { when(operationalTask.getBelongsToField(OperationalTaskFieldsOTFO.ORDER)).thenReturn(order); when(order.getBelongsToField(OrderFields.TECHNOLOGY)).thenReturn(technology); boolean result = operationalTaskValidatorsOTFO.validatesWith(operationalTaskDD, operationalTask); Assert.assertTrue(result); }
LineChangeoverNormsForOrderDetailsListeners { public final void showPreviousOrder(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { LookupComponent previousOrderLookup = (LookupComponent) view.getComponentByReference(OrderFieldsLCNFO.PREVIOUS_ORDER); Long previousOrderId = (Long) previousOrderLookup.getFieldValue(); if (previousOrderId == null) { return; } Map<String, Object> parameters = Maps.newHashMap(); parameters.put("form.id", previousOrderId); String url = "../page/orders/orderDetails.html"; view.redirectTo(url, false, true, parameters); } final void showPreviousOrder(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showBestFittingLineChangeoverNorm(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showLineChangeoverNormForGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showLineChangeoverNormForTechnology(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void checkIfOrderHasCorrectStateAndIsPrevious(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void fillPreviousOrderForm(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void showOwnLineChangeoverDurationField(final ViewDefinitionState view, final ComponentState componentState, final String[] args); }
@Test public void shouldNotRedirectToPreviousOrderIfPreviousOrderIsNull() { stubLookup(previousOrderLookup, null); lineChangeoverNormsForOrderDetailsListeners.showPreviousOrder(view, null, null); verify(view, never()).redirectTo(anyString(), anyBoolean(), anyBoolean(), anyMap()); } @Test public void shouldRedirectToPreviousOrderIfPreviousOrderIsNotNull() { stubLookup(previousOrderLookup, entityWithId); lineChangeoverNormsForOrderDetailsListeners.showPreviousOrder(view, null, null); String url = "../page/orders/orderDetails.html"; verify(view).redirectTo(eq(url), anyBoolean(), anyBoolean(), parametersCaptor.capture()); Map<String, Object> usedParameters = parametersCaptor.getValue(); assertEquals(L_ID, usedParameters.get("form.id")); }
LineChangeoverNormsForOrderDetailsListeners { public final void showBestFittingLineChangeoverNorm(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { FieldComponent lineChangeoverNormField = (FieldComponent) view .getComponentByReference(OrderFieldsLCNFO.LINE_CHANGEOVER_NORM); Long lineChangeoverNormId = (Long) lineChangeoverNormField.getFieldValue(); if (lineChangeoverNormId == null) { return; } Map<String, Object> parameters = Maps.newHashMap(); parameters.put("form.id", lineChangeoverNormId); String url = "../page/lineChangeoverNorms/lineChangeoverNormsDetails.html"; view.redirectTo(url, false, true, parameters); } final void showPreviousOrder(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showBestFittingLineChangeoverNorm(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showLineChangeoverNormForGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showLineChangeoverNormForTechnology(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void checkIfOrderHasCorrectStateAndIsPrevious(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void fillPreviousOrderForm(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void showOwnLineChangeoverDurationField(final ViewDefinitionState view, final ComponentState componentState, final String[] args); }
@Test public void shouldNotRedirectToBestFittingLineChangeoverNormIfLineChangeoverIsNull() { stubLookup(lineChangeoverNormLookup, null); lineChangeoverNormsForOrderDetailsListeners.showBestFittingLineChangeoverNorm(view, null, null); verify(view, never()).redirectTo(anyString(), anyBoolean(), anyBoolean(), anyMap()); } @Test public void shouldRedirectToBestFittingLineChangeoverNormIfLineChangeoverNormIsNotNull() { stubLookup(lineChangeoverNormLookup, entityWithId); lineChangeoverNormsForOrderDetailsListeners.showBestFittingLineChangeoverNorm(view, null, null); String url = "../page/lineChangeoverNorms/lineChangeoverNormsDetails.html"; verify(view).redirectTo(eq(url), anyBoolean(), anyBoolean(), parametersCaptor.capture()); Map<String, Object> usedParameters = parametersCaptor.getValue(); assertEquals(L_ID, usedParameters.get("form.id")); }
LineChangeoverNormsForOrderDetailsListeners { public final void showLineChangeoverNormForGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { FieldComponent previousOrderTechnologyGroupNumberField = (FieldComponent) view .getComponentByReference("previousOrderTechnologyGroupNumber"); FieldComponent technologyGroupNumberField = (FieldComponent) view.getComponentByReference("technologyGroupNumber"); String previousOrderTechnologyGroupNumber = (String) previousOrderTechnologyGroupNumberField.getFieldValue(); String technologyGroupNumber = (String) technologyGroupNumberField.getFieldValue(); if (StringUtils.isEmpty(previousOrderTechnologyGroupNumber) || StringUtils.isEmpty(technologyGroupNumber)) { return; } Map<String, String> filters = Maps.newHashMap(); filters.put("fromTechnologyGroup", previousOrderTechnologyGroupNumber); filters.put("toTechnologyGroup", technologyGroupNumber); Map<String, Object> gridOptions = Maps.newHashMap(); gridOptions.put(L_FILTERS, filters); Map<String, Object> parameters = Maps.newHashMap(); parameters.put(L_GRID_OPTIONS, gridOptions); parameters.put(L_WINDOW_ACTIVE_MENU, "technology.lineChangeoverNorms"); String url = "../page/lineChangeoverNorms/lineChangeoverNormsList.html"; view.redirectTo(url, false, true, parameters); } final void showPreviousOrder(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showBestFittingLineChangeoverNorm(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showLineChangeoverNormForGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showLineChangeoverNormForTechnology(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void checkIfOrderHasCorrectStateAndIsPrevious(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void fillPreviousOrderForm(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void showOwnLineChangeoverDurationField(final ViewDefinitionState view, final ComponentState componentState, final String[] args); }
@Test public void shouldNotRedirectToLineChangeoverNormForGroupIfTechnologyGroupNumbersAreEmpty() { given(previousOrderTechnologyGroupNumberField.getFieldValue()).willReturn(null); given(technologyGroupNumberField.getFieldValue()).willReturn(null); lineChangeoverNormsForOrderDetailsListeners.showLineChangeoverNormForGroup(view, null, null); verify(view, never()).redirectTo(anyString(), anyBoolean(), anyBoolean(), anyMap()); } @Test public void shouldRedirectToLineChangeoverNormForGroupIfTechnologyGroupNumbersAreNotEmpty() { given(previousOrderTechnologyGroupNumberField.getFieldValue()).willReturn(L_TECHNOLOGY_GROUP_NUMBER); given(technologyGroupNumberField.getFieldValue()).willReturn(L_TECHNOLOGY_GROUP_NUMBER); lineChangeoverNormsForOrderDetailsListeners.showLineChangeoverNormForGroup(view, null, null); String url = "../page/lineChangeoverNorms/lineChangeoverNormsList.html"; verify(view).redirectTo(eq(url), anyBoolean(), anyBoolean(), parametersCaptor.capture()); Map<String, Object> usedParameters = parametersCaptor.getValue(); assertEquals(2, usedParameters.size()); assertEquals("technology.lineChangeoverNorms", usedParameters.get(L_WINDOW_ACTIVE_MENU)); Map<String, Object> gridOptions = (Map<String, Object>) usedParameters.get(L_GRID_OPTIONS); assertEquals(1, gridOptions.size()); Map<String, Object> filters = (Map<String, Object>) gridOptions.get(L_FILTERS); assertEquals(2, filters.size()); assertEquals(L_TECHNOLOGY_GROUP_NUMBER, filters.get("fromTechnologyGroup")); assertEquals(L_TECHNOLOGY_GROUP_NUMBER, filters.get("toTechnologyGroup")); }
LineChangeoverNormsForOrderDetailsListeners { public final void showLineChangeoverNormForTechnology(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { FieldComponent previousOrderTechnologyNumberField = (FieldComponent) view .getComponentByReference("previousOrderTechnologyNumber"); FieldComponent technologyNumberField = (FieldComponent) view.getComponentByReference("technologyNumber"); String previousOrderTechnologyNumber = (String) previousOrderTechnologyNumberField.getFieldValue(); String technologyNumber = (String) technologyNumberField.getFieldValue(); if (StringUtils.isEmpty(previousOrderTechnologyNumber) || StringUtils.isEmpty(technologyNumber)) { return; } Map<String, String> filters = Maps.newHashMap(); filters.put("fromTechnology", previousOrderTechnologyNumber); filters.put("toTechnology", technologyNumber); Map<String, Object> gridOptions = Maps.newHashMap(); gridOptions.put(L_FILTERS, filters); Map<String, Object> parameters = Maps.newHashMap(); parameters.put(L_GRID_OPTIONS, gridOptions); parameters.put(L_WINDOW_ACTIVE_MENU, "technology.lineChangeoverNorms"); String url = "../page/lineChangeoverNorms/lineChangeoverNormsList.html"; view.redirectTo(url, false, true, parameters); } final void showPreviousOrder(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showBestFittingLineChangeoverNorm(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showLineChangeoverNormForGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showLineChangeoverNormForTechnology(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void checkIfOrderHasCorrectStateAndIsPrevious(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void fillPreviousOrderForm(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void showOwnLineChangeoverDurationField(final ViewDefinitionState view, final ComponentState componentState, final String[] args); }
@Test public void shouldNotRedirectToLineChangeoverNormsForTechnologyIfTechnologyNumbersAreEmpty() { given(previousOrderTechnologyNumberField.getFieldValue()).willReturn(null); given(technologyNumberField.getFieldValue()).willReturn(null); lineChangeoverNormsForOrderDetailsListeners.showLineChangeoverNormForTechnology(view, null, null); verify(view, never()).redirectTo(anyString(), anyBoolean(), anyBoolean(), anyMap()); } @Test public void shouldRedirectToLineChangeoverNormsForTechnologyIfTechnologyNumbersAreNotEmpty() { given(previousOrderTechnologyNumberField.getFieldValue()).willReturn(L_TECHNOLOGY_NUMBER); given(technologyNumberField.getFieldValue()).willReturn(L_TECHNOLOGY_NUMBER); lineChangeoverNormsForOrderDetailsListeners.showLineChangeoverNormForTechnology(view, null, null); String url = "../page/lineChangeoverNorms/lineChangeoverNormsList.html"; verify(view).redirectTo(eq(url), anyBoolean(), anyBoolean(), parametersCaptor.capture()); Map<String, Object> usedParameters = parametersCaptor.getValue(); assertEquals(2, usedParameters.size()); assertEquals("technology.lineChangeoverNorms", usedParameters.get(L_WINDOW_ACTIVE_MENU)); Map<String, Object> gridOptions = (Map<String, Object>) usedParameters.get(L_GRID_OPTIONS); assertEquals(1, gridOptions.size()); Map<String, Object> filters = (Map<String, Object>) gridOptions.get(L_FILTERS); assertEquals(2, filters.size()); assertEquals(L_TECHNOLOGY_GROUP_NUMBER, filters.get("fromTechnology")); assertEquals(L_TECHNOLOGY_GROUP_NUMBER, filters.get("toTechnology")); }
LineChangeoverNormsForOrderDetailsListeners { public final void checkIfOrderHasCorrectStateAndIsPrevious(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { LookupComponent previousOrderLookup = (LookupComponent) view.getComponentByReference(OrderFieldsLCNFO.PREVIOUS_ORDER); LookupComponent orderLookup = (LookupComponent) view.getComponentByReference(OrderFieldsLCNFO.ORDER); Entity previousOrder = previousOrderLookup.getEntity(); Entity order = orderLookup.getEntity(); if (!lineChangeoverNormsForOrdersService.previousOrderEndsBeforeOrIsWithdrawed(previousOrder, order)) { previousOrderLookup.addMessage("orders.order.previousOrder.message.orderIsIncorrect", ComponentState.MessageType.FAILURE); } } final void showPreviousOrder(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showBestFittingLineChangeoverNorm(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showLineChangeoverNormForGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showLineChangeoverNormForTechnology(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void checkIfOrderHasCorrectStateAndIsPrevious(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void fillPreviousOrderForm(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void showOwnLineChangeoverDurationField(final ViewDefinitionState view, final ComponentState componentState, final String[] args); }
@Test public void shouldNotAddMessageWhenOrdersAreNotSpecified() { stubLookup(previousOrderLookup, null); stubLookup(orderLookup, null); given(lineChangeoverNormsForOrdersService.previousOrderEndsBeforeOrIsWithdrawed(null, null)).willReturn(true); lineChangeoverNormsForOrderDetailsListeners.checkIfOrderHasCorrectStateAndIsPrevious(view, null, null); verify(previousOrderLookup, never()).addMessage(anyString(), eq(ComponentState.MessageType.FAILURE)); } @Test public void shouldNotAddMessageWhenPreviousOrderIsCorrect() { stubLookup(previousOrderLookup, entityWithId); stubLookup(orderLookup, entityWithId); given(lineChangeoverNormsForOrdersService.previousOrderEndsBeforeOrIsWithdrawed(entityWithId, entityWithId)).willReturn( true); lineChangeoverNormsForOrderDetailsListeners.checkIfOrderHasCorrectStateAndIsPrevious(view, null, null); verify(previousOrderLookup, never()).addMessage(anyString(), eq(ComponentState.MessageType.FAILURE)); } @Test public void shouldAddMessageWhenPreviousOrderIsIncorrect() { stubLookup(previousOrderLookup, entityWithId); stubLookup(orderLookup, entityWithId); given(lineChangeoverNormsForOrdersService.previousOrderEndsBeforeOrIsWithdrawed(entityWithId, entityWithId)).willReturn( false); lineChangeoverNormsForOrderDetailsListeners.checkIfOrderHasCorrectStateAndIsPrevious(view, null, null); verify(previousOrderLookup).addMessage(anyString(), eq(ComponentState.MessageType.FAILURE)); }
ProductCatalogNumbersHooks { public boolean checkIfExistsCatalogNumberWithProductAndCompany(final DataDefinition dataDefinition, final Entity entity) { SearchCriteriaBuilder criteria = dataDefinitionService .get(ProductCatalogNumbersConstants.PLUGIN_IDENTIFIER, ProductCatalogNumbersConstants.MODEL_PRODUCT_CATALOG_NUMBERS).find() .add(SearchRestrictions.belongsTo(PRODUCT, entity.getBelongsToField(PRODUCT))) .add(SearchRestrictions.belongsTo(COMPANY, entity.getBelongsToField(COMPANY))); if (entity.getId() != null) { criteria.add(SearchRestrictions.ne("id", entity.getId())); } List<Entity> catalogsNumbers = criteria.list().getEntities(); if (catalogsNumbers.isEmpty()) { return true; } else { entity.addGlobalError("productCatalogNumbers.productCatalogNumber.validationError.alreadyExistsProductForCompany"); return false; } } boolean checkIfExistsCatalogNumberWithProductAndCompany(final DataDefinition dataDefinition, final Entity entity); boolean checkIfExistsCatalogNumberWithNumberAndCompany(final DataDefinition dataDefinition, final Entity entity); }
@Test public void shouldReturnTrueWhenEntityWithGivenProductAndCompanyDoesnotExistsInDB() throws Exception { SearchCriterion criterion1 = SearchRestrictions.eq(CATALOG_NUMBER, entity.getStringField(CATALOG_NUMBER)); SearchCriterion criterion2 = SearchRestrictions.belongsTo(PRODUCT, entity.getBelongsToField(PRODUCT)); given(entity.getId()).willReturn(null); given(criteria.add(criterion1)).willReturn(criteria); given(criteria.add(criterion2)).willReturn(criteria); given(criteria.list()).willReturn(searchResult); given(searchResult.getEntities()).willReturn(productCatalogNumbers); given(productCatalogNumbers.isEmpty()).willReturn(true); boolean result = productCatalogNumbersHooks.checkIfExistsCatalogNumberWithProductAndCompany(dataDefinition, entity); Assert.assertTrue(result); } @Test public void shouldReturnFalseWhenEntityWithGivenProductAndCompanyDoesExistsInDB() throws Exception { SearchCriterion criterion1 = SearchRestrictions.eq(CATALOG_NUMBER, entity.getStringField(CATALOG_NUMBER)); SearchCriterion criterion2 = SearchRestrictions.belongsTo(PRODUCT, entity.getBelongsToField(PRODUCT)); given(entity.getId()).willReturn(null); given(criteria.add(criterion1)).willReturn(criteria); given(criteria.add(criterion2)).willReturn(criteria); given(criteria.list()).willReturn(searchResult); given(searchResult.getEntities()).willReturn(productCatalogNumbers); given(productCatalogNumbers.isEmpty()).willReturn(false); boolean result = productCatalogNumbersHooks.checkIfExistsCatalogNumberWithProductAndCompany(dataDefinition, entity); Assert.assertFalse(result); Mockito.verify(entity).addGlobalError( "productCatalogNumbers.productCatalogNumber.validationError.alreadyExistsProductForCompany"); }
LineChangeoverNormsForOrderDetailsListeners { public final void fillPreviousOrderForm(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { lineChangeoverNormsForOrdersService.fillOrderForm(view, LineChangeoverNormsForOrdersConstants.PREVIOUS_ORDER_FIELDS); } final void showPreviousOrder(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showBestFittingLineChangeoverNorm(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showLineChangeoverNormForGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showLineChangeoverNormForTechnology(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void checkIfOrderHasCorrectStateAndIsPrevious(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void fillPreviousOrderForm(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void showOwnLineChangeoverDurationField(final ViewDefinitionState view, final ComponentState componentState, final String[] args); }
@Test public final void shouldFillPreviousOrderForm() { lineChangeoverNormsForOrderDetailsListeners.fillPreviousOrderForm(view, null, null); verify(lineChangeoverNormsForOrdersService).fillOrderForm(view, PREVIOUS_ORDER_FIELDS); }
LineChangeoverNormsForOrderDetailsListeners { public void showOwnLineChangeoverDurationField(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { orderService.changeFieldState(view, OrderFieldsLCNFO.OWN_LINE_CHANGEOVER, OrderFieldsLCNFO.OWN_LINE_CHANGEOVER_DURATION); } final void showPreviousOrder(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showBestFittingLineChangeoverNorm(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showLineChangeoverNormForGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showLineChangeoverNormForTechnology(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void checkIfOrderHasCorrectStateAndIsPrevious(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void fillPreviousOrderForm(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void showOwnLineChangeoverDurationField(final ViewDefinitionState view, final ComponentState componentState, final String[] args); }
@Test public void shouldShowOwnLineChangeoverDurationField() { lineChangeoverNormsForOrderDetailsListeners.showOwnLineChangeoverDurationField(view, null, null); verify(orderService).changeFieldState(view, OWN_LINE_CHANGEOVER, OWN_LINE_CHANGEOVER_DURATION); }
OrderDetailsListenersLCNFO { public final void showChangeover(final ViewDefinitionState viewState, final ComponentState componentState, final String[] args) { Long orderId = (Long) componentState.getFieldValue(); if (orderId == null) { return; } Map<String, Object> parameters = Maps.newHashMap(); parameters.put("form.id", orderId); String url = "/page/lineChangeoverNormsForOrders/lineChangeoverNormsForOrderDetails.html"; viewState.redirectTo(url, false, true, parameters); } final void showChangeover(final ViewDefinitionState viewState, final ComponentState componentState, final String[] args); }
@Test public void shouldntShowChangeoverIfOrderIdIsNull() { given(componentState.getFieldValue()).willReturn(null); String url = "/page/lineChangeoverNormsForOrders/lineChangeoverNormsForOrderDetails.html"; orderDetailsListenersLCNFO.showChangeover(view, componentState, null); verify(view, never()).redirectTo(url, false, true, parameters); } @Test public void shouldShowChangeoverIfOrderIdIsntNull() { given(componentState.getFieldValue()).willReturn(L_ID); parameters.put("form.id", L_ID); String url = "/page/lineChangeoverNormsForOrders/lineChangeoverNormsForOrderDetails.html"; orderDetailsListenersLCNFO.showChangeover(view, componentState, null); verify(view).redirectTo(url, false, true, parameters); }
OrderModelValidatorsLCNFO { public final boolean checkIfOrderHasCorrectStateAndIsPrevious(final DataDefinition orderDD, final Entity order) { Entity previousOrderDB = order.getBelongsToField(OrderFieldsLCNFO.PREVIOUS_ORDER); Entity orderDB = order.getBelongsToField(OrderFieldsLCNFO.ORDER); if (!lineChangeoverNormsForOrdersService.previousOrderEndsBeforeOrIsWithdrawed(previousOrderDB, orderDB)) { order.addError(orderDD.getField(OrderFieldsLCNFO.PREVIOUS_ORDER), "orders.order.previousOrder.message.orderIsIncorrect"); return false; } return true; } final boolean checkIfOrderHasCorrectStateAndIsPrevious(final DataDefinition orderDD, final Entity order); }
@Test public void shouldReturnFalseWhenPreviousOrderIsNotCorrect() { given(lineChangeoverNormsForOrdersService.previousOrderEndsBeforeOrIsWithdrawed(previousOrderDB, orderDB)).willReturn( false); boolean result = orderModelValidatorsLCNFO.checkIfOrderHasCorrectStateAndIsPrevious(orderDD, order); assertFalse(result); verify(order).addError(Mockito.eq(orderDD.getField(PREVIOUS_ORDER)), Mockito.anyString()); } @Test public void shouldReturnTrueWhenPreviousOrderIsCorrect() { given(lineChangeoverNormsForOrdersService.previousOrderEndsBeforeOrIsWithdrawed(previousOrderDB, orderDB)).willReturn( true); boolean result = orderModelValidatorsLCNFO.checkIfOrderHasCorrectStateAndIsPrevious(orderDD, order); assertTrue(result); verify(order, never()).addError(Mockito.eq(orderDD.getField(PREVIOUS_ORDER)), Mockito.anyString()); }
LineChangeoverNormsForOrderDetailsViewHooks { public final void fillOrderForms(final ViewDefinitionState view) { FormComponent orderForm = (FormComponent) view.getComponentByReference(L_FORM); LookupComponent orderLookup = (LookupComponent) view.getComponentByReference(OrderFieldsLCNFO.ORDER); LookupComponent previousOrderLookup = (LookupComponent) view.getComponentByReference(OrderFieldsLCNFO.PREVIOUS_ORDER); if (orderForm.getEntityId() == null) { return; } Entity order = orderForm.getPersistedEntityWithIncludedFormValues(); orderLookup.setFieldValue(order.getId()); orderLookup.requestComponentUpdateState(); lineChangeoverNormsForOrdersService.fillOrderForm(view, LineChangeoverNormsForOrdersConstants.ORDER_FIELDS); if (previousOrderLookup.isEmpty()) { Entity previousOrder = lineChangeoverNormsForOrdersService.getPreviousOrderFromDB(order); if (previousOrder != null) { previousOrderLookup.setFieldValue(previousOrder.getId()); previousOrderLookup.requestComponentUpdateState(); lineChangeoverNormsForOrdersService.fillOrderForm(view, LineChangeoverNormsForOrdersConstants.PREVIOUS_ORDER_FIELDS); } } } final void fillOrderForms(final ViewDefinitionState view); void fillLineChangeoverNorm(final ViewDefinitionState view); void updateRibbonState(final ViewDefinitionState view); void showOwnLineChangeoverDurationField(final ViewDefinitionState view); }
@Test public void shouldNotFillOrderFormsIfOrderFormEntityIdIsNull() { given(view.getComponentByReference(L_FORM)).willReturn(orderForm); given(view.getComponentByReference(PREVIOUS_ORDER)).willReturn(previousOrderLookup); given(view.getComponentByReference(ORDER)).willReturn(orderLookup); stubOrderForm(null); lineChangeoverNormsForOrderDetailsViewHooks.fillOrderForms(view); verify(orderLookup, never()).setFieldValue(Mockito.any()); verify(previousOrderLookup, never()).setFieldValue(Mockito.any()); verify(lineChangeoverNormsForOrdersService, never()).fillOrderForm(view, ORDER_FIELDS); verify(lineChangeoverNormsForOrdersService, never()).fillOrderForm(view, PREVIOUS_ORDER_FIELDS); } @Test public void shouldNotFillOrderFormsIfOrderFormEntityIdIsNotNullAndOrderIsNull() { given(view.getComponentByReference(L_FORM)).willReturn(orderForm); given(view.getComponentByReference(PREVIOUS_ORDER)).willReturn(previousOrderLookup); given(view.getComponentByReference(ORDER)).willReturn(orderLookup); stubOrderForm(null); lineChangeoverNormsForOrderDetailsViewHooks.fillOrderForms(view); verify(orderLookup, never()).setFieldValue(Mockito.any()); verify(previousOrderLookup, never()).setFieldValue(Mockito.any()); verify(lineChangeoverNormsForOrdersService, never()).fillOrderForm(view, ORDER_FIELDS); verify(lineChangeoverNormsForOrdersService, never()).fillOrderForm(view, PREVIOUS_ORDER_FIELDS); } @Test public void shouldFillOrderFormsIfOrderFormEntityIdIsntNullAndOrderIsNotNullAndPreviousOrderIdIsNotNull() { given(view.getComponentByReference(L_FORM)).willReturn(orderForm); given(view.getComponentByReference(PREVIOUS_ORDER)).willReturn(previousOrderLookup); given(view.getComponentByReference(ORDER)).willReturn(orderLookup); stubOrderForm(order); given(previousOrderLookup.isEmpty()).willReturn(false); lineChangeoverNormsForOrderDetailsViewHooks.fillOrderForms(view); verify(orderLookup).setFieldValue(Mockito.any()); verify(previousOrderLookup, never()).setFieldValue(Mockito.any()); verify(lineChangeoverNormsForOrdersService).fillOrderForm(view, ORDER_FIELDS); verify(lineChangeoverNormsForOrdersService, never()).fillOrderForm(view, PREVIOUS_ORDER_FIELDS); } @Test public void shouldFillOrderFormsIfOrderFormEntityIdIsntNullAndOrderIsNotNullAndPreviousOrderIsNull() { given(view.getComponentByReference(L_FORM)).willReturn(orderForm); given(view.getComponentByReference(PREVIOUS_ORDER)).willReturn(previousOrderLookup); given(view.getComponentByReference(ORDER)).willReturn(orderLookup); stubOrderForm(order); given(previousOrderLookup.isEmpty()).willReturn(true); given(lineChangeoverNormsForOrdersService.getPreviousOrderFromDB(order)).willReturn(null); lineChangeoverNormsForOrderDetailsViewHooks.fillOrderForms(view); verify(orderLookup).setFieldValue(Mockito.any()); verify(previousOrderLookup, never()).setFieldValue(Mockito.any()); verify(lineChangeoverNormsForOrdersService).fillOrderForm(view, ORDER_FIELDS); verify(lineChangeoverNormsForOrdersService, never()).fillOrderForm(view, PREVIOUS_ORDER_FIELDS); } @Test public void shouldFillOrderFormsIfOrderFormEntityIdIsNotNullAndOrderIsNotNullAndPreviousOrderIsNotNull() { given(view.getComponentByReference(L_FORM)).willReturn(orderForm); given(view.getComponentByReference(PREVIOUS_ORDER)).willReturn(previousOrderLookup); given(view.getComponentByReference(ORDER)).willReturn(orderLookup); stubOrderForm(order); given(previousOrderLookup.isEmpty()).willReturn(true); given(lineChangeoverNormsForOrdersService.getPreviousOrderFromDB(order)).willReturn(previousOrder); lineChangeoverNormsForOrderDetailsViewHooks.fillOrderForms(view); verify(orderLookup).setFieldValue(Mockito.any()); verify(previousOrderLookup).setFieldValue(Mockito.any()); verify(lineChangeoverNormsForOrdersService).fillOrderForm(view, ORDER_FIELDS); verify(lineChangeoverNormsForOrdersService).fillOrderForm(view, PREVIOUS_ORDER_FIELDS); }
LineChangeoverNormsForOrderDetailsViewHooks { public void fillLineChangeoverNorm(final ViewDefinitionState view) { Entity lineChangeoverNorm = findChangeoverNorm(view); fillChangeoverNormFields(view, lineChangeoverNorm); } final void fillOrderForms(final ViewDefinitionState view); void fillLineChangeoverNorm(final ViewDefinitionState view); void updateRibbonState(final ViewDefinitionState view); void showOwnLineChangeoverDurationField(final ViewDefinitionState view); }
@Test public void shouldntFillLineChangeoverNormIfOrderLookupsAreEmpty() { given(view.getComponentByReference(PREVIOUS_ORDER)).willReturn(previousOrderLookup); given(view.getComponentByReference(ORDER)).willReturn(orderLookup); given(view.getComponentByReference("lineChangeoverNorm")).willReturn(lineChangeoverNormLookup); given(view.getComponentByReference("lineChangeoverNormDuration")).willReturn(lineChangeoverNormDurationField); given(previousOrderLookup.getEntity()).willReturn(null); given(orderLookup.getEntity()).willReturn(null); lineChangeoverNormsForOrderDetailsViewHooks.fillLineChangeoverNorm(view); verify(lineChangeoverNormLookup).setFieldValue(null); verify(lineChangeoverNormLookup, never()).setFieldValue(Mockito.notNull()); verify(lineChangeoverNormDurationField).setFieldValue(null); verify(lineChangeoverNormDurationField, never()).setFieldValue(Mockito.notNull()); } @Test public void shouldntFillLineChangeoverNormIfOrderFieldsAreNullAndOrdersArentNullAndTechnologiesAreNull() { given(view.getComponentByReference(PREVIOUS_ORDER)).willReturn(previousOrderLookup); given(view.getComponentByReference(ORDER)).willReturn(orderLookup); given(view.getComponentByReference("lineChangeoverNorm")).willReturn(lineChangeoverNormLookup); given(view.getComponentByReference("lineChangeoverNormDuration")).willReturn(lineChangeoverNormDurationField); given(previousOrderLookup.getEntity()).willReturn(previousOrder); given(orderLookup.getEntity()).willReturn(order); stubBelongsToField(previousOrder, OrderFields.TECHNOLOGY_PROTOTYPE, null); stubBelongsToField(order, OrderFields.TECHNOLOGY_PROTOTYPE, null); lineChangeoverNormsForOrderDetailsViewHooks.fillLineChangeoverNorm(view); verify(lineChangeoverNormLookup).setFieldValue(null); verify(lineChangeoverNormLookup, never()).setFieldValue(Mockito.notNull()); verify(lineChangeoverNormDurationField).setFieldValue(null); verify(lineChangeoverNormDurationField, never()).setFieldValue(Mockito.notNull()); } @Test public void shouldntFillLineChangeoverNormIfOrderFieldsAreNullAndOrdersAreNotNullAndTechnologiesAreNotNullAndLineChangeoverNormIsNull() { given(view.getComponentByReference(PREVIOUS_ORDER)).willReturn(previousOrderLookup); given(view.getComponentByReference(ORDER)).willReturn(orderLookup); given(view.getComponentByReference("lineChangeoverNorm")).willReturn(lineChangeoverNormLookup); given(view.getComponentByReference("lineChangeoverNormDuration")).willReturn(lineChangeoverNormDurationField); given(previousOrderLookup.getEntity()).willReturn(previousOrder); given(orderLookup.getEntity()).willReturn(order); stubBelongsToField(previousOrder, OrderFields.TECHNOLOGY_PROTOTYPE, fromTechnology); stubBelongsToField(order, OrderFields.TECHNOLOGY_PROTOTYPE, toTechnology); stubBelongsToField(order, OrderFields.PRODUCTION_LINE, productionLine); given(changeoverNormsService.getMatchingChangeoverNorms(fromTechnology, toTechnology, productionLine)).willReturn(null); lineChangeoverNormsForOrderDetailsViewHooks.fillLineChangeoverNorm(view); verify(lineChangeoverNormLookup).setFieldValue(null); verify(lineChangeoverNormDurationField).setFieldValue(null); } @Test public void shouldFillLineChangeoverNormIfOrderFieldsAreNullAndOrdersAreNotNullAndTechnologiesAreNotNullAndLineChangeoverNormIsntNull() { given(view.getComponentByReference(PREVIOUS_ORDER)).willReturn(previousOrderLookup); given(view.getComponentByReference(ORDER)).willReturn(orderLookup); given(view.getComponentByReference("lineChangeoverNorm")).willReturn(lineChangeoverNormLookup); given(view.getComponentByReference("lineChangeoverNormDuration")).willReturn(lineChangeoverNormDurationField); given(previousOrderLookup.getEntity()).willReturn(previousOrder); given(orderLookup.getEntity()).willReturn(order); stubBelongsToField(previousOrder, OrderFields.TECHNOLOGY_PROTOTYPE, fromTechnology); stubBelongsToField(order, OrderFields.TECHNOLOGY_PROTOTYPE, toTechnology); stubBelongsToField(order, OrderFields.PRODUCTION_LINE, productionLine); given(changeoverNormsService.getMatchingChangeoverNorms(fromTechnology, toTechnology, productionLine)).willReturn( lineChangeoverNorm); lineChangeoverNormsForOrderDetailsViewHooks.fillLineChangeoverNorm(view); verify(lineChangeoverNormLookup).setFieldValue(Mockito.any()); verify(lineChangeoverNormDurationField).setFieldValue(Mockito.any()); }
LineChangeoverNormsForOrderDetailsViewHooks { public void updateRibbonState(final ViewDefinitionState view) { FieldComponent productionLineField = (FieldComponent) view.getComponentByReference(OrderFields.PRODUCTION_LINE); LookupComponent previousOrderLookup = (LookupComponent) view.getComponentByReference(OrderFieldsLCNFO.PREVIOUS_ORDER); LookupComponent lineChangeoverNormLookup = (LookupComponent) view.getComponentByReference(OrderFieldsLCNFO.LINE_CHANGEOVER_NORM); FieldComponent previousOrderTechnologyGroupNumberField = (FieldComponent) view .getComponentByReference("previousOrderTechnologyGroupNumber"); FieldComponent technologyGroupNumberField = (FieldComponent) view.getComponentByReference("technologyGroupNumber"); FieldComponent previousOrderTechnologyNumberField = (FieldComponent) view .getComponentByReference("previousOrderTechnologyNumber"); FieldComponent technologyNumberField = (FieldComponent) view.getComponentByReference("technologyNumber"); WindowComponent window = (WindowComponent) view.getComponentByReference("window"); RibbonGroup orders = window.getRibbon().getGroupByName("orders"); RibbonGroup lineChangeoverNorms = window.getRibbon().getGroupByName("lineChangeoverNorms"); RibbonActionItem showPreviousOrder = orders.getItemByName("showPreviousOrder"); RibbonActionItem showBestFittingLineChangeoverNorm = lineChangeoverNorms .getItemByName("showBestFittingLineChangeoverNorm"); RibbonActionItem showChangeoverNormForGroup = lineChangeoverNorms.getItemByName("showLineChangeoverNormForGroup"); RibbonActionItem showChangeoverNormForTechnology = lineChangeoverNorms .getItemByName("showLineChangeoverNormForTechnology"); Entity productionLine = lineChangeoverNormsForOrdersService.getProductionLineFromDB((Long) productionLineField .getFieldValue()); boolean hasDefinedPreviousOrder = !previousOrderLookup.isEmpty(); updateButtonState(showPreviousOrder, hasDefinedPreviousOrder); boolean hasMatchingChangeoverNorm = !lineChangeoverNormLookup.isEmpty(); updateButtonState(showBestFittingLineChangeoverNorm, hasMatchingChangeoverNorm); if (StringUtils.isEmpty((String) previousOrderTechnologyGroupNumberField.getFieldValue()) || StringUtils.isEmpty((String) technologyGroupNumberField.getFieldValue())) { updateButtonState(showChangeoverNormForGroup, false); } else { Entity fromTechnologyGroup = lineChangeoverNormsForOrdersService .getTechnologyGroupByNumberFromDB((String) previousOrderTechnologyGroupNumberField.getFieldValue()); Entity toTechnologyGroup = lineChangeoverNormsForOrdersService .getTechnologyGroupByNumberFromDB((String) technologyGroupNumberField.getFieldValue()); if ((changeoverNormsSearchService.searchMatchingChangeroverNormsForTechnologyGroupWithLine(fromTechnologyGroup, toTechnologyGroup, productionLine) == null) && (changeoverNormsSearchService.searchMatchingChangeroverNormsForTechnologyGroupWithLine( fromTechnologyGroup, toTechnologyGroup, null) == null)) { updateButtonState(showChangeoverNormForGroup, false); } else { updateButtonState(showChangeoverNormForGroup, true); } } if (StringUtils.isEmpty((String) previousOrderTechnologyNumberField.getFieldValue()) || StringUtils.isEmpty((String) technologyNumberField.getFieldValue())) { updateButtonState(showChangeoverNormForTechnology, false); } else { Entity fromTechnology = lineChangeoverNormsForOrdersService .getTechnologyByNumberFromDB((String) previousOrderTechnologyNumberField.getFieldValue()); Entity toTechnology = lineChangeoverNormsForOrdersService.getTechnologyByNumberFromDB((String) technologyNumberField .getFieldValue()); if ((changeoverNormsSearchService.searchMatchingChangeroverNormsForTechnologyWithLine(fromTechnology, toTechnology, productionLine) == null) && (changeoverNormsSearchService.searchMatchingChangeroverNormsForTechnologyWithLine(fromTechnology, toTechnology, null) == null)) { updateButtonState(showChangeoverNormForTechnology, false); } else { updateButtonState(showChangeoverNormForTechnology, true); } } } final void fillOrderForms(final ViewDefinitionState view); void fillLineChangeoverNorm(final ViewDefinitionState view); void updateRibbonState(final ViewDefinitionState view); void showOwnLineChangeoverDurationField(final ViewDefinitionState view); }
@Test public void shouldNotUpdateRibbonState() { given(view.getComponentByReference(PRODUCTION_LINE)).willReturn(productionLineField); given(view.getComponentByReference(PREVIOUS_ORDER)).willReturn(previousOrderLookup); given(view.getComponentByReference(LINE_CHANGEOVER_NORM)).willReturn(lineChangeoverNormLookup); given(view.getComponentByReference("previousOrderTechnologyGroupNumber")).willReturn( previousOrderTechnologyGroupNumberField); given(view.getComponentByReference("technologyGroupNumber")).willReturn(technologyGroupNumberField); given(view.getComponentByReference("previousOrderTechnologyNumber")).willReturn(previousOrderTechnologyNumberField); given(view.getComponentByReference("technologyNumber")).willReturn(technologyNumberField); given(view.getComponentByReference("window")).willReturn(window); given(window.getRibbon()).willReturn(ribbon); given(ribbon.getGroupByName("orders")).willReturn(orders); given(ribbon.getGroupByName("lineChangeoverNorms")).willReturn(lineChangeoverNorms); given(orders.getItemByName("showPreviousOrder")).willReturn(showPreviousOrder); given(lineChangeoverNorms.getItemByName("showBestFittingLineChangeoverNorm")).willReturn( showBestFittingLineChangeoverNorm); given(lineChangeoverNorms.getItemByName("showLineChangeoverNormForGroup")).willReturn(showLineChangeoverNormForGroup); given(lineChangeoverNorms.getItemByName("showLineChangeoverNormForTechnology")).willReturn( showLineChangeoverNormForTechnology); given(productionLineField.getFieldValue()).willReturn(L_ID); given(lineChangeoverNormsForOrdersService.getProductionLineFromDB(L_ID)).willReturn(productionLine); given(previousOrderLookup.isEmpty()).willReturn(true); given(lineChangeoverNormLookup.isEmpty()).willReturn(true); given(previousOrderTechnologyGroupNumberField.getFieldValue()).willReturn(null); given(technologyGroupNumberField.getFieldValue()).willReturn(null); given(previousOrderTechnologyNumberField.getFieldValue()).willReturn(null); given(technologyNumberField.getFieldValue()).willReturn(null); lineChangeoverNormsForOrderDetailsViewHooks.updateRibbonState(view); verify(showPreviousOrder).setEnabled(false); verify(showBestFittingLineChangeoverNorm).setEnabled(false); verify(showLineChangeoverNormForGroup).setEnabled(false); verify(showLineChangeoverNormForTechnology).setEnabled(false); } @Test public void shouldNotUpdateRibbonStateIfSearchLineChangeoverNormIsNull() { given(view.getComponentByReference(PRODUCTION_LINE)).willReturn(productionLineField); given(view.getComponentByReference(PREVIOUS_ORDER)).willReturn(previousOrderLookup); given(view.getComponentByReference(LINE_CHANGEOVER_NORM)).willReturn(lineChangeoverNormLookup); given(view.getComponentByReference("previousOrderTechnologyGroupNumber")).willReturn( previousOrderTechnologyGroupNumberField); given(view.getComponentByReference("technologyGroupNumber")).willReturn(technologyGroupNumberField); given(view.getComponentByReference("previousOrderTechnologyNumber")).willReturn(previousOrderTechnologyNumberField); given(view.getComponentByReference("technologyNumber")).willReturn(technologyNumberField); given(view.getComponentByReference("window")).willReturn((ComponentState) window); given(window.getRibbon()).willReturn(ribbon); given(ribbon.getGroupByName("orders")).willReturn(orders); given(ribbon.getGroupByName("lineChangeoverNorms")).willReturn(lineChangeoverNorms); given(orders.getItemByName("showPreviousOrder")).willReturn(showPreviousOrder); given(lineChangeoverNorms.getItemByName("showBestFittingLineChangeoverNorm")).willReturn( showBestFittingLineChangeoverNorm); given(lineChangeoverNorms.getItemByName("showLineChangeoverNormForGroup")).willReturn(showLineChangeoverNormForGroup); given(lineChangeoverNorms.getItemByName("showLineChangeoverNormForTechnology")).willReturn( showLineChangeoverNormForTechnology); given(productionLineField.getFieldValue()).willReturn(L_ID); given(lineChangeoverNormsForOrdersService.getProductionLineFromDB(L_ID)).willReturn(null); given(previousOrderLookup.isEmpty()).willReturn(true); given(lineChangeoverNormLookup.isEmpty()).willReturn(true); given(previousOrderTechnologyGroupNumberField.getFieldValue()).willReturn(L_PREVIOUS_ORDER_TECHNOLOGY_GROUP_NUMBER); given(technologyGroupNumberField.getFieldValue()).willReturn(L_TECHNOLOGY_GROUP_NUMBER); given(previousOrderTechnologyNumberField.getFieldValue()).willReturn(L_PREVIOUS_ORDER_TECHNOLOGY_NUMBER); given(technologyNumberField.getFieldValue()).willReturn(L_TECHNOLOGY_NUMBER); given(lineChangeoverNormsForOrdersService.getTechnologyGroupByNumberFromDB(L_PREVIOUS_ORDER_TECHNOLOGY_GROUP_NUMBER)) .willReturn(null); given(lineChangeoverNormsForOrdersService.getTechnologyGroupByNumberFromDB(L_TECHNOLOGY_GROUP_NUMBER)).willReturn(null); given(lineChangeoverNormsForOrdersService.getTechnologyByNumberFromDB(L_PREVIOUS_ORDER_TECHNOLOGY_NUMBER)).willReturn( null); given(lineChangeoverNormsForOrdersService.getTechnologyByNumberFromDB(L_TECHNOLOGY_NUMBER)).willReturn(null); given(productionLine.getId()).willReturn(L_ID); given(changeoverNormsSearchService.searchMatchingChangeroverNormsForTechnologyGroupWithLine(null, null, null)) .willReturn(null); given(changeoverNormsSearchService.searchMatchingChangeroverNormsForTechnologyWithLine(null, null, null)) .willReturn(null); lineChangeoverNormsForOrderDetailsViewHooks.updateRibbonState(view); verify(showPreviousOrder).setEnabled(false); verify(showBestFittingLineChangeoverNorm).setEnabled(false); verify(showLineChangeoverNormForGroup).setEnabled(false); verify(showLineChangeoverNormForTechnology).setEnabled(false); } @Test public void shouldUpdateRibbonState() { given(view.getComponentByReference(PRODUCTION_LINE)).willReturn(productionLineField); given(view.getComponentByReference(PREVIOUS_ORDER)).willReturn(previousOrderLookup); given(view.getComponentByReference(LINE_CHANGEOVER_NORM)).willReturn(lineChangeoverNormLookup); given(view.getComponentByReference("previousOrderTechnologyGroupNumber")).willReturn( previousOrderTechnologyGroupNumberField); given(view.getComponentByReference("technologyGroupNumber")).willReturn(technologyGroupNumberField); given(view.getComponentByReference("previousOrderTechnologyNumber")).willReturn(previousOrderTechnologyNumberField); given(view.getComponentByReference("technologyNumber")).willReturn(technologyNumberField); given(view.getComponentByReference("window")).willReturn(window); given(window.getRibbon()).willReturn(ribbon); given(ribbon.getGroupByName("orders")).willReturn(orders); given(ribbon.getGroupByName("lineChangeoverNorms")).willReturn(lineChangeoverNorms); given(orders.getItemByName("showPreviousOrder")).willReturn(showPreviousOrder); given(lineChangeoverNorms.getItemByName("showBestFittingLineChangeoverNorm")).willReturn( showBestFittingLineChangeoverNorm); given(lineChangeoverNorms.getItemByName("showLineChangeoverNormForGroup")).willReturn(showLineChangeoverNormForGroup); given(lineChangeoverNorms.getItemByName("showLineChangeoverNormForTechnology")).willReturn( showLineChangeoverNormForTechnology); given(productionLineField.getFieldValue()).willReturn(L_ID); given(lineChangeoverNormsForOrdersService.getProductionLineFromDB(L_ID)).willReturn(productionLine); given(previousOrderLookup.isEmpty()).willReturn(false); given(lineChangeoverNormLookup.isEmpty()).willReturn(false); given(previousOrderTechnologyGroupNumberField.getFieldValue()).willReturn(L_PREVIOUS_ORDER_TECHNOLOGY_GROUP_NUMBER); given(technologyGroupNumberField.getFieldValue()).willReturn(L_TECHNOLOGY_GROUP_NUMBER); given(previousOrderTechnologyNumberField.getFieldValue()).willReturn(L_PREVIOUS_ORDER_TECHNOLOGY_NUMBER); given(technologyNumberField.getFieldValue()).willReturn(L_TECHNOLOGY_NUMBER); given(lineChangeoverNormsForOrdersService.getTechnologyGroupByNumberFromDB(L_PREVIOUS_ORDER_TECHNOLOGY_GROUP_NUMBER)) .willReturn(fromTechnologyGroup); given(lineChangeoverNormsForOrdersService.getTechnologyGroupByNumberFromDB(L_TECHNOLOGY_GROUP_NUMBER)).willReturn( toTechnologyGroup); given(lineChangeoverNormsForOrdersService.getTechnologyByNumberFromDB(L_PREVIOUS_ORDER_TECHNOLOGY_NUMBER)).willReturn( fromTechnology); given(lineChangeoverNormsForOrdersService.getTechnologyByNumberFromDB(L_TECHNOLOGY_NUMBER)).willReturn(toTechnology); given( changeoverNormsSearchService.searchMatchingChangeroverNormsForTechnologyGroupWithLine(fromTechnologyGroup, toTechnologyGroup, productionLine)).willReturn(lineChangeoverNormForGroup); given( changeoverNormsSearchService.searchMatchingChangeroverNormsForTechnologyWithLine(fromTechnology, toTechnology, productionLine)).willReturn(lineChangeoverNormForTechnology); lineChangeoverNormsForOrderDetailsViewHooks.updateRibbonState(view); verify(showPreviousOrder).setEnabled(true); verify(showBestFittingLineChangeoverNorm).setEnabled(true); verify(showLineChangeoverNormForGroup).setEnabled(true); verify(showLineChangeoverNormForTechnology).setEnabled(true); }
LineChangeoverNormsForOrderDetailsViewHooks { public void showOwnLineChangeoverDurationField(final ViewDefinitionState view) { orderService.changeFieldState(view, OrderFieldsLCNFO.OWN_LINE_CHANGEOVER, OrderFieldsLCNFO.OWN_LINE_CHANGEOVER_DURATION); } final void fillOrderForms(final ViewDefinitionState view); void fillLineChangeoverNorm(final ViewDefinitionState view); void updateRibbonState(final ViewDefinitionState view); void showOwnLineChangeoverDurationField(final ViewDefinitionState view); }
@Test public void shouldShowOwnLineChangeoverDurationField() { lineChangeoverNormsForOrderDetailsViewHooks.showOwnLineChangeoverDurationField(view); verify(orderService).changeFieldState(view, OWN_LINE_CHANGEOVER, OWN_LINE_CHANGEOVER_DURATION); }
TechnologyOperationComponentHooksTS { public void copySubstractingFieldFromLowerInstance(final DataDefinition technologyOperationComponentDD, final Entity technologyOperationComponent) { if (!shouldCopyFromLowerInstance(technologyOperationComponent)) { return; } Entity operation = technologyOperationComponent.getBelongsToField(OPERATION); if (operation != null) { technologyOperationComponent.setField(IS_SUBCONTRACTING, operation.getBooleanField(IS_SUBCONTRACTING)); } } void copySubstractingFieldFromLowerInstance(final DataDefinition technologyOperationComponentDD, final Entity technologyOperationComponent); }
@Test public void shouldSetTrueFromLowerInstance() throws Exception { when(technologyOperationComponent.getField(IS_SUBCONTRACTING)).thenReturn(null); when(operation.getBooleanField(IS_SUBCONTRACTING)).thenReturn(true); technologyOperationComponentHooksTS.copySubstractingFieldFromLowerInstance(technologyOperationComponentDD, technologyOperationComponent); Mockito.verify(technologyOperationComponent).setField(IS_SUBCONTRACTING, true); } @Test public void shouldSetFalseFromLowerInstance() throws Exception { when(technologyOperationComponent.getField(IS_SUBCONTRACTING)).thenReturn(null); when(operation.getBooleanField("isSubcontracting")).thenReturn(false); technologyOperationComponentHooksTS.copySubstractingFieldFromLowerInstance(technologyOperationComponentDD, technologyOperationComponent); Mockito.verify(technologyOperationComponent).setField(IS_SUBCONTRACTING, false); } @Test public final void shouldCopyFalseValueFromFieldFromTheSameLevel() throws Exception { when(technologyOperationComponent.getBooleanField(IS_SUBCONTRACTING)).thenReturn(false); technologyOperationComponentHooksTS.copySubstractingFieldFromLowerInstance(technologyOperationComponentDD, technologyOperationComponent); boolean isSubcontracting = technologyOperationComponent.getBooleanField(IS_SUBCONTRACTING); Assert.assertEquals(false, isSubcontracting); } @Test public final void shouldCopyTrueValueFromFieldFromTheSameLevel() throws Exception { when(technologyOperationComponent.getBooleanField(IS_SUBCONTRACTING)).thenReturn(true); technologyOperationComponentHooksTS.copySubstractingFieldFromLowerInstance(technologyOperationComponentDD, technologyOperationComponent); boolean isSubcontracting = technologyOperationComponent.getBooleanField(IS_SUBCONTRACTING); Assert.assertEquals(true, isSubcontracting); }
MasterOrderHooks { protected void setExternalSynchronizedField(final Entity masterOrder) { masterOrder.setField(MasterOrderFields.EXTERNAL_SYNCHRONIZED, true); } void onCreate(final DataDefinition dataDefinition, final Entity masterOrder); void onSave(final DataDefinition dataDefinition, final Entity masterOrder); void onUpdate(final DataDefinition dataDefinition, final Entity masterOrder); void onCopy(final DataDefinition dataDefinition, final Entity masterOrder); }
@Test public final void shouldSetExternalSynchronized() { masterOrderHooks.setExternalSynchronizedField(masterOrder); verify(masterOrder).setField(MasterOrderFields.EXTERNAL_SYNCHRONIZED, true); }
MasterOrderHooks { protected void changedDeadlineAndInOrder(final Entity masterOrder) { Preconditions.checkArgument(masterOrder.getId() != null, "Method expects already persisted entity"); Date deadline = masterOrder.getDateField(DEADLINE); Entity customer = masterOrder.getBelongsToField(COMPANY); if (deadline == null && customer == null) { return; } List<Entity> allOrders = masterOrder.getHasManyField(MasterOrderFields.ORDERS); boolean hasBeenChanged = false; for (Entity order : allOrders) { if (OrderState.of(order) != OrderState.PENDING) { continue; } if (!ObjectUtils.equals(order.getDateField(OrderFields.DEADLINE), deadline)) { order.setField(OrderFields.DEADLINE, deadline); hasBeenChanged = true; } if (!ObjectUtils.equals(order.getBelongsToField(OrderFields.COMPANY), customer)) { order.setField(OrderFields.COMPANY, customer); hasBeenChanged = true; } } if (hasBeenChanged) { masterOrder.setField(MasterOrderFields.ORDERS, allOrders); } } void onCreate(final DataDefinition dataDefinition, final Entity masterOrder); void onSave(final DataDefinition dataDefinition, final Entity masterOrder); void onUpdate(final DataDefinition dataDefinition, final Entity masterOrder); void onCopy(final DataDefinition dataDefinition, final Entity masterOrder); }
@Test public final void shouldThrowExceptionWhenMasterOrderIsNotSave() { stubId(masterOrder, null); try { masterOrderHooks.changedDeadlineAndInOrder(masterOrder); Assert.fail(); } catch (IllegalArgumentException ignored) { verify(masterOrder, never()).setField(MasterOrderFields.ORDERS, Lists.newArrayList()); } } @Test public final void shouldReturnWhenDeadlineIsNull() { stubId(masterOrder, MASTER_ORDER_ID); stubDateField(masterOrder, MasterOrderFields.DEADLINE, null); stubDateField(masterOrder, MasterOrderFields.COMPANY, null); masterOrderHooks.changedDeadlineAndInOrder(masterOrder); verify(masterOrder, never()).setField(MasterOrderFields.ORDERS, Lists.newArrayList()); } @Test public final void shouldSetDeadline() { DateTime now = DateTime.now(); stubId(masterOrder, MASTER_ORDER_ID); stubDateField(masterOrder, MasterOrderFields.DEADLINE, now.toDate()); stubStringField(order1, OrderFields.STATE, OrderState.PENDING.getStringValue()); stubStringField(order2, OrderFields.STATE, OrderState.IN_PROGRESS.getStringValue()); stubDateField(order1, OrderFields.DEADLINE, now.plusHours(6).toDate()); EntityList orders = mockEntityList(Lists.newArrayList(order1, order2)); stubHasManyField(masterOrder, MasterOrderFields.ORDERS, orders); masterOrderHooks.changedDeadlineAndInOrder(masterOrder); verify(masterOrder).setField(eq(MasterOrderFields.ORDERS), entityListCaptor.capture()); List<Entity> actualOrders = entityListCaptor.getValue(); assertEquals(2, actualOrders.size()); assertTrue(actualOrders.contains(order1)); assertTrue(actualOrders.contains(order2)); } @Test public final void shouldReturnWhenDeadlineInMasterOrderIsNull() { stubId(masterOrder, MASTER_ORDER_ID); given(masterOrder.getBelongsToField(MasterOrderFields.COMPANY)).willReturn(null); masterOrderHooks.changedDeadlineAndInOrder(masterOrder); verify(masterOrder, never()).setField(MasterOrderFields.ORDERS, Lists.newArrayList()); } @Test public final void shouldSetCustomer() { stubId(masterOrder, MASTER_ORDER_ID); stubBelongsToField(masterOrder, MasterOrderFields.COMPANY, customer); stubStringField(order1, OrderFields.STATE, OrderState.PENDING.getStringValue()); stubStringField(order2, OrderFields.STATE, OrderState.IN_PROGRESS.getStringValue()); Entity yetAnotherCustomer = mockEntity(); stubBelongsToField(order1, OrderFields.COMPANY, yetAnotherCustomer); EntityList orders = mockEntityList(Lists.newArrayList(order1, order2)); given(masterOrder.getHasManyField(MasterOrderFields.ORDERS)).willReturn(orders); masterOrderHooks.changedDeadlineAndInOrder(masterOrder); verify(masterOrder).setField(eq(MasterOrderFields.ORDERS), entityListCaptor.capture()); List<Entity> actualOrders = entityListCaptor.getValue(); assertEquals(2, actualOrders.size()); assertTrue(actualOrders.contains(order1)); assertTrue(actualOrders.contains(order2)); }
MasterOrderProductDetailsHooks { public void fillUnitField(final ViewDefinitionState view) { LookupComponent productField = (LookupComponent) view.getComponentByReference(MasterOrderProductFields.PRODUCT); Entity product = productField.getEntity(); String unit = null; if (product != null) { unit = product.getStringField(ProductFields.UNIT); } for (String reference : Arrays.asList("cumulatedOrderQuantityUnit", "masterOrderQuantityUnit", "producedOrderQuantityUnit", "leftToReleaseUnit")) { FieldComponent field = (FieldComponent) view.getComponentByReference(reference); field.setFieldValue(unit); field.requestComponentUpdateState(); } } void fillUnitField(final ViewDefinitionState view); void fillDefaultTechnology(final ViewDefinitionState view); void showErrorWhenCumulatedQuantity(final ViewDefinitionState view); }
@Test public final void shouldSetNullWhenProductDoesnotExists() { given(productField.getEntity()).willReturn(null); masterOrderProductDetailsHooks.fillUnitField(view); verify(cumulatedOrderQuantityUnitField).setFieldValue(null); verify(masterOrderQuantityUnitField).setFieldValue(null); verify(producedOrderQuantityUnitField).setFieldValue(null); } @Test public final void shouldSetUnitFromProduct() { String unit = "szt"; given(productField.getEntity()).willReturn(product); given(product.getStringField(ProductFields.UNIT)).willReturn(unit); masterOrderProductDetailsHooks.fillUnitField(view); verify(cumulatedOrderQuantityUnitField).setFieldValue(unit); verify(masterOrderQuantityUnitField).setFieldValue(unit); verify(producedOrderQuantityUnitField).setFieldValue(unit); }
MasterOrderProductDetailsHooks { public void showErrorWhenCumulatedQuantity(final ViewDefinitionState view) { FormComponent masterOrderProductForm = (FormComponent) view.getComponentByReference(L_FORM); Entity masterOrderProduct = masterOrderProductForm.getPersistedEntityWithIncludedFormValues(); if ((masterOrderProduct == null) || !masterOrderProduct.isValid()) { return; } Entity masterOrder = masterOrderProduct.getBelongsToField(MasterOrderProductFields.MASTER_ORDER); BigDecimal cumulatedQuantity = masterOrderProduct.getDecimalField(MasterOrderProductFields.CUMULATED_ORDER_QUANTITY); BigDecimal masterOrderQuantity = masterOrderProduct.getDecimalField(MasterOrderProductFields.MASTER_ORDER_QUANTITY); if ((cumulatedQuantity != null) && (masterOrderQuantity != null) && (cumulatedQuantity.compareTo(masterOrderQuantity) == -1)) { masterOrderProductForm.addMessage("masterOrders.masterOrder.masterOrderCumulatedQuantityField.wrongQuantity", MessageType.INFO, false); } } void fillUnitField(final ViewDefinitionState view); void fillDefaultTechnology(final ViewDefinitionState view); void showErrorWhenCumulatedQuantity(final ViewDefinitionState view); }
@Test public final void shouldShowMessageError() { BigDecimal cumulatedOrderQuantity = BigDecimal.ONE; BigDecimal masterOrderQuantity = BigDecimal.TEN; given(masterOrderProduct.isValid()).willReturn(true); given(masterOrderProduct.getDecimalField(MasterOrderProductFields.CUMULATED_ORDER_QUANTITY)).willReturn( cumulatedOrderQuantity); given(masterOrderProduct.getDecimalField(MasterOrderProductFields.MASTER_ORDER_QUANTITY)).willReturn(masterOrderQuantity); masterOrderProductDetailsHooks.showErrorWhenCumulatedQuantity(view); verify(masterOrderProductForm).addMessage("masterOrders.masterOrder.masterOrderCumulatedQuantityField.wrongQuantity", MessageType.INFO, false); } @Test public final void shouldDonotShowMessageError() { BigDecimal cumulatedOrderQuantity = BigDecimal.TEN; BigDecimal masterOrderQuantity = BigDecimal.ONE; given(masterOrderProduct.isValid()).willReturn(true); given(masterOrderProduct.getDecimalField(MasterOrderProductFields.CUMULATED_ORDER_QUANTITY)).willReturn( cumulatedOrderQuantity); given(masterOrderProduct.getDecimalField(MasterOrderProductFields.MASTER_ORDER_QUANTITY)).willReturn(masterOrderQuantity); masterOrderProductDetailsHooks.showErrorWhenCumulatedQuantity(view); verify(masterOrderProductForm, Mockito.never()).addMessage( "masterOrders.masterOrder.masterOrderCumulatedQuantityField.wrongQuantity", MessageType.INFO, false); }
OrderValidatorsMO { public boolean checkProductAndTechnology(final DataDefinition orderDD, final Entity order) { Entity masterOrder = order.getBelongsToField(MASTER_ORDER); if (masterOrder == null || masterOrder.getHasManyField(MasterOrderFields.MASTER_ORDER_PRODUCTS).isEmpty()) { return true; } return checkIfOrderMatchesAnyOfMasterOrderProductsWithTechnology(order, masterOrder); } boolean checkOrderNumber(final DataDefinition orderDD, final Entity order); boolean checkCompanyAndDeadline(final DataDefinition orderDD, final Entity order); boolean checkProductAndTechnology(final DataDefinition orderDD, final Entity order); }
@Test public final void shouldReturnFalseIfNoneOfMasterOrderProductMatches() { stubMasterOrderProducts(NOT_EMPTY_ENTITY_LIST); SearchCriteriaBuilder scb = mockCriteriaBuilder(EMPTY_ENTITY_LIST); given(masterDD.find()).willReturn(scb); boolean isValid = orderValidatorsMO.checkProductAndTechnology(orderDD, order); Assert.assertFalse(isValid); Mockito.verify(scb).add(technologyIsEmptyOrMatchTechPrototypeRestriction); } @Test public final void shouldReturnTrueIfSomeMasterOrderProductMatches() { stubMasterOrderProducts(NOT_EMPTY_ENTITY_LIST); SearchCriteriaBuilder scb = mockCriteriaBuilder(NOT_EMPTY_ENTITY_LIST); given(masterDD.find()).willReturn(scb); boolean isValid = orderValidatorsMO.checkProductAndTechnology(orderDD, order); Assert.assertTrue(isValid); Mockito.verify(scb).add(technologyIsEmptyOrMatchTechPrototypeRestriction); } @Test public final void shouldReturnTrueIfSomeMasterOrderProductMatches2() { stubMasterOrderProducts(NOT_EMPTY_ENTITY_LIST); stubOrderTechnologyPrototype(null); SearchCriteriaBuilder scb = mockCriteriaBuilder(NOT_EMPTY_ENTITY_LIST); given(masterDD.find()).willReturn(scb); boolean isValid = orderValidatorsMO.checkProductAndTechnology(orderDD, order); Assert.assertTrue(isValid); Mockito.verify(scb).add(technologyIsNullRestriction); } @Test public final void shouldReturnTrueWhenMasterOrderIsNotSpecified() { given(order.getBelongsToField(MASTER_ORDER)).willReturn(null); boolean result = orderValidatorsMO.checkProductAndTechnology(orderDD, order); Assert.assertEquals(true, result); }
OrderValidatorsMO { public boolean checkCompanyAndDeadline(final DataDefinition orderDD, final Entity order) { boolean isValid = true; Entity masterOrder = order.getBelongsToField(MASTER_ORDER); if (masterOrder == null) { return isValid; } if (!checkIfBelongToFieldIsTheSame(order, masterOrder, COMPANY)) { Entity company = masterOrder.getBelongsToField(COMPANY); order.addError(orderDD.getField(COMPANY), "masterOrders.order.masterOrder.company.fieldIsNotTheSame", createInfoAboutEntity(company, "company")); isValid = false; } if (!checkIfDeadlineIsCorrect(order, masterOrder)) { Date deadline = (Date) masterOrder.getField(DEADLINE); order.addError( orderDD.getField(DEADLINE), "masterOrders.order.masterOrder.deadline.fieldIsNotTheSame", deadline == null ? translationService.translate("masterOrders.order.masterOrder.deadline.hasNotDeadline", Locale.getDefault()) : DateUtils.toDateTimeString(deadline)); isValid = false; } return isValid; } boolean checkOrderNumber(final DataDefinition orderDD, final Entity order); boolean checkCompanyAndDeadline(final DataDefinition orderDD, final Entity order); boolean checkProductAndTechnology(final DataDefinition orderDD, final Entity order); }
@Test public final void shouldCheckCompanyAndDeadlineReturnTrueWhenMasterOrderIsNotSpecified() { given(order.getBelongsToField(OrderFieldsMO.MASTER_ORDER)).willReturn(null); boolean result = orderValidatorsMO.checkCompanyAndDeadline(orderDD, order); Assert.assertTrue(result); }
OrderValidatorsMO { public boolean checkOrderNumber(final DataDefinition orderDD, final Entity order) { Entity masterOrder = order.getBelongsToField(MASTER_ORDER); if (masterOrder == null) { return true; } if (!masterOrder.getBooleanField(ADD_MASTER_PREFIX_TO_NUMBER)) { return true; } String masterOrderNumber = masterOrder.getStringField(MasterOrderFields.NUMBER); String orderNumber = order.getStringField(OrderFields.NUMBER); if (!orderNumber.startsWith(masterOrderNumber)) { order.addError(orderDD.getField(OrderFields.NUMBER), "masterOrders.order.number.numberHasNotPrefix", masterOrderNumber); return false; } return true; } boolean checkOrderNumber(final DataDefinition orderDD, final Entity order); boolean checkCompanyAndDeadline(final DataDefinition orderDD, final Entity order); boolean checkProductAndTechnology(final DataDefinition orderDD, final Entity order); }
@Test public final void shouldCheckOrderNumberReturnTrueWhenMasterOrderIsNotSpecified() { given(order.getBelongsToField(OrderFieldsMO.MASTER_ORDER)).willReturn(null); boolean result = orderValidatorsMO.checkOrderNumber(orderDD, order); Assert.assertEquals(true, result); } @Test public final void shouldCheckOrderNumberReturnTrueWhenAddPrefixIsFalse() { given(order.getBelongsToField(OrderFieldsMO.MASTER_ORDER)).willReturn(masterOrder); given(masterOrder.getBooleanField(MasterOrderFields.ADD_MASTER_PREFIX_TO_NUMBER)).willReturn(false); boolean result = orderValidatorsMO.checkOrderNumber(orderDD, order); Assert.assertEquals(true, result); } @Test public final void shouldCheckOrderNumberReturnFalseWhenNumberIsIncorrect() { String masterOrderNumber = "ZL"; String orderNumber = "ZXS"; given(order.getBelongsToField(OrderFieldsMO.MASTER_ORDER)).willReturn(masterOrder); given(masterOrder.getBooleanField(MasterOrderFields.ADD_MASTER_PREFIX_TO_NUMBER)).willReturn(true); given(masterOrder.getStringField(MasterOrderFields.NUMBER)).willReturn(masterOrderNumber); given(order.getStringField(OrderFields.NUMBER)).willReturn(orderNumber); boolean result = orderValidatorsMO.checkOrderNumber(orderDD, order); Assert.assertEquals(false, result); } @Test public final void shouldCheckOrderNumberReturnTrueWhenNumberIsCorrect() { String masterOrderNumber = "ZL"; String orderNumber = "ZLSADS"; given(order.getBelongsToField(OrderFieldsMO.MASTER_ORDER)).willReturn(masterOrder); given(masterOrder.getBooleanField(MasterOrderFields.ADD_MASTER_PREFIX_TO_NUMBER)).willReturn(true); given(masterOrder.getStringField(MasterOrderFields.NUMBER)).willReturn(masterOrderNumber); given(order.getStringField(OrderFields.NUMBER)).willReturn(orderNumber); boolean result = orderValidatorsMO.checkOrderNumber(orderDD, order); Assert.assertEquals(true, result); }
OperationalTaskDetailsListenersOTFOOverrideUtil { public void setOperationalTaskNameDescriptionAndProductionLineForSubcontracted(final ViewDefinitionState view) { LookupComponent orderLookup = (LookupComponent) view.getComponentByReference(OperationalTaskFieldsOTFO.ORDER); LookupComponent technologyOperationComponentLookup = (LookupComponent) view .getComponentByReference(L_TECHNOLOGY_OPERATION_COMPONENT); FieldComponent nameField = (FieldComponent) view.getComponentByReference(OperationalTaskFields.NAME); FieldComponent descriptionField = (FieldComponent) view.getComponentByReference(OperationalTaskFields.DESCRIPTION); LookupComponent productionLineLookup = (LookupComponent) view .getComponentByReference(OperationalTaskFields.PRODUCTION_LINE); Entity order = orderLookup.getEntity(); Entity technologyOperationComponent = technologyOperationComponentLookup.getEntity(); if ((order == null) || (technologyOperationComponent == null) || isSubcontracting(technologyOperationComponent)) { nameField.setFieldValue(null); descriptionField.setFieldValue(null); productionLineLookup.setFieldValue(null); nameField.requestComponentUpdateState(); descriptionField.requestComponentUpdateState(); productionLineLookup.requestComponentUpdateState(); } } void setOperationalTaskNameDescriptionAndProductionLineForSubcontracted(final ViewDefinitionState view); }
@Test public void shouldntOperationalTaskNameDescriptionAndProductionLineForSubcontractedWhenIsSubcontracting() throws Exception { given(orderLookup.getEntity()).willReturn(order); given(technologyOperationComponentLookup.getEntity()).willReturn(technologyOperationComponent); given(technologyOperationComponent.getBooleanField(TechnologyInstanceOperCompFieldsTS.IS_SUBCONTRACTING)) .willReturn(true); operationalTaskDetailsListenersOTFOOverrideUtil.setOperationalTaskNameDescriptionAndProductionLineForSubcontracted(view); Mockito.verify(nameField).setFieldValue(null); Mockito.verify(descriptionField).setFieldValue(null); Mockito.verify(productionLineLookup).setFieldValue(null); } @Test public void shouldntOperationalTaskNameDescriptionAndProductionLineForSubcontractedWhenTechnologyOperationComponentIsNull() throws Exception { given(orderLookup.getEntity()).willReturn(order); given(technologyOperationComponentLookup.getEntity()).willReturn(null); given(technologyOperationComponent.getBooleanField(TechnologyInstanceOperCompFieldsTS.IS_SUBCONTRACTING)).willReturn( false); operationalTaskDetailsListenersOTFOOverrideUtil.setOperationalTaskNameDescriptionAndProductionLineForSubcontracted(view); Mockito.verify(descriptionField).setFieldValue(null); Mockito.verify(nameField).setFieldValue(null); Mockito.verify(productionLineLookup).setFieldValue(null); }
MrpAlgorithmStrategyTS implements MrpAlgorithmStrategy { public Map<Long, BigDecimal> perform(final OperationProductComponentWithQuantityContainer productComponentWithQuantities, final Set<OperationProductComponentHolder> nonComponents, final MrpAlgorithm mrpAlgorithm, final String operationProductComponentModelName) { OperationProductComponentWithQuantityContainer allWithSameEntityType = productComponentWithQuantities .getAllWithSameEntityType(operationProductComponentModelName); Map<Long, BigDecimal> productWithQuantities = Maps.newHashMap(); for (Entry<OperationProductComponentHolder, BigDecimal> productComponentWithQuantity : allWithSameEntityType.asMap() .entrySet()) { OperationProductComponentHolder operationProductComponentHolder = productComponentWithQuantity.getKey(); if (nonComponents.contains(operationProductComponentHolder)) { Entity product = operationProductComponentHolder.getProduct(); Entity technologyOperationComponent = operationProductComponentHolder.getTechnologyOperationComponent(); if (technologyOperationComponent != null) { List<Entity> children = technologyOperationComponent.getHasManyField(CHILDREN).find() .add(SearchRestrictions.eq(TechnologyOperationComponentFieldsTS.IS_SUBCONTRACTING, true)).list() .getEntities(); boolean isSubcontracting = false; for (Entity child : children) { Entity operationProductOutComponent = child.getHasManyField(OPERATION_PRODUCT_OUT_COMPONENTS).find() .add(SearchRestrictions.belongsTo(PRODUCT, product)).setMaxResults(1).uniqueResult(); if (operationProductOutComponent != null) { isSubcontracting = true; } } if (!isSubcontracting) { continue; } } } productQuantitiesService.addProductQuantitiesToList(productComponentWithQuantity, productWithQuantities); } return productWithQuantities; } boolean isApplicableFor(final MrpAlgorithm mrpAlgorithm); Map<Long, BigDecimal> perform(final OperationProductComponentWithQuantityContainer productComponentWithQuantities, final Set<OperationProductComponentHolder> nonComponents, final MrpAlgorithm mrpAlgorithm, final String operationProductComponentModelName); }
@Test public void shouldReturnMapWithoutProductFromSubcontractingOperation() throws Exception { Map<Long, BigDecimal> productsMap = algorithmStrategyTS.perform(productComponentQuantities, nonComponents, MrpAlgorithm.COMPONENTS_AND_SUBCONTRACTORS_PRODUCTS, "productInComponent"); assertEquals(2, productsMap.size()); assertEquals(new BigDecimal(5), productsMap.get(product1.getId())); assertEquals(BigDecimal.ONE, productsMap.get(product3.getId())); } @Test public void shouldReturnMapWithProductFromOneSubcontractingOperations() throws Exception { when(operComp1.getBooleanField("isSubcontracting")).thenReturn(true); Map<Long, BigDecimal> productsMap = algorithmStrategyTS.perform(productComponentQuantities, nonComponents, MrpAlgorithm.COMPONENTS_AND_SUBCONTRACTORS_PRODUCTS, "productInComponent"); assertEquals(3, productsMap.size()); assertEquals(new BigDecimal(5), productsMap.get(product1.getId())); assertEquals(BigDecimal.ONE, productsMap.get(product2.getId())); assertEquals(BigDecimal.ONE, productsMap.get(product3.getId())); } @Test public void shouldReturnProductFromAllSubcontractingOperation() throws Exception { when(operComp1.getBooleanField("isSubcontracting")).thenReturn(true); when(operComp2.getBooleanField("isSubcontracting")).thenReturn(true); Map<Long, BigDecimal> productsMap = algorithmStrategyTS.perform(productComponentQuantities, nonComponents, MrpAlgorithm.COMPONENTS_AND_SUBCONTRACTORS_PRODUCTS, "productInComponent"); assertEquals(4, productsMap.size()); assertEquals(new BigDecimal(5), productsMap.get(product1.getId())); assertEquals(BigDecimal.ONE, productsMap.get(product2.getId())); assertEquals(BigDecimal.ONE, productsMap.get(product3.getId())); assertEquals(BigDecimal.ONE, productsMap.get(product4.getId())); }
OrderRealizationTimeServiceImpl implements OrderRealizationTimeService { @Override @Transactional public int estimateOperationTimeConsumption(final EntityTreeNode operationComponent, final BigDecimal plannedQuantity, final boolean includeTpz, final boolean includeAdditionalTime, final Entity productionLine) { Entity technology = operationComponent.getBelongsToField(TECHNOLOGY); Map<Long, BigDecimal> operationRunsFromProductionQuantities = Maps.newHashMap(); OperationProductComponentWithQuantityContainer productComponentQuantities = productQuantitiesService .getProductComponentQuantities(technology, plannedQuantity, operationRunsFromProductionQuantities); return evaluateOperationTime(operationComponent, includeTpz, includeAdditionalTime, operationRunsFromProductionQuantities, productionLine, false, productComponentQuantities); } @Override Object setDateToField(final Date date); @Override @Transactional int estimateOperationTimeConsumption(final EntityTreeNode operationComponent, final BigDecimal plannedQuantity, final boolean includeTpz, final boolean includeAdditionalTime, final Entity productionLine); @Override @Transactional int estimateMaxOperationTimeConsumptionForWorkstation(final EntityTreeNode operationComponent, final BigDecimal plannedQuantity, final boolean includeTpz, final boolean includeAdditionalTime, final Entity productionLine); @Override Map<Entity, Integer> estimateOperationTimeConsumptions(final Entity entity, final BigDecimal plannedQuantity, final boolean includeTpz, final boolean includeAdditionalTime, final Entity productionLine); @Override Map<Entity, Integer> estimateMaxOperationTimeConsumptionsForWorkstations(final Entity entity, final BigDecimal plannedQuantity, final boolean includeTpz, final boolean includeAdditionalTime, final Entity productionLine); @Override int evaluateSingleOperationTime(Entity operationComponent, final boolean includeTpz, final boolean includeAdditionalTime, final Map<Long, BigDecimal> operationRuns, final Entity productionLine, final boolean maxForWorkstation); @Override int evaluateSingleOperationTimeIncludedNextOperationAfterProducedQuantity(Entity operationComponent, final boolean includeTpz, final boolean includeAdditionalTime, final Map<Long, BigDecimal> operationRuns, final Entity productionLine, final boolean maxForWorkstation, final OperationProductComponentWithQuantityContainer productComponentQuantities); @Override int evaluateOperationDurationOutOfCycles(final BigDecimal cycles, final Entity operationComponent, final Entity productionLine, final boolean maxForWorkstation, final boolean includeTpz, final boolean includeAdditionalTime); @Override BigDecimal getBigDecimalFromField(final Object value, final Locale locale); @Override int estimateOperationTimeConsumption(EntityTreeNode operationComponent, BigDecimal plannedQuantity, Entity productionLine); }
@Test public void shouldReturnCorrectOperationTimeWithShifts() { boolean includeTpz = true; boolean includeAdditionalTime = true; BigDecimal plannedQuantity = new BigDecimal(1); int time = orderRealizationTimeServiceImpl.estimateOperationTimeConsumption(opComp1, plannedQuantity, includeTpz, includeAdditionalTime, productionLine); assertEquals(10, time); } @Test public void shouldActuallyMakeTimeConsumptionLongerWithMoreWorkstationsDueAdditionalTpz() { boolean includeTpz = true; boolean includeAdditionalTime = true; BigDecimal plannedQuantity = new BigDecimal(1); when(productionLinesService.getWorkstationTypesCount(opComp1, productionLine)).thenReturn(2); when(productionLinesService.getWorkstationTypesCount(opComp2, productionLine)).thenReturn(2); int time = orderRealizationTimeServiceImpl.estimateOperationTimeConsumption(opComp1, plannedQuantity, includeTpz, includeAdditionalTime, productionLine); assertEquals(14, time); }
OrderRealizationTimeServiceImpl implements OrderRealizationTimeService { @Override @Transactional public int estimateMaxOperationTimeConsumptionForWorkstation(final EntityTreeNode operationComponent, final BigDecimal plannedQuantity, final boolean includeTpz, final boolean includeAdditionalTime, final Entity productionLine) { Entity technology = operationComponent.getBelongsToField(TECHNOLOGY); Map<Long, BigDecimal> operationRunsFromProductionQuantities = Maps.newHashMap(); OperationProductComponentWithQuantityContainer productComponentQuantities = productQuantitiesService .getProductComponentQuantities(technology, plannedQuantity, operationRunsFromProductionQuantities); return evaluateOperationTime(operationComponent, includeTpz, includeAdditionalTime, operationRunsFromProductionQuantities, productionLine, true, productComponentQuantities); } @Override Object setDateToField(final Date date); @Override @Transactional int estimateOperationTimeConsumption(final EntityTreeNode operationComponent, final BigDecimal plannedQuantity, final boolean includeTpz, final boolean includeAdditionalTime, final Entity productionLine); @Override @Transactional int estimateMaxOperationTimeConsumptionForWorkstation(final EntityTreeNode operationComponent, final BigDecimal plannedQuantity, final boolean includeTpz, final boolean includeAdditionalTime, final Entity productionLine); @Override Map<Entity, Integer> estimateOperationTimeConsumptions(final Entity entity, final BigDecimal plannedQuantity, final boolean includeTpz, final boolean includeAdditionalTime, final Entity productionLine); @Override Map<Entity, Integer> estimateMaxOperationTimeConsumptionsForWorkstations(final Entity entity, final BigDecimal plannedQuantity, final boolean includeTpz, final boolean includeAdditionalTime, final Entity productionLine); @Override int evaluateSingleOperationTime(Entity operationComponent, final boolean includeTpz, final boolean includeAdditionalTime, final Map<Long, BigDecimal> operationRuns, final Entity productionLine, final boolean maxForWorkstation); @Override int evaluateSingleOperationTimeIncludedNextOperationAfterProducedQuantity(Entity operationComponent, final boolean includeTpz, final boolean includeAdditionalTime, final Map<Long, BigDecimal> operationRuns, final Entity productionLine, final boolean maxForWorkstation, final OperationProductComponentWithQuantityContainer productComponentQuantities); @Override int evaluateOperationDurationOutOfCycles(final BigDecimal cycles, final Entity operationComponent, final Entity productionLine, final boolean maxForWorkstation, final boolean includeTpz, final boolean includeAdditionalTime); @Override BigDecimal getBigDecimalFromField(final Object value, final Locale locale); @Override int estimateOperationTimeConsumption(EntityTreeNode operationComponent, BigDecimal plannedQuantity, Entity productionLine); }
@Test public void shouldCalculateMaxTimeConsumptionPerWorkstationCorrectly() { boolean includeTpz = true; boolean includeAdditionalTime = true; BigDecimal plannedQuantity = new BigDecimal(1); when(productionLinesService.getWorkstationTypesCount(opComp1, productionLine)).thenReturn(2); when(productionLinesService.getWorkstationTypesCount(opComp2, productionLine)).thenReturn(2); int time = orderRealizationTimeServiceImpl.estimateMaxOperationTimeConsumptionForWorkstation(opComp1, plannedQuantity, includeTpz, includeAdditionalTime, productionLine); assertEquals(7, time); }
MultitransferListeners { public void fillUnitsInADL(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { fillUnitsInADL(view, PRODUCTS); } @Transactional void createMultitransfer(final ViewDefinitionState view, final ComponentState state, final String[] args); boolean checkIfTransferIsValid(FormComponent formComponent, Entity transfer); boolean isMultitransferFormValid(final ViewDefinitionState view); Entity createTransfer(final String type, final Date time, final Entity locationFrom, final Entity locationTo, final Entity staff, final Entity product, final BigDecimal quantity); void fillUnitsInADL(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void getFromTemplates(final ViewDefinitionState view, final ComponentState state, final String[] args); void getFromTemplates(final ViewDefinitionState view); void disableDateField(final ViewDefinitionState view, final ComponentState state, final String[] args); void checkIfLocationFromHasExternalNumber(final ViewDefinitionState view, final ComponentState state, final String[] args); void checkIfLocationToHasExternalNumber(final ViewDefinitionState view, final ComponentState state, final String[] args); void checkIfLocationToHasExternalNumber(final ViewDefinitionState view); void checkIfLocationFromHasExternalNumber(final ViewDefinitionState view); }
@Test public void shouldFillUnitsInADL() { multitransferListeners.fillUnitsInADL(view, state, null); verify(unit).setFieldValue(L_UNIT); verify(formComponent).setEntity(productQuantity); }
MultitransferListeners { @Transactional public void createMultitransfer(final ViewDefinitionState view, final ComponentState state, final String[] args) { if (!isMultitransferFormValid(view)) { return; } FormComponent multitransferForm = (FormComponent) view.getComponentByReference(L_FORM); FieldComponent typeField = (FieldComponent) view.getComponentByReference(TYPE); FieldComponent timeField = (FieldComponent) view.getComponentByReference(TIME); FieldComponent locationFromField = (FieldComponent) view.getComponentByReference(LOCATION_FROM); FieldComponent locationToField = (FieldComponent) view.getComponentByReference(LOCATION_TO); FieldComponent staffField = (FieldComponent) view.getComponentByReference(STAFF); typeField.requestComponentUpdateState(); timeField.requestComponentUpdateState(); locationToField.requestComponentUpdateState(); locationFromField.requestComponentUpdateState(); staffField.requestComponentUpdateState(); String type = typeField.getFieldValue().toString(); Date time = DateUtils.parseDate(timeField.getFieldValue()); Entity locationFrom = materialFlowService.getLocationById((Long) locationFromField.getFieldValue()); Entity locationTo = materialFlowService.getLocationById((Long) locationToField.getFieldValue()); Entity staff = materialFlowService.getStaffById((Long) staffField.getFieldValue()); AwesomeDynamicListComponent adlc = (AwesomeDynamicListComponent) view.getComponentByReference(PRODUCTS); List<FormComponent> formComponents = adlc.getFormComponents(); for (FormComponent formComponent : formComponents) { Entity productQuantity = formComponent.getEntity(); BigDecimal quantity = productQuantity.getDecimalField(QUANTITY); Entity product = productQuantity.getBelongsToField(PRODUCT); if ((product != null) && (quantity != null)) { Entity transfer = createTransfer(type, time, locationFrom, locationTo, staff, product, quantity); if (!checkIfTransferIsValid(formComponent, transfer)) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); return; } } } adlc.setFieldValue(null); multitransferForm.setEntity(multitransferForm.getEntity()); state.performEvent(view, "refresh", new String[0]); view.getComponentByReference(L_FORM).addMessage("materialFlowMultitransfers.multitransfer.generate.success", MessageType.SUCCESS); } @Transactional void createMultitransfer(final ViewDefinitionState view, final ComponentState state, final String[] args); boolean checkIfTransferIsValid(FormComponent formComponent, Entity transfer); boolean isMultitransferFormValid(final ViewDefinitionState view); Entity createTransfer(final String type, final Date time, final Entity locationFrom, final Entity locationTo, final Entity staff, final Entity product, final BigDecimal quantity); void fillUnitsInADL(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void getFromTemplates(final ViewDefinitionState view, final ComponentState state, final String[] args); void getFromTemplates(final ViewDefinitionState view); void disableDateField(final ViewDefinitionState view, final ComponentState state, final String[] args); void checkIfLocationFromHasExternalNumber(final ViewDefinitionState view, final ComponentState state, final String[] args); void checkIfLocationToHasExternalNumber(final ViewDefinitionState view, final ComponentState state, final String[] args); void checkIfLocationToHasExternalNumber(final ViewDefinitionState view); void checkIfLocationFromHasExternalNumber(final ViewDefinitionState view); }
@Ignore @Test public void shouldCreateMultitransfer() { multitransferListeners.createMultitransfer(view, state, null); verify(form).addMessage("materialFlow.multitransfer.generate.success", MessageType.SUCCESS); }
MatchingChangeoverNormsDetailsHooks { public void setFieldsVisible(final ViewDefinitionState view) { FormComponent form = (FormComponent) view.getComponentByReference(L_FORM); ComponentState matchingNorm = view.getComponentByReference("matchingNorm"); ComponentState matchingNormNotFound = view.getComponentByReference("matchingNormNotFound"); if (form.getEntityId() == null) { matchingNorm.setVisible(false); matchingNormNotFound.setVisible(true); } else { matchingNorm.setVisible(true); matchingNormNotFound.setVisible(false); } } void setFieldsVisible(final ViewDefinitionState view); void fillOrCleanFields(final ViewDefinitionState view); }
@Test public void shouldntSetFieldsVisibleWhenNormsNotFound() { given(form.getEntityId()).willReturn(null); hooks.setFieldsVisible(view); verify(matchingNorm).setVisible(false); verify(matchingNormNotFound).setVisible(true); } @Test public void shouldSetFieldsVisibleWhenNormsFound() { given(form.getEntityId()).willReturn(1L); hooks.setFieldsVisible(view); verify(matchingNorm).setVisible(true); verify(matchingNormNotFound).setVisible(false); }
MultitransferListeners { public void getFromTemplates(final ViewDefinitionState view, final ComponentState state, final String[] args) { getFromTemplates(view); } @Transactional void createMultitransfer(final ViewDefinitionState view, final ComponentState state, final String[] args); boolean checkIfTransferIsValid(FormComponent formComponent, Entity transfer); boolean isMultitransferFormValid(final ViewDefinitionState view); Entity createTransfer(final String type, final Date time, final Entity locationFrom, final Entity locationTo, final Entity staff, final Entity product, final BigDecimal quantity); void fillUnitsInADL(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void getFromTemplates(final ViewDefinitionState view, final ComponentState state, final String[] args); void getFromTemplates(final ViewDefinitionState view); void disableDateField(final ViewDefinitionState view, final ComponentState state, final String[] args); void checkIfLocationFromHasExternalNumber(final ViewDefinitionState view, final ComponentState state, final String[] args); void checkIfLocationToHasExternalNumber(final ViewDefinitionState view, final ComponentState state, final String[] args); void checkIfLocationToHasExternalNumber(final ViewDefinitionState view); void checkIfLocationFromHasExternalNumber(final ViewDefinitionState view); }
@Ignore @Test public void shouldDownloadProductsFromTemplates() { given(template.getBelongsToField(PRODUCT)).willReturn(product); given( dataDefinitionService.get(MaterialFlowMultitransfersConstants.PLUGIN_IDENTIFIER, MaterialFlowMultitransfersConstants.MODEL_PRODUCT_QUANTITY)).willReturn(productQuantityDD); given(productQuantityDD.create()).willReturn(productQuantity); multitransferListeners.getFromTemplates(view, state, null); verify(productQuantity).setField(PRODUCT, product); verify(adlc).setFieldValue(Arrays.asList(productQuantity)); verify(form).addMessage("materialFlow.multitransfer.template.success", MessageType.SUCCESS); }
MultitransferViewHooks { public void makeFieldsRequired(final ViewDefinitionState view) { for (String componentRef : COMPONENTS) { FieldComponent component = (FieldComponent) view.getComponentByReference(componentRef); component.setRequired(true); component.requestComponentUpdateState(); } } void makeFieldsRequired(final ViewDefinitionState view); void disableDateField(final ViewDefinitionState view); }
@Test public void shouldMakeTimeAndTypeFieldsRequired() { given(view.getComponentByReference(TIME)).willReturn(time); given(view.getComponentByReference(TYPE)).willReturn(type); multitransferViewHooks.makeFieldsRequired(view); verify(time).setRequired(true); verify(type).setRequired(true); }
MessagesUtil { public static String joinArgs(final String[] splittedArgs) { if (ArrayUtils.isEmpty(splittedArgs)) { return null; } return StringUtils.join(splittedArgs, ARGS_SEPARATOR); } private MessagesUtil(); static String joinArgs(final String[] splittedArgs); static String[] splitArgs(final String joinedArgs); static boolean hasFailureMessages(final List<Entity> messages); static boolean hasValidationErrorMessages(final List<Entity> messages); static boolean messageIsTypeOf(final Entity message, final StateMessageType typeLookingFor); static boolean hasCorrespondField(final Entity message); static MessageType convertViewMessageType(final StateMessageType type); static String getKey(final Entity message); static String[] getArgs(final Entity message); static String getCorrespondFieldName(final Entity message); static boolean isAutoClosed(final Entity message); static final String ARGS_SEPARATOR; }
@Test public final void shouldReturnJoinedString() { final String[] splittedArgs = new String[] { "mes", "plugins", "states", "test" }; final String joinedString = MessagesUtil.joinArgs(splittedArgs); final String expectedString = splittedArgs[0] + ARGS_SEPARATOR + splittedArgs[1] + ARGS_SEPARATOR + splittedArgs[2] + ARGS_SEPARATOR + splittedArgs[3]; assertEquals(expectedString, joinedString); } @Test public final void shouldReturnNullIfGivenSplittedStringIsNull() { final String joinedString = MessagesUtil.joinArgs(null); assertNull(joinedString); } @Test public final void shouldReturnNullIfGivenSplittedStringIsEmpty() { final String joinedString = MessagesUtil.joinArgs(new String[] {}); assertNull(joinedString); }
MessagesUtil { public static String[] splitArgs(final String joinedArgs) { if (StringUtils.isBlank(joinedArgs)) { return ArrayUtils.EMPTY_STRING_ARRAY; } return joinedArgs.split(ARGS_SEPARATOR); } private MessagesUtil(); static String joinArgs(final String[] splittedArgs); static String[] splitArgs(final String joinedArgs); static boolean hasFailureMessages(final List<Entity> messages); static boolean hasValidationErrorMessages(final List<Entity> messages); static boolean messageIsTypeOf(final Entity message, final StateMessageType typeLookingFor); static boolean hasCorrespondField(final Entity message); static MessageType convertViewMessageType(final StateMessageType type); static String getKey(final Entity message); static String[] getArgs(final Entity message); static String getCorrespondFieldName(final Entity message); static boolean isAutoClosed(final Entity message); static final String ARGS_SEPARATOR; }
@Test public final void shouldReturnSplittedString() { final String arg1 = "mes"; final String arg2 = "plugins"; final String arg3 = "states"; final String arg4 = "test"; final String joinedArgs = arg1 + ARGS_SEPARATOR + arg2 + ARGS_SEPARATOR + arg3 + ARGS_SEPARATOR + arg4; final String[] splittedString = MessagesUtil.splitArgs(joinedArgs); assertEquals(4, splittedString.length); assertEquals(arg1, splittedString[0]); assertEquals(arg2, splittedString[1]); assertEquals(arg3, splittedString[2]); assertEquals(arg4, splittedString[3]); } @Test public final void shouldReturnEmptyArrayIfGivenJoinedStringIsNull() { final String[] splittedString = MessagesUtil.splitArgs(null); assertNotNull(splittedString); assertEquals(0, splittedString.length); } @Test public final void shouldReturnEmptyArrayIfGivenJoinedStringIsEmpty() { final String[] splittedString = MessagesUtil.splitArgs(""); assertNotNull(splittedString); assertEquals(0, splittedString.length); } @Test public final void shouldReturnEmptyArrayIfGivenJoinedStringIsBlank() { final String[] splittedString = MessagesUtil.splitArgs(" "); assertNotNull(splittedString); assertEquals(0, splittedString.length); }
MessagesUtil { public static boolean hasFailureMessages(final List<Entity> messages) { return hasMessagesOfType(messages, StateMessageType.FAILURE); } private MessagesUtil(); static String joinArgs(final String[] splittedArgs); static String[] splitArgs(final String joinedArgs); static boolean hasFailureMessages(final List<Entity> messages); static boolean hasValidationErrorMessages(final List<Entity> messages); static boolean messageIsTypeOf(final Entity message, final StateMessageType typeLookingFor); static boolean hasCorrespondField(final Entity message); static MessageType convertViewMessageType(final StateMessageType type); static String getKey(final Entity message); static String[] getArgs(final Entity message); static String getCorrespondFieldName(final Entity message); static boolean isAutoClosed(final Entity message); static final String ARGS_SEPARATOR; }
@Test public final void shouldHasFailureMessagesReturnTrue() { List<Entity> messages = Lists.newArrayList(); messages.add(mockMessage(StateMessageType.FAILURE, "test")); EntityList messagesEntityList = mockEntityList(messages); boolean result = MessagesUtil.hasFailureMessages(messagesEntityList); assertTrue(result); } @Test public final void shouldHasFailureMessagesReturnFalse() { List<Entity> messages = Lists.newArrayList(); messages.add(mockMessage(StateMessageType.SUCCESS, "test")); EntityList messagesEntityList = mockEntityList(messages); boolean result = MessagesUtil.hasFailureMessages(messagesEntityList); assertFalse(result); } @Test public final void shouldHasFailureMessagesReturnFalseForEmptyMessages() { List<Entity> messages = Lists.newArrayList(); EntityList messagesEntityList = mockEntityList(messages); boolean result = MessagesUtil.hasFailureMessages(messagesEntityList); assertFalse(result); }
MessagesUtil { public static boolean isAutoClosed(final Entity message) { return message.getField(AUTO_CLOSE) == null || message.getBooleanField(AUTO_CLOSE); } private MessagesUtil(); static String joinArgs(final String[] splittedArgs); static String[] splitArgs(final String joinedArgs); static boolean hasFailureMessages(final List<Entity> messages); static boolean hasValidationErrorMessages(final List<Entity> messages); static boolean messageIsTypeOf(final Entity message, final StateMessageType typeLookingFor); static boolean hasCorrespondField(final Entity message); static MessageType convertViewMessageType(final StateMessageType type); static String getKey(final Entity message); static String[] getArgs(final Entity message); static String getCorrespondFieldName(final Entity message); static boolean isAutoClosed(final Entity message); static final String ARGS_SEPARATOR; }
@Test public final void shouldIsAutoClosedReturnFalseIfFieldValueIsFalse() { final Entity message = mock(Entity.class); given(message.getField(MessageFields.AUTO_CLOSE)).willReturn(false); given(message.getBooleanField(MessageFields.AUTO_CLOSE)).willReturn(false); final boolean result = MessagesUtil.isAutoClosed(message); assertFalse(result); } @Test public final void shouldIsAutoClosedReturnFalseIfFieldValueIsTrue() { final Entity message = mock(Entity.class); given(message.getField(MessageFields.AUTO_CLOSE)).willReturn(true); given(message.getBooleanField(MessageFields.AUTO_CLOSE)).willReturn(true); final boolean result = MessagesUtil.isAutoClosed(message); assertTrue(result); } @Test public final void shouldIsAutoClosedReturnFalseIfFieldValueIsNull() { final Entity message = mock(Entity.class); given(message.getField(MessageFields.AUTO_CLOSE)).willReturn(null); given(message.getBooleanField(MessageFields.AUTO_CLOSE)).willReturn(false); final boolean result = MessagesUtil.isAutoClosed(message); assertTrue(result); }
StateChangeViewClientValidationUtil { public void addValidationErrorMessages(final ComponentState component, final StateChangeContext stateChangeContext) { addValidationErrorMessages(component, stateChangeContext.getOwner(), stateChangeContext); } void addValidationErrorMessages(final ComponentState component, final StateChangeContext stateChangeContext); void addValidationErrorMessages(final ComponentState component, final Entity entity, final MessagesHolder messagesHolder); }
@Test public final void shouldAddValidationErrorToEntityField() { final String existingFieldName = "existingField"; FieldDefinition existingField = mockFieldDefinition(existingFieldName); DataDefinition dataDefinition = mockDataDefinition(Lists.newArrayList(existingField)); given(entity.getDataDefinition()).willReturn(dataDefinition); given(formComponent.getEntity()).willReturn(entity); Entity message = mockValidationErrorMsg(existingFieldName, false, TRANSLATION_KEY); given(messagesHolder.getAllMessages()).willReturn(Lists.newArrayList(message)); validationUtil.addValidationErrorMessages(formComponent, entity, messagesHolder); verify(entity).addError(existingField, TRANSLATION_KEY); } @Test public final void shouldAddValidationErrorToWholeEntityIfFieldDoesNotExist() { DataDefinition dataDefinition = mockDataDefinition(Lists.<FieldDefinition> newArrayList()); given(entity.getDataDefinition()).willReturn(dataDefinition); given(formComponent.getEntity()).willReturn(entity); Entity message = mockValidationErrorMsg("notExistingField", false, TRANSLATION_KEY); given(messagesHolder.getAllMessages()).willReturn(Lists.newArrayList(message)); validationUtil.addValidationErrorMessages(formComponent, entity, messagesHolder); verify(entity, Mockito.never()).addError(Mockito.any(FieldDefinition.class), Mockito.eq(TRANSLATION_KEY)); verify(entity).addGlobalError(TRANSLATION_KEY, false); } @Test public final void shouldAddValidationErrorToWholeEntityIfFieldIsEmpty() { DataDefinition dataDefinition = mockDataDefinition(Lists.<FieldDefinition> newArrayList()); given(entity.getDataDefinition()).willReturn(dataDefinition); given(formComponent.getEntity()).willReturn(entity); Entity message = mockValidationErrorMsg("", false, TRANSLATION_KEY); given(messagesHolder.getAllMessages()).willReturn(Lists.newArrayList(message)); validationUtil.addValidationErrorMessages(formComponent, entity, messagesHolder); verify(entity, Mockito.never()).addError(Mockito.any(FieldDefinition.class), Mockito.eq(TRANSLATION_KEY)); verify(entity).addGlobalError(TRANSLATION_KEY, false); } @Test public final void shouldAddValidationErrorToWholeEntityIfFieldIsNull() { DataDefinition dataDefinition = mockDataDefinition(Lists.<FieldDefinition> newArrayList()); given(entity.getDataDefinition()).willReturn(dataDefinition); given(formComponent.getEntity()).willReturn(entity); Entity message = mockValidationErrorMsg(null, false, TRANSLATION_KEY); given(messagesHolder.getAllMessages()).willReturn(Lists.newArrayList(message)); validationUtil.addValidationErrorMessages(formComponent, entity, messagesHolder); verify(entity, Mockito.never()).addError(Mockito.any(FieldDefinition.class), Mockito.eq(TRANSLATION_KEY)); verify(entity).addGlobalError(TRANSLATION_KEY, false); }
AbstractStateChangeDescriber implements StateChangeEntityDescriber { @Override public void checkFields() { DataDefinition dataDefinition = getDataDefinition(); List<String> fieldNames = Lists.newArrayList(getOwnerFieldName(), getSourceStateFieldName(), getTargetStateFieldName(), getStatusFieldName(), getMessagesFieldName(), getPhaseFieldName(), getDateTimeFieldName(), getShiftFieldName(), getWorkerFieldName()); Set<String> uniqueFieldNames = Sets.newHashSet(fieldNames); checkState(fieldNames.size() == uniqueFieldNames.size(), "Describer methods should return unique field names."); Set<String> existingFieldNames = dataDefinition.getFields().keySet(); checkState(existingFieldNames.containsAll(uniqueFieldNames), "DataDefinition for " + dataDefinition.getPluginIdentifier() + '.' + dataDefinition.getName() + " does not have all fields with name specified by this desciber."); } @Override String getSourceStateFieldName(); @Override String getTargetStateFieldName(); @Override String getStatusFieldName(); @Override String getMessagesFieldName(); @Override String getPhaseFieldName(); @Override String getDateTimeFieldName(); @Override String getShiftFieldName(); @Override String getWorkerFieldName(); @Override String getOwnerStateFieldName(); @Override String getOwnerStateChangesFieldName(); @Override void checkFields(); }
@Test public final void shouldCheckFieldsPass() { try { testStateChangeDescriber.checkFields(); } catch (IllegalStateException e) { fail(); } } @Test public final void shouldCheckFieldsThrowExceptionIfAtLeastOneFieldIsMissing() { dataDefFieldsSet.remove("sourceState"); try { testStateChangeDescriber.checkFields(); } catch (Exception e) { assertTrue(e instanceof IllegalStateException); } } @Test public final void shouldCheckFieldsThrowExceptionIfAtLeastOneFieldNameIsNotUnique() { BrokenTestStateChangeDescriber brokenTestStateChangeDescriber = new BrokenTestStateChangeDescriber(); try { brokenTestStateChangeDescriber.checkFields(); } catch (Exception e) { assertTrue(e instanceof IllegalStateException); } }
MatchingChangeoverNormsDetailsHooks { public void fillOrCleanFields(final ViewDefinitionState view) { FormComponent form = (FormComponent) view.getComponentByReference(L_FORM); if (form.getEntityId() == null) { listeners.clearField(view); listeners.changeStateEditButton(view, false); } else { Entity changeover = dataDefinitionService.get(LineChangeoverNormsConstants.PLUGIN_IDENTIFIER, LineChangeoverNormsConstants.MODEL_LINE_CHANGEOVER_NORMS).get(form.getEntityId()); listeners.fillField(view, changeover); listeners.changeStateEditButton(view, true); } } void setFieldsVisible(final ViewDefinitionState view); void fillOrCleanFields(final ViewDefinitionState view); }
@Test public void shouldFillOrCleanFieldsNormsNotFound() { given(form.getEntityId()).willReturn(null); hooks.fillOrCleanFields(view); verify(listeners).clearField(view); verify(listeners).changeStateEditButton(view, false); } @Test public void shouldFillOrCleanFieldsWhenNormsFound() { given(form.getEntityId()).willReturn(1L); given( dataDefinitionService.get(LineChangeoverNormsConstants.PLUGIN_IDENTIFIER, LineChangeoverNormsConstants.MODEL_LINE_CHANGEOVER_NORMS)).willReturn(changeoverDD); given(changeoverDD.get(1L)).willReturn(changeover); hooks.fillOrCleanFields(view); verify(listeners).fillField(view, changeover); verify(listeners).changeStateEditButton(view, true); }
Sha1Digest implements MessageDigest { public String calculate(final InputStream inputStream) throws IOException { logger.trace("Calculating message digest"); return DigestUtils.sha1Hex(inputStream); } String calculate(final InputStream inputStream); String calculate(final File file); String calculate(String path); boolean verify(String source); boolean verify(String source, String digest); void save(String source); }
@Test public void testCalculateInputStream() throws IOException { try (InputStream inputStream = getClass().getResourceAsStream("message.txt")) { Sha1Digest sha1Digest = new Sha1Digest(); String ret = sha1Digest.calculate(inputStream); assertEquals("The message digest do not match", MESSAGE_DIGEST, ret); } }
WorkerDataUtils { public static <T extends MaestroWorker> BinaryRateWriter writer(final File reportFolder, final T worker) throws IOException { assert worker != null : "Invalid worker type"; if (worker instanceof MaestroSenderWorker) { return new BinaryRateWriter(new File(reportFolder, "sender.dat"), FileHeader.WRITER_DEFAULT_SENDER); } if (worker instanceof MaestroReceiverWorker) { return new BinaryRateWriter(new File(reportFolder, "receiver.dat"), FileHeader.WRITER_DEFAULT_SENDER); } logger.error("Invalid worker class: {}", worker.getClass()); return null; } static BinaryRateWriter writer(final File reportFolder, final T worker); }
@Test public void testCreate() throws IOException { String path = this.getClass().getResource(".").getPath(); File reportDir = new File(path); try (BinaryRateWriter writer = WorkerDataUtils.writer(reportDir, new DummySender())) { assertNotNull("The writer should not be null", writer); assertEquals("The report path does not match", new File(reportDir, "sender.dat"), writer.reportFile()); } }
JmsOptions { public JmsOptions(final String url) { try { final URI uri = new URI(url); final URLQuery urlQuery = new URLQuery(uri); protocol = JMSProtocol.valueOf(urlQuery.getString("protocol", JMSProtocol.AMQP.name())); path = uri.getPath(); type = urlQuery.getString("type", "queue"); configuredLimitDestinations = urlQuery.getInteger("limitDestinations", 0); durable = urlQuery.getBoolean("durable", false); priority = urlQuery.getInteger("priority", 0); ttl = urlQuery.getLong("ttl", 0L); sessionMode = urlQuery.getInteger("sessionMode", Session.AUTO_ACKNOWLEDGE); batchAcknowledge = urlQuery.getInteger("batchAcknowledge", 0); connectionUrl = filterJMSURL(uri); } catch (Throwable t) { logger.warn("Something wrong happened while parsing arguments from url : {}", t.getMessage(), t); } } JmsOptions(final String url); JMSProtocol getProtocol(); long getTtl(); boolean isDurable(); int getSessionMode(); int getConfiguredLimitDestinations(); String getType(); int getPriority(); String getConnectionUrl(); String getPath(); int getBatchAcknowledge(); }
@Test public void testJmsOptions() { final String url = "amqps: JmsOptions jmsOptions = new JmsOptions(url); assertFalse("Expected durable to be false", jmsOptions.isDurable()); assertEquals("The connection URL does not match the expected one", "amqps: jmsOptions.getConnectionUrl()); }
JMSClient implements Client { public static String setupLimitDestinations(final String destinationName, final int limitDestinations, final int clientNumber) { String ret = destinationName; if (limitDestinations >= 1) { logger.debug("Client requested a client-specific limit to the number of destinations: {}", limitDestinations); final int destinationId = clientNumber % limitDestinations; ret = destinationName + '.' + destinationId; logger.info("Requested destination name after using client-specific limit to the number of destinations: {}", ret); return ret; } else { if (limitDestinations < 0) { throw new IllegalArgumentException("Negative number of limit destinations is invalid"); } logger.info("Requested destination name: {}", destinationName); } return ret; } int getNumber(); void setNumber(int number); JmsOptions getOpts(); @Override void start(); static String setupLimitDestinations(final String destinationName, final int limitDestinations, final int clientNumber); @Override void stop(); @Override void setUrl(String url); }
@Test public void testLimitDestinations() { final String requestedDestName = "test.unit.queue"; for (int i = 0; i < 5; i++) { String destinationName = JMSClient.setupLimitDestinations("test.unit.queue", 5, i); assertEquals("The destination name does not match the expected one", requestedDestName + "." + i, destinationName); } } @Test public void testDefaultLimitDestination() { final String requestedDestName = "test.unit.queue"; for (int i = 0; i < 5; i++) { String destinationName = JMSClient.setupLimitDestinations("test.unit.queue", 0, i); assertEquals("The destination name does not match the expected one", requestedDestName, destinationName); } }
StringUtils { public static String capitalize(final String string) { if (string != null && string.length() >= 2) { return string.substring(0, 1).toUpperCase() + string.substring(1); } else { return string; } } private StringUtils(); static String capitalize(final String string); }
@Test public void testCapitalize() { assertEquals("Username", StringUtils.capitalize("username")); assertEquals("u", StringUtils.capitalize("u")); assertEquals("Uu", StringUtils.capitalize("uu")); assertEquals(null, StringUtils.capitalize(null)); assertEquals("", StringUtils.capitalize("")); }
BinaryRateWriter implements RateWriter { @Override public void close() { try { flush(); fileChannel.close(); } catch (IOException e) { Logger logger = LoggerFactory.getLogger(BinaryRateWriter.class); logger.error(e.getMessage(), e); } } BinaryRateWriter(final File reportFile, final FileHeader fileHeader); @Override File reportFile(); void write(int metadata, long count, long timestamp); void flush(); @Override void close(); }
@Test public void testHeader() throws IOException { String path = this.getClass().getResource(".").getPath(); File reportFile = new File(path, "testHeader.dat"); try { BinaryRateWriter binaryRateWriter = new BinaryRateWriter(reportFile, FileHeader.WRITER_DEFAULT_SENDER); binaryRateWriter.close(); try (BinaryRateReader reader = new BinaryRateReader(reportFile)) { FileHeader fileHeader = reader.getHeader(); assertEquals(FileHeader.MAESTRO_FORMAT_NAME, fileHeader.getFormatName().trim()); assertEquals(FileHeader.CURRENT_FILE_VERSION, fileHeader.getFileVersion()); assertEquals(Constants.VERSION_NUMERIC, fileHeader.getMaestroVersion()); assertEquals(Role.SENDER, fileHeader.getRole()); } } finally { clean(reportFile); } }
BinaryRateWriter implements RateWriter { private void write() throws IOException { byteBuffer.flip(); while (byteBuffer.hasRemaining()) { fileChannel.write(byteBuffer); } byteBuffer.flip(); byteBuffer.clear(); } BinaryRateWriter(final File reportFile, final FileHeader fileHeader); @Override File reportFile(); void write(int metadata, long count, long timestamp); void flush(); @Override void close(); }
@Test(expected = InvalidRecordException.class) public void testHeaderWriteRecordsNonSequential() throws IOException { String path = this.getClass().getResource(".").getPath(); File reportFile = new File(path, "testHeaderWriteRecordsNonSequential.dat"); try (BinaryRateWriter binaryRateWriter = new BinaryRateWriter(reportFile, FileHeader.WRITER_DEFAULT_SENDER)) { EpochMicroClock clock = EpochClocks.exclusiveMicro(); long total = TimeUnit.DAYS.toSeconds(1); long now = clock.microTime(); for (int i = 0; i < total; i++) { binaryRateWriter.write(0, i + 1, now); now -= TimeUnit.SECONDS.toMicros(1); } } finally { clean(reportFile); } }
BinaryRateUpdater implements AutoCloseable { public static void joinFile(final BinaryRateUpdater binaryRateUpdater, final File reportFile1) throws IOException { try (BinaryRateReader reader = new BinaryRateReader(reportFile1)) { if (!binaryRateUpdater.isOverlay()) { FileHeader header = binaryRateUpdater.getFileHeader(); if (header == null) { binaryRateUpdater.updateHeader(reader.getHeader()); } } RateEntry entry = reader.readRecord(); long index = 0; while (entry != null) { binaryRateUpdater.update(entry, index); entry = reader.readRecord(); index++; } } } BinaryRateUpdater(final File reportFile); BinaryRateUpdater(final File reportFile, boolean overlay); FileHeader getFileHeader(); void updateHeader(final FileHeader header); void update(RateEntry newer, long index); void flush(); @Override void close(); static void joinFile(final BinaryRateUpdater binaryRateUpdater, final File reportFile1); static BinaryRateUpdater get(Role role, File path); }
@Test public void testJoinFile() throws IOException { String path = this.getClass().getResource(".").getPath(); File reportFile = new File(path, "sender.dat"); File baseFile = new File(path, "sender-0.dat"); FileUtils.copyFile(baseFile, reportFile); try (BinaryRateUpdater binaryRateUpdater = new BinaryRateUpdater(reportFile)) { File reportFile1 = new File(path, "sender-1.dat"); BinaryRateUpdater.joinFile(binaryRateUpdater, reportFile1); File reportFile2 = new File(path, "sender-2.dat"); BinaryRateUpdater.joinFile(binaryRateUpdater, reportFile2); try (BinaryRateReader reader = new BinaryRateReader(reportFile)) { FileHeader fileHeader = reader.getHeader(); assertEquals(FileHeader.MAESTRO_FORMAT_NAME, fileHeader.getFormatName().trim()); assertEquals(FileHeader.CURRENT_FILE_VERSION, fileHeader.getFileVersion()); assertEquals(138, fileHeader.getMaestroVersion()); assertEquals(Role.SENDER, fileHeader.getRole()); long count = 0; RateEntry entry = reader.readRecord(); while (entry != null) { count++; assertEquals("Unexpected value", entry.getCount(), count * 3); entry = reader.readRecord(); } long total = 86400; assertEquals("The number of records don't match", total, count); } } finally { clean(reportFile); } }
PropertyUtils { public static void loadProperties(final File testProperties, Map<String, Object> context) { if (testProperties.exists()) { Properties prop = new Properties(); try (FileInputStream in = new FileInputStream(testProperties)) { prop.load(in); prop.forEach((key, value) -> addToContext(context, key, value)); } catch (FileNotFoundException e) { logger.error("File not found error: {}", e.getMessage(), e); } catch (IOException e) { logger.error("Input/output error: {}", e.getMessage(), e); } } else { logger.debug("There are no properties file at {}", testProperties.getPath()); } } private PropertyUtils(); static void loadProperties(final File testProperties, Map<String, Object> context); }
@Test public void testLoadProperties() { final Map<String, Object> context = new HashMap<>(); final String path = this.getClass().getResource("test-with-query-params.properties").getPath(); final File propertiesFile = new File(path); PropertyUtils.loadProperties(propertiesFile, context); assertEquals("10", context.get("fcl")); assertEquals("testApi", context.get("apiName")); assertEquals("amqp: assertEquals("0.9", context.get("apiVersion")); assertEquals("30", context.get("limitDestinations")); assertEquals("100", context.get("duration")); assertEquals("256", context.get("messageSize")); assertEquals("3", context.get("parallelCount")); assertEquals("true", context.get("variableSize")); assertEquals("value1", context.get("param1")); assertEquals("value2", context.get("param2")); assertEquals("value3", context.get("param3")); } @Test public void testNotFailOnNonExistentFile() { final Map<String, Object> context = new HashMap<>(); final File propertiesFile = new File("does not exist"); PropertyUtils.loadProperties(propertiesFile, context); } @Test public void testLoadPropertiesSetEncrypted() { final Map<String, Object> context = new HashMap<>(); final String path = this.getClass().getResource("test-with-query-params-encrypted-url.properties").getPath(); final File propertiesFile = new File(path); PropertyUtils.loadProperties(propertiesFile, context); assertEquals("10", context.get("fcl")); assertEquals("testApi", context.get("apiName")); assertEquals("amqps: assertEquals("0.9", context.get("apiVersion")); assertEquals("30", context.get("limitDestinations")); assertEquals("100", context.get("duration")); assertEquals("256", context.get("messageSize")); assertEquals("3", context.get("parallelCount")); assertEquals("true", context.get("variableSize")); assertEquals("value1", context.get("param1")); assertEquals("value2", context.get("param2")); assertEquals("value3", context.get("param3")); assertEquals("true", context.get("encrypted")); } @Test public void testLoadPropertiesInvalidUrl() { final Map<String, Object> context = new HashMap<>(); final String path = this.getClass().getResource("test-with-invalid-url.properties").getPath(); final File propertiesFile = new File(path); PropertyUtils.loadProperties(propertiesFile, context); assertEquals("10", context.get("fcl")); assertEquals("testApi", context.get("apiName")); assertEquals("0.9", context.get("apiVersion")); assertEquals("30", context.get("limitDestinations")); assertEquals("100", context.get("duration")); assertEquals("256", context.get("messageSize")); assertEquals("3", context.get("parallelCount")); assertEquals("true", context.get("variableSize")); }
Sha1Digest implements MessageDigest { public boolean verify(String source) throws IOException { try (InputStream stream = new FileInputStream(source + "." + HASH_NAME)) { final String digest = IOUtils.toString(stream, Charset.defaultCharset()).trim(); return verify(source, digest); } } String calculate(final InputStream inputStream); String calculate(final File file); String calculate(String path); boolean verify(String source); boolean verify(String source, String digest); void save(String source); }
@Test public void testVerify() throws IOException { Sha1Digest sha1Digest = new Sha1Digest(); boolean ret = sha1Digest.verify(MESSAGE_FILE, MESSAGE_DIGEST); assertTrue("The message digest do not match", ret); }
DurationDrain extends DurationCount { @Override public boolean canContinue(TestProgress progress) { long count = progress.messageCount(); return !staleChecker.isStale(count); } DurationDrain(); @Override boolean canContinue(TestProgress progress); static final String DURATION_DRAIN_FORMAT; }
@Test public void testCanContinue() { DurationDrain durationDrain = new DurationDrain(); assertEquals(-1, durationDrain.getNumericDuration()); DurationCountTest.DurationCountTestProgress progress = new DurationCountTest.DurationCountTestProgress(); for (int i = 0; i < 10; i++) { assertTrue(durationDrain.canContinue(progress)); progress.increment(); } for (int i = 0; i < 9; i++) { assertTrue("Cannot continue with current count of " + progress.messageCount(), durationDrain.canContinue(progress)); } assertFalse(durationDrain.canContinue(progress)); progress.increment(); assertTrue(durationDrain.canContinue(progress)); }
DurationTime implements TestDuration { @Override public boolean canContinue(final TestProgress snapshot) { final long currentDuration = snapshot.elapsedTime(outputTimeUnit); return currentDuration < expectedDuration; } DurationTime(final String timeSpec); @Override boolean canContinue(final TestProgress snapshot); @Override long getNumericDuration(); @Override TestDuration getWarmUpDuration(); @Override TestDuration getCoolDownDuration(); String toString(); @Override String durationTypeName(); }
@Test(timeout = 15000) public void testCanContinue() throws DurationParseException { DurationTime durationTime = new DurationTime("5s"); DurationTimeProgress progress = new DurationTimeProgress(System.currentTimeMillis()); assertTrue(durationTime.canContinue(progress)); try { Thread.sleep(5000); } catch (InterruptedException e) { fail("Interrupted while waiting for the test to timeout"); } assertFalse(durationTime.canContinue(progress)); assertEquals("time", durationTime.durationTypeName()); assertEquals(5, durationTime.getNumericDuration()); assertEquals(durationTime.getCoolDownDuration(), durationTime.getWarmUpDuration()); }
DurationTime implements TestDuration { @Override public long getNumericDuration() { return expectedDuration; } DurationTime(final String timeSpec); @Override boolean canContinue(final TestProgress snapshot); @Override long getNumericDuration(); @Override TestDuration getWarmUpDuration(); @Override TestDuration getCoolDownDuration(); String toString(); @Override String durationTypeName(); }
@Test public void testExpectedDuration() throws DurationParseException { assertEquals(5, new DurationTime("5s").getNumericDuration()); assertEquals(300, new DurationTime("5m").getNumericDuration()); assertEquals(3900, new DurationTime("1h5m").getNumericDuration()); }
DurationTime implements TestDuration { public String toString() { return timeSpec; } DurationTime(final String timeSpec); @Override boolean canContinue(final TestProgress snapshot); @Override long getNumericDuration(); @Override TestDuration getWarmUpDuration(); @Override TestDuration getCoolDownDuration(); String toString(); @Override String durationTypeName(); }
@Test public void testToStringRetainFormat() throws DurationParseException { assertEquals("5s", new DurationTime("5s").toString()); assertEquals("5m", new DurationTime("5m").toString()); assertEquals("1h5m", new DurationTime("1h5m").toString()); }
DurationCount implements TestDuration { @Override public boolean canContinue(final TestProgress progress) { return progress.messageCount() < count; } DurationCount(final String durationSpec); DurationCount(long count); @Override boolean canContinue(final TestProgress progress); @Override long getNumericDuration(); @Override TestDuration getWarmUpDuration(); @Override TestDuration getCoolDownDuration(); String toString(); @Override String durationTypeName(); static final long WARM_UP_COUNT; }
@Test public void testCanContinue() { DurationCount durationCount = new DurationCount("10"); assertEquals(10L, durationCount.getNumericDuration()); DurationCountTestProgress progress = new DurationCountTestProgress(); for (int i = 0; i < durationCount.getNumericDuration(); i++) { assertTrue(durationCount.canContinue(progress)); progress.increment(); } assertFalse(durationCount.canContinue(progress)); progress.increment(); assertFalse(durationCount.canContinue(progress)); assertEquals("count", durationCount.durationTypeName()); assertEquals("10", durationCount.toString()); assertEquals(durationCount.getCoolDownDuration(), durationCount.getWarmUpDuration()); }
WorkerUtils { public static long getExchangeInterval(final long rate) { return rate > 0 ? (1_000_000_000L / rate) : 0; } private WorkerUtils(); static long getExchangeInterval(final long rate); static long waitNanoInterval(final long expectedFireTime, final long intervalInNanos); }
@Test public void testRate() { assertEquals(0, WorkerUtils.getExchangeInterval(0)); assertEquals(20000, WorkerUtils.getExchangeInterval(50000)); }
XunitWriter { public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } XunitWriter(); void saveToXML(final File outputFile, TestSuites testSuites); }
@Test public void testSaveXmlSuccess() { String path = this.getClass().getResource("/").getPath() + "xunit.success.xml"; TestCase warmUpTc = new TestCase(); warmUpTc.setAssertions(1); warmUpTc.setClassName("singlepoint.FixedRate"); warmUpTc.setName("AMQP-s-1024-c-30-ld-10-durable-false"); warmUpTc.setTime(Duration.ofSeconds(5)); TestCase testRun = new TestCase(); testRun.setAssertions(1); testRun.setClassName("singlepoint.FixedRate"); testRun.setName("AMQP-s-1024-c-100-ld-10-durable-false"); testRun.setTime(Duration.ofSeconds(300)); TestSuite testSuite = new TestSuite(); testSuite.setId("0"); testSuite.setTests(1); testSuite.getTestCaseList().add(warmUpTc); testSuite.getTestCaseList().add(testRun); TestSuites testSuites = new TestSuites(); testSuites.getTestSuiteList().add(testSuite); XunitWriter xunitWriter = new XunitWriter(); File outFile = new File(path); xunitWriter.saveToXML(outFile, testSuites); assertTrue(outFile.exists()); } @Test public void testSaveXmlWithFailure() { String path = this.getClass().getResource("/").getPath() + "xunit.failure.xml"; TestCase warmUpTc = new TestCase(); warmUpTc.setAssertions(1); warmUpTc.setClassName("singlepoint.FixedRate"); warmUpTc.setName("AMQP-s-1024-c-30-ld-10-durable-false"); warmUpTc.setTime(Duration.ofSeconds(5)); TestCase testRun = new TestCase(); testRun.setAssertions(1); testRun.setClassName("singlepoint.FixedRate"); testRun.setName("AMQP-s-1024-c-100-ld-10-durable-false"); testRun.setTime(Duration.ofSeconds(300)); Failure failure = new Failure(); failure.setMessage("AMQP Framing Error"); failure.setContent("SUT disconnected"); testRun.setFailure(failure); TestSuite testSuite = new TestSuite(); testSuite.setId("0"); testSuite.setTests(1); testSuite.getTestCaseList().add(warmUpTc); testSuite.getTestCaseList().add(testRun); TestSuites testSuites = new TestSuites(); testSuites.getTestSuiteList().add(testSuite); XunitWriter xunitWriter = new XunitWriter(); File outFile = new File(path); xunitWriter.saveToXML(outFile, testSuites); assertTrue(outFile.exists()); } @Test public void testSaveXmlWithError() { String path = this.getClass().getResource("/").getPath() + "xunit.error.xml"; TestCase warmUpTc = new TestCase(); warmUpTc.setAssertions(1); warmUpTc.setClassName("singlepoint.FixedRate"); warmUpTc.setName("AMQP-s-1024-c-30-ld-10-durable-false"); warmUpTc.setTime(Duration.ofSeconds(5)); TestCase testRun = new TestCase(); testRun.setAssertions(1); testRun.setClassName("singlepoint.FixedRate"); testRun.setName("AMQP-s-1024-c-100-ld-10-durable-false"); testRun.setTime(Duration.ofSeconds(300)); Error error = new Error(); error.setMessage("java.lang.NullPointerException"); error.setContent("Maestro worker failed: java.lang.NullPointerException"); testRun.setError(error); TestSuite testSuite = new TestSuite(); testSuite.setId("0"); testSuite.setTests(1); testSuite.getTestCaseList().add(warmUpTc); testSuite.getTestCaseList().add(testRun); TestSuites testSuites = new TestSuites(); testSuites.getTestSuiteList().add(testSuite); XunitWriter xunitWriter = new XunitWriter(); File outFile = new File(path); xunitWriter.saveToXML(outFile, testSuites); assertTrue(outFile.exists()); } @Test public void testSaveXmlSuccessAndProperties() { String path = this.getClass().getResource("/").getPath() + "xunit.success.with.properties.xml"; TestCase warmUpTc = new TestCase(); warmUpTc.setAssertions(1); warmUpTc.setClassName("singlepoint.FixedRate"); warmUpTc.setName("AMQP-s-1024-c-30-ld-10-durable-false"); warmUpTc.setTime(Duration.ofSeconds(5)); TestCase testRun = new TestCase(); testRun.setAssertions(1); testRun.setClassName("singlepoint.FixedRate"); testRun.setName("AMQP-s-1024-c-100-ld-10-durable-false"); testRun.setTime(Duration.ofSeconds(300)); TestSuite testSuite = new TestSuite(); testSuite.setId("0"); testSuite.setTests(1); testSuite.getTestCaseList().add(warmUpTc); testSuite.getTestCaseList().add(testRun); TestSuites testSuites = new TestSuites(); testSuites.getTestSuiteList().add(testSuite); Property messageSize = new Property(); messageSize.setValue("1024"); messageSize.setName("size"); Property pairs = new Property(); pairs.setValue("100"); pairs.setName("pairs"); testSuites.getProperties().getPropertyList().add(messageSize); testSuites.getProperties().getPropertyList().add(pairs); XunitWriter xunitWriter = new XunitWriter(); File outFile = new File(path); xunitWriter.saveToXML(outFile, testSuites); assertTrue(outFile.exists()); }
Sha1Digest implements MessageDigest { public void save(String source) throws IOException { final String digest = calculate(source); final File file = new File(source + "." + HASH_NAME); if (file.exists()) { if (!file.delete()) { throw new IOException("Unable to delete an existent file: " + file.getPath()); } } else { if (!file.createNewFile()) { throw new IOException("Unable to create a new file: " + file.getPath()); } } try (FileOutputStream output = new FileOutputStream(file)) { IOUtils.write(digest, output, Charset.defaultCharset()); } } String calculate(final InputStream inputStream); String calculate(final File file); String calculate(String path); boolean verify(String source); boolean verify(String source, String digest); void save(String source); }
@Test public void testSave() throws IOException { Sha1Digest sha1Digest = new Sha1Digest(); sha1Digest.save(MESSAGE_FILE); sha1Digest.verify(MESSAGE_FILE); }
URLUtils { public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } private URLUtils(); static String sanitizeURL(final String url); static String getHostnameFromURL(final String string); static String rewritePath(final String inputUrl, final String string); }
@Test public void testURLPathRewrite() { String originalUrl = "amqp: String expectedUrl = "amqp: String ret = URLUtils.rewritePath(originalUrl, "worker"); assertEquals(expectedUrl, ret); } @Test public void testURLPathRewriteWithUser() { String originalUrl = "amqp: String expectedUrl = "amqp: String ret = URLUtils.rewritePath(originalUrl, "worker"); assertEquals(expectedUrl, ret); } @Test public void testURLPathRewriteWithQuery() { String originalUrl = "amqp: String expectedUrl = "amqp: String ret = URLUtils.rewritePath(originalUrl, "worker"); assertEquals(expectedUrl, ret); } @Test public void testURLPathRewriteWithUserWithQuery() { String originalUrl = "amqp: String expectedUrl = "amqp: String ret = URLUtils.rewritePath(originalUrl, "worker"); assertEquals(expectedUrl, ret); }
ContentStrategyFactory { public static ContentStrategy parse(final String sizeSpec) { ContentStrategy ret; if (sizeSpec.startsWith("~")) { ret = new VariableSizeContent(sizeSpec); } else { ret = new FixedSizeContent(sizeSpec); } return ret; } private ContentStrategyFactory(); static ContentStrategy parse(final String sizeSpec); }
@Test public void testParse() { assertTrue(ContentStrategyFactory.parse("100") instanceof FixedSizeContent); assertTrue(ContentStrategyFactory.parse("~100") instanceof VariableSizeContent); }
VariableSizeContent implements ContentStrategy { @Override public ByteBuffer prepareContent() { final int currentLimit = ThreadLocalRandom.current().nextInt(this.lowerLimitInclusive, this.upperLimitExclusive); buffer.clear(); buffer.limit(currentLimit); return buffer; } VariableSizeContent(int size); VariableSizeContent(final String sizeSpec); int minSize(); int maxSize(); @Override ByteBuffer prepareContent(); }
@Test public void testPrepareContent() { VariableSizeContent content = new VariableSizeContent(100); assertEquals(96, content.minSize()); assertEquals(105, content.maxSize()); for (int i = 0; i < 100; i++) { ByteBuffer buffer = content.prepareContent(); final int length = buffer.remaining(); final int position = buffer.position(); final int offset = buffer.arrayOffset() + position; assertTrue("Generated a buffer starting at offset = " + offset + " with length = " + length + " is invalid", content.minSize() <= length); assertTrue("Generated a buffer starting at offset = " + offset + " with length = " + length + " is invalid", content.maxSize() >= length); } }
FixedSizeContent implements ContentStrategy { @Override public ByteBuffer prepareContent() { return buffer; } FixedSizeContent(int size); FixedSizeContent(final String sizeSpec); @Override ByteBuffer prepareContent(); }
@Test public void testPepareContent() { FixedSizeContent content = new FixedSizeContent(100); for (int i = 0; i < 100; i++) { ByteBuffer buffer = content.prepareContent(); final int length = buffer.remaining(); assertEquals(100, length); } }
MessageSize { public static String variable(long value) { return "~" + Long.toString(value); } private MessageSize(); static String variable(long value); static String fixed(long value); static boolean isVariable(final String sizeSpec); static int toSizeFromSpec(final String sizeSpec); }
@Test public void testVariable() { assertEquals("~1024", MessageSize.variable(1024)); }
WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); static boolean isCleanExit(WorkerStateInfo wsi); }
@Test public void testCleanExitOnDefault() { WorkerStateInfo wsi = new WorkerStateInfo(); assertTrue(WorkerStateInfoUtil.isCleanExit(wsi)); assertNotNull(wsi.getExitStatus()); } @Test public void testCleanExitOnStopped() { WorkerStateInfo wsi = new WorkerStateInfo(); wsi.setState(false, WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED, null); assertTrue(WorkerStateInfoUtil.isCleanExit(wsi)); assertNotNull(wsi.getExitStatus()); } @Test public void testCleanExitOnSuccess() { WorkerStateInfo wsi = new WorkerStateInfo(); wsi.setState(false, WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS, null); assertTrue(WorkerStateInfoUtil.isCleanExit(wsi)); assertNotNull(wsi.getExitStatus()); } @Test public void testFailedExitOnFailure() { WorkerStateInfo wsi = new WorkerStateInfo(); wsi.setState(false, WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_FAILURE, null); assertFalse(WorkerStateInfoUtil.isCleanExit(wsi)); assertNotNull(wsi.getExitStatus()); } @Test public void testCleanExitOnStoppedRunning() { WorkerStateInfo wsi = new WorkerStateInfo(); wsi.setState(true, WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED, null); assertFalse(WorkerStateInfoUtil.isCleanExit(wsi)); assertNull(wsi.getExitStatus()); } @Test public void testCleanExitOnSuccessRunning() { WorkerStateInfo wsi = new WorkerStateInfo(); wsi.setState(true, WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS, null); assertFalse(WorkerStateInfoUtil.isCleanExit(wsi)); assertNull(wsi.getExitStatus()); } @Test public void testFailedExitOnFailureRunning() { WorkerStateInfo wsi = new WorkerStateInfo(); wsi.setState(true, WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_FAILURE, null); assertFalse(WorkerStateInfoUtil.isCleanExit(wsi)); assertNull(wsi.getExitStatus()); }
MessageSize { public static String fixed(long value) { return Long.toString(value); } private MessageSize(); static String variable(long value); static String fixed(long value); static boolean isVariable(final String sizeSpec); static int toSizeFromSpec(final String sizeSpec); }
@Test public void testFixed() { assertEquals("1024", MessageSize.fixed(1024)); }
MessageSize { public static boolean isVariable(final String sizeSpec) { return sizeSpec.startsWith("~"); } private MessageSize(); static String variable(long value); static String fixed(long value); static boolean isVariable(final String sizeSpec); static int toSizeFromSpec(final String sizeSpec); }
@Test public void isVariable() { assertTrue(MessageSize.isVariable("~1024")); assertFalse(MessageSize.isVariable("1024")); }
MessageSize { public static int toSizeFromSpec(final String sizeSpec) { if (isVariable(sizeSpec)) { return Integer.parseInt(sizeSpec.replace("~", "")); } return Integer.parseInt(sizeSpec); } private MessageSize(); static String variable(long value); static String fixed(long value); static boolean isVariable(final String sizeSpec); static int toSizeFromSpec(final String sizeSpec); }
@Test public void toSizeFromSpec() { assertEquals(1024, MessageSize.toSizeFromSpec("~1024")); }
LangUtils { public static <T extends Closeable> void closeQuietly(T object) { if (object != null) { try { object.close(); } catch (IOException ignored) { } } } private LangUtils(); static void closeQuietly(T object); }
@Test public void closeQuietly() { LangUtils.closeQuietly(null); MockCloseeable mock = new MockCloseeable(); LangUtils.closeQuietly(mock); assertTrue(mock.closeCalled); }
URLQuery { public boolean getBoolean(final String name, boolean defaultValue) { String value = getString(name, null); if (value == null) { return defaultValue; } if (value.equalsIgnoreCase("true")) { return true; } else { if (value.equalsIgnoreCase("false")) { return false; } } return defaultValue; } URLQuery(final String uri); URLQuery(URI uri); String getString(final String name, final String defaultValue); boolean getBoolean(final String name, boolean defaultValue); Integer getInteger(final String name, final Integer defaultValue); Long getLong(final String name, final Long defaultValue); @SuppressWarnings("unused") Map<String, String> getParams(); int count(); }
@Test public void testQueryWithFalse() throws Exception { String url = "amqp: URLQuery urlQuery = new URLQuery(new URI(url)); assertFalse(urlQuery.getBoolean("value1", true)); assertTrue(urlQuery.getBoolean("value2", false)); }
URLQuery { public Long getLong(final String name, final Long defaultValue) { String value = getString(name, null); if (value == null) { return defaultValue; } return Long.parseLong(value); } URLQuery(final String uri); URLQuery(URI uri); String getString(final String name, final String defaultValue); boolean getBoolean(final String name, boolean defaultValue); Integer getInteger(final String name, final Integer defaultValue); Long getLong(final String name, final Long defaultValue); @SuppressWarnings("unused") Map<String, String> getParams(); int count(); }
@Test public void testQueryWithLong() throws Exception { String url = "amqp: URLQuery urlQuery = new URLQuery(new URI(url)); assertEquals(1234L, (long) urlQuery.getLong("value1", 0L)); }
ReportDao extends AbstractDao { public void insert(final Report report) { runEmptyInsert( "insert into report(test_id, test_number, test_name, test_script, test_host, test_host_role, " + "test_result, test_result_message, location, aggregated, test_description, test_comments, " + "valid, retired, retired_date, test_date) " + "values(:testId, :testNumber, :testName, :testScript, :testHost, :testHostRole, :testResult, " + ":testResultMessage, :location, :aggregated, :testDescription, :testComments, :valid, " + ":retired, :retiredDate, :testDate)", report); } ReportDao(); ReportDao(TemplateBuilder tp); void insert(final Report report); int update(final Report report); List<Report> fetch(); List<Report> fetchAll(); List<Report> fetchAllAggregated(); Report fetch(int reportId); List<Report> fetch(int testId, int testNumber); List<Report> fetchByTestId(int testId); Report fetchAggregated(int testId, int testNumber); List<ReportAggregationInfo> aggregationInfo(); int getLastTestId(); int getNextTestId(); int getLastTestNumber(int testId); int getNextTestNumber(int testId); }
@Test public void testInsert() { Report report = new Report(); report.setTestHost("localhost"); report.setTestHostRole(HostTypes.SENDER_HOST_TYPE); report.setTestName("unit-test"); report.setTestNumber(1); report.setTestId(1); report.setLocation(this.getClass().getResource(".").getPath()); report.setTestResult(ResultStrings.SUCCESS); report.setTestScript("undefined"); report.setTestDate(Date.from(Instant.now())); dao.insert(report); }
ReportDao extends AbstractDao { public List<Report> fetchAll() throws DataNotFoundException { return runQueryMany("select * from report", new BeanPropertyRowMapper<>(Report.class)); } ReportDao(); ReportDao(TemplateBuilder tp); void insert(final Report report); int update(final Report report); List<Report> fetch(); List<Report> fetchAll(); List<Report> fetchAllAggregated(); Report fetch(int reportId); List<Report> fetch(int testId, int testNumber); List<Report> fetchByTestId(int testId); Report fetchAggregated(int testId, int testNumber); List<ReportAggregationInfo> aggregationInfo(); int getLastTestId(); int getNextTestId(); int getLastTestNumber(int testId); int getNextTestNumber(int testId); }
@Test public void testFetchAll() throws DataNotFoundException { List<Report> reports = dao.fetch(); assertTrue("The database should not be empty", reports.size() > 0); long aggregatedCount = reports.stream().filter(Report::isAggregated).count(); long expectedAggCount = 0; assertEquals("Aggregated reports should not be displayed by default", expectedAggCount, aggregatedCount); }
ReportDao extends AbstractDao { public List<Report> fetch() throws DataNotFoundException { return runQueryMany("select * from report where aggregated = false and valid = true order by report_id desc", new BeanPropertyRowMapper<>(Report.class)); } ReportDao(); ReportDao(TemplateBuilder tp); void insert(final Report report); int update(final Report report); List<Report> fetch(); List<Report> fetchAll(); List<Report> fetchAllAggregated(); Report fetch(int reportId); List<Report> fetch(int testId, int testNumber); List<Report> fetchByTestId(int testId); Report fetchAggregated(int testId, int testNumber); List<ReportAggregationInfo> aggregationInfo(); int getLastTestId(); int getNextTestId(); int getLastTestNumber(int testId); int getNextTestNumber(int testId); }
@Test public void testFetchById() throws DataNotFoundException { List<Report> reports = dao.fetch(2, 1); assertTrue("There should be at least 3 records for the given ID", reports.size() >= 3); long aggregatedCount = reports.stream().filter(Report::isAggregated).count(); long expectedAggCount = 0; assertEquals("Aggregated reports should not be displayed by default", expectedAggCount, aggregatedCount); }
ReportDao extends AbstractDao { public List<ReportAggregationInfo> aggregationInfo() throws DataNotFoundException { return runQueryMany("SELECT test_id,test_number,sum(aggregated) AS aggregations FROM report " + "GROUP BY test_id,test_number ORDER BY test_id desc", new BeanPropertyRowMapper<>(ReportAggregationInfo.class)); } ReportDao(); ReportDao(TemplateBuilder tp); void insert(final Report report); int update(final Report report); List<Report> fetch(); List<Report> fetchAll(); List<Report> fetchAllAggregated(); Report fetch(int reportId); List<Report> fetch(int testId, int testNumber); List<Report> fetchByTestId(int testId); Report fetchAggregated(int testId, int testNumber); List<ReportAggregationInfo> aggregationInfo(); int getLastTestId(); int getNextTestId(); int getLastTestNumber(int testId); int getNextTestNumber(int testId); }
@Test public void testAggregationInfo() throws DataNotFoundException { List<ReportAggregationInfo> aggregationInfos = dao.aggregationInfo(); long expectedAggregatedCount = 2; assertEquals("Unexpected amount of aggregated records", expectedAggregatedCount, aggregationInfos.size()); }
InterconnectInfoConverter { public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map); }
@SuppressWarnings("unchecked") @Test public void parseReceivedMessage() { InterconnectInfoConverter converter = new InterconnectInfoConverter(); Map<String, Object> fakeMap = buildTestMap(); List<Map<String, Object>> ret = converter.parseReceivedMessage(fakeMap); assertNotNull(ret); assertEquals(3, ret.size()); Map<String, Object> map1 = ret.get(0); assertNotNull(map1); assertEquals(2, map1.size()); assertEquals(map1.get("attribute1"), "value1.1"); assertEquals(map1.get("attribute2"), "value1.2"); Map<String, Object> map2 = ret.get(1); assertNotNull(map2); assertEquals(2, map2.size()); assertEquals(map2.get("attribute1"), "value2.1"); assertEquals(map2.get("attribute2"), "value2.2"); Map<String, Object> map3 = ret.get(2); assertNotNull(map3); assertEquals(2, map3.size()); assertEquals(map3.get("attribute1"), "value3.1"); assertEquals(map3.get("attribute2"), "value3.2"); } @Test public void parseReceivedMessageEmptyMap() { InterconnectInfoConverter converter = new InterconnectInfoConverter(); List<Map<String, Object>> ret = converter.parseReceivedMessage(new HashMap<String, Object>()); assertNotNull(ret); assertEquals(0, ret.size()); } @Test public void parseReceivedMessageInvalidAttributeNames() { InterconnectInfoConverter converter = new InterconnectInfoConverter(); List<Map<String, Object>> ret = converter.parseReceivedMessage(buildInvalidMap()); assertNotNull(ret); assertEquals(0, ret.size()); } @Test public void parseReceivedMessageWithEmptyLists() { InterconnectInfoConverter converter = new InterconnectInfoConverter(); List<Map<String, Object>> ret = converter.parseReceivedMessage(buildMapWithEmptyLists()); assertNotNull(ret); assertEquals(0, ret.size()); }