Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • arsnova/arsnova-backend
  • pcvl72/arsnova-backend
  • tksl38/arsnova-backend
3 results
Show changes
Showing
with 509 additions and 524 deletions
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARSnova Backend is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.service.score;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import de.thm.arsnova.model.transport.ScoreStatistics;
import de.thm.arsnova.persistence.SessionStatisticsRepository;
public class ScoreBasedScoreCalculatorTest {
private Score courseScore;
private VariantScoreCalculator lp;
private int id = 1;
private String addQuestion(final String questionVariant, final int points) {
final String questionId = "question" + (id++);
final int piRound = 1;
courseScore.addQuestion(questionId, questionVariant, piRound, points);
return questionId;
}
private void addAnswer(final String questionId, final String userId, final int points) {
final int piRound = 1;
courseScore.addAnswer(questionId, piRound, userId, points);
}
@Before
public void setUp() {
this.courseScore = new Score();
final SessionStatisticsRepository db = mock(SessionStatisticsRepository.class);
when(db.getLearningProgress(null)).thenReturn(courseScore);
this.lp = new ScoreBasedScoreCalculator(db);
}
@Test
public void shouldFilterBasedOnQuestionVariant() {
// Total of 300 Points
final String q1 = this.addQuestion("lecture", 100);
final String q2 = this.addQuestion("lecture", 100);
final String q3 = this.addQuestion("lecture", 100);
final String userId1 = "user1";
final String userId2 = "user2";
final String userId3 = "user3";
// Both users achieve 200 points
this.addAnswer(q1, userId1, 100);
this.addAnswer(q1, userId2, 100);
this.addAnswer(q1, userId3, 0);
this.addAnswer(q2, userId1, 0);
this.addAnswer(q2, userId2, 100);
this.addAnswer(q2, userId3, 0);
this.addAnswer(q3, userId1, 100);
this.addAnswer(q3, userId2, 100);
this.addAnswer(q3, userId3, 0);
lp.setQuestionVariant("lecture");
final ScoreStatistics u1LectureProgress = lp.getMyProgress(null, userId1);
// (500/3) / 300 ~= 0,56.
assertEquals(56, u1LectureProgress.getCourseProgress());
// 200 / 300 ~= 0,67.
assertEquals(67, u1LectureProgress.getMyProgress());
}
@Test
public void shouldNotContainRoundingErrors() {
// Total of 300 Points
final String q1 = this.addQuestion("lecture", 100);
final String q2 = this.addQuestion("lecture", 100);
final String q3 = this.addQuestion("lecture", 100);
final String userId1 = "user1";
final String userId2 = "user2";
// Both users achieve 200 points
this.addAnswer(q1, userId1, 100);
this.addAnswer(q1, userId2, 100);
this.addAnswer(q2, userId1, 0);
this.addAnswer(q2, userId2, 0);
this.addAnswer(q3, userId1, 100);
this.addAnswer(q3, userId2, 100);
lp.setQuestionVariant("lecture");
final ScoreStatistics u1LectureProgress = lp.getMyProgress(null, userId1);
// 200 / 300 = 0,67
assertEquals(67, u1LectureProgress.getCourseProgress());
assertEquals(67, u1LectureProgress.getMyProgress());
}
@Test
public void shouldConsiderAnswersOfSamePiRound() {
final String userId1 = "user1";
final String userId2 = "user2";
// question is in round 2
courseScore.addQuestion("q1", "lecture", 2, 100);
// 25 points in round 1, 75 points in round two for the first user
courseScore.addAnswer("q1", 1, userId1, 25);
courseScore.addAnswer("q1", 2, userId1, 75);
// 75 points in round 1, 25 points in round two for the second user
courseScore.addAnswer("q1", 1, userId2, 75);
courseScore.addAnswer("q1", 2, userId2, 25);
final ScoreStatistics u1Progress = lp.getMyProgress(null, userId1);
final ScoreStatistics u2Progress = lp.getMyProgress(null, userId2);
// only the answer for round 2 should be considered
assertEquals(50, u1Progress.getCourseProgress());
assertEquals(75, u1Progress.getMyProgress());
assertEquals(50, u2Progress.getCourseProgress());
assertEquals(25, u2Progress.getMyProgress());
}
@Test
public void shouldIncludeNominatorAndDenominatorOfResultExcludingStudentCount() {
// two questions
final String q1 = this.addQuestion("lecture", 10);
final String q2 = this.addQuestion("lecture", 10);
// three users
final String userId1 = "user1";
final String userId2 = "user2";
final String userId3 = "user3";
// six answers
this.addAnswer(q1, userId1, 10);
this.addAnswer(q2, userId1, 0);
this.addAnswer(q1, userId2, 10);
this.addAnswer(q2, userId2, 0);
this.addAnswer(q1, userId3, 10);
this.addAnswer(q2, userId3, 0);
final int numerator = lp.getCourseProgress(null).getNumerator();
final int denominator = lp.getCourseProgress(null).getDenominator();
// If the percentage is wrong, then we need to adapt this test case!
assertEquals("Precondition failed -- The underlying calculation has changed",
50, lp.getCourseProgress(null).getCourseProgress());
assertEquals(10, numerator);
assertEquals(20, denominator);
}
}
/*
* Copyright (C) 2012 THM webMedia
*
* This file is part of ARSnova.
*
* ARSnova is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARSnova is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.services;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import de.thm.arsnova.dao.StubDatabaseDao;
import de.thm.arsnova.exceptions.NoContentException;
import de.thm.arsnova.exceptions.NotFoundException;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"file:src/main/webapp/WEB-INF/spring/arsnova-servlet.xml",
"file:src/main/webapp/WEB-INF/spring/spring-main.xml",
"file:src/test/resources/test-config.xml"
})
public class FeedbackServiceTest {
@Autowired
IFeedbackService feedbackService;
@Autowired
StubUserService userService;
@Autowired
private StubDatabaseDao databaseDao;
@After
public final void cleanup() {
databaseDao.cleanupTestData();
userService.setUserAuthenticated(false);
}
@Test(expected = NotFoundException.class)
public void testShouldFindFeedbackForNonExistantSession() {
userService.setUserAuthenticated(true);
feedbackService.getFeedback("00000000");
}
@Test
public void testShouldReturnFeedback() {
userService.setUserAuthenticated(true);
assertNotNull(feedbackService.getFeedback("87654321"));
assertEquals(2, (int) feedbackService.getFeedback("87654321").getValues().get(0));
assertEquals(3, (int) feedbackService.getFeedback("87654321").getValues().get(1));
assertEquals(5, (int) feedbackService.getFeedback("87654321").getValues().get(2));
assertEquals(7, (int) feedbackService.getFeedback("87654321").getValues().get(3));
}
@Test(expected = NotFoundException.class)
public void testShouldFindFeedbackCountForNonExistantSession() {
userService.setUserAuthenticated(true);
feedbackService.getFeedbackCount("00000000");
}
@Test
public void testShouldReturnFeedbackCount() {
userService.setUserAuthenticated(true);
assertEquals(17, feedbackService.getFeedbackCount("87654321"));
}
@Test(expected = NotFoundException.class)
public void testShouldFindAverageFeedbackForNonExistantSession() {
userService.setUserAuthenticated(true);
feedbackService.getAverageFeedback("00000000");
}
@Test
public void testShouldReturnZeroFeedbackCountForNoFeedbackAtAll() {
userService.setUserAuthenticated(true);
assertEquals(0, feedbackService.getFeedbackCount("12345678"));
}
@Test(expected = NoContentException.class)
public void testShouldReturnAverageFeedbackForNoFeedbackAtAll() {
userService.setUserAuthenticated(true);
feedbackService.getAverageFeedback("12345678");
}
@Test
public void testShouldReturnAverageFeedbackRounded() {
userService.setUserAuthenticated(true);
assertEquals(2, feedbackService.getAverageFeedbackRounded("18273645"));
}
@Test
public void testShouldReturnAverageFeedbackNotRounded() {
userService.setUserAuthenticated(true);
assertEquals(2.1904, feedbackService.getAverageFeedback("18273645"), 0.001);
}
}
\ No newline at end of file
/*
* Copyright (C) 2012 THM webMedia
*
* This file is part of ARSnova.
*
* ARSnova is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARSnova is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.services;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import de.thm.arsnova.dao.StubDatabaseDao;
import de.thm.arsnova.entities.InterposedQuestion;
import de.thm.arsnova.exceptions.NotFoundException;
import de.thm.arsnova.exceptions.UnauthorizedException;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"file:src/main/webapp/WEB-INF/spring/arsnova-servlet.xml",
"file:src/main/webapp/WEB-INF/spring/spring-main.xml",
"file:src/test/resources/test-config.xml"
})
public class QuestionServiceTest {
@Autowired
IQuestionService questionService;
@Autowired
StubUserService userService;
@Autowired
private StubDatabaseDao databaseDao;
@After
public final void cleanup() {
databaseDao.cleanupTestData();
userService.setUserAuthenticated(false);
}
@Test(expected = UnauthorizedException.class)
public void testShouldNotReturnQuestionsIfNotAuthenticated() {
userService.setUserAuthenticated(false);
questionService.getSkillQuestions("12345678");
}
@Test(expected = NotFoundException.class)
public void testShouldFindQuestionsForNonExistantSession() {
userService.setUserAuthenticated(true);
questionService.getSkillQuestions("00000000");
}
@Test
public void testShouldFindQuestions() {
userService.setUserAuthenticated(true);
assertEquals(1, questionService.getSkillQuestionCount("12345678"));
}
@Test
public void testShouldMarkInterposedQuestionAsReadIfSessionCreator() throws Exception {
userService.setUserAuthenticated(true);
InterposedQuestion theQ = new InterposedQuestion();
theQ.setRead(false);
theQ.set_id("the internal id");
theQ.setSessionId("12345678");
databaseDao.interposedQuestion = theQ;
questionService.readInterposedQuestion(theQ.get_id());
assertTrue(theQ.isRead());
}
@Test
public void testShouldNotMarkInterposedQuestionAsReadIfRegularUser() throws Exception {
userService.setUserAuthenticated(true, "regular user");
InterposedQuestion theQ = new InterposedQuestion();
theQ.setRead(false);
theQ.set_id("the internal id");
theQ.setSessionId("12345678");
databaseDao.interposedQuestion = theQ;
questionService.readInterposedQuestion(theQ.get_id());
assertFalse(theQ.isRead());
}
}
/*
* Copyright (C) 2012 THM webMedia
*
* This file is part of ARSnova.
*
* ARSnova is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARSnova is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.services;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import de.thm.arsnova.dao.StubDatabaseDao;
import de.thm.arsnova.entities.Session;
import de.thm.arsnova.exceptions.NotFoundException;
import de.thm.arsnova.exceptions.UnauthorizedException;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"file:src/main/webapp/WEB-INF/spring/arsnova-servlet.xml",
"file:src/main/webapp/WEB-INF/spring/spring-main.xml",
"file:src/test/resources/test-config.xml" })
public class SessionServiceTest {
@Autowired
private ISessionService sessionService;
@Autowired
private StubUserService userService;
@Autowired
private StubDatabaseDao databaseDao;
@After
public final void cleanup() {
databaseDao.cleanupTestData();
userService.setUserAuthenticated(false);
}
@Test
public void testShouldGenerateSessionKeyword() {
System.out.println(sessionService.generateKeyword());
assertTrue(sessionService.generateKeyword().matches("^[0-9]{8}$"));
}
@Test(expected = NotFoundException.class)
public void testShouldFindNonExistantSession() {
userService.setUserAuthenticated(true);
sessionService.joinSession("00000000");
}
@Test(expected = UnauthorizedException.class)
public void testShouldNotReturnSessionIfUnauthorized() {
userService.setUserAuthenticated(false);
sessionService.joinSession("12345678");
}
@Test(expected = UnauthorizedException.class)
public void testShouldNotSaveSessionIfUnauthorized() {
userService.setUserAuthenticated(false);
Session session = new Session();
session.setActive(true);
session.setCreator("ptsr00");
session.setKeyword("11111111");
session.setName("TestSessionX");
session.setShortName("TSX");
sessionService.saveSession(session);
userService.setUserAuthenticated(true);
assertNull(sessionService.joinSession("11111111"));
}
@Test
public void testShouldSaveSession() {
userService.setUserAuthenticated(true);
Session session = new Session();
session.setActive(true);
session.setCreator("ptsr00");
session.setKeyword("11111111");
session.setName("TestSessionX");
session.setShortName("TSX");
sessionService.saveSession(session);
assertNotNull(sessionService.joinSession("11111111"));
}
}
\ No newline at end of file
package de.thm.arsnova.services;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import de.thm.arsnova.dao.StubDatabaseDao;
import de.thm.arsnova.entities.Session;
import de.thm.arsnova.entities.Statistics;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"file:src/main/webapp/WEB-INF/spring/arsnova-servlet.xml",
"file:src/main/webapp/WEB-INF/spring/spring-main.xml",
"file:src/test/resources/test-config.xml"
})
public class StatisticsServiceTest {
@Autowired
private IStatisticsService statisticsService;
@Autowired
private StubUserService userService;
@Autowired
private StubDatabaseDao databaseDao;
@Before
public final void startup() {
// Create new session to be appended to the existing two sessions
Session session = new Session();
session.setKeyword("1111222");
session.setActive(false);
databaseDao.saveSession(session);
}
@After
public final void cleanup() {
databaseDao.cleanupTestData();
}
@Test
public final void testShouldReturnNoActiveUsers() {
int actual = statisticsService.countActiveUsers();
assertEquals(0, actual);
}
@Test
public final void testShouldReturnCurrentActiveUsers() {
Session session = new Session();
session.setKeyword("1278127812");
userService.setUserAuthenticated(true);
databaseDao.registerAsOnlineUser(userService.getCurrentUser(), session);
int actual = statisticsService.countActiveUsers();
assertEquals(1, actual);
userService.setUserAuthenticated(false);
}
@Test
public final void testShouldReturnStatistics() {
Statistics actual = statisticsService.getStatistics();
assertEquals(2, actual.getOpenSessions());
assertEquals(1, actual.getClosedSessions());
}
}
package de.thm.arsnova.services;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import junit.framework.Assert;
import org.jasig.cas.client.authentication.AttributePrincipalImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.scribe.up.profile.google.Google2AttributesDefinition;
import org.scribe.up.profile.google.Google2Profile;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import de.thm.arsnova.entities.User;
@RunWith(BlockJUnit4ClassRunner.class)
public class UserServiceTest {
private static final ConcurrentHashMap<UUID, User> socketid2user = new ConcurrentHashMap<UUID, User>();
private static final ConcurrentHashMap<String, String> user2session = new ConcurrentHashMap<String, String>();
@Test
public void testSocket2UserPersistence() throws IOException, ClassNotFoundException {
socketid2user.put(UUID.randomUUID(), new User(new UsernamePasswordAuthenticationToken("ptsr00", UUID.randomUUID())));
socketid2user.put(UUID.randomUUID(), new User(new AttributePrincipalImpl("ptstr0")));
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put(Google2AttributesDefinition.EMAIL, "mail@host.com");
Google2Profile profile = new Google2Profile("ptsr00", attributes);
socketid2user.put(UUID.randomUUID(), new User(profile));
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_GUEST"));
socketid2user.put(UUID.randomUUID(), new User(new AnonymousAuthenticationToken("ptsr00", UUID.randomUUID(), authorities)));
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(out);
objOut.writeObject(socketid2user);
objOut.close();
ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));
Map<UUID, String> actual = (Map<UUID, String>) objIn.readObject();
Assert.assertEquals(actual, socketid2user);
}
@Test
public void testUser2SessionPersistence() throws IOException, ClassNotFoundException {
user2session.put("ptsr00", UUID.randomUUID().toString());
user2session.put("ptsr01", UUID.randomUUID().toString());
user2session.put("ptsr02", UUID.randomUUID().toString());
user2session.put("ptsr03", UUID.randomUUID().toString());
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(out);
objOut.writeObject(user2session);
objOut.close();
ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));
Map<String, String> actual = (Map<String, String>) objIn.readObject();
Assert.assertEquals(actual, user2session);
}
}
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARSnova Backend is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.test.context.support;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.security.test.context.support.WithSecurityContext;
import de.thm.arsnova.model.UserProfile;
/**
* @author Daniel Gerhardt
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@WithSecurityContext(
factory = WithMockUserSecurityContextFactory.class
)
public @interface WithMockUser {
String value() default "user";
UserProfile.AuthProvider authProvider() default UserProfile.AuthProvider.ARSNOVA;
String loginId() default "";
String userId() default "";
String[] roles() default {"USER"};
String password() default "password";
}
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARSnova Backend is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.test.context.support;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.support.WithSecurityContextFactory;
import org.springframework.util.StringUtils;
import de.thm.arsnova.model.UserProfile;
import de.thm.arsnova.security.User;
/**
* @author Daniel Gerhardt
*/
public class WithMockUserSecurityContextFactory implements WithSecurityContextFactory<WithMockUser> {
@Override
public SecurityContext createSecurityContext(final WithMockUser withMockUser) {
final String loginId = StringUtils.hasLength(withMockUser.loginId()) ? withMockUser.loginId() : withMockUser.value();
final UserProfile userProfile = new UserProfile(withMockUser.authProvider(), loginId);
userProfile.setId(!withMockUser.userId().isEmpty() ? withMockUser.userId() : loginId);
final User user = new User(userProfile, Arrays.stream(withMockUser.roles())
.map(r -> new SimpleGrantedAuthority("ROLE_" + r)).collect(Collectors.toList()));
final Authentication authentication =
new UsernamePasswordAuthenticationToken(user, withMockUser.password(), user.getAuthorities());
final SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
return context;
}
}
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARSnova Backend is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.util;
import static de.thm.arsnova.util.ImageUtils.IMAGE_PREFIX_MIDDLE;
import static de.thm.arsnova.util.ImageUtils.IMAGE_PREFIX_START;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import de.thm.arsnova.config.AppConfig;
import de.thm.arsnova.config.TestAppConfig;
import de.thm.arsnova.config.TestPersistanceConfig;
import de.thm.arsnova.config.TestSecurityConfig;
import de.thm.arsnova.config.WebSocketConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {
AppConfig.class,
TestAppConfig.class,
TestPersistanceConfig.class,
TestSecurityConfig.class,
WebSocketConfig.class})
@ActiveProfiles("test")
public class ImageUtilsTest {
private ImageUtils imageUtils = new ImageUtils();
@Test
public void testNullIsNoValidBase64String() {
assertFalse("\"null\" is no valid Base64 String.", imageUtils.isBase64EncodedImage(null));
}
@Test
public void testEmptyStringIsNoValidBase64String() {
assertFalse("The empty String is no valid Base64 String.", imageUtils.isBase64EncodedImage(""));
}
@Test
public void testWrongStringIsNoValidBase64String() {
final String[] fakeStrings = new String[] {
"data:picture/png;base64,IMAGE-DATA",
"data:image/png;base63,IMAGE-DATA"
};
for (final String fakeString : fakeStrings) {
assertFalse(
String.format("The String %s is not a valid Base64 String.", fakeString),
imageUtils.isBase64EncodedImage(fakeString)
);
}
}
@Test
public void testValidBase64String() {
final String imageString = String.format("%spng%sIMAGE-DATA", IMAGE_PREFIX_START, IMAGE_PREFIX_MIDDLE);
assertTrue(imageUtils.isBase64EncodedImage(imageString));
}
@Test
public void testImageInfoExtraction() {
final String extension = "png";
final String imageData = "IMAGE-DATA";
final String imageString = String.format("%s%s%s%s", IMAGE_PREFIX_START,
extension, IMAGE_PREFIX_MIDDLE, imageData);
final String[] imageInfo = imageUtils.extractImageInfo(imageString);
assertNotNull(imageInfo);
assertEquals("Extracted information doesn't match its specification.", 2, imageInfo.length);
assertEquals("Extracted extension is invalid.", extension, imageInfo[0]);
assertEquals("Extracted Base64-Image String is invalid.", imageData, imageInfo[1]);
}
}
package de.thm.arsnova.websocket.handler;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import de.thm.arsnova.websocket.message.CreateFeedback;
import de.thm.arsnova.websocket.message.CreateFeedbackPayload;
import de.thm.arsnova.websocket.message.FeedbackChanged;
import de.thm.arsnova.websocket.message.FeedbackChangedPayload;
import de.thm.arsnova.websocket.message.GetFeedback;
@RunWith(SpringRunner.class)
public class FeedbackCommandHandlerTest {
@MockBean
private SimpMessagingTemplate messagingTemplate;
private FeedbackCommandHandler commandHandler;
@Before
public void setUp() {
this.commandHandler = new FeedbackCommandHandler(messagingTemplate);
}
@Test
public void getFeedback() {
final String roomId = "12345678";
final GetFeedback getFeedback = new GetFeedback();
final FeedbackCommandHandler.GetFeedbackCommand getFeedbackCommand =
new FeedbackCommandHandler.GetFeedbackCommand(roomId, null);
commandHandler.handle(getFeedbackCommand);
final FeedbackChangedPayload feedbackChangedPayload = new FeedbackChangedPayload();
final int[] expectedVals = new int[]{0, 0, 0, 0};
feedbackChangedPayload.setValues(expectedVals);
final FeedbackChanged feedbackChanged = new FeedbackChanged();
feedbackChanged.setPayload(feedbackChangedPayload);
final ArgumentCaptor<String> topicCaptor = ArgumentCaptor.forClass(String.class);
final ArgumentCaptor<FeedbackChanged> messageCaptor =
ArgumentCaptor.forClass(FeedbackChanged.class);
verify(messagingTemplate).convertAndSend(topicCaptor.capture(), messageCaptor.capture());
assertThat(topicCaptor.getValue()).isEqualTo("/topic/" + roomId + ".feedback.stream");
assertThat(messageCaptor.getValue()).isEqualTo(feedbackChanged);
}
@Test
public void sendFeedback() {
final String roomId = "12345678";
final CreateFeedbackPayload createFeedbackPayload = new CreateFeedbackPayload(1);
createFeedbackPayload.setValue(1);
final CreateFeedback createFeedback = new CreateFeedback();
createFeedback.setPayload(createFeedbackPayload);
final FeedbackCommandHandler.CreateFeedbackCommand createFeedbackCommand =
new FeedbackCommandHandler.CreateFeedbackCommand(roomId, createFeedback);
commandHandler.handle(createFeedbackCommand);
final ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(messagingTemplate).convertAndSend(captor.capture(), any(FeedbackChanged.class));
assertThat(captor.getValue()).isEqualTo("/topic/" + roomId + ".feedback.stream");
}
}
package de.thm.arsnova.websocket.handler;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import de.thm.arsnova.websocket.message.CreateFeedback;
@RunWith(SpringRunner.class)
public class FeedbackHandlerTest {
@MockBean
private FeedbackCommandHandler feedbackCommandHandler;
private FeedbackHandler feedbackHandler;
@Before
public void setUp() {
this.feedbackHandler = new FeedbackHandler(feedbackCommandHandler);
}
@Test
public void sendFeedback() throws Exception {
feedbackHandler.send(
"12345678",
new CreateFeedback()
);
final ArgumentCaptor<FeedbackCommandHandler.CreateFeedbackCommand> captor =
ArgumentCaptor.forClass(FeedbackCommandHandler.CreateFeedbackCommand.class);
verify(feedbackCommandHandler, times(1)).handle(captor.capture());
assertThat(captor.getValue().getRoomId()).isEqualTo("12345678");
assertThat(captor.getValue().getPayload()).isInstanceOf(CreateFeedback.class);
}
}
security.arsnova-url=http://localhost:8080
security.cas-server-url=https://cas.thm.de/cas
security.facebook.key=318531508227494
security.facebook.secret=e3f38cfc72bb63e35641b637081a6177
security.twitter.key=PEVtidSG0HzSrxVRPpsCXw
security.twitter.secret=mC0HOvxiEgqwdDWCcDoy3q75nUQPu1bYRp1ncHWGd0
security.google.key=110959746118.apps.googleusercontent.com
security.google.secret=CkzUJZswY8rjWCCYnHVovyGA
security.ssl=false
security.keystore=/etc/arsnova.thm.de.jks
security.storepass=arsnova
couchdb.host=localhost
couchdb.port=5984
couchdb.name=arsnova
# minutes, after which the feedback is deleted
feedback.cleanup=10
socketio.ip=0.0.0.0
socketio.port=10443
connector.uri=http://localhost:8080/connector-service
connector.username=test
connector.password=test
\ No newline at end of file
# Configuration overrides for test environment
arsnova:
security:
admin-accounts: "TestAdmin"
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<bean id="sessionService" class="de.thm.arsnova.services.SessionService">
<property name="databaseDao" ref="databaseDao" />
</bean>
<bean id="databaseDao" class="de.thm.arsnova.dao.StubDatabaseDao">
</bean>
<bean id="authorizationAdviser" class="de.thm.arsnova.aop.AuthorizationAdviser">
<property name="userService" ref="userService" />
</bean>
<bean id="userService" class="de.thm.arsnova.services.StubUserService" />
</beans>
dn: dc=example, dc=com
objectclass: organization
objectclass: top
o: Dummy Organisation
dn: uid=ptsr00, dc=example, dc=com
objectclass: person
objectclass: organizationalperson
objectclass: inetorgperson
uid: ptsr00
sn: Tester
givenName: Patrick
userPassword:: VGVzdA==
dn: uid=ptsr01, dc=example, dc=com
objectclass: person
objectclass: organizationalperson
objectclass: inetorgperson
uid: ptsr01
sn: Tester
givenName: Patricia
userPassword:: VGVzdA==