Skip to content

Commit

Permalink
Fixed tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Researcher86 committed Jun 19, 2017
1 parent 3822cc2 commit 4017a30
Show file tree
Hide file tree
Showing 13 changed files with 70 additions and 94 deletions.
2 changes: 0 additions & 2 deletions v3/src/main/java/ownradio/domain/Device.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,13 @@
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "devices")
public class Device extends AbstractEntity {
@ManyToOne
@JoinColumn(name = "userid")
private User user;

// private String name;
public Device (User user, String name){
setRecname(name);
setUser(user);
Expand Down
5 changes: 3 additions & 2 deletions v3/src/main/java/ownradio/domain/Ratio.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import lombok.Setter;

import javax.persistence.*;
import java.util.UUID;

/**
* Сущность для хранения коэффициентов схожести интересов
Expand All @@ -22,12 +23,12 @@ public class Ratio extends AbstractEntity {
// @ManyToOne
@JoinColumn(name = "userid")
@Column(nullable = false)
private User userid1;
private UUID userid1;

// @ManyToOne
@JoinColumn(name = "userid")
@Column(nullable = false)
private User userid2;
private UUID userid2;

private Integer ratio;
}
5 changes: 5 additions & 0 deletions v3/src/main/java/ownradio/recommendation/Critic.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ public String getName() {
return name;
}

/**
* Добавить новый рейтинг/оценку текущему критику
*
* @param rating рейтинг
*/
public void addRating(Rating rating) {
ratings.add(rating);
}
Expand Down
29 changes: 14 additions & 15 deletions v3/src/main/java/ownradio/recommendation/Recommender.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ public Recommender(List<Critic> criticList, Calculation calculation) {
/**
* Возвращает список наилучших соответствий для критика
*
* @param critic Критик
* @return Список коэффициентов сходства
* @param critic критик
* @return список коэффициентов сходства
*/
public List<Ratio> topMatches(Critic critic) {
return criticsExcludeTo(critic)
Expand All @@ -46,20 +46,19 @@ public List<Ratio> recommendedTo(Critic critic) {
Map<Rating, Double> totals = new HashMap<>();
Map<Rating, Double> simSums = new HashMap<>();

criticsExcludeTo(critic)
.forEach(other -> {
double sim = calculation.similarity(critic, other);
// игнорировать нулевые и отрицательные оценки
if (sim > 0) {
// оценивать только то, что критик еще не смотрел
other.notLookingTo(critic).forEach(rating -> {
// Коэффициент подобия * Оценка
totals.put(rating, totals.getOrDefault(rating, 0.0) + other.getRatingPoint(rating.getName()) * sim);
// Сумма коэффициентов подобия
simSums.put(rating, simSums.getOrDefault(rating, 0.0) + sim);
});
}
criticsExcludeTo(critic).forEach(other -> {
double sim = calculation.similarity(critic, other);
// игнорировать нулевые и отрицательные оценки
if (sim > 0) {
// оценивать только то, что критик еще не смотрел
other.notLookingTo(critic).forEach(rating -> {
// Коэффициент подобия * Оценка
totals.put(rating, totals.getOrDefault(rating, 0.0) + other.getRatingPoint(rating.getName()) * sim);
// Сумма коэффициентов подобия
simSums.put(rating, simSums.getOrDefault(rating, 0.0) + sim);
});
}
});

return getRatios(totals, simSums);
}
Expand Down
10 changes: 4 additions & 6 deletions v3/src/main/java/ownradio/repository/TrackRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,13 @@
* @author Alpenov Tanat
*/
public interface TrackRepository extends JpaRepository<Track, UUID> {
// @Query(value = "select CAST(getnexttrackid(?1) AS VARCHAR)", nativeQuery = true)
@Query(value = "select t from Track t, Rating r where t = r.track AND r.user.recid = ?1 " +
" and r.ratingsum >= 0" +
" ORDER BY random()")
// @Query(value = "select CAST(getnexttrackid(?1) AS VARCHAR)", nativeQuery = true)
@Query(value = "select t from Track t, Rating r where t = r.track and r.user.recid = ?1 and r.ratingsum >= 0 order by random()")
List<Track> getNextTrackId(UUID deviceId, Pageable pageable);

// @Query(value = "select * from getnexttrack_v2(?1)", nativeQuery = true)
// List<Object[]> getNextTrackV2(UUID deviceId);

@Query(value = "select * from getnexttrack_v2(?1)", nativeQuery = true)
List<String[]> getNextTrackV2(UUID deviceId);
@Query(value = "SELECT * FROM getnexttrack_v2(?1)", nativeQuery = true)
List<Object[]> getNextTrackV2(UUID deviceId);
}
3 changes: 2 additions & 1 deletion v3/src/main/java/ownradio/service/impl/TrackServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,9 @@ public Track getRecommendedTracks(UUID userId) {
}

List<Critic> criticList = new ArrayList<>(critics.values());
Recommender recommender = new Recommender(criticList, new SimpleCalculation());
Critic critic2 = criticList.stream().filter(critic -> critic.equals(new Critic(userId.toString()))).findFirst().get();

Recommender recommender = new Recommender(criticList, new SimpleCalculation());
List<Ratio> ratios = recommender.recommendedTo(critic2);

if (ratings.isEmpty()) {
Expand Down
2 changes: 1 addition & 1 deletion v3/src/main/resources/application-dev.properties
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ spring.http.multipart.max-request-size=256Mb
#spring.jackson.property-naming-strategy=CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.ddl-auto=validate
logging.file=logs/app.log
#logging.level.ownradio=info
#logging.level.org.springframework=info
Expand Down
44 changes: 0 additions & 44 deletions v3/src/test/java/ownradio/domain/UserTest.java

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public void correlationPearson() throws Exception {
}

@Test
public void myCalcRatio() throws Exception {
public void simpleCalculation() throws Exception {
Critic c1 = new Critic("User1");
c1.addRating(new Rating("Track1", 1));
c1.addRating(new Rating("Track2", 1));
Expand Down
23 changes: 17 additions & 6 deletions v3/src/test/java/ownradio/repository/HistoryRepositoryTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import ownradio.domain.Device;
import ownradio.domain.History;
import ownradio.domain.Track;
Expand All @@ -20,25 +23,33 @@
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;

@ActiveProfiles("dev")
@RunWith(SpringRunner.class)
@DataJpaTest
@SpringBootTest
@Transactional
public class HistoryRepositoryTest {
@Autowired
private HistoryRepository historyRepository;

@Autowired
private TestEntityManager entityManager;
private UserRepository userRepository;

@Autowired
private DeviceRepository deviceRepository;

@Autowired
private TrackRepository trackRepository;

private History history;

@Before
public void setUp() throws Exception {
User user = entityManager.persist(new User());
Device device = entityManager.persist(new Device(user, "1"));
Track track = entityManager.persist(new Track("1", device, "1", 0, "", 0, null, null, null, 1));
User user = userRepository.save(new User());
Device device = deviceRepository.save(new Device(user, "1"));
Track track = trackRepository.save(new Track("1", device, "1", 0, "", 0, null, null, null, 1));

history = new History(track, Calendar.getInstance(), 0, "post", 1, device, 1, "");
entityManager.persist(history);
historyRepository.save(history);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,9 @@
/**
* Created by a.polunina on 10.11.2016.
*/
@ActiveProfiles("prod")
@ActiveProfiles("dev")
@RunWith(SpringRunner.class)
@SpringBootTest
//@DataJpaTest
public class RatingRepositoryTest {
@Autowired
private RatingRepository ratingRepository;
Expand Down
34 changes: 21 additions & 13 deletions v3/src/test/java/ownradio/repository/TrackRepositoryTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,52 +7,60 @@
import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import ownradio.domain.Device;
import ownradio.domain.Track;
import ownradio.domain.User;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import static org.junit.Assert.assertTrue;

@ActiveProfiles("dev")
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@SpringBootTest
@Transactional
public class TrackRepositoryTest {
@Autowired
private UserRepository userRepository;

@Autowired
private TrackRepository trackRepository;

@Autowired
private TestEntityManager entityManager;
private DeviceRepository deviceRepository;

private User user;
private Device device;

@Before
public void setUp() throws Exception {
user = entityManager.persist(new User());
device = entityManager.persist(new Device(user, "123"));
entityManager.persist(new Track("1", device, "1", 0, "", 0, null, null, null, 1));
entityManager.persist(new Track("2", device, "1", 0, "", 0, null, null, null, 1));
entityManager.persist(new Track("4", device, "1", 0, "", 0, null, null, null, 1));
// user = userRepository.save(new User());
// device = deviceRepository.save(new Device(user, "123"));
// trackRepository.save(new Track("1", device, "1", 0, "", 0, null, null, null, 1));
// trackRepository.save(new Track("2", device, "1", 0, "", 0, null, null, null, 1));
// trackRepository.save(new Track("4", device, "1", 0, "", 0, null, null, null, 1));
}

@Test
public void getNextTrackId() throws Exception {
Set<UUID> trackSet = new HashSet<>();

// Set<Track> trackSet = new HashSet<>();
//
// for (int i = 0; i < 3; i++) {
// UUID track = trackRepository.getNextTrackId(device.getRecid(), new PageRequest(0, 1));
// trackSet.add(track);
// List<Track> track = trackRepository.getNextTrackId(device.getRecid(), new PageRequest(0, 1));
// trackSet.add(track.get(0));
// }
//
// assertTrue(trackSet.size() > 1);

assertTrue(trackSet.size() > 1);
trackRepository.getNextTrackId(UUID.fromString("11111111-0000-0888-0000-000000000000"), new PageRequest(0, 1));
}

}
2 changes: 1 addition & 1 deletion v3/src/test/java/ownradio/service/HistoryServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class HistoryServiceTest {

@Test
public void getTracksHistoryByDevice() throws Exception {
historyService.getTracksHistoryByDevice(UUID.fromString("00000000-0000-0000-0000-000000000002"), null);
historyService.getTracksHistoryByDevice(UUID.fromString("00000000-0000-0000-0000-000000000002"), 0);
}

}

0 comments on commit 4017a30

Please sign in to comment.