method2testcases
stringlengths 118
6.63k
|
---|
### Question:
OMIManagerImpl implements OMIManager, ApplicationContextAware { public SMSMessageFormatter createMessageFormatter() { try{ return (SMSMessageFormatter)context.getBean("messageFormatter"); } catch(Exception ex){ logger.error("SMSMessageFormatter creation failed", ex); return null; } } void setApplicationContext(ApplicationContext applicationContext); OMIService createOMIService(); MessageStoreManager createMessageStoreManager(); SMSMessageFormatter createMessageFormatter(); }### Answer:
@Test public void testCreateMessageFormatter() { System.out.println("createMessageFormatter"); SMSMessageFormatter result = omiManager.createMessageFormatter(); assertNotNull(result); } |
### Question:
MessageStoreManagerImpl implements MessageStoreManager, ApplicationContextAware { public GatewayRequest constructMessage(MessageRequest messageRequest, Language defaultLang) { GatewayRequest gatewayRequest = buildGatewayRequest(messageRequest); GatewayRequestDetails gatewayDetails = (GatewayRequestDetails) applicationContext.getBean("gatewayRequestDetails", GatewayRequestDetails.class); gatewayDetails.setMessageType(messageRequest.getMessageType()); try { if (messageRequest.getMessageType() == MessageType.TEXT) { String template = fetchTemplate(messageRequest, defaultLang); logger.debug("message template fetched"); logger.debug(template); String message = parseTemplate(template, messageRequest.getPersInfos()); logger.debug("message contructed"); logger.debug(message); int maxLength = (charsPerSMS - concatAllowance) * maxConcat - 1; message = message.length() <= maxLength ? message : message.substring(0, maxLength); int numPages = (int) Math.ceil(message.length() % (charsPerSMS - concatAllowance)); gatewayDetails.setNumberOfPages(numPages); gatewayRequest.setMessage(message); gatewayDetails.setMessage(message); } gatewayRequest.setMessageStatus(MStatus.SCHEDULED); gatewayRequest.setGatewayRequestDetails(gatewayDetails); } catch (MotechException ex) { logger.error("MotechException: " + ex.getMessage()); gatewayRequest.setMessageStatus(MStatus.FAILED); gatewayRequest.setMessage(null); GatewayResponse gwResp = coreManager.createGatewayResponse(); gwResp.setGatewayRequest(gatewayRequest); gwResp.setMessageStatus(MStatus.FAILED); gwResp.setResponseText(ex.getMessage()); gatewayRequest.getResponseDetails().add(gwResp); } gatewayDetails.getGatewayRequests().add(gatewayRequest); logger.debug("GatewayRequest object successfully constructed"); logger.debug(gatewayDetails); return gatewayRequest; } GatewayRequest constructMessage(MessageRequest messageRequest, Language defaultLang); String parseTemplate(String template, Set<NameValuePair> templateParams); String formatPhoneNumber(String requesterPhone, MessageType type); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); void setMaxConcat(int maxConcat); void setCharsPerSMS(int charsPerSMS); void setConcatAllowance(int concatAllowance); void setLocalNumberExpression(String localNumberExpression); void setDefaultCountryCode(String defaultCountryCode); void setApplicationContext(ApplicationContext applicationContext); }### Answer:
@Test public void testConstructMessage() { System.out.println("consrtuctMessage"); MessageRequest message = new MessageRequestImpl(); message.setMessageType(MessageType.TEXT); Language defaultLang = new LanguageImpl(); message.setPersInfos(new HashSet<NameValuePair>()); message.setNotificationType(new NotificationTypeImpl()); expect( mockCore.createMessageTemplateDAO() ).andReturn(mockTemplateDao); expect( mockTemplateDao.getTemplateByLangNotifMType((Language)anyObject(), (NotificationType) anyObject(), (MessageType) anyObject(), (Language) anyObject()) ).andReturn(template); expect( applicationContext.getBean("gatewayRequest", GatewayRequest.class) ).andReturn(new GatewayRequestImpl()); expect( applicationContext.getBean("gatewayRequestDetails", GatewayRequestDetails.class) ).andReturn(new GatewayRequestDetailsImpl()); replay(mockCore, mockTemplateDao, applicationContext); System.out.println("111111" + instance); GatewayRequest result = instance.constructMessage(message, defaultLang); assertNotNull(result); verify(mockCore, mockTemplateDao, applicationContext); } |
### Question:
MessageStoreManagerImpl implements MessageStoreManager, ApplicationContextAware { public String parseTemplate(String template, Set<NameValuePair> templateParams) { String tag, value; if (templateParams == null) { return template; } for (NameValuePair detail : templateParams) { tag = "<" + detail.getName() + ">"; value = detail.getValue(); if (value != null && !value.isEmpty()) template = template.replaceAll(tag, value); } return template.trim(); } GatewayRequest constructMessage(MessageRequest messageRequest, Language defaultLang); String parseTemplate(String template, Set<NameValuePair> templateParams); String formatPhoneNumber(String requesterPhone, MessageType type); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); void setMaxConcat(int maxConcat); void setCharsPerSMS(int charsPerSMS); void setConcatAllowance(int concatAllowance); void setLocalNumberExpression(String localNumberExpression); void setDefaultCountryCode(String defaultCountryCode); void setApplicationContext(ApplicationContext applicationContext); }### Answer:
@Test public void testParseTemplate() { System.out.println("parseTemplate"); String tpl = "Testing the <method> method of the <class> class"; Set<NameValuePair> params = new HashSet<NameValuePair>(); params.add(new NameValuePair("method", "parseTemplate")); params.add(new NameValuePair("class", "MessageStoreManagerImpl")); String expResult = "Testing the parseTemplate method of the MessageStoreManagerImpl class"; String result = instance.parseTemplate(tpl, params); assertEquals(expResult, result); }
@Test public void testParseTemplate_MissingParam() { System.out.println("parseTemplate"); String tpl = "Testing the <method> method of the <class> class"; Set<NameValuePair> params = new HashSet<NameValuePair>(); params.add(new NameValuePair("method", "parseTemplate")); String expResult = "Testing the parseTemplate method of the <class> class"; String result = instance.parseTemplate(tpl, params); assertEquals(expResult, result); }
@Test public void testParseTemplate_NULLParam() { System.out.println("parseTemplate"); String tpl = "Testing the <method> method of the <class> class"; String result = instance.parseTemplate(tpl, null); assertEquals(tpl, result); } |
### Question:
MessageStoreManagerImpl implements MessageStoreManager, ApplicationContextAware { String fetchTemplate(MessageRequest messageData, Language defaultLang) { if (messageData.getNotificationType() == null) return ""; MessageTemplate template = coreManager.createMessageTemplateDAO().getTemplateByLangNotifMType(messageData.getLanguage(), messageData.getNotificationType(), messageData.getMessageType(), defaultLang); if (template == null) throw new MotechException("No such NotificationType found"); return template.getTemplate(); } GatewayRequest constructMessage(MessageRequest messageRequest, Language defaultLang); String parseTemplate(String template, Set<NameValuePair> templateParams); String formatPhoneNumber(String requesterPhone, MessageType type); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); void setMaxConcat(int maxConcat); void setCharsPerSMS(int charsPerSMS); void setConcatAllowance(int concatAllowance); void setLocalNumberExpression(String localNumberExpression); void setDefaultCountryCode(String defaultCountryCode); void setApplicationContext(ApplicationContext applicationContext); }### Answer:
@Test public void testFetchTemplate() { System.out.println("fetchTemplate"); mockTemplateDao = createMock(MessageTemplateDAO.class); MessageRequest message = new MessageRequestImpl(); Language defaultLang = new LanguageImpl(); message.setNotificationType(new NotificationTypeImpl()); expect( mockCore.createMessageTemplateDAO() ).andReturn(mockTemplateDao); expect( mockTemplateDao.getTemplateByLangNotifMType((Language)anyObject(), (NotificationType) anyObject(), (MessageType) anyObject(), (Language) anyObject()) ).andReturn(template); replay(mockCore, mockTemplateDao); String result = instance.fetchTemplate(message, defaultLang); assertEquals(result, "testing"); verify(mockCore, mockTemplateDao); } |
### Question:
MessageStoreManagerImpl implements MessageStoreManager, ApplicationContextAware { public String formatPhoneNumber(String requesterPhone, MessageType type) { if (requesterPhone == null || requesterPhone.isEmpty()) { return null; } String[] recipients = requesterPhone.split(DELIMITER); StringBuilder builder = new StringBuilder(); for (String recipient : recipients) { builder.append(format(recipient, type)).append(DELIMITER); } String formattedNumber = builder.substring(0,builder.length()-1); return formattedNumber; } GatewayRequest constructMessage(MessageRequest messageRequest, Language defaultLang); String parseTemplate(String template, Set<NameValuePair> templateParams); String formatPhoneNumber(String requesterPhone, MessageType type); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); void setMaxConcat(int maxConcat); void setCharsPerSMS(int charsPerSMS); void setConcatAllowance(int concatAllowance); void setLocalNumberExpression(String localNumberExpression); void setDefaultCountryCode(String defaultCountryCode); void setApplicationContext(ApplicationContext applicationContext); }### Answer:
@Test public void countryCodeShouldBeAppendedForTextMessageRecipients() { String formattedNumber = instance.formatPhoneNumber("0123456789,0223423456", MessageType.TEXT); assertEquals("233123456789,233223423456",formattedNumber); assertEquals("233111111111",instance.formatPhoneNumber("0111111111",MessageType.TEXT)); assertEquals("111111111,222222222",instance.formatPhoneNumber("111111111,222222222",MessageType.TEXT)); }
@Test public void leadingZeroShouldBeRemovedForVoiceMessageRecipients() { String formattedNumber = instance.formatPhoneNumber("0123456789,0223423456", MessageType.VOICE); assertEquals("123456789,223423456",formattedNumber); assertEquals("111111111",instance.formatPhoneNumber("111111111",MessageType.VOICE)); assertEquals("111111111,222222222",instance.formatPhoneNumber("111111111,222222222",MessageType.VOICE)); } |
### Question:
LogStatusActionImpl implements StatusAction { public void doAction(GatewayResponse response){ LogType logType; String summary = "Status of message with id " + response.getRequestId() + " is: " + response.getMessageStatus().toString() + ". Response from gateway was: " + response.getResponseText(); if(response.getMessageStatus() == MStatus.DELIVERED){ logType = LogType.SUCCESS; } else if(response.getMessageStatus() == MStatus.SENT){ logType = LogType.SUCCESS; } else{ logType = LogType.FAILURE; } try{ getRegWs().log(logType, summary); } catch(Exception e){ logger.error("Error communicating with logging service", e); } } void doAction(GatewayResponse response); RegistrarService getRegWs(); void setRegWs(RegistrarService regWs); }### Answer:
@Test public void testDoAction(){ System.out.println("doAction"); GatewayRequest messageDetails = new GatewayRequestImpl(); messageDetails.setDateFrom(new Date()); messageDetails.setMessage("a message for testing"); messageDetails.setDateTo(new Date()); messageDetails.setRecipientsNumber("000000000000"); messageDetails.setGatewayRequestDetails(mockGatewayRequestDetails); GatewayResponse response = new GatewayResponseImpl(); response.setGatewayRequest(messageDetails); response.setGatewayMessageId("werfet54y56g645v4e"); response.setMessageStatus(MStatus.PENDING); response.setRecipientNumber("000000000000"); response.setResponseText("Some gateway response message"); response.setId(15000000002l); mockService.log((LogType) anyObject(), (String) anyObject()); expectLastCall(); replay(mockService); instance.doAction(response); verify(mockService); } |
### Question:
IMPManagerImpl implements ApplicationContextAware, IMPManager { public IMPService createIMPService(){ return (IMPService)context.getBean("impService"); } IMPService createIMPService(); IncomingMessageParser createIncomingMessageParser(); IncomingMessageXMLParser createIncomingMessageXMLParser(); IncomingMessageFormValidator createIncomingMessageFormValidator(); CommandAction createCommandAction(); void setApplicationContext(ApplicationContext applicationContext); }### Answer:
@Test public void testCreateIMPService() { System.out.println("createIMPService"); IMPService result = impManager.createIMPService(); assertNotNull(result); } |
### Question:
ReportStatusActionImpl implements StatusAction { public void doAction(GatewayResponse response) { if (response.getRequestId() == null || response.getRequestId().isEmpty()) { return; } if (response.getRecipientNumber() == null || response.getRecipientNumber().isEmpty()) { return; } try { if (response.getMessageStatus() == MStatus.DELIVERED) { getRegWs().setMessageStatus(response.getRequestId(), true); } else if (response.getMessageStatus() == MStatus.FAILED) { getRegWs().setMessageStatus(response.getRequestId(), false); } } catch (Exception e) { logger.error("Error communicating with event engine", e); } } void doAction(GatewayResponse response); RegistrarService getRegWs(); void setRegWs(RegistrarService regWs); }### Answer:
@Test public void testDoAction(){ System.out.println("doAction"); GatewayRequestDetails grd = new GatewayRequestDetailsImpl(); grd.setId(17000000002l); GatewayRequest messageDetails = new GatewayRequestImpl(); messageDetails.setDateFrom(new Date()); messageDetails.setMessage("a message for testing"); messageDetails.setDateTo(new Date()); messageDetails.setRecipientsNumber("000000000000"); messageDetails.setGatewayRequestDetails(grd); GatewayResponse response = new GatewayResponseImpl(); response.setGatewayRequest(messageDetails); response.setGatewayMessageId("werfet54y56g645v4e"); response.setMessageStatus(MStatus.DELIVERED); response.setRecipientNumber("000000000000"); response.setResponseText("Some gateway response message"); response.setId(17000000003l); instance.doAction(response); } |
### Question:
StatusHandlerImpl implements StatusHandler { public void handleStatus(GatewayResponse response) { List<StatusAction> actions = actionRegister.get(response.getMessageStatus()); if (actions != null) { for (StatusAction action : actions) { action.doAction(response); } } } void handleStatus(GatewayResponse response); boolean registerStatusAction(MStatus status, StatusAction action); Map<MStatus, List<StatusAction>> getActionRegister(); void setActionRegister(Map<MStatus, List<StatusAction>> registry); }### Answer:
@Test public void testHandleStatus(){ System.out.println("handleStatus"); GatewayResponse response = new GatewayResponseImpl(); response.setGatewayMessageId("DoActionwerfet54y56g645v4e"); response.setMessageStatus(MStatus.DELIVERED); response.setRecipientNumber("000000000000"); response.setResponseText("Some gateway response message"); response.setId(18000000001l); List<StatusAction> actionList = new ArrayList<StatusAction>(); actionList.add(mockAction); expect( mockRegister.get((MStatus) anyObject()) ).andReturn(actionList); mockAction.doAction(response); expectLastCall(); replay(mockRegister, mockAction); instance.handleStatus(response); verify(mockRegister, mockAction); } |
### Question:
StatusHandlerImpl implements StatusHandler { public boolean registerStatusAction(MStatus status, StatusAction action) { return actionRegister.get(status).add(action); } void handleStatus(GatewayResponse response); boolean registerStatusAction(MStatus status, StatusAction action); Map<MStatus, List<StatusAction>> getActionRegister(); void setActionRegister(Map<MStatus, List<StatusAction>> registry); }### Answer:
@Test public void testregisterStatusAction(){ System.out.println("registerStatusAction"); List<StatusAction> actionList = new ArrayList<StatusAction>(); expect( mockRegister.get((MStatus)anyObject()) ).andReturn(actionList); replay(mockRegister); instance.registerStatusAction(MStatus.PENDING, mockAction); verify(mockRegister); } |
### Question:
IMPManagerImpl implements ApplicationContextAware, IMPManager { public IncomingMessageParser createIncomingMessageParser(){ return (IncomingMessageParser)context.getBean("imParser"); } IMPService createIMPService(); IncomingMessageParser createIncomingMessageParser(); IncomingMessageXMLParser createIncomingMessageXMLParser(); IncomingMessageFormValidator createIncomingMessageFormValidator(); CommandAction createCommandAction(); void setApplicationContext(ApplicationContext applicationContext); }### Answer:
@Test public void testCreateIncomingMessageParser() { System.out.println("createIncomingMessageParser"); IncomingMessageParser result = impManager.createIncomingMessageParser(); assertNotNull(result); } |
### Question:
IntellIVRController extends AbstractController implements ResourceLoaderAware { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { String content = getContent(request); log.debug("Received: " + content); Object output = null; if ( !contentIsValid(content) ) { log.debug("Received invalid content"); AutoCreate ac = new AutoCreate(); ResponseType rt = new ResponseType(); rt.setStatus(StatusType.ERROR); rt.setErrorCode(ErrorCodeType.MOTECH_MALFORMED_XML); rt.setErrorString("Malformed XML content"); ac.setResponse(rt); output = ac; } else { try { Object obj = unmarshaller.unmarshal(new ByteArrayInputStream(content.getBytes())); if ( obj instanceof AutoCreate ) { AutoCreate ac = new AutoCreate(); ac.setResponse(reportHandler.handleReport(((AutoCreate)obj).getReport())); log.info("Received valid call report"); output = ac; } if ( obj instanceof GetIVRConfigRequest ) { AutoCreate ac = new AutoCreate(); ac.setResponse(ivrConfigHandler.handleRequest((GetIVRConfigRequest)obj)); log.info("Received valid ivr config request"); output = ac; } } catch ( Exception e ) { log.error("Error unmarshaling content: " + content, e); } } if ( output == null ) { AutoCreate ac = new AutoCreate(); ResponseType rt = new ResponseType(); rt.setStatus(StatusType.ERROR); rt.setErrorCode(ErrorCodeType.MOTECH_UNKNOWN_ERROR); rt.setErrorString("An unknown error has occured"); ac.setResponse(rt); output = ac; } PrintWriter out = response.getWriter(); try { response.setContentType("text/xml"); marshaller.marshal(output, out); ByteArrayOutputStream debugOut = new ByteArrayOutputStream(); marshaller.marshal(output, debugOut); log.debug("Responded with: " + debugOut.toString()); } catch (JAXBException e) { log.error("Error marshalling object: " + output.toString(), e); } return null; } void init(); void setResourceLoader(ResourceLoader resourceLoader); GetIVRConfigRequestHandler getIvrConfigHandler(); void setIvrConfigHandler(GetIVRConfigRequestHandler ivrConfigHandler); ReportHandler getReportHandler(); void setReportHandler(ReportHandler reportHandler); }### Answer:
@Test public void shouldLogSaxParseExceptionWhenInvalidXMLContentIsPostedToServlet() throws Exception { String invalidXMLContent = "blahblahblah"; ResponseType expectedResponse = new ResponseType(); expectedResponse.setStatus(StatusType.ERROR); expectedResponse.setErrorCode(ErrorCodeType.MOTECH_MALFORMED_XML); mockRequest.setContent(invalidXMLContent.getBytes()); intellivrController.handleRequestInternal(mockRequest, mockResponse); Object o = unmarshaller.unmarshal(new ByteArrayInputStream(mockResponse.getContentAsByteArray())); assertTrue(o instanceof AutoCreate); ResponseType response = ((AutoCreate) o).getResponse(); assertEquals(response.getStatus(), StatusType.ERROR); assertEquals(response.getErrorCode(), ErrorCodeType.MOTECH_MALFORMED_XML); } |
### Question:
ClickatellGatewayMessageHandlerImpl implements GatewayMessageHandler { public Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse) { logger.debug("Parsing message gateway response"); logger.debug(gatewayResponse); if(message == null) return null; if(gatewayResponse.trim().isEmpty()) return null; Set<GatewayResponse> responses = new HashSet<GatewayResponse>(); String[] responseLines = gatewayResponse.trim().split("\n"); for(String line : responseLines){ String[] responseParts = line.split(" "); if(responseParts[0].equalsIgnoreCase("ID:")){ GatewayResponse response = getCoreManager().createGatewayResponse(); response.setGatewayMessageId(responseParts[1]); response.setRequestId(message.getRequestId()); response.setMessageStatus(MStatus.PENDING); response.setGatewayRequest(message); response.setResponseText(gatewayResponse); response.setDateCreated(new Date()); if(responseParts.length == 4) response.setRecipientNumber(responseParts[3]); else response.setRecipientNumber(message.getRecipientsNumber()); responses.add(response); } else{ logger.error("Gateway returned error: " + gatewayResponse); String errorCode = responseParts[1]; MStatus status = lookupResponse(errorCode.replaceAll(",", "").trim()); GatewayResponse response = getCoreManager().createGatewayResponse(); response.setRequestId(message.getRequestId()); response.setMessageStatus(status); response.setGatewayRequest(message); response.setResponseText(gatewayResponse); response.setDateCreated(new Date()); responses.add(response); } } logger.debug(responses); return responses; } Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse); MStatus parseMessageStatus(String gatewayResponse); MStatus lookupStatus(String code); MStatus lookupResponse(String code); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); Map<MStatus, String> getCodeStatusMap(); void setCodeStatusMap(Map<MStatus, String> codeStatusMap); Map<MStatus, String> getCodeResponseMap(); void setCodeResponseMap(Map<MStatus, String> codeResponseMap); }### Answer:
@Test public void testParseMessageResponse() { System.out.println("parseMessageResponse"); GatewayRequest message = null; String gatewayResponse = ""; GatewayRequest expResult = null; Set<GatewayResponse> result = instance.parseMessageResponse(message, gatewayResponse); assertEquals(expResult, result); } |
### Question:
ClickatellGatewayMessageHandlerImpl implements GatewayMessageHandler { public MStatus parseMessageStatus(String gatewayResponse) { logger.debug("Parsing message gateway status response"); String status; String[] responseParts = gatewayResponse.split(" "); if(responseParts.length == 2){ status = responseParts[1]; } else if(responseParts.length == 4){ status = responseParts[3]; } else{ status = ""; } return lookupStatus(status); } Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse); MStatus parseMessageStatus(String gatewayResponse); MStatus lookupStatus(String code); MStatus lookupResponse(String code); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); Map<MStatus, String> getCodeStatusMap(); void setCodeStatusMap(Map<MStatus, String> codeStatusMap); Map<MStatus, String> getCodeResponseMap(); void setCodeResponseMap(Map<MStatus, String> codeResponseMap); }### Answer:
@Test public void testParseMessageStatus() { System.out.println("parseMessageStatus"); String messageStatus = ""; MStatus expResult = MStatus.RETRY; MStatus result = instance.parseMessageStatus(messageStatus); assertEquals(expResult, result); } |
### Question:
ClickatellGatewayManagerImpl implements GatewayManager { public Set<GatewayResponse> sendMessage(GatewayRequest messageDetails) { try { postData = "api_id=" + URLEncoder.encode(apiId, "UTF-8"); postData += "&user=" + URLEncoder.encode(user, "UTF-8"); postData += "&password=" + URLEncoder.encode(password, "UTF-8"); postData += "&to=" + URLEncoder.encode(messageDetails.getRecipientsNumber(), "UTF-8"); postData += "&text=" + URLEncoder.encode(messageDetails.getMessage(), "UTF-8"); postData += "&from=" + URLEncoder.encode(sender, "UTF-8"); postData += "&concat=" + URLEncoder.encode(String.valueOf(messageDetails.getGatewayRequestDetails().getNumberOfPages()), "UTF-8"); postData += "&deliv_ack=" + URLEncoder.encode(deliveryAcknowledge, "UTF-8"); postData += "&callback=" + URLEncoder.encode(callback, "UTF-8"); } catch (UnsupportedEncodingException ex) { logger.fatal("Error constructing request: parameter encoding failed", ex); throw new RuntimeException("Error constructing message"); } URL url; URLConnection conn; try { url = new URL(baseUrl + "sendmsg"); conn = url.openConnection(); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } catch (MalformedURLException ex) { logger.fatal("Error initializing Clikatell Gateway: invalid url", ex); throw new RuntimeException("Invalid gatewat URL"); } catch (IOException ex) { logger.fatal("Error iitializing Clickatell Gateway: unable to open URL connection", ex); throw new RuntimeException("Could not connect to gateway"); } BufferedReader in; String data = ""; String gatewayResponse = ""; try { conn.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write(postData); out.flush(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); while((data = in.readLine()) != null) gatewayResponse += data + "\n"; out.close(); in.close(); } catch (IOException ex) { logger.error("Error processing gateway request", ex); gatewayResponse = ex.getMessage(); } messageDetails.setDateSent(new Date()); return messageHandler.parseMessageResponse(messageDetails, gatewayResponse); } ClickatellGatewayManagerImpl(); Set<GatewayResponse> sendMessage(GatewayRequest messageDetails); String getMessageStatus(GatewayResponse response); MStatus mapMessageStatus(GatewayResponse response); GatewayMessageHandler getMessageHandler(); void setMessageHandler(GatewayMessageHandler messageHandler); String getApiId(); void setApiId(String apiId); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); String getSender(); void setSender(String sender); String getDeliveryAcknowledge(); void setDeliveryAcknowledge(String deliveryAcknowledge); String getCallback(); void setCallback(String callback); void setBaseUrl(String baseUrl); }### Answer:
@Test public void testSendMessage() { System.out.println("sendMessage"); GatewayRequest messageDetails = new GatewayRequestImpl(); messageDetails.setDateFrom(new Date()); messageDetails.setMessage("a message for testing"); messageDetails.setDateTo(new Date()); messageDetails.setRecipientsNumber("000000000000"); messageDetails.setGatewayRequestDetails(mockGatewayRequestDetails); expect( mockHandler.parseMessageResponse((GatewayRequest) anyObject(), (String) anyObject()) ).andReturn(new HashSet<GatewayResponse>()); replay(mockHandler); Set<GatewayResponse> result = instance.sendMessage(messageDetails); assertNotNull(result); verify(mockHandler); } |
### Question:
ClickatellGatewayManagerImpl implements GatewayManager { public String getMessageStatus(GatewayResponse response) { try { postData = "api_id=" + URLEncoder.encode(apiId, "UTF-8"); postData += "&user=" + URLEncoder.encode(user, "UTF-8"); postData += "&password=" + URLEncoder.encode(password, "UTF-8"); postData += "&apimsgid=" + URLEncoder.encode(response.getGatewayMessageId(), "UTF-8"); } catch (UnsupportedEncodingException ex) { logger.fatal("Error constructing request: parameter encoding failed", ex); throw new RuntimeException("Error constructing message"); } URL url; URLConnection conn; try { url = new URL(baseUrl + "querymsg"); conn = url.openConnection(); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } catch (MalformedURLException ex) { logger.fatal("Error initializing Clikatell Gateway: invalid url", ex); throw new RuntimeException("Invalid gatewat URL"); } catch (IOException ex) { logger.fatal("Error iitializing Clickatell Gateway: unable to open URL connection", ex); throw new RuntimeException("Could not connect to gateway"); } BufferedReader in; String data = ""; String gatewayResponse = ""; try { conn.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write(postData); out.flush(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); while((data = in.readLine()) != null) gatewayResponse += data + "\n"; out.close(); in.close(); } catch (IOException ex) { logger.fatal("Error processing gateway request", ex); throw new RuntimeException("Unable to communicate with gateway"); } return gatewayResponse; } ClickatellGatewayManagerImpl(); Set<GatewayResponse> sendMessage(GatewayRequest messageDetails); String getMessageStatus(GatewayResponse response); MStatus mapMessageStatus(GatewayResponse response); GatewayMessageHandler getMessageHandler(); void setMessageHandler(GatewayMessageHandler messageHandler); String getApiId(); void setApiId(String apiId); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); String getSender(); void setSender(String sender); String getDeliveryAcknowledge(); void setDeliveryAcknowledge(String deliveryAcknowledge); String getCallback(); void setCallback(String callback); void setBaseUrl(String baseUrl); }### Answer:
@Test public void testGetMessageStatus() { System.out.println("getMessageStatus"); GatewayResponseImpl response = new GatewayResponseImpl(); response.setGatewayMessageId("testId"); String result = instance.getMessageStatus(response); assertNotNull(result); } |
### Question:
ClickatellGatewayManagerImpl implements GatewayManager { public MStatus mapMessageStatus(GatewayResponse response) { return messageHandler.parseMessageStatus(response.getResponseText()); } ClickatellGatewayManagerImpl(); Set<GatewayResponse> sendMessage(GatewayRequest messageDetails); String getMessageStatus(GatewayResponse response); MStatus mapMessageStatus(GatewayResponse response); GatewayMessageHandler getMessageHandler(); void setMessageHandler(GatewayMessageHandler messageHandler); String getApiId(); void setApiId(String apiId); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); String getSender(); void setSender(String sender); String getDeliveryAcknowledge(); void setDeliveryAcknowledge(String deliveryAcknowledge); String getCallback(); void setCallback(String callback); void setBaseUrl(String baseUrl); }### Answer:
@Test public void testMapMessageStatus() { System.out.println("mapMessageStatus"); GatewayResponseImpl response = new GatewayResponseImpl(); response.setResponseText("Some gateway response message"); expect( mockHandler.parseMessageStatus((String) anyObject()) ).andReturn(MStatus.DELIVERED); replay(mockHandler); MStatus result = instance.mapMessageStatus(response); assertEquals(result, MStatus.DELIVERED); verify(mockHandler); } |
### Question:
IMPManagerImpl implements ApplicationContextAware, IMPManager { public IncomingMessageFormValidator createIncomingMessageFormValidator(){ return (IncomingMessageFormValidator)context.getBean("imFormValidator"); } IMPService createIMPService(); IncomingMessageParser createIncomingMessageParser(); IncomingMessageXMLParser createIncomingMessageXMLParser(); IncomingMessageFormValidator createIncomingMessageFormValidator(); CommandAction createCommandAction(); void setApplicationContext(ApplicationContext applicationContext); }### Answer:
@Test public void testCreateIncomingMessageFormValidator() { System.out.println("createIncomingMessageFormValidator"); IncomingMessageFormValidator result = impManager.createIncomingMessageFormValidator(); assertNotNull(result); } |
### Question:
Instantiators { public static <T> Converter<T> createConverter( Class<T> klass, InstantiatorModule... modules) { return createConverterForType(klass, modules); } private Instantiators(); static Instantiator<T> createInstantiator(
Class<T> klass, InstantiatorModule... modules); @SuppressWarnings({ "unchecked", "rawtypes" }) static Option<Instantiator<T>> createInstantiator(
Errors errors, Class<T> klass, InstantiatorModule... modules); static Converter<T> createConverter(
Class<T> klass, InstantiatorModule... modules); static Converter<T> createConverter(
TypeLiteral<T> typeLiteral, InstantiatorModule... modules); }### Answer:
@Test public void createUriConverter() throws URISyntaxException { assertEquals( new URI("www.kaching.com"), createConverter(URI.class).fromString("www.kaching.com")); }
@Test public void createConverterPairConverter() throws URISyntaxException { Converter<ConvertedPair> converter = createConverter(ConvertedPair.class); assertEquals( "1:2", converter.toString(converter.fromString("1:2"))); } |
### Question:
StringConstructorConverter implements Converter<T> { @Override @SuppressWarnings("unchecked") public T fromString(String representation) { try { constructor.setAccessible(true); return (T) constructor.newInstance(representation); } catch (IllegalArgumentException e) { throw new IllegalStateException( "unreachable since we check the number of arguments the " + "constructor takes when building this converter", e); } catch (InstantiationException e) { throw new IllegalStateException( "unreachable since we check that the class is not abstract", e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { try { throw e.getTargetException(); } catch (RuntimeException targetException) { throw targetException; } catch (Throwable targetException) { throw new RuntimeException(e); } } } StringConstructorConverter(Constructor<?> constructor); @Override String toString(T value); @Override @SuppressWarnings("unchecked") T fromString(String representation); }### Answer:
@Test public void properlyBubblesException() { try { converter(TakesSingleStringAndThrows.class).fromString(null); fail(); } catch (RuntimeException e) { assertEquals(PrivateLocalRuntimException.class, e.getClass()); } } |
### Question:
InstantiatorImpl implements Instantiator<T> { @SuppressWarnings("unchecked") public List<String> fromInstance(T instance) { List<String> parameters = Lists.newArrayListWithCapacity(fields.length); for (int i = 0; i < fields.length; i++) { try { Field field = fields[i]; String parameterAsString; if (field != null) { Object value = field.get(instance); if (wrapInOption.get(i)) { value = ((Option<Object>) value).getOrElse((Object) null); } parameterAsString = value == null ? null : converters[i].toString(value); } else { parameterAsString = null; } parameters.add(parameterAsString); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } return parameters; } InstantiatorImpl(
Constructor<T> constructor,
Converter<?>[] converters,
Field[] fields,
BitSet optionality,
BitSet wrapInOption,
String[] defaultValues,
Object[] defaultConstants,
String[] parameterNames); @Override T newInstance(String... values); @Override T newInstance(Map<String, String> namedValues); @Override T newInstance(Iterable<String> values); @SuppressWarnings("unchecked") List<String> fromInstance(T instance); @Override Constructor<T> getConstructor(); @Override String toString(); }### Answer:
@Test public void fromInstanceSimple() { assertEquals( newArrayList("56"), createFactory(new Errors(), Simple.class).build().getOrThrow() .fromInstance(new Simple(56))); }
@Test public void fromInstanceHasEnum() { assertEquals( newArrayList("FOO"), createFactory(new Errors(), HasEnum.class).build().getOrThrow() .fromInstance(new HasEnum(IsEnum.FOO))); }
@Test public void fromInstanceNatives() { List<String> parameters = createFactory(new Errors(), Natives.class).build().getOrThrow() .fromInstance(new Natives(2, 3.4, (short) 5, '6', 7l, true, 8.0f, (byte) 9)); assertEquals( newArrayList( "2", "3.4", "5", "6", "7", "true", "8.0", "9"), parameters); } |
### Question:
InstantiatorImpl implements Instantiator<T> { @Override public T newInstance(String... values) { return newInstance(Arrays.asList(values)); } InstantiatorImpl(
Constructor<T> constructor,
Converter<?>[] converters,
Field[] fields,
BitSet optionality,
BitSet wrapInOption,
String[] defaultValues,
Object[] defaultConstants,
String[] parameterNames); @Override T newInstance(String... values); @Override T newInstance(Map<String, String> namedValues); @Override T newInstance(Iterable<String> values); @SuppressWarnings("unchecked") List<String> fromInstance(T instance); @Override Constructor<T> getConstructor(); @Override String toString(); }### Answer:
@Test public void newInstanceHasEnum() { assertEquals( IsEnum.FOO, createFactory(new Errors(), HasEnum.class).build().getOrThrow() .newInstance("FOO") .value); }
@Test(expected = UnsupportedOperationException.class) public void fromInstanceByNameThrowsIfNoParamaterNames() throws Exception { InstantiatorImpl<String> instantiator = new InstantiatorImpl<String>( null, null, null, null, null, null, null, null); instantiator.newInstance((Map<String, String>) null); } |
### Question:
InstantiatorImpl implements Instantiator<T> { @Override public Constructor<T> getConstructor() { return constructor; } InstantiatorImpl(
Constructor<T> constructor,
Converter<?>[] converters,
Field[] fields,
BitSet optionality,
BitSet wrapInOption,
String[] defaultValues,
Object[] defaultConstants,
String[] parameterNames); @Override T newInstance(String... values); @Override T newInstance(Map<String, String> namedValues); @Override T newInstance(Iterable<String> values); @SuppressWarnings("unchecked") List<String> fromInstance(T instance); @Override Constructor<T> getConstructor(); @Override String toString(); }### Answer:
@Test public void getConstructor() throws Exception { Constructor<Object> constructor = Object.class.getConstructor(); InstantiatorImpl<Object> instantiator = new InstantiatorImpl<Object>( constructor, null, null, new BitSet(), new BitSet(), null, null, null); assertTrue(constructor == instantiator.getConstructor()); } |
### Question:
CollectionOfElementsConverter implements Converter<T> { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public T fromString(String representation) { if (representation == null) { return null; } else { Collection collection = collectionProvider.get(); if (!representation.isEmpty()) { for (String part : representation.split(",")) { collection.add(elementConverter.fromString(part)); } } return (T) collection; } } CollectionOfElementsConverter(
Type kindOfCollection,
Converter<?> elementConverter); @Override String toString(T value); @Override @SuppressWarnings({ "unchecked", "rawtypes" }) T fromString(String representation); }### Answer:
@Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void createsRightKindOfCollection() { assertEquals( HashSet.class, new CollectionOfElementsConverter(Set.class, C_BOOLEAN).fromString("").getClass()); } |
### Question:
ConstructorAnalysis { static AnalysisResult analyse( Class<?> klass, Constructor<?> constructor) throws IOException { Class<?>[] parameterTypes = constructor.getParameterTypes(); InputStream in = klass.getResourceAsStream("/" + klass.getName().replace('.', '/') + ".class"); if (in == null) { throw new IllegalArgumentException(format("can not find bytecode for %s", klass)); } return analyse(in, klass.getName().replace('.', '/'), klass.getSuperclass().getName().replace('.', '/'), parameterTypes); } }### Answer:
@Test public void regression1() throws IOException { InputStream classInputStream = this.getClass().getResourceAsStream("example_scala_class01.bin"); assertNotNull(classInputStream); Map<String, FormalParameter> assignements = analyse(classInputStream, "com/kaching/trading/rules/formula/FormulaValue", "java/lang/Object", int.class).assignments; assertMapEqualAsString(ImmutableMap.of("number", "p0"), assignements); }
@Test public void regression2() throws IOException { InputStream classInputStream = this.getClass().getResourceAsStream("example_scala_class02.bin"); assertNotNull(classInputStream); Map<String, FormalParameter> assignements = analyse(classInputStream, "com/kaching/user/GetAllModels", "com/kaching/platform/queryengine/AbstractQuery", Boolean.class).assignments; assertMapEqualAsString(ImmutableMap.of("com$kaching$user$GetAllModels$$withHistory", "p0"), assignements); } |
### Question:
NullHandlingConverter implements Converter<T> { public T fromString(String representation) { return representation == null ? null : fromNonNullableString(representation); } T fromString(String representation); String toString(T value); }### Answer:
@Test public void fromNullString() throws Exception { Converter<Boolean> converter = new NullHandlingConverter<Boolean>() { @Override protected Boolean fromNonNullableString(String representation) { throw new UnsupportedOperationException(); } @Override protected String nonNullableToString(Boolean value) { throw new UnsupportedOperationException(); } }; assertNull(converter.fromString(null)); }
@Test public void fromNotNullString() throws Exception { Converter<Boolean> converter = new NullHandlingConverter<Boolean>() { @Override protected Boolean fromNonNullableString(String representation) { return true; } @Override protected String nonNullableToString(Boolean value) { throw new UnsupportedOperationException(); } }; assertTrue(converter.fromString("")); } |
### Question:
NullHandlingConverter implements Converter<T> { public String toString(T value) { return value == null ? null : nonNullableToString(value); } T fromString(String representation); String toString(T value); }### Answer:
@Test public void nullToString() throws Exception { Converter<Boolean> converter = new NullHandlingConverter<Boolean>() { @Override protected Boolean fromNonNullableString(String representation) { throw new UnsupportedOperationException(); } @Override protected String nonNullableToString(Boolean value) { throw new UnsupportedOperationException(); } }; assertNull(converter.toString(null)); }
@Test public void notNullToString() throws Exception { Converter<Boolean> converter = new NullHandlingConverter<Boolean>() { @Override protected Boolean fromNonNullableString(String representation) { throw new UnsupportedOperationException(); } @Override protected String nonNullableToString(Boolean value) { return ""; } }; assertEquals("", converter.toString(true)); } |
### Question:
InstantiatorErrors { @SuppressWarnings("rawtypes") static Errors incorrectBoundForConverter( Errors errors, Type targetType, Class<? extends Converter> converterClass, Type producedType) { return errors.addMessage( "the converter %2$s, mentioned on %1$s using @%4$s, does not produce " + "instances of %1$s. It produces %3$s.", targetType, converterClass, producedType, ConvertedBy.class.getSimpleName()); } }### Answer:
@Test public void incorrectBoundForConverter() { check( "the converter interface com.kaching.platform.converters.Converter, " + "mentioned on class java.lang.String using @ConvertedBy, " + "does not produce instances of class java.lang.String. It produces " + "class java.lang.Integer.", InstantiatorErrors.incorrectBoundForConverter( new Errors(), String.class, Converter.class, Integer.class)); } |
### Question:
InstantiatorErrors { static Errors incorrectDefaultValue(Errors errors, String value, RuntimeException e) { return errors.addMessage( "%s: For default value \"%s\"", e.getClass().getName(), value); } }### Answer:
@Test public void incorrectDefaultValue() { check( "java.lang.NumberFormatException: For default value \"90z\"", InstantiatorErrors.incorrectDefaultValue( new Errors(), "90z", new NumberFormatException("the message"))); } |
### Question:
InstantiatorErrors { static Errors illegalConstructor(Errors errors, Class<?> klass, String message) { return errors.addMessage( "%s has an illegal constructor%s", klass, message == null ? "" : ": " + message); } }### Answer:
@Test public void illegalConstructor1() { check( "class java.lang.String has an illegal constructor: hello", InstantiatorErrors.illegalConstructor( new Errors(), String.class, "hello")); }
@Test public void illegalConstructor2() { check( "class java.lang.String has an illegal constructor", InstantiatorErrors.illegalConstructor( new Errors(), String.class, null)); } |
### Question:
InstantiatorErrors { static Errors enumHasAmbiguousNames(Errors errors, Class<? extends Enum<?>> clazz) { return errors.addMessage( "enum %s has ambiguous names", clazz.getName()); } }### Answer:
@Test public void enumHasAmbiguousNames() { check( "enum com.kaching.platform.converters.InstantiatorErrorsTest$AmbiguousEnum has ambiguous names", InstantiatorErrors.enumHasAmbiguousNames( new Errors(), AmbiguousEnum.class)); } |
### Question:
InstantiatorErrors { static Errors moreThanOneMatchingFunction(Errors errors, Type type) { return errors.addMessage( "%s has more than one matching function", type); } }### Answer:
@Test public void moreThanOneMatchingFunction() { check( "class com.kaching.platform.converters.InstantiatorErrorsTest$AmbiguousEnum has more than one matching function", InstantiatorErrors.moreThanOneMatchingFunction( new Errors(), AmbiguousEnum.class)); } |
### Question:
InstantiatorErrors { static Errors noConverterForType(Errors errors, Type type) { return errors.addMessage( "no converter for %s", type); } }### Answer:
@Test public void noConverterForType() { check( "no converter for java.util.List<java.lang.String>", InstantiatorErrors.noConverterForType( new Errors(), new TypeLiteral<List<String>>() {}.getType())); } |
### Question:
InstantiatorErrors { static Errors noSuchField(Errors errors, String fieldName) { return errors.addMessage( "no such field %s", fieldName); } }### Answer:
@Test public void addinTwiceTheSameMessageDoesNotDuplicateTheError() { check( "no such field a", noSuchField(noSuchField(new Errors(), "a"), "a")); } |
### Question:
InstantiatorErrors { static Errors cannotSpecifyDefaultValueAndConstant(Errors errors, Optional annotation) { return errors.addMessage( "cannot specify both a default constant and a default value %s", annotation.toString().replaceFirst(Optional.class.getName(), Optional.class.getSimpleName())); } }### Answer:
@Test public void cannotSpecifyDefaultValueAndConstant() throws Exception { check( "cannot specify both a default constant and a default value " + "@Optional(constant=FOO, value=4)", InstantiatorErrors.cannotSpecifyDefaultValueAndConstant( new Errors(), inspectMeCannotSpecifyDefaultValueAndConstant(8))); } |
### Question:
InstantiatorErrors { static Errors unableToResolveConstant(Errors errors, Class<?> container, String constant) { return unableToResolveFullyQualifiedConstant( errors, localConstantQualifier(container, constant)); } }### Answer:
@Test public void unableToResolveLocalConstant() throws Exception { check( "unable to resolve constant com.kaching.platform.converters.InstantiatorErrorsTest#MY_CONSTANT", InstantiatorErrors.unableToResolveConstant( new Errors(), InstantiatorErrorsTest.class, "MY_CONSTANT")); } |
### Question:
AbstractImmutableType extends AbstractType { public Object assemble( Serializable cached, SessionImplementor session, Object owner) throws HibernateException { return cached; } final Object deepCopy(Object value); final boolean isMutable(); final Serializable disassemble(Object value); Serializable disassemble(Object value, SessionImplementor session); Object assemble(
Serializable cached, SessionImplementor session, Object owner); final Object assemble(Serializable cached, Object owner); final Object replace(Object original, Object target, Object owner); Object replace(Object original, Object target,
SessionImplementor session, Object owner); void nullSafeSet(PreparedStatement st, Object value, int index); void nullSafeSet(PreparedStatement st, Object value, int index,
SessionImplementor session); void setPropertyValue(Object component, int property, Object value); }### Answer:
@Test public void assemble() { assertEquals(serializable, type.assemble(serializable, null)); assertEquals(serializable, type.assemble(serializable, null, null)); } |
### Question:
AbstractImmutableType extends AbstractType { public final Object deepCopy(Object value) { return value; } final Object deepCopy(Object value); final boolean isMutable(); final Serializable disassemble(Object value); Serializable disassemble(Object value, SessionImplementor session); Object assemble(
Serializable cached, SessionImplementor session, Object owner); final Object assemble(Serializable cached, Object owner); final Object replace(Object original, Object target, Object owner); Object replace(Object original, Object target,
SessionImplementor session, Object owner); void nullSafeSet(PreparedStatement st, Object value, int index); void nullSafeSet(PreparedStatement st, Object value, int index,
SessionImplementor session); void setPropertyValue(Object component, int property, Object value); }### Answer:
@Test public void deepCopy() { assertEquals(serializable, type.deepCopy(serializable)); } |
### Question:
AbstractImmutableType extends AbstractType { public final Serializable disassemble(Object value) throws HibernateException { return (Serializable) value; } final Object deepCopy(Object value); final boolean isMutable(); final Serializable disassemble(Object value); Serializable disassemble(Object value, SessionImplementor session); Object assemble(
Serializable cached, SessionImplementor session, Object owner); final Object assemble(Serializable cached, Object owner); final Object replace(Object original, Object target, Object owner); Object replace(Object original, Object target,
SessionImplementor session, Object owner); void nullSafeSet(PreparedStatement st, Object value, int index); void nullSafeSet(PreparedStatement st, Object value, int index,
SessionImplementor session); void setPropertyValue(Object component, int property, Object value); }### Answer:
@Test public void disassemble() { assertEquals(serializable, type.disassemble(serializable)); assertEquals(serializable, type.disassemble(serializable, null)); } |
### Question:
AbstractImmutableType extends AbstractType { public final boolean isMutable() { return false; } final Object deepCopy(Object value); final boolean isMutable(); final Serializable disassemble(Object value); Serializable disassemble(Object value, SessionImplementor session); Object assemble(
Serializable cached, SessionImplementor session, Object owner); final Object assemble(Serializable cached, Object owner); final Object replace(Object original, Object target, Object owner); Object replace(Object original, Object target,
SessionImplementor session, Object owner); void nullSafeSet(PreparedStatement st, Object value, int index); void nullSafeSet(PreparedStatement st, Object value, int index,
SessionImplementor session); void setPropertyValue(Object component, int property, Object value); }### Answer:
@Test public void isMutable() { assertFalse(type.isMutable()); } |
### Question:
AbstractType { public final boolean equals(Object x, Object y) throws HibernateException { if (x == y) { return true; } else if (x == null || y == null) { return false; } else { return x.equals(y); } } final boolean equals(Object x, Object y); final int hashCode(Object value); }### Answer:
@Test public void equality() { assertTrue(type.equals(null, null)); assertFalse(type.equals(serializable, null)); assertFalse(type.equals(null, serializable)); assertTrue(type.equals(serializable, serializable)); } |
### Question:
AbstractType { public final int hashCode(Object value) throws HibernateException { return value.hashCode(); } final boolean equals(Object x, Object y); final int hashCode(Object value); }### Answer:
@Test public void hashing() { assertEquals(serializable.hashCode(), type.hashCode(serializable)); } |
### Question:
AbstractStringImmutableType extends AbstractImmutableType implements UserType { public final T nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException { String representation = rs.getString(names[0]); if (rs.wasNull() || representation == null) { return null; } else { return converter().fromString(representation); } } final T nullSafeGet(ResultSet rs, String[] names, Object owner); @SuppressWarnings("unchecked") @Override final void nullSafeSet(PreparedStatement st, Object value, int index); final int[] sqlTypes(); }### Answer:
@Test public void getButWasNull() throws Exception { final ResultSet rs = mockery.mock(ResultSet.class); final Sequence execution = mockery.sequence("execution"); mockery.checking(new Expectations() {{ one(rs).getString(with(equal("name0here"))); inSequence(execution); will(returnValue("78")); one(rs).wasNull(); inSequence(execution); will(returnValue(true)); }}); assertNull(type.nullSafeGet(rs, new String[] { "name0here" }, null)); mockery.assertIsSatisfied(); }
@Test public void getHadData() throws Exception { final ResultSet rs = mockery.mock(ResultSet.class); final Sequence execution = mockery.sequence("execution"); mockery.checking(new Expectations() {{ one(rs).getString(with(equal("name0here"))); inSequence(execution); will(returnValue("98")); one(rs).wasNull(); inSequence(execution); will(returnValue(false)); }}); Object value = type.nullSafeGet(rs, new String[] { "name0here" }, null); assertNotNull(value); assertEquals(98, value); mockery.assertIsSatisfied(); } |
### Question:
TypeLiterals { @SuppressWarnings("unchecked") public static <T> TypeLiteral<T> get(Class<T> type, Type... parameters) { return (TypeLiteral<T>) TypeLiteral.get(new ParameterizedTypeImpl(type, parameters)); } private TypeLiterals(); @SuppressWarnings("unchecked") static TypeLiteral<T> get(Class<T> type, Type... parameters); static TypeLiteral<T> get(Class<T> type, Class<?>... parameters); static TypeLiteral<T> get(Class<T> type, TypeLiteral<?>... literals); }### Answer:
@Test public void get1() throws Exception { TypeLiteral<?> expected = new TypeLiteral<List<Foo>>() {}; TypeLiteral<?> actual = TypeLiterals.get(List.class, Foo.class); assertEquals(expected, actual); }
@Test public void get2() throws Exception { TypeLiteral<?> expected = new TypeLiteral<Pair<Integer, Double>>() {}; TypeLiteral<?> actual = TypeLiterals.get( Pair.class, Integer.class, Double.class); assertEquals(expected, actual); }
@Test public void get3() throws Exception { TypeLiteral<?> expected = new TypeLiteral<List<List<Foo>>>() {}; TypeLiteral<?> inner = new TypeLiteral<List<Foo>>() {}; TypeLiteral<?> actual = TypeLiterals.get(List.class, inner); assertEquals(expected, actual); }
@Test public void get4() throws Exception { TypeLiteral<?> a = TypeLiterals.get(List.class, Integer.class); TypeLiteral<?> b = TypeLiterals.get(List.class, Double.class); assertNotEquals(a, b); }
@Test public void get5() throws Exception { TypeLiteral<?> a = TypeLiterals.get(List.class, new TypeLiteral<Double>() {}); TypeLiteral<?> b = TypeLiterals.get(List.class, Double.class); assertEquals(a, b); }
@Test public void toString1() throws Exception { assertEquals("java.util.List<java.lang.Double>", TypeLiterals.get(List.class, Double.class).toString()); }
@Test public void toString2() throws Exception { assertEquals("java.util.Map<java.lang.Integer, java.lang.Double>", TypeLiterals.get(Map.class, Integer.class, Double.class).toString()); }
@Test public void toString3() throws Exception { assertEquals("java.util.List<java.lang.Double>", TypeLiterals.get(List.class, new TypeLiteral<Double>() {}).toString()); } |
### Question:
ResultsMatcher extends TypeSafeDiagnosingMatcher<RecurrenceRule> { public static Matcher<RecurrenceRule> results(DateTime start, Matcher<Integer> count) { return new ResultsMatcher(start, is(count)); } ResultsMatcher(DateTime start, Matcher<Integer> countMatcher); static Matcher<RecurrenceRule> results(DateTime start, Matcher<Integer> count); static Matcher<RecurrenceRule> results(DateTime start, int count); @Override void describeTo(Description description); }### Answer:
@Test public void test() throws Exception { assertThat(results(DateTime.parse("20180101"), 10), AllOf.<Matcher<RecurrenceRule>>allOf( matches(new RecurrenceRule("FREQ=DAILY;COUNT=10")), mismatches(new RecurrenceRule("FREQ=DAILY;COUNT=9"), "number of instances was <9>"), mismatches(new RecurrenceRule("FREQ=DAILY;COUNT=12"), "number of instances was <12>"), describesAs("number of instances is <10>") )); assertThat(results(DateTime.parse("20180101"), lessThan(20)), AllOf.<Matcher<RecurrenceRule>>allOf( matches(new RecurrenceRule("FREQ=DAILY;COUNT=1")), matches(new RecurrenceRule("FREQ=DAILY;COUNT=19")), mismatches(new RecurrenceRule("FREQ=DAILY;COUNT=20"), "number of instances <20> was equal to <20>"), mismatches(new RecurrenceRule("FREQ=DAILY;COUNT=21"), "number of instances <21> was greater than <20>"), describesAs("number of instances is a value less than <20>") )); } |
### Question:
WeekOfYearMatcher extends FeatureMatcher<DateTime, Integer> { public static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher) { return new WeekOfYearMatcher(weekOfYearMatcher); } WeekOfYearMatcher(Matcher<Integer> subMatcher); static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher); static Matcher<DateTime> inWeekOfYear(Integer... weekOfYear); }### Answer:
@Test public void test() throws Exception { assertThat(inWeekOfYear(16), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180418T010001Z")), mismatches(DateTime.parse("20180415T005959Z"), "week of year was <15>"), mismatches(DateTime.parse("20180423T010000Z"), "week of year was <17>"), describesAs("week of year (<16>)") )); assertThat(inWeekOfYear(1, 16, 52), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180101T010001Z")), matches(DateTime.parse("20180418T010001Z")), matches(DateTime.parse("20181230T010001Z")), matches(DateTime.parse("20181231T010001Z")), matches(DateTime.parse("20190101T010001Z")), mismatches(DateTime.parse("20180108T010001Z"), "week of year was <2>"), mismatches(DateTime.parse("20180415T005959Z"), "week of year was <15>"), mismatches(DateTime.parse("20180423T010000Z"), "week of year was <17>"), mismatches(DateTime.parse("20181223T010001Z"), "week of year was <51>"), mismatches(DateTime.parse("20181223T010001Z"), "week of year was <51>"), mismatches(DateTime.parse("20190107T010001Z"), "week of year was <2>"), describesAs("week of year (<1> or <16> or <52>)") )); } |
### Question:
DayOfMonthMatcher extends FeatureMatcher<DateTime, Integer> { public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) { return new DayOfMonthMatcher(dayMatcher); } DayOfMonthMatcher(Matcher<Integer> subMatcher); static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher); static Matcher<DateTime> onDayOfMonth(Integer... days); }### Answer:
@Test public void test() throws Exception { assertThat(onDayOfMonth(10), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180710T010001Z")), mismatches(DateTime.parse("20181001T005959Z"), "day of month was <1>"), mismatches(DateTime.parse("20181011T010000Z"), "day of month was <11>"), describesAs("day of month (<10>)") )); assertThat(onDayOfMonth(6, 8, 10), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180706T010001Z")), matches(DateTime.parse("20180708T010002Z")), matches(DateTime.parse("20180710T010003Z")), mismatches(DateTime.parse("20180605T005959Z"), "day of month was <5>"), mismatches(DateTime.parse("20180811T005958Z"), "day of month was <11>"), mismatches(DateTime.parse("20181009T005957Z"), "day of month was <9>"), mismatches(DateTime.parse("20180907T010000Z"), "day of month was <7>"), describesAs("day of month (<6> or <8> or <10>)") )); } |
### Question:
MonthMatcher extends FeatureMatcher<DateTime, Integer> { public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) { return new MonthMatcher(monthMatcher); } MonthMatcher(Matcher<Integer> subMatcher); static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher); static Matcher<DateTime> inMonth(Integer... months); }### Answer:
@Test public void test() throws Exception { assertThat(inMonth(10), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20181001T010001Z")), mismatches(DateTime.parse("20180901T005959Z"), "month was <9>"), mismatches(DateTime.parse("20181101T010000Z"), "month was <11>"), describesAs("month (<10>)") )); assertThat(inMonth(6, 8, 10), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20181001T010001Z")), matches(DateTime.parse("20180801T010002Z")), matches(DateTime.parse("20180601T010003Z")), mismatches(DateTime.parse("20180501T005959Z"), "month was <5>"), mismatches(DateTime.parse("20180701T005958Z"), "month was <7>"), mismatches(DateTime.parse("20180901T005957Z"), "month was <9>"), mismatches(DateTime.parse("20181101T010000Z"), "month was <11>"), describesAs("month (<6> or <8> or <10>)") )); } |
### Question:
AfterMatcher extends TypeSafeDiagnosingMatcher<DateTime> { public static Matcher<DateTime> after(String dateTime) { return after(DateTime.parse(dateTime)); } AfterMatcher(DateTime referenceDate); static Matcher<DateTime> after(String dateTime); static Matcher<DateTime> after(DateTime dateTime); @Override void describeTo(Description description); }### Answer:
@Test public void test() throws Exception { assertThat(after(DateTime.parse("20180101T010000Z")), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180101T010001Z")), mismatches(DateTime.parse("20180101T005959Z"), "not after 20180101T010000Z"), mismatches(DateTime.parse("20180101T010000Z"), "not after 20180101T010000Z"), describesAs("after 20180101T010000Z") )); assertThat(after("20180101T010000Z"), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180101T010001Z")), mismatches(DateTime.parse("20180101T005959Z"), "not after 20180101T010000Z"), mismatches(DateTime.parse("20180101T010000Z"), "not after 20180101T010000Z"), describesAs("after 20180101T010000Z") )); } |
### Question:
WeekDayMatcher extends FeatureMatcher<DateTime, Weekday> { public static Matcher<DateTime> onWeekDay(Matcher<Weekday> weekdayMatcher) { return new WeekDayMatcher(weekdayMatcher); } WeekDayMatcher(Matcher<Weekday> subMatcher); static Matcher<DateTime> onWeekDay(Matcher<Weekday> weekdayMatcher); static Matcher<DateTime> onWeekDay(Weekday... weekdays); }### Answer:
@Test public void test() throws Exception { assertThat(onWeekDay(Weekday.WE), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180808T010001Z")), mismatches(DateTime.parse("20180809T005959Z"), "weekday was <TH>"), mismatches(DateTime.parse("20180807T010000Z"), "weekday was <TU>"), describesAs("weekday (<WE>)") )); assertThat(onWeekDay(Weekday.MO, Weekday.WE, Weekday.FR), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180808T010001Z")), matches(DateTime.parse("20180806T010002Z")), matches(DateTime.parse("20180810T010003Z")), mismatches(DateTime.parse("20180805T005959Z"), "weekday was <SU>"), mismatches(DateTime.parse("20180804T005958Z"), "weekday was <SA>"), mismatches(DateTime.parse("20180814T005957Z"), "weekday was <TU>"), mismatches(DateTime.parse("20180816T010000Z"), "weekday was <TH>"), describesAs("weekday (<MO> or <WE> or <FR>)") )); } |
### Question:
BeforeMatcher extends TypeSafeDiagnosingMatcher<DateTime> { public static Matcher<DateTime> before(String dateTime) { return before(DateTime.parse(dateTime)); } BeforeMatcher(DateTime referenceDate); static Matcher<DateTime> before(String dateTime); static Matcher<DateTime> before(DateTime dateTime); @Override void describeTo(Description description); }### Answer:
@Test public void test() throws Exception { assertThat(before(DateTime.parse("20180101T010000Z")), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180101T000059Z")), mismatches(DateTime.parse("20180101T010001Z"), "not before 20180101T010000Z"), mismatches(DateTime.parse("20180101T010000Z"), "not before 20180101T010000Z"), describesAs("before 20180101T010000Z") )); assertThat(before("20180101T010000Z"), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180101T000059Z")), mismatches(DateTime.parse("20180101T010001Z"), "not before 20180101T010000Z"), mismatches(DateTime.parse("20180101T010000Z"), "not before 20180101T010000Z"), describesAs("before 20180101T010000Z") )); } |
### Question:
DayOfYearMatcher extends FeatureMatcher<DateTime, Integer> { public static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher) { return new DayOfYearMatcher(dayMatcher); } DayOfYearMatcher(Matcher<Integer> subMatcher); static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher); static Matcher<DateTime> onDayOfYear(Integer... days); }### Answer:
@Test public void test() throws Exception { assertThat(onDayOfYear(10), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180110T010001Z")), mismatches(DateTime.parse("20180111T005959Z"), "day of year was <11>"), mismatches(DateTime.parse("20180109T010000Z"), "day of year was <9>"), describesAs("day of year (<10>)") )); assertThat(onDayOfYear(1, 8, 365), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180101T010001Z")), matches(DateTime.parse("20180108T010002Z")), matches(DateTime.parse("20181231T010003Z")), mismatches(DateTime.parse("20180102T005959Z"), "day of year was <2>"), mismatches(DateTime.parse("20180107T005959Z"), "day of year was <7>"), mismatches(DateTime.parse("20180109T005959Z"), "day of year was <9>"), mismatches(DateTime.parse("20180228T005958Z"), "day of year was <59>"), mismatches(DateTime.parse("20181230T005957Z"), "day of year was <364>"), describesAs("day of year (<1> or <8> or <365>)") )); } |
### Question:
YearMatcher extends FeatureMatcher<DateTime, Integer> { public static Matcher<DateTime> inYear(Matcher<Integer> yearMatcher) { return new YearMatcher(yearMatcher); } YearMatcher(Matcher<Integer> subMatcher); static Matcher<DateTime> inYear(Matcher<Integer> yearMatcher); static Matcher<DateTime> inYear(Integer... years); }### Answer:
@Test public void test() throws Exception { assertThat(inYear(2018), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20181001T010001Z")), mismatches(DateTime.parse("20210901T005959Z"), "year was <2021>"), mismatches(DateTime.parse("20171101T010000Z"), "year was <2017>"), describesAs("year (<2018>)") )); assertThat(inYear(2018, 2019, 2020), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20181001T010001Z")), matches(DateTime.parse("20190801T010002Z")), matches(DateTime.parse("20200601T010003Z")), mismatches(DateTime.parse("20110501T005959Z"), "year was <2011>"), mismatches(DateTime.parse("20170701T005958Z"), "year was <2017>"), mismatches(DateTime.parse("20210901T005957Z"), "year was <2021>"), mismatches(DateTime.parse("20301101T010000Z"), "year was <2030>"), describesAs("year (<2018> or <2019> or <2020>)") )); } |
### Question:
VanillaSharedReplicatedHashMap extends AbstractVanillaSharedHashMap<K, V> implements SharedHashMap<K, V>, ReplicaExternalizable<K, V>, EntryResolver<K, V>,
Closeable { @NotNull @Override public Set<Entry<K, V>> entrySet() { return new EntrySet(); } VanillaSharedReplicatedHashMap(@NotNull SharedHashMapBuilder builder,
@NotNull Class<K> kClass,
@NotNull Class<V> vClass); @Override long lastModificationTime(byte remoteIdentifier); @Override V put(K key, V value); @Override V putIfAbsent(@net.openhft.lang.model.constraints.NotNull K key, V value); @Override V remove(final Object key); @Override void close(); @Override byte identifier(); @Override Replica.ModificationIterator acquireModificationIterator(short remoteIdentifier,
@NotNull final ModificationNotifier modificationNotifier); @Override boolean remove(@net.openhft.lang.model.constraints.NotNull final Object key, final Object value); @Override void writeExternalEntry(@NotNull AbstractBytes entry, @NotNull Bytes destination, int chronicleId); @Override void readExternalEntry(@NotNull Bytes source); @NotNull @Override Set<Entry<K, V>> entrySet(); @Override K key(@NotNull AbstractBytes entry, K usingKey); @Override V value(@NotNull AbstractBytes entry, V usingValue); @Override boolean wasRemoved(@NotNull AbstractBytes entry); static final int RESERVED_MOD_ITER; }### Answer:
@Test public void testEntrySetToArray() throws IOException { SharedHashMap map = map5(); Set s = map.entrySet(); Object[] ar = s.toArray(); assertEquals(5, ar.length); for (int i = 0; i < 5; ++i) { assertTrue(map.containsKey(((Map.Entry) (ar[i])).getKey())); assertTrue(map.containsValue(((Map.Entry) (ar[i])).getValue())); } }
@Test public void testEntrySet() throws IOException { SharedHashMap map = map5(); Set s = map.entrySet(); assertEquals(5, s.size()); Iterator it = s.iterator(); while (it.hasNext()) { Map.Entry e = (Map.Entry) it.next(); assertTrue( (e.getKey().equals(JSR166TestCase.one) && e.getValue().equals("A")) || (e.getKey().equals(JSR166TestCase.two) && e.getValue().equals("B")) || (e.getKey().equals(JSR166TestCase.three) && e.getValue().equals("C")) || (e.getKey().equals(JSR166TestCase.four) && e.getValue().equals("D")) || (e.getKey().equals(JSR166TestCase.five) && e.getValue().equals("E")) ); } } |
### Question:
HugeHashMap extends AbstractMap<K, V> implements HugeMap<K, V> { @Override public V put(K key, V value) { long hash = hasher.hash(key); int segment = hasher.getSegment(hash); int segmentHash = hasher.segmentHash(hash); segments[segment].put(segmentHash, key, value, true, true); return null; } HugeHashMap(); HugeHashMap(HugeConfig config, Class<K> kClass, Class<V> vClass); @Override V put(K key, V value); @Override V get(Object key); @Override V get(K key, V value); @Override V remove(Object key); @Override boolean containsKey(Object key); @NotNull @Override Set<Entry<K, V>> entrySet(); @Override V putIfAbsent(@NotNull K key, V value); @Override boolean remove(@NotNull Object key, Object value); @Override boolean replace(@NotNull K key, @NotNull V oldValue, @NotNull V newValue); @Override V replace(@NotNull K key, @NotNull V value); @Override boolean isEmpty(); @Override int size(); @Override long offHeapUsed(); @Override void clear(); }### Answer:
@Test @Ignore public void testPut() throws ExecutionException, InterruptedException { int count = 1000000; HugeConfig config = HugeConfig.DEFAULT.clone() .setSegments(256) .setSmallEntrySize(72) .setCapacity(count); final HugeHashMap<CharSequence, SampleValues> map = new HugeHashMap<CharSequence, SampleValues>( config, CharSequence.class, SampleValues.class); long start = System.nanoTime(); final SampleValues value = new SampleValues(); StringBuilder user = new StringBuilder(); for (int i = 0; i < count; i++) { value.ee = i; value.gg = i; value.ii = i; map.put(users(user, i), value); } for (int i = 0; i < count; i++) { assertNotNull(map.get(users(user, i), value)); assertEquals(i, value.ee); assertEquals(i, value.gg, 0.0); assertEquals(i, value.ii); } for (int i = 0; i < count; i++) assertNotNull(map.get(users(user, i), value)); for (int i = 0; i < count; i++) map.remove(users(user, i)); long time = System.nanoTime() - start; System.out.printf("Put/get %,d K operations per second%n", (int) (count * 4 * 1e6 / time)); } |
### Question:
HugeHashMap extends AbstractMap<K, V> implements HugeMap<K, V> { @Override public V remove(Object key) { long hash = hasher.hash(key); int segment = hasher.getSegment(hash); int segmentHash = hasher.segmentHash(hash); segments[segment].remove(segmentHash, (K) key); return null; } HugeHashMap(); HugeHashMap(HugeConfig config, Class<K> kClass, Class<V> vClass); @Override V put(K key, V value); @Override V get(Object key); @Override V get(K key, V value); @Override V remove(Object key); @Override boolean containsKey(Object key); @NotNull @Override Set<Entry<K, V>> entrySet(); @Override V putIfAbsent(@NotNull K key, V value); @Override boolean remove(@NotNull Object key, Object value); @Override boolean replace(@NotNull K key, @NotNull V oldValue, @NotNull V newValue); @Override V replace(@NotNull K key, @NotNull V value); @Override boolean isEmpty(); @Override int size(); @Override long offHeapUsed(); @Override void clear(); }### Answer:
@Test public void clearMapViaKeyIteratorRemoves() { int noOfElements = 16 * 1024; HugeHashMap<Integer, String> map = getViewTestMap(noOfElements); int sum = 0; for (Iterator it = map.keySet().iterator(); it.hasNext(); ) { it.next(); it.remove(); ++sum; } assertEquals(noOfElements, sum); }
@Test public void clearMapViaValueIteratorRemoves() { int noOfElements = 16 * 1024; HugeHashMap<Integer, String> map = getViewTestMap(noOfElements); int sum = 0; for (Iterator it = map.values().iterator(); it.hasNext(); ) { it.next(); it.remove(); ++sum; } assertEquals(noOfElements, sum); } |
### Question:
VanillaSharedReplicatedHashMap extends AbstractVanillaSharedHashMap<K, V> implements SharedHashMap<K, V>, ReplicaExternalizable<K, V>, EntryResolver<K, V>,
Closeable { @Override public V putIfAbsent(@net.openhft.lang.model.constraints.NotNull K key, V value) { return put0(key, value, false, localIdentifier, timeProvider.currentTimeMillis()); } VanillaSharedReplicatedHashMap(@NotNull SharedHashMapBuilder builder,
@NotNull Class<K> kClass,
@NotNull Class<V> vClass); @Override long lastModificationTime(byte remoteIdentifier); @Override V put(K key, V value); @Override V putIfAbsent(@net.openhft.lang.model.constraints.NotNull K key, V value); @Override V remove(final Object key); @Override void close(); @Override byte identifier(); @Override Replica.ModificationIterator acquireModificationIterator(short remoteIdentifier,
@NotNull final ModificationNotifier modificationNotifier); @Override boolean remove(@net.openhft.lang.model.constraints.NotNull final Object key, final Object value); @Override void writeExternalEntry(@NotNull AbstractBytes entry, @NotNull Bytes destination, int chronicleId); @Override void readExternalEntry(@NotNull Bytes source); @NotNull @Override Set<Entry<K, V>> entrySet(); @Override K key(@NotNull AbstractBytes entry, K usingKey); @Override V value(@NotNull AbstractBytes entry, V usingValue); @Override boolean wasRemoved(@NotNull AbstractBytes entry); static final int RESERVED_MOD_ITER; }### Answer:
@Test public void testPutIfAbsent() throws IOException { SharedHashMap map = map5(); map.putIfAbsent(JSR166TestCase.six, "Z"); assertTrue(map.containsKey(JSR166TestCase.six)); }
@Test public void testPutIfAbsent2() throws IOException { SharedHashMap map = map5(); final Object z = map.putIfAbsent(JSR166TestCase.one, "Z"); assertEquals("A", z); }
@Test public void testPutIfAbsent1_NullPointerException() throws IOException { try { SharedHashMap c = newShmIntString(5); c.putIfAbsent(null, "whatever"); shouldThrow(); } catch (NullPointerException success) { } }
@Test public void testPutIfAbsent2_NullPointerException() throws IOException { try { SharedHashMap c = newShmIntString(5); c.putIfAbsent(JSR166TestCase.notPresent, null); shouldThrow(); } catch (NullPointerException success) { } } |
### Question:
VanillaSharedReplicatedHashMap extends AbstractVanillaSharedHashMap<K, V> implements SharedHashMap<K, V>, ReplicaExternalizable<K, V>, EntryResolver<K, V>,
Closeable { @Override public V remove(final Object key) { return removeIfValueIs(key, null, localIdentifier, timeProvider.currentTimeMillis()); } VanillaSharedReplicatedHashMap(@NotNull SharedHashMapBuilder builder,
@NotNull Class<K> kClass,
@NotNull Class<V> vClass); @Override long lastModificationTime(byte remoteIdentifier); @Override V put(K key, V value); @Override V putIfAbsent(@net.openhft.lang.model.constraints.NotNull K key, V value); @Override V remove(final Object key); @Override void close(); @Override byte identifier(); @Override Replica.ModificationIterator acquireModificationIterator(short remoteIdentifier,
@NotNull final ModificationNotifier modificationNotifier); @Override boolean remove(@net.openhft.lang.model.constraints.NotNull final Object key, final Object value); @Override void writeExternalEntry(@NotNull AbstractBytes entry, @NotNull Bytes destination, int chronicleId); @Override void readExternalEntry(@NotNull Bytes source); @NotNull @Override Set<Entry<K, V>> entrySet(); @Override K key(@NotNull AbstractBytes entry, K usingKey); @Override V value(@NotNull AbstractBytes entry, V usingValue); @Override boolean wasRemoved(@NotNull AbstractBytes entry); static final int RESERVED_MOD_ITER; }### Answer:
@Test public void testRemove() throws IOException { SharedHashMap map = map5(); map.remove(JSR166TestCase.five); assertEquals(4, map.size()); assertFalse(map.containsKey(JSR166TestCase.five)); }
@Test public void testRemove2() throws IOException { SharedHashMap map = map5(); map.remove(JSR166TestCase.five, "E"); assertEquals(4, map.size()); assertFalse(map.containsKey(JSR166TestCase.five)); map.remove(JSR166TestCase.four, "A"); assertEquals(4, map.size()); assertTrue(map.containsKey(JSR166TestCase.four)); } |
### Question:
VanillaSharedReplicatedHashMap extends AbstractVanillaSharedHashMap<K, V> implements SharedHashMap<K, V>, ReplicaExternalizable<K, V>, EntryResolver<K, V>,
Closeable { @Override public V put(K key, V value) { return put0(key, value, true, localIdentifier, timeProvider.currentTimeMillis()); } VanillaSharedReplicatedHashMap(@NotNull SharedHashMapBuilder builder,
@NotNull Class<K> kClass,
@NotNull Class<V> vClass); @Override long lastModificationTime(byte remoteIdentifier); @Override V put(K key, V value); @Override V putIfAbsent(@net.openhft.lang.model.constraints.NotNull K key, V value); @Override V remove(final Object key); @Override void close(); @Override byte identifier(); @Override Replica.ModificationIterator acquireModificationIterator(short remoteIdentifier,
@NotNull final ModificationNotifier modificationNotifier); @Override boolean remove(@net.openhft.lang.model.constraints.NotNull final Object key, final Object value); @Override void writeExternalEntry(@NotNull AbstractBytes entry, @NotNull Bytes destination, int chronicleId); @Override void readExternalEntry(@NotNull Bytes source); @NotNull @Override Set<Entry<K, V>> entrySet(); @Override K key(@NotNull AbstractBytes entry, K usingKey); @Override V value(@NotNull AbstractBytes entry, V usingValue); @Override boolean wasRemoved(@NotNull AbstractBytes entry); static final int RESERVED_MOD_ITER; }### Answer:
@Test public void testPut1_NullPointerException() throws IOException { try { SharedHashMap c = newShmIntString(5); c.put(null, "whatever"); shouldThrow(); } catch (NullPointerException success) { } }
@Test public void testPut2_NullPointerException() throws IOException { try { SharedHashMap c = newShmIntString(5); c.put(JSR166TestCase.notPresent, null); shouldThrow(); } catch (NullPointerException success) { } } |
### Question:
DataExtractionSupport { public String process(Object extractionObj, Response response, Map retrievedParametersFlowMode) { String outputStr = ""; this.retrievedParametersFlowMode = retrievedParametersFlowMode; logUtils.trace("extractionObj = '{}'", extractionObj.toString()); if (extractionObj.getClass().equals(String.class)) { outputStr = processString((String) extractionObj, response); } else if (extractionObj.getClass().equals(HashMap.class)) { outputStr = processMap((Map) extractionObj, response); } else { throw new HeatException(logUtils.getExceptionDetails() + "actualValue/expectedValue belongs to " + extractionObj.getClass().toString() + " not supported"); } logUtils.trace("outputStr = '{}' (class: {})", outputStr, extractionObj.getClass().toString()); return outputStr; } DataExtractionSupport(LoggingUtils logUtils); String process(Object extractionObj, Response response, Map retrievedParametersFlowMode); static final String STRING_TO_PARSE_JSON_ELEMENT; static final String REGEXP_JSON_ELEMENT; static final String REGEXP_MATCH_JSON_ELEMENT; static final String OCCURRENCE_JSON_ELEMENT; }### Answer:
@Test public void testSimpleString() { underTest = new DataExtractionSupport(logUtils); String processedStr = underTest.process(getSimpleStringObject(), null, null); Assert.assertEquals(processedStr, getSimpleStringObject()); }
@Test(expectedExceptions = { HeatException.class }, expectedExceptionsMessageRegExp = ".* actualValue/expectedValue belongs to class .* not supported") public void testNotSupportedObject() throws Exception { underTest = new DataExtractionSupport(logUtils); underTest.process(getNotSupportedClassObject(), null, null); }
@Test public void testRegularExtractionMapObject() { underTest = new DataExtractionSupport(logUtils); String processedStr = underTest.process(getRegexpExtractionMapObject(), null, null); Assert.assertEquals(processedStr, "123"); }
@Test public void testOccurrenceExtractionMapObject() { underTest = new DataExtractionSupport(logUtils); String processedStr = underTest.process(getOccurrenceOfMapObject(), null, null); Assert.assertEquals(processedStr, "2"); }
@Test(expectedExceptions = { HeatException.class }, expectedExceptionsMessageRegExp = ".* configuration .* not supported") public void testNotSupportedMapObject() throws Exception { underTest = new DataExtractionSupport(logUtils); underTest.process(getNotSupportedMapObject(), null, null); } |
### Question:
MultipartUtils { public static List<MultiPartSpecification> convertToMultipart(List<Map<String, String>> parts) { return parts.stream() .map(part -> { final MultiPartSpecification specification; final String name = part.get(TestCaseUtils.JSON_FIELD_MULTIPART_NAME); Preconditions.checkNotNull(name, "'%s' for a part is mandatory", TestCaseUtils.JSON_FIELD_MULTIPART_NAME); if (part.containsKey(TestCaseUtils.JSON_FIELD_MULTIPART_FILE)) { final String filepath = part.get(TestCaseUtils.JSON_FIELD_MULTIPART_FILE); Preconditions.checkState(StringUtils.isNotBlank(filepath), "'%s' is mandatory. Missing for part [%s]", TestCaseUtils.JSON_FIELD_MULTIPART_FILE, name); final File content = resolve(filepath); Preconditions.checkNotNull(content.exists(), "Can't find file: ", filepath); final String contentType = Optional.ofNullable(part.get(TestCaseUtils.JSON_FIELD_MULTIPART_CONTENT_TYPE)) .orElse(URLConnection.guessContentTypeFromName(filepath)); Preconditions.checkArgument(StringUtils.isNotBlank(contentType), "'%s' isn't specified and can't be automatically detected. Missing for part [%s]", TestCaseUtils.JSON_FIELD_MULTIPART_CONTENT_TYPE, name); specification = new MultiPartSpecBuilder(content) .fileName(content.getName()) .mimeType(contentType) .controlName(name) .build(); } else { final String value = part.get(TestCaseUtils.JSON_FIELD_MULTIPART_VALUE); Preconditions.checkNotNull(StringUtils.isNotBlank(value), "'%s' is mandatory. Missing for part [%s]", TestCaseUtils.JSON_FIELD_MULTIPART_VALUE, name); specification = new MultiPartSpecBuilder(value) .controlName(name) .build(); } return specification; }) .collect(Collectors.toList()); } static List<MultiPartSpecification> convertToMultipart(List<Map<String, String>> parts); static File resolve(String filepath); }### Answer:
@Test public void testSimpleValue() throws Exception { final List<Map<String, String>> parts = ImmutableList.of( ImmutableMap.of( TestCaseUtils.JSON_FIELD_MULTIPART_NAME, "simpleField", TestCaseUtils.JSON_FIELD_MULTIPART_VALUE, "simpleValue" ) ); final List<MultiPartSpecification> spec = MultipartUtils.convertToMultipart(parts); assertEquals(spec.size(), 1); assertEquals(spec.get(0).getContent(), "simpleValue"); assertEquals(spec.get(0).getControlName(), "simpleField"); assertNull(spec.get(0).getCharset()); assertNull(spec.get(0).getFileName()); assertNull(spec.get(0).getMimeType()); }
@Test public void testMultipleValues() throws Exception { final List<Map<String, String>> parts = ImmutableList.of( ImmutableMap.of( TestCaseUtils.JSON_FIELD_MULTIPART_NAME, "simpleField", TestCaseUtils.JSON_FIELD_MULTIPART_VALUE, "simpleValue" ), ImmutableMap.of( TestCaseUtils.JSON_FIELD_MULTIPART_NAME, "simpleField", TestCaseUtils.JSON_FIELD_MULTIPART_VALUE, "simpleValue" ) ); final List<MultiPartSpecification> spec = MultipartUtils.convertToMultipart(parts); assertEquals(spec.size(), 2); }
@Test public void testFileWithNoMimetype() throws Exception { final List<Map<String, String>> parts = ImmutableList.of( ImmutableMap.of( TestCaseUtils.JSON_FIELD_MULTIPART_NAME, "upload", TestCaseUtils.JSON_FIELD_MULTIPART_FILE, "/files/multipart.something" ) ); try { MultipartUtils.convertToMultipart(parts); fail("It should fail for missing mimetype"); } catch (IllegalArgumentException e) { assertEquals(e.getMessage(), "'contentType' isn't specified and can't be automatically detected. Missing for part [upload]"); } } |
### Question:
PlaceholderHandler { public String processHeaderPlaceholder(String inputString) { String outputString = inputString; if (response != null) { outputString = processGenericPlaceholders(inputString, REGEXP_HEADER_PLACEHOLDER, this::getHeaderVar); } return outputString; } PlaceholderHandler(); Map<String, HeatPlaceholderModuleProvider> constructProviderMap(Map<String, HeatPlaceholderModuleProvider> providerMapInput,
List<String> handledPlaceholders,
HeatPlaceholderModuleProvider provider); Object placeholderProcessString(String inputStr); String getPathVar(String inputObj); String processHeaderPlaceholder(String inputString); Map<String, Object> placeholderProcessMap(Map<String, Object> requestParamsMap); void setResponse(Response rsp); void setPreloadedVariables(Map<String, Object> preloadedVarsInput); Map<String, Object> getPreloadedVariables(); void setFlowVariables(Map<Integer, Map<String, String>> flowPreloadedVariables); static final String DEFAULT_PRELOADED_VALUE; static final String PLACEHOLDER_SYMBOL; static final String PLACEHOLDER_SYMBOL_BEGIN; static final String PLACEHOLDER_SYMBOL_END; static final String PLACEHOLDER_JSON_SCHEMA_NO_CHECK; static final String PATH_PLACEHOLDER; static final String PLACEHOLDER_NOT_PRESENT; static final String PLACEHOLDER_PRESENT; static final String PATH_JSONPATH_REGEXP; }### Answer:
@Test (enabled = true) public void testProcessHeaderPlaceholder() { underTest = new PlaceholderHandler(); underTest.setResponse(buildResponse()); String stringToProcess = "PIPPO_${header[test_header]}"; String output = (String) underTest.placeholderProcessString(stringToProcess); Assert.assertEquals(output, "PIPPO_test_value"); stringToProcess = "PIPPO_${header[test_header]}_PLUTO"; output = (String) underTest.placeholderProcessString(stringToProcess); Assert.assertEquals(output, "PIPPO_test_value_PLUTO"); stringToProcess = "PIPPO_${header[test_header]}_PLUTO_${header[test_header]}"; output = (String) underTest.placeholderProcessString(stringToProcess); Assert.assertEquals(output, "PIPPO_test_value_PLUTO_test_value"); stringToProcess = "PIPPO_${header[test_header]}_PLUTO_${header[test_header2]}"; output = (String) underTest.placeholderProcessString(stringToProcess); Assert.assertEquals(output, "PIPPO_test_value_PLUTO_test_value2"); stringToProcess = "PIPPO_${header[test_header]}_PLUTO_${header[test_header2]}_PAPERINO"; output = (String) underTest.placeholderProcessString(stringToProcess); Assert.assertEquals(output, "PIPPO_test_value_PLUTO_test_value2_PAPERINO"); } |
### Question:
PlaceholderHandler { private String processCookiePlaceholder(String input) { String outputObj = input; if (response != null) { outputObj = processGenericPlaceholders(input, REGEXP_COOKIE_PLACEHOLDER, this::getCookieVar); } return outputObj; } PlaceholderHandler(); Map<String, HeatPlaceholderModuleProvider> constructProviderMap(Map<String, HeatPlaceholderModuleProvider> providerMapInput,
List<String> handledPlaceholders,
HeatPlaceholderModuleProvider provider); Object placeholderProcessString(String inputStr); String getPathVar(String inputObj); String processHeaderPlaceholder(String inputString); Map<String, Object> placeholderProcessMap(Map<String, Object> requestParamsMap); void setResponse(Response rsp); void setPreloadedVariables(Map<String, Object> preloadedVarsInput); Map<String, Object> getPreloadedVariables(); void setFlowVariables(Map<Integer, Map<String, String>> flowPreloadedVariables); static final String DEFAULT_PRELOADED_VALUE; static final String PLACEHOLDER_SYMBOL; static final String PLACEHOLDER_SYMBOL_BEGIN; static final String PLACEHOLDER_SYMBOL_END; static final String PLACEHOLDER_JSON_SCHEMA_NO_CHECK; static final String PATH_PLACEHOLDER; static final String PLACEHOLDER_NOT_PRESENT; static final String PLACEHOLDER_PRESENT; static final String PATH_JSONPATH_REGEXP; }### Answer:
@Test (enabled = true) public void testProcessCookiePlaceholder() { underTest = new PlaceholderHandler(); underTest.setResponse(buildResponse()); String stringToProcess = "PIPPO_${cookie[test_cookie]}"; String output = (String) underTest.placeholderProcessString(stringToProcess); Assert.assertEquals(output, "PIPPO_test_value"); stringToProcess = "PIPPO_${cookie[test_cookie]}_PLUTO"; output = (String) underTest.placeholderProcessString(stringToProcess); Assert.assertEquals(output, "PIPPO_test_value_PLUTO"); stringToProcess = "PIPPO_${cookie[test_cookie]}_PLUTO_${cookie[test_cookie]}"; output = (String) underTest.placeholderProcessString(stringToProcess); Assert.assertEquals(output, "PIPPO_test_value_PLUTO_test_value"); stringToProcess = "PIPPO_${cookie[test_cookie]}_PLUTO_${cookie[test_cookie2]}"; output = (String) underTest.placeholderProcessString(stringToProcess); Assert.assertEquals(output, "PIPPO_test_value_PLUTO_test_value2"); stringToProcess = "PIPPO_${cookie[test_cookie]}_PLUTO_${cookie[test_cookie2]}_PAPERINO"; output = (String) underTest.placeholderProcessString(stringToProcess); Assert.assertEquals(output, "PIPPO_test_value_PLUTO_test_value2_PAPERINO"); } |
### Question:
OperationHandler { public boolean execute() { boolean isExecutionOk = true; if (!fieldsToCheck.containsKey(JSON_ELEM_ACTUAL_VALUE) || !fieldsToCheck.containsKey(JSON_ELEM_EXPECTED_VALUE)) { throw new HeatException("json input format not supported! '" + fieldsToCheck.toString() + "'"); } if (isComparingBlock()) { isExecutionOk &= multipleModeOperationExecution(); } else { isExecutionOk &= singleModeOperationExecution(); } return isExecutionOk; } OperationHandler(Map fieldsToCheck,
Object response); boolean execute(); void setOperationBlocking(boolean isBlocking); void setFlowOutputParameters(Map<Integer, Map<String, String>> retrievedParameters); LoggingUtils getLogUtils(); static final String OPERATION_JSON_ELEMENT; static final String FORMAT_OF_TYPE_CHECK_JSON_ELEMENT; static final String JSON_ELEM_DESCRIPTION; static final String JSON_ELEM_EXPECTED_VALUE; static final String JSON_ELEM_ACTUAL_VALUE; static final String JSON_ELEM_REFERRING_OBJECT; }### Answer:
@Test (enabled = true) public void testCompareEqualsFields() { underTest = new OperationHandler(getEqualsFieldsToCheck(), buildResponses()); boolean execution = underTest.execute(); Assert.assertTrue(execution); }
@Test(enabled = true, expectedExceptions = HeatException.class) public void testCompareDifferentFields() { underTest = new OperationHandler(getDifferentFieldsToCheck(), buildResponses()); underTest.execute(); } |
### Question:
MotechUserRepository { public User newUser(WebStaff webStaff) { User user = new User(); user.setSystemId(identifierGenerator.generateStaffId()); user.setGender(MotechConstants.GENDER_UNKNOWN_OPENMRS); PersonName name = new PersonName(webStaff.getFirstName(), null, webStaff.getLastName()); user.addName(name); String phoneValue = webStaff.getPhone() == null ? "" : webStaff.getPhone(); String typeValue = webStaff.getType() == null ? "" : webStaff.getType(); createPhoneNumber(user, phoneValue); createType(user, typeValue); Role role = userService.getRole(OpenmrsConstants.PROVIDER_ROLE); user.addRole(role); return user; } MotechUserRepository(IdentifierGenerator identifierGenerator, UserService userService, PersonService personService, MotechUsers motechUsers); User newUser(WebStaff webStaff); User updateUser(User staff, WebStaff webStaff); MotechUserTypes userTypes(); }### Answer:
@Test public void testNewUser() throws Exception { PersonService personService = mock(PersonService.class); IdentifierGenerator identifierGenerator = mock(IdentifierGenerator.class); UserService userService = mock(UserService.class); Role role = mock(Role.class); PersonAttributeType phoneNumberAttributeType = new PersonAttributeType(); phoneNumberAttributeType.setId(1); PersonAttributeType staffTypeAttributeType = new PersonAttributeType(); staffTypeAttributeType.setId(2); when(identifierGenerator.generateStaffId()).thenReturn("27"); when(personService.getPersonAttributeTypeByName(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_PHONE_NUMBER.getAttributeName())).thenReturn(phoneNumberAttributeType); when(personService.getPersonAttributeTypeByName(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_STAFF_TYPE.getAttributeName())).thenReturn(staffTypeAttributeType); when(userService.getRole("Provider")).thenReturn(role); MotechUserRepository motechUserRepository = new MotechUserRepository(identifierGenerator, userService, personService, motechUsers); User user = motechUserRepository.newUser(new WebStaff("Jenny", "Jones ", "1001", "CHO")); verify(identifierGenerator).generateStaffId(); verify(personService).getPersonAttributeTypeByName("Phone Number"); verify(personService).getPersonAttributeTypeByName("Staff Type"); verify(userService).getRole("Provider"); assertThat(user.getSystemId(), equalTo("27")); } |
### Question:
StaffMessageServiceImpl implements StaffMessageService { boolean isMessageTimeWithinBlackoutPeriod(Date deliveryDate) { Date checkForDate = (deliveryDate != null ? deliveryDate : new Date()); Blackout blackout = motechService().getBlackoutSettings(); if (blackout == null) { return false; } Calendar blackoutCalendar = new DateUtil().calendarFor(checkForDate); adjustForBlackoutStartDate(checkForDate, blackout, blackoutCalendar); Date blackoutStart = blackoutCalendar.getTime(); setBlackOutTime(blackout.getEndTime(), blackoutCalendar); if (blackoutCalendar.getTime().before(blackoutStart)) { blackoutCalendar.add(Calendar.DATE, 1); } Date blackoutEnd = blackoutCalendar.getTime(); return checkForDate.after(blackoutStart) && checkForDate.before(blackoutEnd); } StaffMessageServiceImpl(); StaffMessageServiceImpl(
ContextService contextService,
MessageService mobileService
); void sendStaffCareMessages(Date startDate, Date endDate,
Date deliveryDate, Date deliveryTime,
String[] careGroups,
boolean sendUpcoming,
boolean blackoutEnabled,
boolean sendNoDefaulterAndNoUpcomingCareMessage); void sendUpcomingMessages(Date startDate, Date endDate, Date deliveryDate, String[] careGroups, Facility facility, Boolean sendNoUpcomingCareMessage); void sendDefaulterMessages(Date startDate, Date deliveryDate, String[] careGroups, Facility facility, Boolean sendNoDefaulterMessage); void setContextService(ContextService contextService); void setExpectedEncountersFilter(FilterChain expectedEncountersFilter); void setExpectedObsFilter(FilterChain expectedObsFilter); void setMobileService(MessageService mobileService); void setCareModelConverter(WebServiceCareModelConverter careModelConverter); }### Answer:
@Test public void testShouldFindOutIfMessageTimeIsDuringBlackoutPeriod() { DateUtil dateUtil = new DateUtil(); Calendar calendar = dateUtil.getCalendarWithTime(23, 13, 54); Date morningMessageTime = calendar.getTime(); calendar = dateUtil.getCalendarWithTime(3, 13, 54); Date nightMessageTime = calendar.getTime(); calendar = dateUtil.getCalendarWithTime(19, 30, 30); Date eveningMessageTime = calendar.getTime(); Blackout blackout = new Blackout(Time.valueOf("23:00:00"), Time.valueOf("06:00:00")); expect(contextService.getMotechService()).andReturn(motechService).times(3); expect(motechService.getBlackoutSettings()).andReturn(blackout).times(3); replay(contextService, adminService, motechService); assertTrue(staffMessageServiceImpl.isMessageTimeWithinBlackoutPeriod(morningMessageTime)); assertTrue(staffMessageServiceImpl.isMessageTimeWithinBlackoutPeriod(nightMessageTime)); assertFalse(staffMessageServiceImpl.isMessageTimeWithinBlackoutPeriod(eveningMessageTime)); verify(contextService, adminService, motechService); } |
### Question:
MotechUserRepository { public MotechUserTypes userTypes() { return motechUsers.types(); } MotechUserRepository(IdentifierGenerator identifierGenerator, UserService userService, PersonService personService, MotechUsers motechUsers); User newUser(WebStaff webStaff); User updateUser(User staff, WebStaff webStaff); MotechUserTypes userTypes(); }### Answer:
@Test public void shouldRetrieveUserTypes() { MotechUserRepository repository = new MotechUserRepository(null, null, null, motechUsers); MotechUserTypes userTypes = repository.userTypes(); assertTrue(userTypes.hasTypes(2)); assertTrue(userTypes.hasType("CHO")); assertTrue(userTypes.hasType("CHN")); } |
### Question:
DemoPatientController extends BasePatientController { @ModelAttribute("regions") public List<String> getRegions() { return JSONLocationSerializer.getAllRegions(); } @Autowired void setContextService(ContextService contextService); void setRegistrarBean(RegistrarBean registrarBean); void setWebModelConverter(WebModelConverter webModelConverter); @InitBinder void initBinder(WebDataBinder binder); @ModelAttribute("regions") List<String> getRegions(); @ModelAttribute("districts") List<String> getDistricts(); @ModelAttribute("communities") List<Community> getCommunities(); @RequestMapping(method = RequestMethod.GET) void viewForm(@RequestParam(required = false) Integer id,ModelMap model); @ModelAttribute("patient") WebPatient getWebPatient(@RequestParam(required = false) Integer id); @RequestMapping(method = RequestMethod.POST) String submitForm(@ModelAttribute("patient") WebPatient patient,
Errors errors, ModelMap model, SessionStatus status,
HttpSession session); }### Answer:
@Test public void testGetRegions() throws Exception { ContextService contextService = createMock(ContextService.class); MotechService motechService = createMock(MotechService.class); JSONLocationSerializer JSONLocationSerializer = new JSONLocationSerializer(); JSONLocationSerializer.setContextService(contextService); demoPatientController.setContextService(contextService); demoPatientController.setJSONLocationSerializer(JSONLocationSerializer); expect(contextService.getMotechService()).andReturn(motechService); expect(motechService.getAllRegions()).andReturn(Collections.<String>emptyList()).once(); replay(contextService, motechService); demoPatientController.getRegions(); verify(contextService, motechService); } |
### Question:
DemoPatientController extends BasePatientController { @ModelAttribute("districts") public List<String> getDistricts() { return JSONLocationSerializer.getAllDistricts(); } @Autowired void setContextService(ContextService contextService); void setRegistrarBean(RegistrarBean registrarBean); void setWebModelConverter(WebModelConverter webModelConverter); @InitBinder void initBinder(WebDataBinder binder); @ModelAttribute("regions") List<String> getRegions(); @ModelAttribute("districts") List<String> getDistricts(); @ModelAttribute("communities") List<Community> getCommunities(); @RequestMapping(method = RequestMethod.GET) void viewForm(@RequestParam(required = false) Integer id,ModelMap model); @ModelAttribute("patient") WebPatient getWebPatient(@RequestParam(required = false) Integer id); @RequestMapping(method = RequestMethod.POST) String submitForm(@ModelAttribute("patient") WebPatient patient,
Errors errors, ModelMap model, SessionStatus status,
HttpSession session); }### Answer:
@Test public void testGetDistricts() throws Exception { ContextService contextService = createMock(ContextService.class); MotechService motechService = createMock(MotechService.class); JSONLocationSerializer JSONLocationSerializer = new JSONLocationSerializer(); JSONLocationSerializer.setContextService(contextService); demoPatientController.setContextService(contextService); demoPatientController.setJSONLocationSerializer(JSONLocationSerializer); expect(contextService.getMotechService()).andReturn(motechService); expect(motechService.getAllDistricts()).andReturn(Collections.<String>emptyList()).once(); replay(contextService, motechService); demoPatientController.getDistricts(); verify(contextService, motechService); } |
### Question:
DemoPatientController extends BasePatientController { @ModelAttribute("communities") public List<Community> getCommunities() { return JSONLocationSerializer.getAllCommunities(false); } @Autowired void setContextService(ContextService contextService); void setRegistrarBean(RegistrarBean registrarBean); void setWebModelConverter(WebModelConverter webModelConverter); @InitBinder void initBinder(WebDataBinder binder); @ModelAttribute("regions") List<String> getRegions(); @ModelAttribute("districts") List<String> getDistricts(); @ModelAttribute("communities") List<Community> getCommunities(); @RequestMapping(method = RequestMethod.GET) void viewForm(@RequestParam(required = false) Integer id,ModelMap model); @ModelAttribute("patient") WebPatient getWebPatient(@RequestParam(required = false) Integer id); @RequestMapping(method = RequestMethod.POST) String submitForm(@ModelAttribute("patient") WebPatient patient,
Errors errors, ModelMap model, SessionStatus status,
HttpSession session); }### Answer:
@Test public void testGetCommunities() throws Exception { ContextService contextService = createMock(ContextService.class); MotechService motechService = createMock(MotechService.class); JSONLocationSerializer JSONLocationSerializer = new JSONLocationSerializer(); JSONLocationSerializer.setContextService(contextService); demoPatientController.setContextService(contextService); demoPatientController.setJSONLocationSerializer(JSONLocationSerializer); expect(contextService.getMotechService()).andReturn(motechService); expect(motechService.getAllCommunities(false)).andReturn(Collections.<Community>emptyList()).once(); replay(contextService, motechService); demoPatientController.getCommunities(); verify(contextService, motechService); } |
### Question:
FacilityController { @RequestMapping(value = "/module/motechmodule/addfacility.form", method = RequestMethod.GET) public String viewAddFacilityForm(ModelMap modelMap){ populateLocation(modelMap); modelMap.addAttribute("facility", new WebFacility()); return "/module/motechmodule/addfacility"; } FacilityController(); FacilityController(ContextService contextService); @ModelAttribute("facilities") List<Facility> getFacilities(); @RequestMapping(value = "/module/motechmodule/facility.form", method = RequestMethod.GET) String viewFacilities(); @RequestMapping(value = "/module/motechmodule/addfacility.form", method = RequestMethod.GET) String viewAddFacilityForm(ModelMap modelMap); @RequestMapping(value = "/module/motechmodule/addfacility.form", method = RequestMethod.POST) String submitAddFacility(@ModelAttribute("facility") WebFacility facility, Errors errors,ModelMap modelMap, SessionStatus status); @ModelAttribute("locations") List<Location> getLocations(); }### Answer:
@Test public void shouldPopulateWithLocationDataWhenShowingNewFacilityForm() { Location l1 = getLocation("C1", "R1", "D1", "P1"); Location l2 = getLocation("C1", "R1", "D2", "P2"); Location l3 = getLocation("C1", "R2", "D3", "P3"); Location l4 = getLocation("C1", "R2", "D4", "P4"); when(locationService.getAllLocations()).thenReturn(Arrays.asList(l1, l2, l3, l4)); ModelMap modelMap = new ModelMap(); String path = controller.viewAddFacilityForm(modelMap); assertEquals("/module/motechmodule/addfacility", path); Set<String> countries = (Set<String>) modelMap.get("countries"); assertTrue(countries.contains("C1")); Map<String, TreeSet<String>> m1 = (Map<String, TreeSet<String>>) modelMap.get("regions"); TreeSet<String> regions = m1.get("C1"); assertTrue(regions.containsAll(Arrays.asList("R1", "R2"))); Map<String, TreeSet<String>> m2 = (Map<String, TreeSet<String>>) modelMap.get("districts"); TreeSet<String> districts = m2.get("R1"); assertTrue(districts.containsAll(Arrays.asList("D1", "D2"))); Map<String, TreeSet<String>> m3 = (Map<String, TreeSet<String>>) modelMap.get("provinces"); TreeSet<String> provinces = m3.get("D1"); assertTrue(provinces.containsAll(Arrays.asList("P1"))); verify(contextService).getLocationService(); verify(locationService).getAllLocations(); } |
### Question:
FacilityController { @RequestMapping(value = "/module/motechmodule/addfacility.form", method = RequestMethod.POST) public String submitAddFacility(@ModelAttribute("facility") WebFacility facility, Errors errors,ModelMap modelMap, SessionStatus status){ if(contextService.getMotechService().getLocationByName(facility.getName()) != null){ errors.rejectValue("name","motechmodule.Facility.duplicate.location"); } if(errors.hasErrors()){ populateLocation(modelMap); return "/module/motechmodule/addfacility"; } contextService.getLocationService().saveLocation(facility.getFacility().getLocation()); contextService.getRegistrarBean().saveNewFacility(facility.getFacility()); return "redirect:/module/motechmodule/facility.form"; } FacilityController(); FacilityController(ContextService contextService); @ModelAttribute("facilities") List<Facility> getFacilities(); @RequestMapping(value = "/module/motechmodule/facility.form", method = RequestMethod.GET) String viewFacilities(); @RequestMapping(value = "/module/motechmodule/addfacility.form", method = RequestMethod.GET) String viewAddFacilityForm(ModelMap modelMap); @RequestMapping(value = "/module/motechmodule/addfacility.form", method = RequestMethod.POST) String submitAddFacility(@ModelAttribute("facility") WebFacility facility, Errors errors,ModelMap modelMap, SessionStatus status); @ModelAttribute("locations") List<Location> getLocations(); }### Answer:
@Test public void shouldFetchLocationDataInCaseOfDuplicateLocationError() { ModelMap modelMap = new ModelMap(); when(webFacility.getFacility()).thenReturn(facility); when(webFacility.getName()).thenReturn("name"); when(facility.getLocation()).thenReturn(location); when(motechService.getLocationByName("name")).thenReturn(location); when(errors.hasErrors()).thenReturn(true); String path = controller.submitAddFacility(webFacility, errors, modelMap, null); assertEquals(path,"/module/motechmodule/addfacility"); verify(errors).rejectValue("name","motechmodule.Facility.duplicate.location"); verify(locationService,never()).saveLocation(location); verify(registrarBean,never()).saveNewFacility(facility); verify(locationService).getAllLocations(); }
@Test public void shouldSaveNewLocationForNoErrors() { ModelMap modelMap = new ModelMap(); when(webFacility.getFacility()).thenReturn(facility); when(webFacility.getName()).thenReturn("name"); when(facility.getLocation()).thenReturn(location); when(motechService.getLocationByName("name")).thenReturn(null); when(errors.hasErrors()).thenReturn(false); String path = controller.submitAddFacility(webFacility, errors, modelMap, null); assertEquals(path,"redirect:/module/motechmodule/facility.form"); verify(locationService).saveLocation(location); verify(registrarBean).saveNewFacility(facility); verify(locationService,never()).getAllLocations(); } |
### Question:
SMSController { @RequestMapping(value = VIEW, method = RequestMethod.GET) public ModelAndView render() { ModelAndView modelAndView = new ModelAndView(VIEW, "bulkMessage", new WebBulkMessage()); locationSerializer.populateJavascriptMaps(modelAndView.getModelMap()); return modelAndView; } @RequestMapping(value = VIEW, method = RequestMethod.GET) ModelAndView render(); void setLocationSerializer(JSONLocationSerializer locationSerializer); @RequestMapping(value = VIEW, method = RequestMethod.POST) ModelAndView send(@ModelAttribute WebBulkMessage bulkMessage); void setMessageService(MessageService messageService); }### Answer:
@Test public void shouldRenderTheCorrectPage() { expect(contextService.getMotechService()).andReturn(motechService); expect(motechService.getAllFacilities()).andReturn(Collections.<Facility>emptyList()); expect(motechService.getAllLanguages()).andReturn(Collections.<MessageLanguage>emptyList()); replay(contextService, motechService); ModelAndView modelAndView = controller.render(); verify(contextService, motechService); assertNotNull(modelAndView); assertEquals("/module/motechmodule/sms", modelAndView.getViewName()); WebBulkMessage message = (WebBulkMessage) modelAndView.getModelMap().get("bulkMessage"); assertNotNull(message); assertNotNull(modelAndView.getModel().get("regionMap")); assertNotNull(modelAndView.getModel().get("districtMap")); assertNotNull(modelAndView.getModel().get("facilities")); } |
### Question:
StaffController { @RequestMapping(method = RequestMethod.POST) public String registerStaff(@ModelAttribute("staff") WebStaff staff, Errors errors, ModelMap model) { log.debug("Register Staff"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "motechmodule.firstName.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "motechmodule.lastName.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "type", "motechmodule.staffType.required"); validateTextLength(errors, "firstName", staff.getFirstName(), MotechConstants.MAX_STRING_LENGTH_OPENMRS); validateTextLength(errors, "lastName", staff.getLastName(), MotechConstants.MAX_STRING_LENGTH_OPENMRS); validateTextLength(errors, "phone", staff.getPhone(), MotechConstants.MAX_STRING_LENGTH_OPENMRS); if (staff.getPhone() != null && !staff.getPhone().matches( MotechConstants.PHONE_REGEX_PATTERN)) { errors.rejectValue("phone", "motechmodule.phoneNumber.invalid"); } if (!errors.hasErrors()) { User user = registrarBean.registerStaff(staff.getFirstName(), staff .getLastName(), staff.getPhone(), staff.getType(), staff.getStaffId()); model.addAttribute("successMsg", (staff.isNew() ? NEW : EDIT).message(user)); } model.addAttribute("staffTypes", registrarBean.getStaffTypes()); return "/module/motechmodule/staff"; } @InitBinder void initBinder(WebDataBinder binder); @ModelAttribute("staff") WebStaff getWebStaff(); @RequestMapping(method = RequestMethod.GET) String viewStaffForm(@RequestParam(value = "staffId", required = false) String staffId, ModelMap model); @RequestMapping(method = RequestMethod.POST) String registerStaff(@ModelAttribute("staff") WebStaff staff,
Errors errors, ModelMap model); void setRegistrarBean(RegistrarBean registrarBean); void setOpenmrsBean(OpenmrsBean openmrsBean); }### Answer:
@Test public void registerStaff() { RegistrarBean registrarBean = createMock(RegistrarBean.class); Errors errors = createMock(Errors.class); StaffController controller = new StaffController(); controller.setRegistrarBean(registrarBean); ModelMap map = new ModelMap(); WebStaff staff = new WebStaff(); staff.setFirstName("Joseph"); staff.setLastName("Jones"); staff.setPhone("0123456789"); staff.setType("CHO"); expect(errors.getFieldValue("firstName")).andReturn(staff.getFirstName()); expect(errors.getFieldValue("lastName")).andReturn(staff.getLastName()); expect(errors.getFieldValue("type")).andReturn(staff.getType()); expect(errors.hasErrors()).andReturn(false); expect(registrarBean.registerStaff(staff.getFirstName(),staff.getLastName(),staff.getPhone(), staff.getType(),staff.getStaffId())).andReturn(user(staff)); List<String> staffTypes = new ArrayList<String>(); staffTypes.add("CHO"); expect(registrarBean.getStaffTypes()).andReturn(staffTypes); replay(errors,registrarBean); String view = controller.registerStaff(staff, errors, map); verify(errors,registrarBean); assertEquals("/module/motechmodule/staff",view); assertEquals(staffTypes,map.get("staffTypes")); assertEquals("Added user: Name = Joseph Jones, Staff ID = 465",map.get("successMsg")); } |
### Question:
AuthenticationServiceImpl implements AuthenticationService { public User getAuthenticatedUser() { return contextService.getAuthenticatedUser(); } AuthenticationServiceImpl(ContextService contextService); User getAuthenticatedUser(); }### Answer:
@Test public void shouldDelegateCallToContextService(){ AuthenticationServiceImpl service = new AuthenticationServiceImpl(contextService); User user = new User(); when(contextService.getAuthenticatedUser()).thenReturn(user); User authenticatedUser = service.getAuthenticatedUser(); verify(contextService).getAuthenticatedUser(); assertSame(user,authenticatedUser); } |
### Question:
SupportCaseExtractionStrategy implements MessageContentExtractionStrategy { public SupportCase extractFrom(IncomingMessage message) { try { String dateRaisedOn = message.extractDateWith(this); String phoneNumber = message.extractPhoneNumberWith(this); String sender = message.extractSenderWith(this); String description = message.extractDescriptionWith(this); return new SupportCase(sender,phoneNumber,dateRaisedOn,description); } catch (Exception ex){ return new SupportCase(); } } SupportCase extractFrom(IncomingMessage message); String extractDateFrom(String time); String extractPhoneNumberFrom(String phoneNumber); String extractSenderFrom(String text); String extractDescriptionFrom(String text); }### Answer:
@Test public void shouldExtractMessageContent() throws ParseException, MessageContentExtractionException { SupportCaseExtractionStrategy strategy = new SupportCaseExtractionStrategy(); IncomingMessage message = new IncomingMessage(); message.setKey(" SUPPORT"); message.setTime("2011-06-25 09:30:29 "); message.setText("SUPPORT 123 Cannot Upload Forms "); message.setNumber("+233123456789 "); SupportCase supportCase = strategy.extractFrom(message); assertEquals("123",supportCase.getRaisedBy()); assertEquals("+233123456789",supportCase.getPhoneNumber()); assertEquals("2011-06-25 09:30:29",supportCase.getDateRaisedOn()); assertEquals("Cannot Upload Forms",supportCase.getDescription()); } |
### Question:
Password { public String create(){ StringBuilder sb = new StringBuilder(); for (int i = 0; i < length ; i++) { int charIndex = (int) (Math.random() * PASSCHARS.length); sb.append(PASSCHARS[charIndex]); } return sb.toString(); } Password(Integer length); String create(); }### Answer:
@Test public void createPasswordWithSpecifiedLength(){ String password = new Password(10).create(); assertNotNull(password); assertEquals(10,password.length()); } |
### Question:
DateUtil { public boolean isSameMonth(Date date, Date otherDate) { Calendar calendar = calendarFor(date); Calendar otherCalendar = calendarFor(otherDate); return calendar.get(Calendar.MONTH) == otherCalendar.get(Calendar.MONTH); } boolean isSameMonth(Date date, Date otherDate); boolean isSameYear(Date date, Date otherDate); Calendar calendarFor(Date date); Date dateFor(int day, int month, int year); Calendar getCalendarWithTime(int hourOfTheDay, int minutes, int seconds); }### Answer:
@Test public void isSameMonth() { assertTrue(dateUtil.isSameMonth(new Date(), new Date())); }
@Test public void isNotSameMonth() { assertFalse(dateUtil.isSameMonth(new Date(), DateUtils.addMonths(new Date(), -1))); } |
### Question:
DateUtil { public boolean isSameYear(Date date, Date otherDate) { Calendar calendar = calendarFor(date); Calendar otherCalendar = calendarFor(otherDate); return calendar.get(Calendar.YEAR) == otherCalendar.get(Calendar.YEAR); } boolean isSameMonth(Date date, Date otherDate); boolean isSameYear(Date date, Date otherDate); Calendar calendarFor(Date date); Date dateFor(int day, int month, int year); Calendar getCalendarWithTime(int hourOfTheDay, int minutes, int seconds); }### Answer:
@Test public void isSameYear() { assertTrue(dateUtil.isSameYear(new Date(), new Date())); }
@Test public void isNotSameYear() { assertFalse(dateUtil.isSameYear(new Date(), DateUtils.addYears(new Date(), -1))); } |
### Question:
DateUtil { public Calendar getCalendarWithTime(int hourOfTheDay, int minutes, int seconds) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, hourOfTheDay); calendar.set(Calendar.MINUTE, minutes); calendar.set(Calendar.SECOND, seconds); return calendar; } boolean isSameMonth(Date date, Date otherDate); boolean isSameYear(Date date, Date otherDate); Calendar calendarFor(Date date); Date dateFor(int day, int month, int year); Calendar getCalendarWithTime(int hourOfTheDay, int minutes, int seconds); }### Answer:
@Test public void shouldReturnCalendarWithGivenTime() { Calendar calendar = dateUtil.getCalendarWithTime(10, 50, 20); assertNotNull(calendar); assertEquals(10, calendar.get(Calendar.HOUR_OF_DAY)); assertEquals(50, calendar.get(Calendar.MINUTE)); assertEquals(20, calendar.get(Calendar.SECOND)); } |
### Question:
CareConfiguration { public Boolean canAlertBeSent(Integer alertCount) { return alertCount < maxAlertsToBeSent ; } CareConfiguration(); CareConfiguration(Long id, String name, Integer maxAlertsToBeSent); Boolean canAlertBeSent(Integer alertCount); }### Answer:
@Test public void shouldCheckWhetherMaximumAlertsHaveBeenSent() { CareConfiguration careConfiguration = new CareConfiguration(1L, "ANC", 4); assertTrue(careConfiguration.canAlertBeSent(1)); assertTrue(careConfiguration.canAlertBeSent(2)); assertFalse(careConfiguration.canAlertBeSent(4)); assertFalse(careConfiguration.canAlertBeSent(5)); } |
### Question:
RegistrationRequirement implements Requirement { public boolean meetsRequirement(Patient patient, Date date) { Date childRegistrationDate = registrarBean.getChildRegistrationDate(); List<Encounter> encounters = registrarBean.getEncounters(patient, MotechConstants.ENCOUNTER_TYPE_PATIENTREGVISIT, patient.getBirthdate()); if (encounters == null || encounters.isEmpty()) return false; return childRegistrationDate.before(encounters.get(0).getEncounterDatetime()); } boolean meetsRequirement(Patient patient, Date date); RegistrarBean getRegistrarBean(); void setRegistrarBean(RegistrarBean registrarBean); }### Answer:
@Test public void shouldReturnTrueWhenPatientIsRegisteredAfterValidDate() { Calendar cal = Calendar.getInstance(); cal.set(2000, 1, 1); Date birthDate = cal.getTime(); cal.set(2011, 4, 19); Date validRegDate = cal.getTime(); cal.set(2011, 5, 19); Date encounterDate = cal.getTime(); Patient patient = new Patient(); patient.setBirthdate(birthDate); Encounter encounter = new Encounter(); encounter.setEncounterDatetime(encounterDate); when(registerBean.getChildRegistrationDate()).thenReturn(validRegDate); when(registerBean.getEncounters(patient, MotechConstants.ENCOUNTER_TYPE_PATIENTREGVISIT, patient.getBirthdate())).thenReturn(Arrays.asList(encounter)); assertTrue(requirement.meetsRequirement(patient, new Date())); }
@Test public void shouldReturnFalseWhenPatientIsRegisteredBeforeValidDate() { Calendar cal = Calendar.getInstance(); cal.set(2000, 1, 1); Date birthDate = cal.getTime(); cal.set(2011, 4, 19); Date validRegDate = cal.getTime(); cal.set(2011, 3, 19); Date encounterDate = cal.getTime(); Patient patient = new Patient(); patient.setBirthdate(birthDate); Encounter encounter = new Encounter(); encounter.setEncounterDatetime(encounterDate); when(registerBean.getChildRegistrationDate()).thenReturn(validRegDate); when(registerBean.getEncounters(patient, MotechConstants.ENCOUNTER_TYPE_PATIENTREGVISIT, patient.getBirthdate())).thenReturn(Arrays.asList(encounter)); assertFalse(requirement.meetsRequirement(patient, new Date())); }
@Test public void shouldReturnFalseIfNoEncountersArePresentForPatient() { Calendar cal = Calendar.getInstance(); cal.set(2000, 1, 1); Date birthDate = cal.getTime(); cal.set(2011, 4, 19); Date validRegDate = cal.getTime(); cal.set(2011, 3, 19); Date encounterDate = cal.getTime(); Patient patient = new Patient(); patient.setBirthdate(birthDate); Encounter encounter = new Encounter(); encounter.setEncounterDatetime(encounterDate); when(registerBean.getChildRegistrationDate()).thenReturn(validRegDate); when(registerBean.getEncounters(patient, MotechConstants.ENCOUNTER_TYPE_PATIENTREGVISIT, patient.getBirthdate())).thenReturn(Collections.EMPTY_LIST); assertFalse(requirement.meetsRequirement(patient, new Date())); } |
### Question:
HttpClient implements WebClient { public Response get(String fromUrl) { DefaultHttpClient client = new DefaultHttpClient(); try { HttpResponse httpResponse = client.execute(new HttpGet(fromUrl)); return new WebResponse(httpResponse).read(); } catch (IOException e) { return new Response(MailingConstants.MESSAGE_PROCESSING_FAILED); } } Response get(String fromUrl); }### Answer:
@Ignore("Should be an integration test") @Test public void shouldMakeAHttpGetRequest() { HttpClient client = new HttpClient(); Response response = client.get("http: "text=support+465+Connection+Broken&number=%2B233123456789" + "&key=support&code=1982&time=2011-01-01+10:10:10"); assertEquals("Welcome to MOTECH. Your message has been submitted to the support team" ,response.getContent()); } |
### Question:
MailingServiceImpl implements MailingService { public void send(Email mail) { SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setTo(mail.to()); mailMessage.setFrom(mail.from()); mailMessage.setSubject(mail.subject()); mailMessage.setText(mail.text()); mailSenderFactory.mailSender().send(mailMessage); } MailingServiceImpl(MailSenderFactory mailSenderFactory); void send(Email mail); }### Answer:
@Test public void shouldEmail() { MailSenderFactory mailSenderFactory = createMock(MailSenderFactory.class); JavaMailSender sender = createMock(JavaMailSender.class); expect(mailSenderFactory.mailSender()).andReturn(sender); sender.send(equalsMessage(expectedMessage())); expectLastCall(); Email mail = new Email("[email protected]", "[email protected]", "Hi", "Hello World"); replay(mailSenderFactory,sender); new MailingServiceImpl(mailSenderFactory).send(mail); verify(mailSenderFactory,sender); } |
### Question:
PatientBuilder { public Patient build() { if (registrantType == RegistrantType.CHILD_UNDER_FIVE) { return buildChild(); } else { return buildPatient(); } } PatientBuilder(PersonService personService, MotechService motechService, IdentifierGenerator idGenerator,
RegistrantType registrantType, PatientService patientService, LocationService locationService); PatientBuilder setMotechId(Integer motechId); PatientBuilder setName(String fistName, String middleName, String lastName); PatientBuilder setAddress1(String address1); PatientBuilder setPreferredName(String preferredName); PatientBuilder setGender(Gender gender); PatientBuilder setBirthDate(Date birthDate); PatientBuilder setBirthDateEstimated(boolean birthDateEstimated); PatientBuilder setParent(Patient parent); PatientBuilder addAttribute(PersonAttributeTypeEnum patientAttributeType, Object originalValue, String methodName); PatientBuilder addAttribute(PersonAttributeTypeEnum patientAttributeType, Object originalValue, Object invocationTarget, String methodName); Patient build(); }### Answer:
@Test public void shouldNotAddPatientToCommunityWhenCommunityIsNotSet() { Community community = mock(Community.class); Patient patient = builder.build(); verify(community, never()).add(patient); } |
### Question:
TokenReloadCrumbExclusion extends CrumbExclusion { @Override public boolean process(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (TokenReloadAction.tokenReloadEnabled()) { String pathInfo = request.getPathInfo(); if (pathInfo != null && pathInfo.equals("/" + TokenReloadAction.URL_NAME + "/")) { chain.doFilter(request, response); return true; } } return false; } @Override boolean process(HttpServletRequest request, HttpServletResponse response, FilterChain chain); }### Answer:
@Test public void crumbExclusionIsDisabledByDefault() throws Exception { System.clearProperty("casc.reload.token"); TokenReloadCrumbExclusion crumbExclusion = new TokenReloadCrumbExclusion(); assertFalse(crumbExclusion.process(newRequestWithPath("/reload-configuration-as-code/"), null, null)); }
@Test public void crumbExclusionChecksRequestPath() throws Exception { System.setProperty("casc.reload.token", "someSecretValue"); TokenReloadCrumbExclusion crumbExclusion = new TokenReloadCrumbExclusion(); assertFalse(crumbExclusion.process(newRequestWithPath("/reload-configuration-as-code/2"), null, null)); }
@Test public void crumbExclustionAllowsReloadIfEnabledAndRequestPathMatch() throws Exception { System.setProperty("casc.reload.token", "someSecretValue"); TokenReloadCrumbExclusion crumbExclusion = new TokenReloadCrumbExclusion(); AtomicBoolean callProcessed = new AtomicBoolean(false); assertTrue(crumbExclusion.process(newRequestWithPath("/reload-configuration-as-code/"), null, (request, response) -> callProcessed.set(true))); assertTrue(callProcessed.get()); } |
### Question:
PrimitiveConfigurator implements Configurator { @NonNull @Override public Object configure(CNode config, ConfigurationContext context) throws ConfiguratorException { return Stapler.lookupConverter(target).convert(target, context.getSecretSourceResolver().resolve(config.asScalar().toString())); } PrimitiveConfigurator(Class clazz); @Override Class getTarget(); @NonNull @Override Set<Attribute> describe(); @NonNull @Override Object configure(CNode config, ConfigurationContext context); @Override Object check(CNode config, ConfigurationContext context); @CheckForNull @Override CNode describe(Object instance, ConfigurationContext context); @NonNull @Override List<Configurator> getConfigurators(ConfigurationContext context); }### Answer:
@Test public void _boolean() throws Exception { Configurator c = registry.lookupOrFail(boolean.class); final Object value = c.configure(new Scalar("true"), context); assertTrue((Boolean) value); }
@Test public void _int() throws Exception { Configurator c = registry.lookupOrFail(int.class); final Object value = c.configure(new Scalar("123"), context); assertEquals(123, (int) value); }
@Test public void _Integer() throws Exception { Configurator c = registry.lookupOrFail(Integer.class); final Object value = c.configure(new Scalar("123"), context); assertEquals(123, (int) value); }
@Test public void _string() throws Exception { Configurator c = registry.lookupOrFail(String.class); final Object value = c.configure(new Scalar("abc"), context); assertEquals("abc", value); }
@Test public void _enum() throws Exception { Configurator<Node.Mode> c = registry.lookupOrFail(Node.Mode.class); final Node.Mode value = c.configure(new Scalar("NORMAL"), context); assertEquals(Node.Mode.NORMAL, value); }
@Test public void _enum2() throws Exception { Configurator<TimeUnit> c = registry.lookupOrFail(TimeUnit.class); final TimeUnit value = c.configure(new Scalar("DAYS"), context); assertEquals(TimeUnit.DAYS, value); }
@Test public void _Integer_env() throws Exception { environment.set("ENV_FOR_TEST", "123"); Configurator c = registry.lookupOrFail(Integer.class); final Object value = c.configure(new Scalar("${ENV_FOR_TEST}"), context); assertEquals(123, (int) value); }
@Test public void _string_env() throws Exception { environment.set("ENV_FOR_TEST", "abc"); Configurator c = registry.lookupOrFail(String.class); final Object value = c.configure(new Scalar("${ENV_FOR_TEST}"), context); assertEquals("abc", value); }
@Test public void _string_env_default() throws Exception { environment.set("NOT_THERE", "abc"); Configurator c = registry.lookupOrFail(String.class); final Object value = c.configure(new Scalar("${ENV_FOR_TEST:-unsecured-token}"), context); assertEquals("unsecured-token", value); }
@Test public void _int_env_default() throws Exception { Configurator c = registry.lookupOrFail(Integer.class); final Object value = c.configure(new Scalar("${ENV_FOR_TEST:-123}"), context); assertEquals(123, value); } |
### Question:
StaticFieldExporter { @Deprecated public static void export(Module module, List<Class<?>> classesToConvert) { new StaticFieldExporter(module, null).export(classesToConvert); } StaticFieldExporter(Module module, Configuration conf); @Deprecated static void export(Module module, List<Class<?>> classesToConvert); void export(List<Class<?>> classesToConvert); }### Answer:
@Test public void testTypeScriptDefinition() throws IOException, IllegalArgumentException { Writer out = new StringWriter(); ArrayList<Class<?>> classesToConvert = new ArrayList<Class<?>>(); classesToConvert.add(TestClass.class); Module module = new Module("mod"); new StaticFieldExporter(module, null).export(classesToConvert); module.write(out); out.close(); final String result = out.toString(); System.out.println(result); assertTrue(result.contains("export class TestClassStatic")); assertTrue(result.contains("export enum ChangedEnumName")); assertTrue(result.contains("static MY_CONSTANT_STRING: string = 'Test';")); assertTrue(result .contains("static MY_CONSTANT_ENUM_ARRAY_2: ChangedEnumName[] = [ ChangedEnumName.VAL1, ChangedEnumName.VAL2 ];")); assertFalse(result.contains("doNotExportAsStatic")); } |
### Question:
SQLFile { public static List<String> statementsFrom(Reader reader) throws IOException { SQLFile file = new SQLFile(); file.parse(reader); return file.getStatements(); } void parse(Reader in); List<String> getStatements(); static List<String> statementsFrom(Reader reader); static List<String> statementsFrom(File sqlfile); }### Answer:
@Test public void testReadMultiLineCommand() throws IOException { String firstLine = "CREATE TABLE 'testTable'"; String secondLine = "_id INTEGER PRIMARY KEY AUTOINCREMENT;"; String singleLineCommand = firstLine + " " + secondLine; String multiLineCommand = firstLine + "\n" + secondLine; List<String> statementsFromMultiline = SQLFile.statementsFrom(new StringReader(multiLineCommand)); assertEquals(singleLineCommand, statementsFromMultiline.get(0)); }
@Test public void testSkippingTrailingComments() throws IOException { String rawLine = "CREATE TABLE 'testTable'"; String comment = "-- adding some comment that should get stripped off"; String nextLine = "_id INTEGER PRIMARY KEY AUTOINCREMENT;"; String lineCommand = rawLine + comment + "\n" + nextLine; List<String> statements = SQLFile.statementsFrom(new StringReader(lineCommand)); assertEquals(rawLine + " " + nextLine, statements.get(0)); } |
### Question:
AllDateTypes { public LocalDate getLocalDate() { return localDate; } AllDateTypes(); Date getDate(); void setDate(Date date); LocalDate getLocalDate(); void setLocalDate(LocalDate localDate); LocalDateTime getLocalDateTime(); void setLocalDateTime(LocalDateTime localDateTime); DayOfWeek getDayOfWeek(); void setDayOfWeek(DayOfWeek dayOfWeek); LocalTime getSixThirty(); void setSixThirty(LocalTime sixThirty); ZoneId getZoneId(); void setZoneId(ZoneId zoneId); ZonedDateTime getZonedDateTime(); void setZonedDateTime(ZonedDateTime zonedDateTime); ZoneOffset getOffset(); void setOffset(ZoneOffset offset); OffsetDateTime getOffsetDateTime(); void setOffsetDateTime(OffsetDateTime offsetDateTime); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void givenLocalDate_shouldSerialize() throws ParseException { String expectedJson = "{\"year\":2017,\"month\":12,\"day\":25}"; String actualJson = new GsonBuilder().create().toJson(new AllDateTypes().getLocalDate()); assertThat(actualJson).isEqualTo(expectedJson); } |
### Question:
RuntimeSampler { public static GsonBuilder gsonBuilder() { return new GsonBuilder() .serializeNulls() .setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { return false; } @Override public boolean shouldSkipClass(Class<?> aClass) { return false; } }) .excludeFieldsWithModifiers(Modifier.PROTECTED) .excludeFieldsWithoutExposeAnnotation() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .setFieldNamingStrategy((field) -> field.getName().toLowerCase()) .setDateFormat("MM/dd/yyyy") .setPrettyPrinting(); } static GsonBuilder gsonBuilder(); }### Answer:
@Test public void test_using_gsonBuilder() { String expectedJson = "{\n" + " \"byteprimitive\": 0,\n" + " \"shortprimitive\": 0,\n" + " \"charprimitive\": \"\\u0000\",\n" + " \"intprimitive\": 0,\n" + " \"longprimitive\": 0,\n" + " \"floatprimitive\": 0.0,\n" + " \"doubleprimitive\": 0.0,\n" + " \"aboolean\": false,\n" + " \"bytewrapper\": 0,\n" + " \"shortwrapper\": 0,\n" + " \"charwrapper\": \"\\u0000\",\n" + " \"intwrapper\": 0,\n" + " \"longwrapper\": 0,\n" + " \"floatwrapper\": 0.0,\n" + " \"doublewrapper\": 0.0,\n" + " \"booleanwrapper\": false,\n" + " \"string\": \"Hello World\"\n" + "}"; String actualJson = RuntimeSampler.gsonBuilder().create().toJson(new AllBasicTypes()); String cc = RuntimeSampler.gsonBuilder().create().fromJson("", String.class); assertThat(actualJson).isEqualTo(expectedJson); } |
### Question:
RuntimeSampler { public static JsonbConfig jsonbConfig() { return new JsonbConfig() .withNullValues(true) .withPropertyVisibilityStrategy(new PropertyVisibilityStrategy() { @Override public boolean isVisible(Field field) { return false; } @Override public boolean isVisible(Method method) { return false; } }) .withPropertyNamingStrategy(PropertyNamingStrategy.CASE_INSENSITIVE) .withPropertyOrderStrategy(PropertyOrderStrategy.REVERSE) .withAdapters(new ClassAdapter()) .withDeserializers(new CustomDeserializer()) .withSerializers(new CustomSerializer()) .withBinaryDataStrategy(BinaryDataStrategy.BASE_64_URL) .withDateFormat("MM/dd/yyyy", Locale.ENGLISH) .withLocale(Locale.CANADA) .withEncoding("UTF-8") .withStrictIJSON(true) .withFormatting(true); } static JsonbConfig jsonbConfig(); }### Answer:
@Test public void test_using_jsonbConfig() { String expectedJson = "\n" + "{\n" + " \"string\": null,\n" + " \"shortWrapper\": null,\n" + " \"shortPrimitive\": null,\n" + " \"longWrapper\": null,\n" + " \"longPrimitive\": null,\n" + " \"intWrapper\": null,\n" + " \"intPrimitive\": null,\n" + " \"floatWrapper\": null,\n" + " \"floatPrimitive\": null,\n" + " \"doubleWrapper\": null,\n" + " \"doublePrimitive\": null,\n" + " \"charWrapper\": null,\n" + " \"charPrimitive\": null,\n" + " \"byteWrapper\": null,\n" + " \"bytePrimitive\": null,\n" + " \"booleanWrapper\": null,\n" + " \"aBoolean\": null\n" + "}"; String actualJson = JsonbBuilder.create(RuntimeSampler.jsonbConfig()).toJson(new AllBasicTypes()); assertThat(actualJson).isEqualTo(expectedJson); } |
### Question:
AllDateTypes { public Date getDate() { return date; } AllDateTypes(); Date getDate(); void setDate(Date date); LocalDate getLocalDate(); void setLocalDate(LocalDate localDate); LocalDateTime getLocalDateTime(); void setLocalDateTime(LocalDateTime localDateTime); DayOfWeek getDayOfWeek(); void setDayOfWeek(DayOfWeek dayOfWeek); LocalTime getLocalTime(); void setLocalTime(LocalTime localTime); ZoneId getZoneId(); void setZoneId(ZoneId zoneId); ZonedDateTime getZonedDateTime(); void setZonedDateTime(ZonedDateTime zonedDateTime); ZoneOffset getOffset(); void setOffset(ZoneOffset offset); OffsetDateTime getOffsetDateTime(); void setOffsetDateTime(OffsetDateTime offsetDateTime); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void givenDate_shouldSerialize() throws ParseException, JsonProcessingException { String expectedJson = "1514160000000"; String actualJson = new ObjectMapper().writeValueAsString(new AllDateTypes().getDate()); assertThat(actualJson).isEqualTo(expectedJson); } |
### Question:
AllDateTypes { public LocalDate getLocalDate() { return localDate; } AllDateTypes(); Date getDate(); void setDate(Date date); LocalDate getLocalDate(); void setLocalDate(LocalDate localDate); LocalDateTime getLocalDateTime(); void setLocalDateTime(LocalDateTime localDateTime); DayOfWeek getDayOfWeek(); void setDayOfWeek(DayOfWeek dayOfWeek); LocalTime getLocalTime(); void setLocalTime(LocalTime localTime); ZoneId getZoneId(); void setZoneId(ZoneId zoneId); ZonedDateTime getZonedDateTime(); void setZonedDateTime(ZonedDateTime zonedDateTime); ZoneOffset getOffset(); void setOffset(ZoneOffset offset); OffsetDateTime getOffsetDateTime(); void setOffsetDateTime(OffsetDateTime offsetDateTime); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void givenLocalDate_shouldSerialize() throws ParseException, JsonProcessingException { String expectedJson = "{\"year\":2017,\"month\":\"DECEMBER\",\"chronology\":{\"id\":\"ISO\",\"calendarType\":\"iso8601\"},\"dayOfMonth\":25,\"dayOfWeek\":\"MONDAY\",\"dayOfYear\":359,\"leapYear\":false,\"monthValue\":12,\"era\":\"CE\"}"; String actualJson = new ObjectMapper().writeValueAsString(new AllDateTypes().getLocalDate()); assertThat(actualJson).isEqualTo(expectedJson); } |
### Question:
AllDateTypes { public LocalDateTime getLocalDateTime() { return localDateTime; } AllDateTypes(); Date getDate(); void setDate(Date date); LocalDate getLocalDate(); void setLocalDate(LocalDate localDate); LocalDateTime getLocalDateTime(); void setLocalDateTime(LocalDateTime localDateTime); DayOfWeek getDayOfWeek(); void setDayOfWeek(DayOfWeek dayOfWeek); LocalTime getLocalTime(); void setLocalTime(LocalTime localTime); ZoneId getZoneId(); void setZoneId(ZoneId zoneId); ZonedDateTime getZonedDateTime(); void setZonedDateTime(ZonedDateTime zonedDateTime); ZoneOffset getOffset(); void setOffset(ZoneOffset offset); OffsetDateTime getOffsetDateTime(); void setOffsetDateTime(OffsetDateTime offsetDateTime); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void givenLocalDateTime_shouldSerialize() throws ParseException, JsonProcessingException { String expectedJson = "{\"hour\":0,\"minute\":0,\"nano\":0,\"second\":0,\"dayOfMonth\":25,\"dayOfWeek\":\"MONDAY\",\"dayOfYear\":359,\"month\":\"DECEMBER\",\"monthValue\":12,\"year\":2017,\"chronology\":{\"id\":\"ISO\",\"calendarType\":\"iso8601\"}}"; String actualJson = new ObjectMapper().writeValueAsString(new AllDateTypes().getLocalDateTime()); assertThat(actualJson).isEqualTo(expectedJson); } |
### Question:
AllDateTypes { public LocalTime getLocalTime() { return localTime; } AllDateTypes(); Date getDate(); void setDate(Date date); LocalDate getLocalDate(); void setLocalDate(LocalDate localDate); LocalDateTime getLocalDateTime(); void setLocalDateTime(LocalDateTime localDateTime); DayOfWeek getDayOfWeek(); void setDayOfWeek(DayOfWeek dayOfWeek); LocalTime getLocalTime(); void setLocalTime(LocalTime localTime); ZoneId getZoneId(); void setZoneId(ZoneId zoneId); ZonedDateTime getZonedDateTime(); void setZonedDateTime(ZonedDateTime zonedDateTime); ZoneOffset getOffset(); void setOffset(ZoneOffset offset); OffsetDateTime getOffsetDateTime(); void setOffsetDateTime(OffsetDateTime offsetDateTime); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void givenLocalTime_shouldSerialize() throws ParseException, JsonProcessingException { String expectedJson = "{\"hour\":23,\"minute\":0,\"second\":0,\"nano\":0}"; String actualJson = new ObjectMapper().writeValueAsString(new AllDateTypes().getLocalTime()); assertThat(actualJson).isEqualTo(expectedJson); } |
### Question:
RuntimeSampler { public static ObjectMapper objectMapper() { return new ObjectMapper() .setDefaultPropertyInclusion(JsonInclude.Include.ALWAYS) .setDefaultVisibility(JsonAutoDetect.Value.construct(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC)) .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .configure(SerializationFeature.WRITE_NULL_MAP_VALUES, true) .setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE) .setDateFormat(new SimpleDateFormat("MM/dd/yyyy")) .setDefaultPrettyPrinter(new DefaultPrettyPrinter()) .setLocale(Locale.CANADA); } static ObjectMapper objectMapper(); }### Answer:
@Test public void test_using_customised_objectMapper() throws IOException { String expectedJson = "{\"aBoolean\":false,\"booleanWrapper\":false,\"bytePrimitive\":0,\"byteWrapper\":0,\"charPrimitive\":\"\\u0000\",\"charWrapper\":\"\\u0000\",\"doublePrimitive\":0.0,\"doubleWrapper\":0.0,\"floatPrimitive\":0.0,\"floatWrapper\":0.0,\"intPrimitive\":0,\"intWrapper\":0,\"longPrimitive\":0,\"longWrapper\":0,\"shortPrimitive\":0,\"shortWrapper\":0,\"string\":\"Hello World\"}"; String actualJson = RuntimeSampler.objectMapper().writeValueAsString(new AllBasicTypes()); assertThat(actualJson).isEqualTo(expectedJson); } |
### Question:
MatrixChecker { static void verifyArrays(@NonNull double[][] arrays) { checkNotNull(arrays); final int m = arrays.length; checkExpression(m > 0, "Row should be positive"); final int n = arrays[0].length; for (int i = 1; i < m; ++i) { checkExpression(arrays[i].length == n, "All rows must have the same length"); } } }### Answer:
@Test public void testVerifyArrays() { final double[][] arrays = new double[][]{ new double[]{1, 2, 3}, new double[]{4, 5, 6} }; MatrixChecker.verifyArrays(arrays); }
@Test(expected = IllegalArgumentException.class) public void testVerifyArrays2() { MatrixChecker.verifyArrays(new double[0][0]); }
@Test(expected = IllegalArgumentException.class) public void testVerifyArrays3() { final double[][] arrays = new double[][]{ new double[]{1, 2, 3}, new double[]{4, 5, 6, 4} }; MatrixChecker.verifyArrays(arrays); } |
### Question:
Matrix implements Serializable { public static Matrix array(@NonNull double[][] arrays) { verifyArrays(arrays); final int row = arrays.length; final int col = arrays[0].length; final double[] array = new double[row * col]; for (int i = 0; i < row; ++i) { System.arraycopy(arrays[i], 0, array, i * col, col); } return Matrix.array(array, row); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer:
@Test public void testArray() { final double[] original = new double[]{ 1D, 2D, 3D, 4D, 5D, 6D }; final Matrix matrix = Matrix.array(original, 2); assertNotSame(original, matrix.getArray()); assertEquals(matrix.getRow(), 2); assertEquals(matrix.getCol(), 3); }
@Test(expected = IllegalArgumentException.class) public void testArray2() { final double[] original = new double[]{ 1D, 2D, 3D, 4D, 5D, 6D }; Matrix.array(original, 4); } |
### Question:
Matrix implements Serializable { public Matrix copy() { final double[] array = mArray.clone(); return Matrix.array(array, mRow); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer:
@Test public void testCopy() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 2); final Matrix b = a.copy(); assertNotSame(a, b); assertNotSame(a.getArray(), b.getArray()); assertEquals(b.getRow(), 2); assertEquals(b.getCol(), 3); assertArrayEquals(b.getArray(), new double[]{ 1, 2, 3, 4, 5, 6 }, 0); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.