Skip to content

Commit

Permalink
Add Integration Tests
Browse files Browse the repository at this point in the history
  • Loading branch information
benzuzu committed Jul 25, 2023
1 parent 7c8d35c commit 17f240d
Show file tree
Hide file tree
Showing 8 changed files with 440 additions and 26 deletions.
14 changes: 14 additions & 0 deletions src/main/java/org/mskcc/cbio/oncokb/config/SlackConfiguration.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package org.mskcc.cbio.oncokb.config;

import com.slack.api.Slack;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SlackConfiguration {

@Bean
public Slack slack() {
return Slack.getInstance();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ public enum MailType {
, APPROVAL(new MailTypeBuilder()
.templateName("approvalEmail")
.description("User Approval")
.titleKey("email.approval.title"))
.titleKey("email.approval.title")
.stringTemplateName("approvalEmailString.txt"))
, APPROVAL_ALIGN_LICENSE_WITH_COMPANY(new MailTypeBuilder()
.templateName("approvalAlignLicenseWithCompanyEmail")
.description("Autocorrect user license to company license")
Expand Down
14 changes: 5 additions & 9 deletions src/main/java/org/mskcc/cbio/oncokb/service/SlackService.java
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,16 @@ public class SlackService {
private final MailService mailService;
private final EmailService emailService;
private final UserMailsService userMailsService;
private final UserMapper userMapper;
private final Slack slack;

@Autowired
private UserMapper userMapper;

public SlackService(ApplicationProperties applicationProperties, MailService mailService, EmailService emailService, UserMailsService userMailsService) {
public SlackService(ApplicationProperties applicationProperties, MailService mailService, EmailService emailService, UserMailsService userMailsService, UserMapper userMapper, Slack slack) {
this.applicationProperties = applicationProperties;
this.mailService = mailService;
this.emailService = emailService;
this.userMailsService = userMailsService;
this.userMapper = userMapper;
this.slack = slack;
}

@Async
Expand Down Expand Up @@ -119,7 +120,6 @@ public void sendApprovedConfirmation(UserDTO userDTO, Company company) {
.text(text)
.build();

Slack slack = Slack.getInstance();
try {
// This is an automatic message when user from whitelist is registered.
WebhookResponse response = slack.send(this.applicationProperties.getSlack().getUserRegistrationWebhook(), payload);
Expand All @@ -135,7 +135,6 @@ public void sendConfirmationOnUserAcceptsTrialAgreement(UserDTO userDTO, Instant
.text(userDTO.getEmail() + " has read and agreed to the trial license agreement. The account has been activated, the trial period ends on " + expirationDate)
.build();

Slack slack = Slack.getInstance();
try {
WebhookResponse response = slack.send(this.applicationProperties.getSlack().getUserRegistrationWebhook(), payload);

Expand All @@ -158,7 +157,6 @@ public void sendConfirmationOnUserAcceptsTrialAgreement(UserDTO userDTO, Instant

public List<UserIdMessagePair> getAllUnapprovedUserRequestsSentAfter(int daysAgo) {
List<UserIdMessagePair> userList = new ArrayList<>();
Slack slack = Slack.getInstance();
final String REQUEST_MESSAGE_TEXT = "This content can't be displayed.";

try {
Expand Down Expand Up @@ -228,7 +226,6 @@ private void sendBlocks(String url, List<LayoutBlock> layoutBlocks) {
.blocks(layoutBlocks)
.build();

Slack slack = Slack.getInstance();
try {
WebhookResponse response = slack.send(url, payload);
log.info("Send the latest user blocks to slack with response code " + response.getCode());
Expand Down Expand Up @@ -677,7 +674,6 @@ private void sendModal(String triggerId, View view) {
.view(view)
.build();

Slack slack = Slack.getInstance();
try {
ViewsOpenResponse response = slack.methods().viewsOpen(request);
if (!response.isOk()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,18 @@ public class SlackController {

private final UserService userService;

@Autowired
private UserMapper userMapper;
private final UserMapper userMapper;

private final UserRepository userRepository;

private final MailService mailService;

public SlackController(UserService userService, UserRepository userRepository, MailService mailService, SlackService slackService) {
public SlackController(UserService userService, UserRepository userRepository, MailService mailService, SlackService slackService, UserMapper userMapper) {
this.userService = userService;
this.userRepository = userRepository;
this.mailService = mailService;
this.slackService = slackService;
this.userMapper = userMapper;
}

// We do not put any auth protection for the slack call
Expand All @@ -62,6 +62,7 @@ public SlackController(UserService userService, UserRepository userRepository, M
public ResponseEntity<String> approveUser(@RequestParam("payload") String actionJSON) throws IOException {
Gson snakeCase = GsonFactory.createSnakeCase();
UnknownPayload pl = snakeCase.fromJson(actionJSON, UnknownPayload.class);
log.debug("delete later");
if (pl.getType().equals(BlockActionPayload.TYPE)) {
BlockActionPayload blockActionPayload = snakeCase.fromJson(actionJSON, BlockActionPayload.class);
ActionId actionId = this.slackService.getActionId(blockActionPayload);
Expand Down
26 changes: 13 additions & 13 deletions src/main/resources/config/application-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ spring:
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:mysql://localhost:3306/oncokb_public?useUnicode=true&characterEncoding=utf8&useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&createDatabaseIfNotExist=true
username: root
password: root
password: annaben123
hikari:
poolName: Hikari
auto-commit: false
Expand All @@ -52,11 +52,11 @@ spring:
show-sql: true
liquibase:
# Remove 'faker' if you do not want the sample data to be loaded automatically
contexts: dev, faker
contexts: dev
mail:
host: smtp.gmail.com
username:
password:
username: [email protected]
password: wambrlgrknmtaowj
port: 587
protocol: smtp
tls: true
Expand Down Expand Up @@ -142,8 +142,8 @@ application:
slack: # Add the following if you wish to integrate user registration to Slack and send the weekly unapproved users email
# You will need to expose your app using a public-facing URL to achieve interactivity with components (use ngrok)
# specific to the app you install to your Slack workspace
user-registration-webhook: # for sending user requests to Slack
slack-bot-oauth-token: # for permission to read conversation history (generation of unapproved users list)
user-registration-webhook: https://hooks.slack.com/services/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 # for sending user requests to Slack
slack-bot-oauth-token: xoxp-4676495597-2180980600950-3967749158372-dc12ff23e1b33aaf82a9f8fb8f27a239 # for permission to read conversation history (generation of unapproved users list)
# for Slack link in weekly unapproved users email
slack-base-url:
user-registration-channel-id:
Expand All @@ -154,10 +154,10 @@ application:
password: 'oncokb-public-redis-password'
address: 'redis://localhost:6379'
email-addresses:
license-address:
registration-address:
contact-address:
tech-dev-address:
license-address: [email protected]
registration-address: [email protected]
contact-address: [email protected]
tech-dev-address: [email protected]
public-website-api-threshold: 10
academic-email-clarify-domain:
frontend:
Expand All @@ -168,9 +168,9 @@ application:
recaptcha-site-key:
recaptcha-threshold: 0.1
aws:
s3-access-key:
s3-secret-key:
s3-region:
s3-access-key: AKIARAXHP3JMLUTOQ4EJ
s3-secret-key: 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
s3-region: us-east-1
github-token:
db-read-only: false # Certain endpoints will be disabled when readonly is set to true
recaptcha:
Expand Down
130 changes: 130 additions & 0 deletions src/test/java/org/mskcc/cbio/oncokb/service/SlackServiceIT.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package org.mskcc.cbio.oncokb.service;

import com.slack.api.Slack;
import com.slack.api.model.block.LayoutBlock;
import com.slack.api.model.block.SectionBlock;
import com.slack.api.model.block.composition.TextObject;
import com.slack.api.webhook.Payload;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mskcc.cbio.oncokb.OncokbPublicApp;
import org.mskcc.cbio.oncokb.config.application.ApplicationProperties;
import org.mskcc.cbio.oncokb.config.application.SlackProperties;
import org.mskcc.cbio.oncokb.domain.Company;
import org.mskcc.cbio.oncokb.domain.enumeration.LicenseStatus;
import org.mskcc.cbio.oncokb.domain.enumeration.LicenseType;
import org.mskcc.cbio.oncokb.service.dto.UserDTO;
import org.mskcc.cbio.oncokb.service.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;

@SpringBootTest(classes = OncokbPublicApp.class)
class SlackServiceIT {

// Testing Slack url for applicationProperties
private static final String USER_REGISTRATION_WEBHOOK = "https://hooks.slack.com/example";

@Autowired
private ApplicationProperties applicationProperties;

@Autowired
private MailService mailService;

@Autowired
private EmailService emailService;

@Autowired
private UserMailsService userMailsService;

@Autowired
private UserMapper userMapper;

@Spy
private Slack slack;

@Captor
private ArgumentCaptor<String> urlCaptor;

@Captor
private ArgumentCaptor<Payload> payloadCaptor;

private SlackService slackService;

@BeforeEach
public void setup() throws IOException {
MockitoAnnotations.initMocks(this);
doReturn(null).when(slack).send(any(String.class), any(Payload.class));

// Specify webhook address for testing
applicationProperties.setSlack(new SlackProperties());
applicationProperties.getSlack().setUserRegistrationWebhook(USER_REGISTRATION_WEBHOOK);

slackService = new SlackService(applicationProperties, mailService, emailService, userMailsService, userMapper, slack);
}

@Test
void testSendUserRegistrationToChannel() throws IOException {
// Create mock user
UserDTO user = new UserDTO();
user.setId(0L);
user.setEmail("[email protected]");
user.setFirstName("john");
user.setLastName("doe");
user.setJobTitle("job title");
user.setCompanyName("company name");
user.setCity("city");
user.setCountry("country");
user.setLicenseType(LicenseType.COMMERCIAL);
Company company = new Company();
company.setName("company name");
company.setLicenseType(LicenseType.COMMERCIAL);
company.setLicenseStatus(LicenseStatus.UNKNOWN);

// Mock send Slack blocks
slackService.sendUserRegistrationToChannel(user, false, company);
verify(slack).send(urlCaptor.capture(), payloadCaptor.capture());
String url = urlCaptor.getValue();
Payload payload = payloadCaptor.getValue();

// Ensure url is correct
assertThat(url).isEqualTo(USER_REGISTRATION_WEBHOOK);

// Ensure all crucial information is in payload
Set<String> expectedValues = new HashSet<>();
expectedValues.add(LicenseType.COMMERCIAL.getName());
expectedValues.add("Not Activated");
expectedValues.add("REGULAR");
expectedValues.add("[email protected]");
expectedValues.add("john doe");
expectedValues.add("job title");
expectedValues.add("company name");
expectedValues.add("city");
expectedValues.add("country");
for (LayoutBlock block : payload.getBlocks()) {
if (block instanceof SectionBlock) {
SectionBlock sectionBlock = (SectionBlock) block;
if (sectionBlock.getText() != null) {
expectedValues.removeIf(sectionBlock.getText().getText()::contains);
}
if (sectionBlock.getFields() != null) {
for (TextObject textObject : sectionBlock.getFields()) {
expectedValues.removeIf(textObject.getText()::contains);
}
}
}
}
assertThat(expectedValues).isEmpty();
}
}
Loading

0 comments on commit 17f240d

Please sign in to comment.