diff --git a/src/main/java/org/prebid/server/auction/BidResponseCreator.java b/src/main/java/org/prebid/server/auction/BidResponseCreator.java index ee42b2982ed..c1ccc7922f9 100644 --- a/src/main/java/org/prebid/server/auction/BidResponseCreator.java +++ b/src/main/java/org/prebid/server/auction/BidResponseCreator.java @@ -1491,6 +1491,7 @@ private Events createEvents(String bidder, bidId, bidder, account.getId(), + true, eventsContext) : null; } diff --git a/src/main/java/org/prebid/server/bidder/ccx/CcxBidder.java b/src/main/java/org/prebid/server/bidder/ccx/CcxBidder.java index 91fcdc71a1c..2422dddcc76 100644 --- a/src/main/java/org/prebid/server/bidder/ccx/CcxBidder.java +++ b/src/main/java/org/prebid/server/bidder/ccx/CcxBidder.java @@ -35,7 +35,6 @@ public CcxBidder(String endpointUrl, JacksonMapper mapper) { @Override public Result>> makeHttpRequests(BidRequest request) { - return Result.withValue(BidderUtil.defaultRequest(request, endpointUrl, mapper)); } diff --git a/src/main/java/org/prebid/server/bidder/freewheelssp/FreewheelSSPBidder.java b/src/main/java/org/prebid/server/bidder/freewheelssp/FreewheelSSPBidder.java index c8f41b7282d..988184c80be 100644 --- a/src/main/java/org/prebid/server/bidder/freewheelssp/FreewheelSSPBidder.java +++ b/src/main/java/org/prebid/server/bidder/freewheelssp/FreewheelSSPBidder.java @@ -3,7 +3,6 @@ import com.iab.openrtb.request.BidRequest; import com.iab.openrtb.response.BidResponse; import com.iab.openrtb.response.SeatBid; -import io.vertx.core.http.HttpMethod; import org.apache.commons.collections4.CollectionUtils; import org.prebid.server.bidder.Bidder; import org.prebid.server.bidder.model.BidderBid; @@ -37,15 +36,11 @@ public FreewheelSSPBidder(String endpointUrl, JacksonMapper mapper) { @Override public final Result>> makeHttpRequests(BidRequest bidRequest) { - return Result.withValue( - HttpRequest.builder() - .method(HttpMethod.POST) - .uri(endpointUrl) - .headers(HttpUtil.headers().add(COMPONENT_ID_HEADER_NAME, COMPONENT_ID_HEADER_VALUE)) - .body(mapper.encodeToBytes(bidRequest)) - .impIds(BidderUtil.impIds(bidRequest)) - .payload(bidRequest) - .build()); + return Result.withValue(BidderUtil.defaultRequest( + bidRequest, + HttpUtil.headers().add(COMPONENT_ID_HEADER_NAME, COMPONENT_ID_HEADER_VALUE), + endpointUrl, + mapper)); } @Override diff --git a/src/main/java/org/prebid/server/bidder/jixie/JixieBidder.java b/src/main/java/org/prebid/server/bidder/jixie/JixieBidder.java index 41096948172..d149faeb4dc 100644 --- a/src/main/java/org/prebid/server/bidder/jixie/JixieBidder.java +++ b/src/main/java/org/prebid/server/bidder/jixie/JixieBidder.java @@ -6,7 +6,6 @@ import com.iab.openrtb.response.BidResponse; import com.iab.openrtb.response.SeatBid; import io.vertx.core.MultiMap; -import io.vertx.core.http.HttpMethod; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.prebid.server.bidder.Bidder; @@ -19,6 +18,7 @@ import org.prebid.server.json.DecodeException; import org.prebid.server.json.JacksonMapper; import org.prebid.server.proto.openrtb.ext.response.BidType; +import org.prebid.server.util.BidderUtil; import org.prebid.server.util.HttpUtil; import java.util.Collection; @@ -38,14 +38,11 @@ public JixieBidder(String endpointUrl, JacksonMapper mapper) { @Override public Result>> makeHttpRequests(BidRequest request) { - - return Result.withValue(HttpRequest.builder() - .method(HttpMethod.POST) - .uri(endpointUrl) - .headers(resolveHeaders(request.getDevice(), request.getSite())) - .payload(request) - .body(mapper.encodeToBytes(request)) - .build()); + return Result.withValue(BidderUtil.defaultRequest( + request, + resolveHeaders(request.getDevice(), request.getSite()), + endpointUrl, + mapper)); } private static MultiMap resolveHeaders(Device device, Site site) { diff --git a/src/main/java/org/prebid/server/bidder/loopme/LoopmeBidder.java b/src/main/java/org/prebid/server/bidder/loopme/LoopmeBidder.java index 20161acc420..0b8ffb6fa81 100644 --- a/src/main/java/org/prebid/server/bidder/loopme/LoopmeBidder.java +++ b/src/main/java/org/prebid/server/bidder/loopme/LoopmeBidder.java @@ -35,7 +35,6 @@ public LoopmeBidder(String endpointUrl, JacksonMapper mapper) { @Override public Result>> makeHttpRequests(BidRequest request) { - return Result.withValue(BidderUtil.defaultRequest(request, endpointUrl, mapper)); } diff --git a/src/main/java/org/prebid/server/bidder/vrtcal/VrtcalBidder.java b/src/main/java/org/prebid/server/bidder/vrtcal/VrtcalBidder.java index d1973e4465d..54d4f9d2b3b 100644 --- a/src/main/java/org/prebid/server/bidder/vrtcal/VrtcalBidder.java +++ b/src/main/java/org/prebid/server/bidder/vrtcal/VrtcalBidder.java @@ -36,7 +36,6 @@ public VrtcalBidder(String endpointUrl, JacksonMapper mapper) { @Override public Result>> makeHttpRequests(BidRequest request) { - return Result.withValue(BidderUtil.defaultRequest(request, endpointUrl, mapper)); } diff --git a/src/main/java/org/prebid/server/cache/CacheService.java b/src/main/java/org/prebid/server/cache/CacheService.java index a19b9f9fd71..9656dd38501 100644 --- a/src/main/java/org/prebid/server/cache/CacheService.java +++ b/src/main/java/org/prebid/server/cache/CacheService.java @@ -527,6 +527,7 @@ private String generateWinUrl(String bidId, bidId, bidder, accountId, + true, eventsContext) : null; } diff --git a/src/main/java/org/prebid/server/events/EventsService.java b/src/main/java/org/prebid/server/events/EventsService.java index 72ec0472d96..819dfeb0e0a 100644 --- a/src/main/java/org/prebid/server/events/EventsService.java +++ b/src/main/java/org/prebid/server/events/EventsService.java @@ -19,13 +19,16 @@ public EventsService(String externalUrl) { public Events createEvent(String bidId, String bidder, String accountId, + boolean analyticsEnabled, EventsContext eventsContext) { + return Events.of( eventUrl( EventRequest.Type.win, bidId, bidder, accountId, + analytics(analyticsEnabled), EventRequest.Format.image, eventsContext), eventUrl( @@ -33,6 +36,7 @@ public Events createEvent(String bidId, bidId, bidder, accountId, + analytics(analyticsEnabled), EventRequest.Format.image, eventsContext)); } @@ -43,6 +47,7 @@ public Events createEvent(String bidId, public String winUrl(String bidId, String bidder, String accountId, + boolean analyticsEnabled, EventsContext eventsContext) { return eventUrl( @@ -50,6 +55,7 @@ public String winUrl(String bidId, bidId, bidder, accountId, + analytics(analyticsEnabled), EventRequest.Format.image, eventsContext); } @@ -66,6 +72,7 @@ public String vastUrlTracking(String bidId, bidId, bidder, accountId, + null, EventRequest.Format.blank, eventsContext); } @@ -74,6 +81,7 @@ private String eventUrl(EventRequest.Type type, String bidId, String bidder, String accountId, + EventRequest.Analytics analytics, EventRequest.Format format, EventsContext eventsContext) { @@ -86,8 +94,13 @@ private String eventUrl(EventRequest.Type type, .timestamp(eventsContext.getAuctionTimestamp()) .format(format) .integration(eventsContext.getIntegration()) + .analytics(analytics) .build(); return EventUtil.toUrl(externalUrl, eventRequest); } + + private static EventRequest.Analytics analytics(boolean analyticsEnabled) { + return analyticsEnabled ? null : EventRequest.Analytics.disabled; + } } diff --git a/src/main/java/org/prebid/server/handler/LoggerControlKnobHandler.java b/src/main/java/org/prebid/server/handler/LoggerControlKnobHandler.java index 1624ff820d0..498567ac521 100644 --- a/src/main/java/org/prebid/server/handler/LoggerControlKnobHandler.java +++ b/src/main/java/org/prebid/server/handler/LoggerControlKnobHandler.java @@ -81,7 +81,8 @@ private Integer durationAsInt(MultiMap parameters) { try { return value != null ? Integer.parseInt(value) : null; } catch (NumberFormatException e) { - throw new InvalidRequestException("Invalid '%s' parameter value".formatted(LoggerControlKnobHandler.DURATION_PARAMETER)); + throw new InvalidRequestException("Invalid '%s' parameter value" + .formatted(LoggerControlKnobHandler.DURATION_PARAMETER)); } } } diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/alert/Action.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/alert/Action.groovy deleted file mode 100644 index 8760760c00a..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/alert/Action.groovy +++ /dev/null @@ -1,6 +0,0 @@ -package org.prebid.server.functional.model.deals.alert - -enum Action { - - RAISE -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/alert/AlertEvent.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/alert/AlertEvent.groovy deleted file mode 100644 index 596b7221c46..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/alert/AlertEvent.groovy +++ /dev/null @@ -1,20 +0,0 @@ -package org.prebid.server.functional.model.deals.alert - -import com.fasterxml.jackson.databind.PropertyNamingStrategies -import com.fasterxml.jackson.databind.annotation.JsonNaming -import groovy.transform.ToString - -import java.time.ZonedDateTime - -@ToString(includeNames = true, ignoreNulls = true) -@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy) -class AlertEvent { - - String id - Action action - AlertPriority priority - ZonedDateTime updatedAt - String name - String details - AlertSource source -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/alert/AlertPriority.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/alert/AlertPriority.groovy deleted file mode 100644 index 502b2d5eb25..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/alert/AlertPriority.groovy +++ /dev/null @@ -1,6 +0,0 @@ -package org.prebid.server.functional.model.deals.alert - -enum AlertPriority { - - HIGH, MEDIUM, LOW -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/alert/AlertSource.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/alert/AlertSource.groovy deleted file mode 100644 index 3175711c4be..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/alert/AlertSource.groovy +++ /dev/null @@ -1,17 +0,0 @@ -package org.prebid.server.functional.model.deals.alert - -import com.fasterxml.jackson.databind.PropertyNamingStrategies -import com.fasterxml.jackson.databind.annotation.JsonNaming -import groovy.transform.ToString - -@ToString(includeNames = true, ignoreNulls = true) -@JsonNaming(PropertyNamingStrategies.KebabCaseStrategy) -class AlertSource { - - String env - String dataCenter - String region - String system - String subSystem - String hostId -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/DeliverySchedule.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/DeliverySchedule.groovy deleted file mode 100644 index 8b59632171b..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/DeliverySchedule.groovy +++ /dev/null @@ -1,37 +0,0 @@ -package org.prebid.server.functional.model.deals.lineitem - -import com.fasterxml.jackson.annotation.JsonFormat -import groovy.transform.ToString -import org.prebid.server.functional.util.PBSUtils - -import java.time.ZoneId -import java.time.ZonedDateTime - -import static java.time.ZoneOffset.UTC -import static org.prebid.server.functional.model.deals.lineitem.LineItem.TIME_PATTERN - -@ToString(includeNames = true, ignoreNulls = true) -class DeliverySchedule { - - String planId - - @JsonFormat(pattern = TIME_PATTERN) - ZonedDateTime startTimeStamp - - @JsonFormat(pattern = TIME_PATTERN) - ZonedDateTime endTimeStamp - - @JsonFormat(pattern = TIME_PATTERN) - ZonedDateTime updatedTimeStamp - - Set tokens - - static getDefaultDeliverySchedule() { - new DeliverySchedule(planId: PBSUtils.randomString, - startTimeStamp: ZonedDateTime.now(ZoneId.from(UTC)), - endTimeStamp: ZonedDateTime.now(ZoneId.from(UTC)).plusDays(1), - updatedTimeStamp: ZonedDateTime.now(ZoneId.from(UTC)), - tokens: [Token.defaultToken] - ) - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/FrequencyCap.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/FrequencyCap.groovy deleted file mode 100644 index 995ae1b9309..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/FrequencyCap.groovy +++ /dev/null @@ -1,23 +0,0 @@ -package org.prebid.server.functional.model.deals.lineitem - -import groovy.transform.ToString -import org.prebid.server.functional.util.PBSUtils - -import static PeriodType.DAY - -@ToString(includeNames = true, ignoreNulls = true) -class FrequencyCap { - - String fcapId - Integer count - Integer periods - String periodType - - static getDefaultFrequencyCap() { - new FrequencyCap(count: 1, - fcapId: PBSUtils.randomString, - periods: 1, - periodType: DAY - ) - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/LineItem.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/LineItem.groovy deleted file mode 100644 index 43051f0ab50..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/LineItem.groovy +++ /dev/null @@ -1,74 +0,0 @@ -package org.prebid.server.functional.model.deals.lineitem - -import com.fasterxml.jackson.annotation.JsonFormat -import groovy.transform.ToString -import org.prebid.server.functional.model.deals.lineitem.targeting.Targeting -import org.prebid.server.functional.util.PBSUtils - -import java.time.ZoneId -import java.time.ZonedDateTime - -import static LineItemStatus.ACTIVE -import static java.time.ZoneOffset.UTC -import static org.prebid.server.functional.model.bidder.BidderName.GENERIC -import static org.prebid.server.functional.model.deals.lineitem.RelativePriority.VERY_HIGH - -@ToString(includeNames = true, ignoreNulls = true) -class LineItem { - - public static final String TIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'" - - String lineItemId - - String extLineItemId - - String dealId - - List sizes - - String accountId - - String source - - Price price - - RelativePriority relativePriority - - @JsonFormat(pattern = TIME_PATTERN) - ZonedDateTime startTimeStamp - - @JsonFormat(pattern = TIME_PATTERN) - ZonedDateTime endTimeStamp - - @JsonFormat(pattern = TIME_PATTERN) - ZonedDateTime updatedTimeStamp - - LineItemStatus status - - List frequencyCaps - - List deliverySchedules - - Targeting targeting - - static LineItem getDefaultLineItem(String accountId) { - int plannerAdapterLineItemId = PBSUtils.randomNumber - String plannerAdapterName = PBSUtils.randomString - new LineItem(lineItemId: "${plannerAdapterName}-$plannerAdapterLineItemId", - extLineItemId: plannerAdapterLineItemId, - dealId: PBSUtils.randomString, - sizes: [LineItemSize.defaultLineItemSize], - accountId: accountId, - source: GENERIC.name().toLowerCase(), - price: Price.defaultPrice, - relativePriority: VERY_HIGH, - startTimeStamp: ZonedDateTime.now(ZoneId.from(UTC)), - endTimeStamp: ZonedDateTime.now(ZoneId.from(UTC)).plusMonths(1), - updatedTimeStamp: ZonedDateTime.now(ZoneId.from(UTC)), - status: ACTIVE, - frequencyCaps: [], - deliverySchedules: [DeliverySchedule.defaultDeliverySchedule], - targeting: Targeting.defaultTargeting - ) - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/LineItemSize.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/LineItemSize.groovy deleted file mode 100644 index 2ff7af18dec..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/LineItemSize.groovy +++ /dev/null @@ -1,16 +0,0 @@ -package org.prebid.server.functional.model.deals.lineitem - -import groovy.transform.ToString - -@ToString(includeNames = true) -class LineItemSize { - - Integer w - Integer h - - static getDefaultLineItemSize() { - new LineItemSize(w: 300, - h: 250 - ) - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/LineItemStatus.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/LineItemStatus.groovy deleted file mode 100644 index c2dded2d3d2..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/LineItemStatus.groovy +++ /dev/null @@ -1,22 +0,0 @@ -package org.prebid.server.functional.model.deals.lineitem - -import com.fasterxml.jackson.annotation.JsonValue - -enum LineItemStatus { - - ACTIVE("active"), - DELETED("deleted"), - PAUSED("paused") - - @JsonValue - final String value - - private LineItemStatus(String value) { - this.value = value - } - - @Override - String toString() { - value - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/MediaType.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/MediaType.groovy deleted file mode 100644 index 949da3d9b53..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/MediaType.groovy +++ /dev/null @@ -1,20 +0,0 @@ -package org.prebid.server.functional.model.deals.lineitem - -import com.fasterxml.jackson.annotation.JsonValue - -enum MediaType { - - BANNER("banner") - - @JsonValue - final String value - - private MediaType(String value) { - this.value = value - } - - @Override - String toString() { - value - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/PeriodType.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/PeriodType.groovy deleted file mode 100644 index 10ca6f59d9c..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/PeriodType.groovy +++ /dev/null @@ -1,24 +0,0 @@ -package org.prebid.server.functional.model.deals.lineitem - -import com.fasterxml.jackson.annotation.JsonValue - -enum PeriodType { - - HOUR("hour"), - DAY("day"), - WEEK("week"), - MONTH("month"), - CAMPAIGN("campaign") - - @JsonValue - final String value - - private PeriodType(String value) { - this.value = value - } - - @Override - String toString() { - value - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/Price.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/Price.groovy deleted file mode 100644 index 5c0bb616ed6..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/Price.groovy +++ /dev/null @@ -1,15 +0,0 @@ -package org.prebid.server.functional.model.deals.lineitem - -import groovy.transform.ToString -import org.prebid.server.functional.util.PBSUtils - -@ToString(includeNames = true, ignoreNulls = true) -class Price { - - BigDecimal cpm - String currency - - static getDefaultPrice() { - new Price(cpm: PBSUtils.randomPrice, currency: "USD") - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/RelativePriority.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/RelativePriority.groovy deleted file mode 100644 index 911da0b365f..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/RelativePriority.groovy +++ /dev/null @@ -1,24 +0,0 @@ -package org.prebid.server.functional.model.deals.lineitem - -import com.fasterxml.jackson.annotation.JsonValue - -enum RelativePriority { - - VERY_HIGH(1), - HIGH(2), - MEDIUM(3), - LOW(4), - VERY_LOW(5) - - @JsonValue - final Integer value - - private RelativePriority(Integer value) { - this.value = value - } - - @Override - String toString() { - value - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/Token.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/Token.groovy deleted file mode 100644 index e7dd3f2fc5d..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/Token.groovy +++ /dev/null @@ -1,19 +0,0 @@ -package org.prebid.server.functional.model.deals.lineitem - -import com.fasterxml.jackson.annotation.JsonProperty -import groovy.transform.ToString - -@ToString(includeNames = true, ignoreNulls = true) -class Token { - - @JsonProperty("class") - Integer priorityClass - - Integer total - - static getDefaultToken() { - new Token(priorityClass: 1, - total: 1000 - ) - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/targeting/BooleanOperator.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/targeting/BooleanOperator.groovy deleted file mode 100644 index 0e4a4740e53..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/targeting/BooleanOperator.groovy +++ /dev/null @@ -1,20 +0,0 @@ -package org.prebid.server.functional.model.deals.lineitem.targeting - -import com.fasterxml.jackson.annotation.JsonValue - -enum BooleanOperator { - - AND('$and'), - OR('$or'), - NOT('$not'), - - INVALID('$invalid'), - UPPERCASE_AND('$AND') - - @JsonValue - final String value - - private BooleanOperator(String value) { - this.value = value - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/targeting/MatchingFunction.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/targeting/MatchingFunction.groovy deleted file mode 100644 index 54a1353808e..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/targeting/MatchingFunction.groovy +++ /dev/null @@ -1,18 +0,0 @@ -package org.prebid.server.functional.model.deals.lineitem.targeting - -import com.fasterxml.jackson.annotation.JsonValue - -enum MatchingFunction { - - MATCHES('$matches'), - IN('$in'), - INTERSECTS('$intersects'), - WITHIN('$within') - - @JsonValue - final String value - - private MatchingFunction(String value) { - this.value = value - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/targeting/MatchingFunctionNode.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/targeting/MatchingFunctionNode.groovy deleted file mode 100644 index 6e639fe4383..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/targeting/MatchingFunctionNode.groovy +++ /dev/null @@ -1,17 +0,0 @@ -package org.prebid.server.functional.model.deals.lineitem.targeting - -import com.fasterxml.jackson.annotation.JsonValue -import groovy.transform.PackageScope - -@PackageScope -class MatchingFunctionNode { - - Map> matchingFunctionMultipleValuesNode - - Map matchingFunctionSingleValueNode - - @JsonValue - def getMatchingFunctionNode() { - matchingFunctionMultipleValuesNode ?: matchingFunctionSingleValueNode - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/targeting/Targeting.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/targeting/Targeting.groovy deleted file mode 100644 index 12c9633cbaf..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/targeting/Targeting.groovy +++ /dev/null @@ -1,92 +0,0 @@ -package org.prebid.server.functional.model.deals.lineitem.targeting - -import com.fasterxml.jackson.annotation.JsonValue -import org.prebid.server.functional.model.deals.lineitem.LineItemSize - -import static BooleanOperator.AND -import static MatchingFunction.INTERSECTS -import static TargetingType.AD_UNIT_MEDIA_TYPE -import static TargetingType.AD_UNIT_SIZE -import static org.prebid.server.functional.model.deals.lineitem.MediaType.BANNER -import static org.prebid.server.functional.model.deals.lineitem.targeting.BooleanOperator.NOT -import static org.prebid.server.functional.model.deals.lineitem.targeting.BooleanOperator.OR - -class Targeting { - - private final Map> rootNode - - private final Map singleTargetingRootNode - - @JsonValue - def getSerializableRootNode() { - rootNode ?: singleTargetingRootNode - } - - private Targeting(Builder builder) { - rootNode = [(builder.rootOperator): builder.targetingNodes] - } - - private Targeting(Builder builder, TargetingNode targetingNode) { - singleTargetingRootNode = [(builder.rootOperator): targetingNode] - } - - Map> getTargetingRootNode() { - rootNode.asImmutable() - } - - static Targeting getDefaultTargeting() { - defaultTargetingBuilder.build() - } - - static Builder getDefaultTargetingBuilder() { - new Builder().addTargeting(AD_UNIT_SIZE, INTERSECTS, [LineItemSize.defaultLineItemSize]) - .addTargeting(AD_UNIT_MEDIA_TYPE, INTERSECTS, [BANNER]) - } - - static Targeting getInvalidTwoRootNodesTargeting() { - defaultTargeting.tap { rootNode.put(OR, []) } - } - - static class Builder { - - private BooleanOperator rootOperator - private List targetingNodes = [] - - Builder(BooleanOperator rootOperator = AND) { - this.rootOperator = rootOperator - } - - Builder addTargeting(TargetingType targetingType, - MatchingFunction matchingFunction, - List targetingValues) { - MatchingFunctionNode matchingFunctionNode = new MatchingFunctionNode(matchingFunctionMultipleValuesNode: [(matchingFunction): targetingValues]) - addTargetingNode(targetingType, matchingFunctionNode) - this - } - - Builder addTargeting(TargetingType targetingType, - MatchingFunction matchingFunction, - Object targetingValue) { - MatchingFunctionNode matchingFunctionNode = new MatchingFunctionNode(matchingFunctionSingleValueNode: [(matchingFunction): targetingValue]) - addTargetingNode(targetingType, matchingFunctionNode) - this - } - - private void addTargetingNode(TargetingType targetingType, - MatchingFunctionNode matchingFunctionNode) { - targetingNodes << new TargetingNode([(targetingType): matchingFunctionNode]) - } - - Targeting build() { - new Targeting(this) - } - - Targeting buildNotBooleanOperatorTargeting(TargetingType targetingType, - MatchingFunction matchingFunction, - List targetingValues) { - rootOperator = NOT - MatchingFunctionNode matchingFunctionNode = new MatchingFunctionNode(matchingFunctionSingleValueNode: [(matchingFunction): targetingValues]) - new Targeting(this, new TargetingNode([(targetingType): matchingFunctionNode])) - } - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/targeting/TargetingNode.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/targeting/TargetingNode.groovy deleted file mode 100644 index 4e8ccecd318..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/targeting/TargetingNode.groovy +++ /dev/null @@ -1,13 +0,0 @@ -package org.prebid.server.functional.model.deals.lineitem.targeting - -import com.fasterxml.jackson.annotation.JsonValue -import groovy.transform.PackageScope -import groovy.transform.TupleConstructor - -@PackageScope -@TupleConstructor -class TargetingNode { - - @JsonValue - Map targetingNode -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/targeting/TargetingType.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/targeting/TargetingType.groovy deleted file mode 100644 index 5434d38a59a..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/lineitem/targeting/TargetingType.groovy +++ /dev/null @@ -1,46 +0,0 @@ -package org.prebid.server.functional.model.deals.lineitem.targeting - -import com.fasterxml.jackson.annotation.JsonValue - -enum TargetingType { - - AD_UNIT_SIZE("adunit.size"), - AD_UNIT_MEDIA_TYPE("adunit.mediatype"), - AD_UNIT_AD_SLOT("adunit.adslot"), - SITE_DOMAIN("site.domain"), - SITE_PUBLISHER_DOMAIN("site.publisher.domain"), - REFERRER("site.referrer"), - APP_BUNDLE("app.bundle"), - DEVICE_COUNTRY("device.geo.ext.geoprovider.country"), - DEVICE_TYPE("device.ext.deviceinfoprovider.type"), - DEVICE_OS("device.ext.deviceinfoprovider.osfamily"), - DEVICE_REGION("device.geo.ext.geoprovider.region"), - DEVICE_METRO("device.geo.ext.geoprovider.metro"), - PAGE_POSITION("pos"), - LOCATION("geo.distance"), - BIDP("bidp."), - BIDP_ACCOUNT_ID(BIDP.value + "rubicon.accountId"), - USER_SEGMENT("segment."), - USER_SEGMENT_NAME(USER_SEGMENT.value + "name"), - UFPD("ufpd."), - UFPD_KEYWORDS(UFPD.value + "keywords"), - UFPD_BUYER_UID(UFPD.value + "buyeruid"), - UFPD_BUYER_UIDS(UFPD.value + "buyeruids"), - UFPD_YOB(UFPD.value + "yob"), - SFPD("sfpd."), - SFPD_AMP(SFPD.value + "amp"), - SFPD_LANGUAGE(SFPD.value + "language"), - SFPD_KEYWORDS(SFPD.value + "keywords"), - SFPD_BUYER_ID(SFPD.value + "buyerid"), - SFPD_BUYER_IDS(SFPD.value + "buyerids"), - DOW("user.ext.time.userdow"), - HOUR("user.ext.time.userhour"), - INVALID("invalid.targeting.type") - - @JsonValue - final String value - - private TargetingType(String value) { - this.value = value - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/register/CurrencyServiceState.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/register/CurrencyServiceState.groovy deleted file mode 100644 index 4c0db24acd3..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/register/CurrencyServiceState.groovy +++ /dev/null @@ -1,11 +0,0 @@ -package org.prebid.server.functional.model.deals.register - -import groovy.transform.ToString - -import java.time.ZonedDateTime - -@ToString(includeNames = true, ignoreNulls = true) -class CurrencyServiceState { - - ZonedDateTime lastUpdate -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/register/RegisterRequest.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/register/RegisterRequest.groovy deleted file mode 100644 index 75daf33adc3..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/register/RegisterRequest.groovy +++ /dev/null @@ -1,13 +0,0 @@ -package org.prebid.server.functional.model.deals.register - -import groovy.transform.ToString - -@ToString(includeNames = true, ignoreNulls = true) -class RegisterRequest { - - BigDecimal healthIndex - Status status - String hostInstanceId - String region - String vendor -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/register/Status.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/register/Status.groovy deleted file mode 100644 index ad065e9ac4a..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/register/Status.groovy +++ /dev/null @@ -1,11 +0,0 @@ -package org.prebid.server.functional.model.deals.register - -import groovy.transform.ToString -import org.prebid.server.functional.model.deals.report.DeliveryStatisticsReport - -@ToString(includeNames = true, ignoreNulls = true) -class Status { - - CurrencyServiceState currencyRates - DeliveryStatisticsReport dealsStatus -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/report/DeliverySchedule.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/report/DeliverySchedule.groovy deleted file mode 100644 index 5701757e569..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/report/DeliverySchedule.groovy +++ /dev/null @@ -1,15 +0,0 @@ -package org.prebid.server.functional.model.deals.report - -import groovy.transform.ToString - -import java.time.ZonedDateTime - -@ToString(includeNames = true, ignoreNulls = true) -class DeliverySchedule { - - String planId - ZonedDateTime planStartTimeStamp - ZonedDateTime planExpirationTimeStamp - ZonedDateTime planUpdatedTimeStamp - Set tokens -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/report/DeliveryStatisticsReport.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/report/DeliveryStatisticsReport.groovy deleted file mode 100644 index 5ee7340c3dd..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/report/DeliveryStatisticsReport.groovy +++ /dev/null @@ -1,19 +0,0 @@ -package org.prebid.server.functional.model.deals.report - -import groovy.transform.ToString - -import java.time.ZonedDateTime - -@ToString(includeNames = true, ignoreNulls = true) -class DeliveryStatisticsReport { - - String reportId - String instanceId - String vendor - String region - Long clientAuctions - Set lineItemStatus - ZonedDateTime reportTimeStamp - ZonedDateTime dataWindowStartTimeStamp - ZonedDateTime dataWindowEndTimeStamp -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/report/Event.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/report/Event.groovy deleted file mode 100644 index 495bfaf673e..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/report/Event.groovy +++ /dev/null @@ -1,10 +0,0 @@ -package org.prebid.server.functional.model.deals.report - -import groovy.transform.ToString - -@ToString(includeNames = true, ignoreNulls = true) -class Event { - - String type - Long count -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/report/LineItemStatus.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/report/LineItemStatus.groovy deleted file mode 100644 index a68029852c6..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/report/LineItemStatus.groovy +++ /dev/null @@ -1,30 +0,0 @@ -package org.prebid.server.functional.model.deals.report - -import groovy.transform.ToString - -@ToString(includeNames = true, ignoreNulls = true) -class LineItemStatus { - - String lineItemSource - String lineItemId - String dealId - String extLineItemId - Long accountAuctions - Long domainMatched - Long targetMatched - Long targetMatchedButFcapped - Long targetMatchedButFcapLookupFailed - Long pacingDeferred - Long sentToBidder - Long sentToBidderAsTopMatch - Long receivedFromBidder - Long receivedFromBidderInvalidated - Long sentToClient - Long sentToClientAsTopMatch - Set lostToLineItems - Set events - Set deliverySchedule - String readyAt - Long spentTokens - Long pacingFrequency -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/report/LineItemStatusReport.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/report/LineItemStatusReport.groovy deleted file mode 100644 index 6fb1766c534..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/report/LineItemStatusReport.groovy +++ /dev/null @@ -1,17 +0,0 @@ -package org.prebid.server.functional.model.deals.report - -import groovy.transform.ToString - -import java.time.ZonedDateTime - -@ToString(includeNames = true, ignoreNulls = true) -class LineItemStatusReport { - - String lineItemId - DeliverySchedule deliverySchedule - Long spentTokens - ZonedDateTime readyToServeTimestamp - Long pacingFrequency - String accountId - Map target -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/report/LostToLineItem.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/report/LostToLineItem.groovy deleted file mode 100644 index 58567ffc974..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/report/LostToLineItem.groovy +++ /dev/null @@ -1,11 +0,0 @@ -package org.prebid.server.functional.model.deals.report - -import groovy.transform.ToString - -@ToString(includeNames = true, ignoreNulls = true) -class LostToLineItem { - - String lineItemSource - String lineItemId - Long count -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/report/Token.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/report/Token.groovy deleted file mode 100644 index 89310a5d73e..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/report/Token.groovy +++ /dev/null @@ -1,17 +0,0 @@ -package org.prebid.server.functional.model.deals.report - -import com.fasterxml.jackson.annotation.JsonProperty -import groovy.transform.ToString - -@ToString(includeNames = true, ignoreNulls = true) -class Token { - - @JsonProperty("class") - Integer priorityClass - - Integer total - - Long spent - - Long totalSpent -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/userdata/Segment.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/userdata/Segment.groovy deleted file mode 100644 index f11d8f32ff1..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/userdata/Segment.groovy +++ /dev/null @@ -1,14 +0,0 @@ -package org.prebid.server.functional.model.deals.userdata - -import groovy.transform.ToString -import org.prebid.server.functional.util.PBSUtils - -@ToString(includeNames = true, ignoreNulls = true) -class Segment { - - String id - - static getDefaultSegment() { - new Segment(id: PBSUtils.randomString) - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/userdata/User.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/userdata/User.groovy deleted file mode 100644 index 6d2e527a0e6..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/userdata/User.groovy +++ /dev/null @@ -1,16 +0,0 @@ -package org.prebid.server.functional.model.deals.userdata - -import groovy.transform.ToString - -@ToString(includeNames = true, ignoreNulls = true) -class User { - - List data - UserExt ext - - static getDefaultUser() { - new User(data: [UserData.defaultUserData], - ext: UserExt.defaultUserExt - ) - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/userdata/UserData.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/userdata/UserData.groovy deleted file mode 100644 index 5687d89285e..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/userdata/UserData.groovy +++ /dev/null @@ -1,19 +0,0 @@ -package org.prebid.server.functional.model.deals.userdata - -import groovy.transform.ToString -import org.prebid.server.functional.util.PBSUtils - -@ToString(includeNames = true, ignoreNulls = true) -class UserData { - - String id - String name - List segment - - static UserData getDefaultUserData() { - new UserData(id: PBSUtils.randomString, - name: PBSUtils.randomString, - segment: [Segment.defaultSegment] - ) - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/userdata/UserDetails.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/userdata/UserDetails.groovy deleted file mode 100644 index 780ec674b24..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/userdata/UserDetails.groovy +++ /dev/null @@ -1,10 +0,0 @@ -package org.prebid.server.functional.model.deals.userdata - -import groovy.transform.ToString - -@ToString(includeNames = true, ignoreNulls = true) -class UserDetails { - - List userData - List fcapIds -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/userdata/UserDetailsRequest.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/userdata/UserDetailsRequest.groovy deleted file mode 100644 index 74985c5808f..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/userdata/UserDetailsRequest.groovy +++ /dev/null @@ -1,12 +0,0 @@ -package org.prebid.server.functional.model.deals.userdata - -import groovy.transform.ToString - -import java.time.ZonedDateTime - -@ToString(includeNames = true, ignoreNulls = true) -class UserDetailsRequest { - - ZonedDateTime time - List ids -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/userdata/UserDetailsResponse.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/userdata/UserDetailsResponse.groovy deleted file mode 100644 index 143aee234d9..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/userdata/UserDetailsResponse.groovy +++ /dev/null @@ -1,14 +0,0 @@ -package org.prebid.server.functional.model.deals.userdata - -import groovy.transform.ToString -import org.prebid.server.functional.model.ResponseModel - -@ToString(includeNames = true, ignoreNulls = true) -class UserDetailsResponse implements ResponseModel { - - User user - - static UserDetailsResponse getDefaultUserResponse(User user = User.defaultUser) { - new UserDetailsResponse(user: user) - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/userdata/UserExt.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/userdata/UserExt.groovy deleted file mode 100644 index 53a89aa97e2..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/userdata/UserExt.groovy +++ /dev/null @@ -1,14 +0,0 @@ -package org.prebid.server.functional.model.deals.userdata - -import groovy.transform.ToString -import org.prebid.server.functional.util.PBSUtils - -@ToString(includeNames = true, ignoreNulls = true) -class UserExt { - - List fcapIds - - static getDefaultUserExt() { - new UserExt(fcapIds: [PBSUtils.randomString]) - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/userdata/UserId.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/userdata/UserId.groovy deleted file mode 100644 index 8edeac5336d..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/userdata/UserId.groovy +++ /dev/null @@ -1,10 +0,0 @@ -package org.prebid.server.functional.model.deals.userdata - -import groovy.transform.ToString - -@ToString(includeNames = true, ignoreNulls = true) -class UserId { - - String type - String id -} diff --git a/src/test/groovy/org/prebid/server/functional/model/deals/userdata/WinEventNotification.groovy b/src/test/groovy/org/prebid/server/functional/model/deals/userdata/WinEventNotification.groovy deleted file mode 100644 index bea8f7c296b..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/deals/userdata/WinEventNotification.groovy +++ /dev/null @@ -1,19 +0,0 @@ -package org.prebid.server.functional.model.deals.userdata - -import groovy.transform.ToString -import org.prebid.server.functional.model.deals.lineitem.FrequencyCap - -import java.time.ZonedDateTime - -@ToString(includeNames = true, ignoreNulls = true) -class WinEventNotification { - - String bidderCode - String bidId - String lineItemId - String region - List userIds - ZonedDateTime winEventDateTime - ZonedDateTime lineUpdatedDateTime - List frequencyCaps -} diff --git a/src/test/groovy/org/prebid/server/functional/model/mock/services/generalplanner/PlansResponse.groovy b/src/test/groovy/org/prebid/server/functional/model/mock/services/generalplanner/PlansResponse.groovy deleted file mode 100644 index f9a9d4548e7..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/mock/services/generalplanner/PlansResponse.groovy +++ /dev/null @@ -1,19 +0,0 @@ -package org.prebid.server.functional.model.mock.services.generalplanner - -import com.fasterxml.jackson.annotation.JsonValue -import org.prebid.server.functional.model.ResponseModel -import org.prebid.server.functional.model.deals.lineitem.LineItem - -class PlansResponse implements ResponseModel { - - List lineItems - - static PlansResponse getDefaultPlansResponse(String accountId) { - new PlansResponse(lineItems: [LineItem.getDefaultLineItem(accountId)]) - } - - @JsonValue - List getLineItems() { - lineItems - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/request/dealsupdate/ForceDealsUpdateRequest.groovy b/src/test/groovy/org/prebid/server/functional/model/request/dealsupdate/ForceDealsUpdateRequest.groovy deleted file mode 100644 index aaa1c0b2ece..00000000000 --- a/src/test/groovy/org/prebid/server/functional/model/request/dealsupdate/ForceDealsUpdateRequest.groovy +++ /dev/null @@ -1,48 +0,0 @@ -package org.prebid.server.functional.model.request.dealsupdate - -import com.fasterxml.jackson.databind.PropertyNamingStrategies -import com.fasterxml.jackson.databind.annotation.JsonNaming -import groovy.transform.ToString - -import static org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest.Action.CREATE_REPORT -import static org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest.Action.INVALIDATE_LINE_ITEMS -import static org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest.Action.REGISTER_INSTANCE -import static org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest.Action.RESET_ALERT_COUNT -import static org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest.Action.SEND_REPORT -import static org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest.Action.UPDATE_LINE_ITEMS - -@ToString(includeNames = true, ignoreNulls = true) -@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy) -class ForceDealsUpdateRequest { - - String actionName - - static ForceDealsUpdateRequest getUpdateLineItemsRequest() { - new ForceDealsUpdateRequest(actionName: UPDATE_LINE_ITEMS.name()) - } - - static ForceDealsUpdateRequest getSendReportRequest() { - new ForceDealsUpdateRequest(actionName: SEND_REPORT.name()) - } - - static ForceDealsUpdateRequest getRegisterInstanceRequest() { - new ForceDealsUpdateRequest(actionName: REGISTER_INSTANCE.name()) - } - - static ForceDealsUpdateRequest getResetAlertCountRequest() { - new ForceDealsUpdateRequest(actionName: RESET_ALERT_COUNT.name()) - } - - static ForceDealsUpdateRequest getCreateReportRequest() { - new ForceDealsUpdateRequest(actionName: CREATE_REPORT.name()) - } - - static ForceDealsUpdateRequest getInvalidateLineItemsRequest() { - new ForceDealsUpdateRequest(actionName: INVALIDATE_LINE_ITEMS.name()) - } - - private enum Action { - - UPDATE_LINE_ITEMS, SEND_REPORT, REGISTER_INSTANCE, RESET_ALERT_COUNT, CREATE_REPORT, INVALIDATE_LINE_ITEMS - } -} diff --git a/src/test/groovy/org/prebid/server/functional/model/request/event/EventRequest.groovy b/src/test/groovy/org/prebid/server/functional/model/request/event/EventRequest.groovy index 9d7000cb7b3..6ed94f08161 100644 --- a/src/test/groovy/org/prebid/server/functional/model/request/event/EventRequest.groovy +++ b/src/test/groovy/org/prebid/server/functional/model/request/event/EventRequest.groovy @@ -24,8 +24,6 @@ class EventRequest { Integer analytics @JsonProperty("ts") Long timestamp - @JsonProperty("l") - String lineItemId static EventRequest getDefaultEventRequest() { def request = new EventRequest() diff --git a/src/test/groovy/org/prebid/server/functional/model/response/auction/BidResponse.groovy b/src/test/groovy/org/prebid/server/functional/model/response/auction/BidResponse.groovy index caae943a322..99e37de76ab 100644 --- a/src/test/groovy/org/prebid/server/functional/model/response/auction/BidResponse.groovy +++ b/src/test/groovy/org/prebid/server/functional/model/response/auction/BidResponse.groovy @@ -5,7 +5,6 @@ import groovy.transform.ToString import org.prebid.server.functional.model.Currency import org.prebid.server.functional.model.ResponseModel import org.prebid.server.functional.model.bidder.BidderName -import org.prebid.server.functional.model.mock.services.generalplanner.PlansResponse import org.prebid.server.functional.model.request.auction.BidRequest import static org.prebid.server.functional.model.bidder.BidderName.GENERIC @@ -29,16 +28,4 @@ class BidResponse implements ResponseModel { bidResponse.seatbid = [seatBid] bidResponse } - - static BidResponse getDefaultPgBidResponse(BidRequest bidRequest, PlansResponse plansResponse) { - def bidResponse = getDefaultBidResponse(bidRequest) - def bid = bidResponse.seatbid[0].bid[0] - def lineItem = plansResponse.lineItems[0] - bid.dealid = lineItem.dealId - if (lineItem.sizes) { - bid.w = lineItem.sizes[0].w - bid.h = lineItem.sizes[0].h - } - bidResponse - } } diff --git a/src/test/groovy/org/prebid/server/functional/service/PrebidServerService.groovy b/src/test/groovy/org/prebid/server/functional/service/PrebidServerService.groovy index a80cffe0c11..ade27a2fd6e 100644 --- a/src/test/groovy/org/prebid/server/functional/service/PrebidServerService.groovy +++ b/src/test/groovy/org/prebid/server/functional/service/PrebidServerService.groovy @@ -9,12 +9,10 @@ import io.restassured.response.Response import io.restassured.specification.RequestSpecification import org.prebid.server.functional.model.UidsCookie import org.prebid.server.functional.model.bidder.BidderName -import org.prebid.server.functional.model.deals.report.LineItemStatusReport import org.prebid.server.functional.model.mock.services.prebidcache.response.PrebidCacheResponse import org.prebid.server.functional.model.request.amp.AmpRequest import org.prebid.server.functional.model.request.auction.BidRequest import org.prebid.server.functional.model.request.cookiesync.CookieSyncRequest -import org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest import org.prebid.server.functional.model.request.event.EventRequest import org.prebid.server.functional.model.request.logging.httpinteraction.HttpInteractionRequest import org.prebid.server.functional.model.request.setuid.SetuidRequest @@ -59,8 +57,6 @@ class PrebidServerService implements ObjectMapperWrapper { static final String CURRENCY_RATES_ENDPOINT = "/currency/rates" static final String HTTP_INTERACTION_ENDPOINT = "/logging/httpinteraction" static final String COLLECTED_METRICS_ENDPOINT = "/collected-metrics" - static final String FORCE_DEALS_UPDATE_ENDPOINT = "/pbs-admin/force-deals-update" - static final String LINE_ITEM_STATUS_ENDPOINT = "/pbs-admin/lineitem-status" static final String PROMETHEUS_METRICS_ENDPOINT = "/metrics" static final String UIDS_COOKIE_NAME = "uids" @@ -290,26 +286,6 @@ class PrebidServerService implements ObjectMapperWrapper { decode(response.asString(), new TypeReference>() {}) } - @Step("[GET] /pbs-admin/force-deals-update") - void sendForceDealsUpdateRequest(ForceDealsUpdateRequest forceDealsUpdateRequest) { - def response = given(adminRequestSpecification).queryParams(toMap(forceDealsUpdateRequest)) - .get(FORCE_DEALS_UPDATE_ENDPOINT) - - checkResponseStatusCode(response, 204) - } - - @Step("[GET] /pbs-admin/lineitem-status") - LineItemStatusReport sendLineItemStatusRequest(String lineItemId) { - def request = given(adminRequestSpecification) - if (lineItemId != null) { - request.queryParam("id", lineItemId) - } - - def response = request.get(LINE_ITEM_STATUS_ENDPOINT) - - checkResponseStatusCode(response) - response.as(LineItemStatusReport) - } @Step("[GET] /metrics") String sendPrometheusMetricsRequest() { diff --git a/src/test/groovy/org/prebid/server/functional/testcontainers/PbsPgConfig.groovy b/src/test/groovy/org/prebid/server/functional/testcontainers/PbsPgConfig.groovy deleted file mode 100644 index 47de3679541..00000000000 --- a/src/test/groovy/org/prebid/server/functional/testcontainers/PbsPgConfig.groovy +++ /dev/null @@ -1,135 +0,0 @@ -package org.prebid.server.functional.testcontainers - -import org.prebid.server.functional.model.Currency -import org.prebid.server.functional.testcontainers.container.NetworkServiceContainer -import org.prebid.server.functional.util.PBSUtils - -import java.time.LocalDate - -import static org.prebid.server.functional.testcontainers.scaffolding.pg.Alert.ALERT_ENDPOINT_PATH -import static org.prebid.server.functional.testcontainers.scaffolding.pg.DeliveryStatistics.REPORT_DELIVERY_ENDPOINT_PATH -import static org.prebid.server.functional.testcontainers.scaffolding.pg.GeneralPlanner.PLANS_ENDPOINT_PATH -import static org.prebid.server.functional.testcontainers.scaffolding.pg.GeneralPlanner.REGISTER_ENDPOINT_PATH -import static org.prebid.server.functional.testcontainers.scaffolding.pg.UserData.USER_DETAILS_ENDPOINT_PATH -import static org.prebid.server.functional.testcontainers.scaffolding.pg.UserData.WIN_EVENT_ENDPOINT_PATH - -class PbsPgConfig { - - public static final String PG_ENDPOINT_USERNAME = "pg" - public static final String PG_ENDPOINT_PASSWORD = "pg" - - private static final int NEXT_MONTH = LocalDate.now().plusMonths(1).monthValue - - final Map properties - final String env - final String dataCenter - final String region - final String system - final String subSystem - final String hostId - final String vendor - final Currency currency - final String userIdType - final int maxDealsPerBidder - final int lineItemsPerReport - - PbsPgConfig(NetworkServiceContainer networkServiceContainer) { - properties = getPgConfig(networkServiceContainer.rootUri).asImmutable() - env = properties.get("profile") - dataCenter = properties.get("data-center") - region = properties.get("datacenter-region") - system = properties.get("system") - subSystem = properties.get("sub-system") - hostId = properties.get("host-id") - vendor = properties.get("vendor") - currency = properties.get("auction.ad-server-currency") - userIdType = properties.get("deals.user-data.user-ids[0].type") - maxDealsPerBidder = getIntProperty(properties, "deals.max-deals-per-bidder") - lineItemsPerReport = getIntProperty(properties, "deals.delivery-stats.line-items-per-report") - } - - private static Map getPgConfig(String networkServiceContainerUri) { - pbsGeneralSettings() + adminDealsUpdateEndpoint() + deals() + deliveryProgress() + - planner(networkServiceContainerUri) + deliveryStatistics(networkServiceContainerUri) + - alert(networkServiceContainerUri) + userData(networkServiceContainerUri) + adminLineItemStatusEndpoint() - } - - private static Map pbsGeneralSettings() { - ["host-id" : PBSUtils.randomString, - "datacenter-region" : PBSUtils.randomString, - "vendor" : PBSUtils.randomString, - "profile" : PBSUtils.randomString, - "system" : PBSUtils.randomString, - "sub-system" : PBSUtils.randomString, - "data-center" : PBSUtils.randomString, - "auction.ad-server-currency": "USD", - ] - } - - private static Map adminDealsUpdateEndpoint() { - ["admin-endpoints.force-deals-update.enabled": "true"] - } - - private static Map adminLineItemStatusEndpoint() { - ["admin-endpoints.lineitem-status.enabled": "true"] - } - - private static Map deals() { - ["deals.enabled" : "true", - "deals.simulation.enabled" : "false", - "deals.max-deals-per-bidder": "3" - ] - } - - private static Map planner(String networkServiceContainerUri) { - ["deals.planner.plan-endpoint" : networkServiceContainerUri + PLANS_ENDPOINT_PATH, - "deals.planner.register-endpoint" : networkServiceContainerUri + REGISTER_ENDPOINT_PATH, - "deals.planner.update-period" : "0 15 10 15 $NEXT_MONTH ?" as String, - "deals.planner.plan-advance-period": "0 15 10 15 $NEXT_MONTH ?" as String, - "deals.planner.timeout-ms" : "5000", - "deals.planner.username" : PG_ENDPOINT_USERNAME, - "deals.planner.password" : PG_ENDPOINT_PASSWORD, - "deals.planner.register-period-sec": "3600" - ] - } - - private static Map deliveryStatistics(String networkServiceContainerUri) { - ["deals.delivery-stats.endpoint" : networkServiceContainerUri + - REPORT_DELIVERY_ENDPOINT_PATH, - "deals.delivery-stats.username" : PG_ENDPOINT_USERNAME, - "deals.delivery-stats.password" : PG_ENDPOINT_PASSWORD, - "deals.delivery-stats.delivery-period" : "0 15 10 15 $NEXT_MONTH ?" as String, - "deals.delivery-stats.timeout-ms" : "10000", - "deals.delivery-stats.request-compression-enabled": "false", - "deals.delivery-stats.line-items-per-report" : "5" - ] - } - - private static Map deliveryProgress() { - ["deals.delivery-progress.report-reset-period": "0 15 10 15 $NEXT_MONTH ?" as String] - } - - private static Map alert(String networkServiceContainerUri) { - ["deals.alert-proxy.enabled" : "true", - "deals.alert-proxy.url" : networkServiceContainerUri + ALERT_ENDPOINT_PATH, - "deals.alert-proxy.username" : PG_ENDPOINT_USERNAME, - "deals.alert-proxy.password" : PG_ENDPOINT_PASSWORD, - "deals.alert-proxy.timeout-sec": "10" - ] - } - - private static Map userData(String networkServiceContainerUri) { - ["deals.user-data.user-details-endpoint": networkServiceContainerUri + USER_DETAILS_ENDPOINT_PATH, - "deals.user-data.win-event-endpoint" : networkServiceContainerUri + WIN_EVENT_ENDPOINT_PATH, - "deals.user-data.timeout" : "1000", - "deals.user-data.user-ids[0].type" : "autotest", - "deals.user-data.user-ids[0].source" : "uid", - "deals.user-data.user-ids[0].location" : "generic" - ] - } - - private static getIntProperty(Map properties, String propertyName) { - def property = properties.get(propertyName) - property ? property as int : -1 - } -} diff --git a/src/test/groovy/org/prebid/server/functional/testcontainers/scaffolding/pg/Alert.groovy b/src/test/groovy/org/prebid/server/functional/testcontainers/scaffolding/pg/Alert.groovy deleted file mode 100644 index 49efd6b3441..00000000000 --- a/src/test/groovy/org/prebid/server/functional/testcontainers/scaffolding/pg/Alert.groovy +++ /dev/null @@ -1,50 +0,0 @@ -package org.prebid.server.functional.testcontainers.scaffolding.pg - -import com.fasterxml.jackson.core.type.TypeReference -import org.mockserver.model.HttpRequest -import org.prebid.server.functional.model.deals.alert.AlertEvent -import org.prebid.server.functional.testcontainers.scaffolding.NetworkScaffolding -import org.testcontainers.containers.MockServerContainer - -import static org.mockserver.model.HttpRequest.request -import static org.mockserver.model.HttpResponse.response -import static org.mockserver.model.HttpStatusCode.OK_200 -import static org.mockserver.model.JsonPathBody.jsonPath - -class Alert extends NetworkScaffolding { - - static final String ALERT_ENDPOINT_PATH = "/deals/alert" - - Alert(MockServerContainer mockServerContainer) { - super(mockServerContainer, ALERT_ENDPOINT_PATH) - } - - AlertEvent getRecordedAlertRequest() { - def body = getRecordedRequestsBody(request).last() - // 0 index element is returned after deserialization as PBS responses with SingletonList - decode(body, new TypeReference>() {})[0] - } - - Map> getLastRecordedAlertRequestHeaders() { - getLastRecordedRequestHeaders(request) - } - - @Override - void setResponse() { - mockServerClient.when(request().withPath(endpoint)) - .respond(response().withStatusCode(OK_200.code())) - } - - @Override - protected HttpRequest getRequest(String alertId) { - request().withMethod("POST") - .withPath(ALERT_ENDPOINT_PATH) - .withBody(jsonPath("\$[?(@.id == '$alertId')]")) - } - - @Override - protected HttpRequest getRequest() { - request().withMethod("POST") - .withPath(ALERT_ENDPOINT_PATH) - } -} diff --git a/src/test/groovy/org/prebid/server/functional/testcontainers/scaffolding/pg/DeliveryStatistics.groovy b/src/test/groovy/org/prebid/server/functional/testcontainers/scaffolding/pg/DeliveryStatistics.groovy deleted file mode 100644 index 32f8f26b4d3..00000000000 --- a/src/test/groovy/org/prebid/server/functional/testcontainers/scaffolding/pg/DeliveryStatistics.groovy +++ /dev/null @@ -1,57 +0,0 @@ -package org.prebid.server.functional.testcontainers.scaffolding.pg - -import org.mockserver.model.HttpRequest -import org.mockserver.model.HttpStatusCode -import org.prebid.server.functional.model.deals.report.DeliveryStatisticsReport -import org.prebid.server.functional.testcontainers.scaffolding.NetworkScaffolding -import org.testcontainers.containers.MockServerContainer - -import static org.mockserver.model.ClearType.ALL -import static org.mockserver.model.HttpRequest.request -import static org.mockserver.model.HttpResponse.response -import static org.mockserver.model.HttpStatusCode.OK_200 -import static org.mockserver.model.JsonPathBody.jsonPath - -class DeliveryStatistics extends NetworkScaffolding { - - static final String REPORT_DELIVERY_ENDPOINT_PATH = "/deals/report/delivery" - - DeliveryStatistics(MockServerContainer mockServerContainer) { - super(mockServerContainer, REPORT_DELIVERY_ENDPOINT_PATH) - } - - Map> getLastRecordedDeliveryRequestHeaders() { - getLastRecordedRequestHeaders(request) - } - - DeliveryStatisticsReport getLastRecordedDeliveryStatisticsReportRequest() { - recordedDeliveryStatisticsReportRequests.last() - } - - void resetRecordedRequests() { - reset(REPORT_DELIVERY_ENDPOINT_PATH, ALL) - } - - void setResponse(HttpStatusCode statusCode = OK_200) { - mockServerClient.when(request().withPath(endpoint)) - .respond(response().withStatusCode(statusCode.code())) - } - - List getRecordedDeliveryStatisticsReportRequests() { - def body = getRecordedRequestsBody(request) - body.collect { decode(it, DeliveryStatisticsReport) } - } - - @Override - protected HttpRequest getRequest(String reportId) { - request().withMethod("POST") - .withPath(REPORT_DELIVERY_ENDPOINT_PATH) - .withBody(jsonPath("\$[?(@.reportId == '$reportId')]")) - } - - @Override - protected HttpRequest getRequest() { - request().withMethod("POST") - .withPath(REPORT_DELIVERY_ENDPOINT_PATH) - } -} diff --git a/src/test/groovy/org/prebid/server/functional/testcontainers/scaffolding/pg/GeneralPlanner.groovy b/src/test/groovy/org/prebid/server/functional/testcontainers/scaffolding/pg/GeneralPlanner.groovy deleted file mode 100644 index be27be483f6..00000000000 --- a/src/test/groovy/org/prebid/server/functional/testcontainers/scaffolding/pg/GeneralPlanner.groovy +++ /dev/null @@ -1,96 +0,0 @@ -package org.prebid.server.functional.testcontainers.scaffolding.pg - -import org.mockserver.matchers.Times -import org.mockserver.model.HttpRequest -import org.mockserver.model.HttpStatusCode -import org.prebid.server.functional.model.deals.register.RegisterRequest -import org.prebid.server.functional.model.mock.services.generalplanner.PlansResponse -import org.prebid.server.functional.testcontainers.scaffolding.NetworkScaffolding -import org.testcontainers.containers.MockServerContainer - -import static org.mockserver.model.HttpRequest.request -import static org.mockserver.model.HttpResponse.response -import static org.mockserver.model.HttpStatusCode.OK_200 -import static org.mockserver.model.JsonPathBody.jsonPath - -class GeneralPlanner extends NetworkScaffolding { - - static final String PLANS_ENDPOINT_PATH = "/deals/plans" - static final String REGISTER_ENDPOINT_PATH = "/deals/register" - - GeneralPlanner(MockServerContainer mockServerContainer) { - super(mockServerContainer, REGISTER_ENDPOINT_PATH) - } - - void initRegisterResponse(HttpStatusCode statusCode = OK_200) { - reset() - setResponse(statusCode) - } - - void initPlansResponse(PlansResponse plansResponse, - HttpStatusCode statusCode = OK_200, - Times times = Times.exactly(1)) { - resetPlansEndpoint() - setPlansResponse(plansResponse, statusCode, times) - } - - void resetPlansEndpoint() { - reset(PLANS_ENDPOINT_PATH) - } - - int getRecordedPlansRequestCount() { - getRequestCount(plansRequest) - } - - RegisterRequest getLastRecordedRegisterRequest() { - recordedRegisterRequests.last() - } - - List getRecordedRegisterRequests() { - def body = getRecordedRequestsBody(request) - body.collect { decode(it, RegisterRequest) } - } - - void setResponse(HttpStatusCode statusCode = OK_200) { - mockServerClient.when(request().withPath(endpoint)) - .respond(response().withStatusCode(statusCode.code())) - } - - Map> getLastRecordedRegisterRequestHeaders() { - getLastRecordedRequestHeaders(request) - } - - Map> getLastRecordedPlansRequestHeaders() { - getLastRecordedRequestHeaders(plansRequest) - } - - @Override - void reset() { - super.reset(PLANS_ENDPOINT_PATH) - super.reset(REGISTER_ENDPOINT_PATH) - } - - private void setPlansResponse(PlansResponse plansResponse, - HttpStatusCode statusCode, - Times times = Times.exactly(1)) { - setResponse(plansRequest, plansResponse, statusCode, times) - } - - @Override - protected HttpRequest getRequest(String hostInstanceId) { - request().withMethod("POST") - .withPath(REGISTER_ENDPOINT_PATH) - .withBody(jsonPath("\$[?(@.hostInstanceId == '$hostInstanceId')]")) - } - - @Override - protected HttpRequest getRequest() { - request().withMethod("POST") - .withPath(REGISTER_ENDPOINT_PATH) - } - - private static HttpRequest getPlansRequest() { - request().withMethod("GET") - .withPath(PLANS_ENDPOINT_PATH) - } -} diff --git a/src/test/groovy/org/prebid/server/functional/testcontainers/scaffolding/pg/UserData.groovy b/src/test/groovy/org/prebid/server/functional/testcontainers/scaffolding/pg/UserData.groovy deleted file mode 100644 index 9a0caafa140..00000000000 --- a/src/test/groovy/org/prebid/server/functional/testcontainers/scaffolding/pg/UserData.groovy +++ /dev/null @@ -1,77 +0,0 @@ -package org.prebid.server.functional.testcontainers.scaffolding.pg - -import org.mockserver.model.HttpRequest -import org.mockserver.model.HttpStatusCode -import org.prebid.server.functional.model.deals.userdata.UserDetailsRequest -import org.prebid.server.functional.model.deals.userdata.UserDetailsResponse -import org.prebid.server.functional.model.deals.userdata.WinEventNotification -import org.prebid.server.functional.testcontainers.scaffolding.NetworkScaffolding -import org.testcontainers.containers.MockServerContainer - -import static org.mockserver.model.HttpRequest.request -import static org.mockserver.model.HttpResponse.response -import static org.mockserver.model.HttpStatusCode.OK_200 -import static org.mockserver.model.JsonPathBody.jsonPath - -class UserData extends NetworkScaffolding { - - static final String USER_DETAILS_ENDPOINT_PATH = "/deals/user-details" - static final String WIN_EVENT_ENDPOINT_PATH = "/deals/win-event" - - UserData(MockServerContainer mockServerContainer) { - super(mockServerContainer, WIN_EVENT_ENDPOINT_PATH) - } - - UserDetailsRequest getRecordedUserDetailsRequest() { - def body = getRecordedRequestsBody(userDetailsRequest).last() - decode(body, UserDetailsRequest) - } - - WinEventNotification getRecordedWinEventRequest() { - def body = getRecordedRequestsBody(request).last() - decode(body, WinEventNotification) - } - - void setUserDataResponse(UserDetailsResponse userDataResponse, HttpStatusCode httpStatusCode = OK_200) { - resetUserDetailsEndpoint() - setResponse(userDetailsRequest, userDataResponse, httpStatusCode) - } - - int getRecordedUserDetailsRequestCount() { - getRequestCount(userDetailsRequest) - } - - void resetUserDetailsEndpoint() { - reset(USER_DETAILS_ENDPOINT_PATH) - } - - @Override - void reset() { - super.reset(USER_DETAILS_ENDPOINT_PATH) - super.reset(WIN_EVENT_ENDPOINT_PATH) - } - - @Override - void setResponse() { - mockServerClient.when(request().withPath(endpoint)) - .respond(response().withStatusCode(OK_200.code())) - } - - @Override - protected HttpRequest getRequest(String bidId) { - request().withMethod("POST") - .withPath(WIN_EVENT_ENDPOINT_PATH) - .withBody(jsonPath("\$[?(@.bidId == '$bidId')]")) - } - - @Override - protected HttpRequest getRequest() { - request().withMethod("POST") - .withPath(WIN_EVENT_ENDPOINT_PATH) - } - - private static HttpRequest getUserDetailsRequest() { - request().withMethod("POST") - .withPath(USER_DETAILS_ENDPOINT_PATH) - } -} diff --git a/src/test/groovy/org/prebid/server/functional/tests/pg/AlertSpec.groovy b/src/test/groovy/org/prebid/server/functional/tests/pg/AlertSpec.groovy deleted file mode 100644 index bae95e69d96..00000000000 --- a/src/test/groovy/org/prebid/server/functional/tests/pg/AlertSpec.groovy +++ /dev/null @@ -1,281 +0,0 @@ -package org.prebid.server.functional.tests.pg - -import org.mockserver.matchers.Times -import org.prebid.server.functional.model.mock.services.generalplanner.PlansResponse -import org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest -import org.prebid.server.functional.util.HttpUtil -import org.prebid.server.functional.util.PBSUtils -import spock.lang.Retry - -import java.time.ZoneId -import java.time.ZonedDateTime - -import static java.time.ZoneOffset.UTC -import static org.mockserver.model.HttpStatusCode.INTERNAL_SERVER_ERROR_500 -import static org.mockserver.model.HttpStatusCode.NOT_FOUND_404 -import static org.mockserver.model.HttpStatusCode.NO_CONTENT_204 -import static org.prebid.server.functional.model.deals.alert.Action.RAISE -import static org.prebid.server.functional.model.deals.alert.AlertPriority.LOW -import static org.prebid.server.functional.model.deals.alert.AlertPriority.MEDIUM -import static org.prebid.server.functional.testcontainers.PbsPgConfig.PG_ENDPOINT_PASSWORD -import static org.prebid.server.functional.testcontainers.PbsPgConfig.PG_ENDPOINT_USERNAME -import static org.prebid.server.functional.util.HttpUtil.AUTHORIZATION_HEADER -import static org.prebid.server.functional.util.HttpUtil.CONTENT_TYPE_HEADER -import static org.prebid.server.functional.util.HttpUtil.CONTENT_TYPE_HEADER_VALUE -import static org.prebid.server.functional.util.HttpUtil.PG_TRX_ID_HEADER -import static org.prebid.server.functional.util.HttpUtil.UUID_REGEX - -class AlertSpec extends BasePgSpec { - - private static final String PBS_REGISTER_CLIENT_ERROR = "pbs-register-client-error" - private static final String PBS_PLANNER_CLIENT_ERROR = "pbs-planner-client-error" - private static final String PBS_PLANNER_EMPTY_RESPONSE = "pbs-planner-empty-response-error" - private static final String PBS_DELIVERY_CLIENT_ERROR = "pbs-delivery-stats-client-error" - private static final Integer DEFAULT_ALERT_PERIOD = 15 - - @Retry(exceptions = [IllegalStateException.class]) - def "PBS should send alert request when the threshold is reached"() { - given: "Changed Planner Register endpoint response to return bad status code" - generalPlanner.initRegisterResponse(NOT_FOUND_404) - - and: "PBS alert counter is reset" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.resetAlertCountRequest) - - and: "Initial Alert Service request count is taken" - def initialRequestCount = alert.requestCount - - when: "Initiating PBS to register its instance through the bad Planner for the first time" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.registerInstanceRequest) - - then: "PBS sends an alert request to the Alert Service for the first time" - PBSUtils.waitUntil { alert.requestCount == initialRequestCount + 1 } - - when: "Initiating PBS to register its instance through the bad Planner until the period threshold of alerts is reached" - (2..DEFAULT_ALERT_PERIOD).forEach { - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.registerInstanceRequest) - } - - then: "PBS sends an alert request to the Alert Service for the second time" - PBSUtils.waitUntil { alert.requestCount == initialRequestCount + 2 } - - and: "Request has the right number of failed register attempts" - def alertRequest = alert.recordedAlertRequest - assert alertRequest.details.startsWith("Service register failed to send request $DEFAULT_ALERT_PERIOD " + - "time(s) with error message") - - cleanup: "Return initial Planner response status code" - generalPlanner.initRegisterResponse() - } - - def "PBS should send an alert request with appropriate headers"() { - given: "Changed Planner Register endpoint response to return bad status code" - generalPlanner.initRegisterResponse(NOT_FOUND_404) - - and: "PBS alert counter is reset" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.resetAlertCountRequest) - - and: "Initial Alert Service request count is taken" - def initialRequestCount = alert.requestCount - - when: "Initiating PBS to register its instance through the bad Planner" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.registerInstanceRequest) - - and: "PBS sends an alert request to the Alert Service" - PBSUtils.waitUntil { alert.requestCount == initialRequestCount + 1 } - - then: "Request headers correspond to the payload" - def alertRequestHeaders = alert.lastRecordedAlertRequestHeaders - assert alertRequestHeaders - - and: "Request has an authorization header with a basic auth token" - def basicAuthToken = HttpUtil.makeBasicAuthHeaderValue(PG_ENDPOINT_USERNAME, PG_ENDPOINT_PASSWORD) - assert alertRequestHeaders.get(AUTHORIZATION_HEADER) == [basicAuthToken] - - and: "Request has a header with uuid value" - def uuidHeaderValue = alertRequestHeaders.get(PG_TRX_ID_HEADER) - assert uuidHeaderValue?.size() == 1 - assert (uuidHeaderValue[0] =~ UUID_REGEX).matches() - - and: "Request has a content type header" - assert alertRequestHeaders.get(CONTENT_TYPE_HEADER) == [CONTENT_TYPE_HEADER_VALUE] - - cleanup: "Return initial Planner response status code" - generalPlanner.initRegisterResponse() - } - - def "PBS should send an alert when fetching line items response status wasn't OK ('#httpStatusCode')"() { - given: "Changed Planner line items endpoint response to return bad status code" - // PBS will make 2 requests to the planner: 1 normal, 2 - recovery request - generalPlanner.initPlansResponse(PlansResponse.getDefaultPlansResponse(PBSUtils.randomString), httpStatusCode, Times.exactly(2)) - - and: "PBS alert counter is reset" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.resetAlertCountRequest) - - and: "Initial Alert Service request count is taken" - def initialRequestCount = alert.requestCount - - when: "Initiating PBS to fetch line items through the bad Planner" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.updateLineItemsRequest) - - then: "PBS sends an alert request to the Alert Service" - PBSUtils.waitUntil { alert.requestCount == initialRequestCount + 1 } - - and: "Alert request should correspond to the payload" - verifyAll(alert.recordedAlertRequest) { alertRequest -> - (alertRequest.id =~ UUID_REGEX).matches() - alertRequest.action == RAISE - alertRequest.priority == MEDIUM - alertRequest.updatedAt.isBefore(ZonedDateTime.now(ZoneId.from(UTC))) - alertRequest.name == PBS_PLANNER_CLIENT_ERROR - alertRequest.details == "Service planner failed to send request 1 time(s) with error message :" + - " Failed to retrieve line items from GP. Reason: Failed to fetch data from Planner, HTTP status code ${httpStatusCode.code()}" - - alertRequest.source.env == pgConfig.env - alertRequest.source.dataCenter == pgConfig.dataCenter - alertRequest.source.region == pgConfig.region - alertRequest.source.system == pgConfig.system - alertRequest.source.subSystem == pgConfig.subSystem - alertRequest.source.hostId == pgConfig.hostId - } - - cleanup: "Return initial Planner response status code" - generalPlanner.initPlansResponse(PlansResponse.getDefaultPlansResponse(PBSUtils.randomString)) - - where: "Bad status codes" - httpStatusCode << [NO_CONTENT_204, NOT_FOUND_404, INTERNAL_SERVER_ERROR_500] - } - - def "PBS should send an alert when register PBS instance response status wasn't OK ('#httpStatusCode')"() { - given: "Changed Planner register endpoint response to return bad status code" - generalPlanner.initRegisterResponse(httpStatusCode) - - and: "PBS alert counter is reset" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.resetAlertCountRequest) - - and: "Initial Alert Service request count is taken" - def initialRequestCount = alert.requestCount - - when: "Initiating PBS to register its instance through the bad Planner" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.registerInstanceRequest) - - then: "PBS sends an alert request to the Alert Service" - PBSUtils.waitUntil { alert.requestCount == initialRequestCount + 1 } - - and: "Alert request should correspond to the payload" - verifyAll(alert.recordedAlertRequest) { alertRequest -> - (alertRequest.id =~ UUID_REGEX).matches() - alertRequest.action == RAISE - alertRequest.priority == MEDIUM - alertRequest.updatedAt.isBefore(ZonedDateTime.now(ZoneId.from(UTC))) - alertRequest.name == PBS_REGISTER_CLIENT_ERROR - alertRequest.details.startsWith("Service register failed to send request 1 time(s) with error message :" + - " Planner responded with non-successful code ${httpStatusCode.code()}") - - alertRequest.source.env == pgConfig.env - alertRequest.source.dataCenter == pgConfig.dataCenter - alertRequest.source.region == pgConfig.region - alertRequest.source.system == pgConfig.system - alertRequest.source.subSystem == pgConfig.subSystem - alertRequest.source.hostId == pgConfig.hostId - } - - cleanup: "Return initial Planner response status code" - generalPlanner.initRegisterResponse() - - where: "Bad status codes" - httpStatusCode << [NOT_FOUND_404, INTERNAL_SERVER_ERROR_500] - } - - def "PBS should send an alert when send delivery statistics report response status wasn't OK ('#httpStatusCode')"() { - given: "Changed Delivery Statistics endpoint response to return bad status code" - deliveryStatistics.reset() - deliveryStatistics.setResponse(httpStatusCode) - - and: "Set line items response" - generalPlanner.initPlansResponse(PlansResponse.getDefaultPlansResponse(PBSUtils.randomString)) - - and: "PBS alert counter is reset" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.resetAlertCountRequest) - - and: "Initial Alert Service request count is taken" - def initialRequestCount = alert.requestCount - - and: "Report to send is generated by PBS" - updateLineItemsAndWait() - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.createReportRequest) - - when: "Initiating PBS to send delivery statistics report through the bad Delivery Statistics Service" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.sendReportRequest) - - then: "PBS sends an alert request to the Alert Service" - PBSUtils.waitUntil { alert.requestCount == initialRequestCount + 1 } - - and: "Alert request should correspond to the payload" - verifyAll(alert.recordedAlertRequest) { alertRequest -> - (alertRequest.id =~ UUID_REGEX).matches() - alertRequest.action == RAISE - alertRequest.priority == MEDIUM - alertRequest.updatedAt.isBefore(ZonedDateTime.now(ZoneId.from(UTC))) - alertRequest.name == PBS_DELIVERY_CLIENT_ERROR - alertRequest.details.startsWith("Service deliveryStats failed to send request 1 time(s) with error message : " + - "Report was not send to delivery stats service with a reason: Delivery stats service responded with " + - "status code = ${httpStatusCode.code()} for report with id = ") - - alertRequest.source.env == pgConfig.env - alertRequest.source.dataCenter == pgConfig.dataCenter - alertRequest.source.region == pgConfig.region - alertRequest.source.system == pgConfig.system - alertRequest.source.subSystem == pgConfig.subSystem - alertRequest.source.hostId == pgConfig.hostId - } - - cleanup: "Return initial Delivery Statistics response status code" - deliveryStatistics.reset() - deliveryStatistics.setResponse() - - and: "Report to delivery statistics is sent" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.createReportRequest) - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.sendReportRequest) - - where: "Bad status codes" - httpStatusCode << [NOT_FOUND_404, INTERNAL_SERVER_ERROR_500] - } - - def "PBS should send an alert when Planner returns empty response"() { - given: "Changed Planner get plans response to return no plans" - generalPlanner.initPlansResponse(new PlansResponse(lineItems: [])) - - and: "PBS alert counter is reset" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.resetAlertCountRequest) - - and: "Initial Alert Service request count is taken" - def initialRequestCount = alert.requestCount - - when: "Initiating PBS to fetch line items through the Planner" - updateLineItemsAndWait() - - then: "PBS sends an alert request to the Alert Service" - PBSUtils.waitUntil { alert.requestCount == initialRequestCount + 1 } - - and: "Alert request should correspond to the payload" - verifyAll(alert.recordedAlertRequest) { alertRequest -> - (alertRequest.id =~ UUID_REGEX).matches() - alertRequest.action == RAISE - alertRequest.priority == LOW - alertRequest.updatedAt.isBefore(ZonedDateTime.now(ZoneId.from(UTC))) - alertRequest.name == PBS_PLANNER_EMPTY_RESPONSE - alertRequest.details.startsWith("Service planner failed to send request 1 time(s) with error message : " + - "Response without line items was received from planner") - - alertRequest.source.env == pgConfig.env - alertRequest.source.dataCenter == pgConfig.dataCenter - alertRequest.source.region == pgConfig.region - alertRequest.source.system == pgConfig.system - alertRequest.source.subSystem == pgConfig.subSystem - alertRequest.source.hostId == pgConfig.hostId - } - - cleanup: "Return initial Planner response" - generalPlanner.initPlansResponse(PlansResponse.getDefaultPlansResponse(PBSUtils.randomString)) - } -} diff --git a/src/test/groovy/org/prebid/server/functional/tests/pg/BasePgSpec.groovy b/src/test/groovy/org/prebid/server/functional/tests/pg/BasePgSpec.groovy deleted file mode 100644 index 9159bba8bb0..00000000000 --- a/src/test/groovy/org/prebid/server/functional/tests/pg/BasePgSpec.groovy +++ /dev/null @@ -1,60 +0,0 @@ -package org.prebid.server.functional.tests.pg - -import org.prebid.server.functional.model.deals.userdata.UserDetailsResponse -import org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest -import org.prebid.server.functional.service.PrebidServerService -import org.prebid.server.functional.testcontainers.Dependencies -import org.prebid.server.functional.testcontainers.PbsPgConfig -import org.prebid.server.functional.testcontainers.PbsServiceFactory -import org.prebid.server.functional.testcontainers.scaffolding.Bidder -import org.prebid.server.functional.testcontainers.scaffolding.pg.Alert -import org.prebid.server.functional.testcontainers.scaffolding.pg.DeliveryStatistics -import org.prebid.server.functional.testcontainers.scaffolding.pg.GeneralPlanner -import org.prebid.server.functional.testcontainers.scaffolding.pg.UserData -import org.prebid.server.functional.util.PBSUtils -import spock.lang.Retry -import spock.lang.Shared -import spock.lang.Specification - -@Retry(mode = Retry.Mode.SETUP_FEATURE_CLEANUP) -abstract class BasePgSpec extends Specification { - - protected static final PbsServiceFactory pbsServiceFactory = new PbsServiceFactory(Dependencies.networkServiceContainer) - - protected static final GeneralPlanner generalPlanner = new GeneralPlanner(Dependencies.networkServiceContainer) - protected static final DeliveryStatistics deliveryStatistics = new DeliveryStatistics(Dependencies.networkServiceContainer) - protected static final Alert alert = new Alert(Dependencies.networkServiceContainer) - protected static final UserData userData = new UserData(Dependencies.networkServiceContainer) - - protected static final PbsPgConfig pgConfig = new PbsPgConfig(Dependencies.networkServiceContainer) - protected static final Bidder bidder = new Bidder(Dependencies.networkServiceContainer) - - @Shared - protected final PrebidServerService pgPbsService = pbsServiceFactory.getService(pgConfig.properties) - - def setupSpec() { - bidder.setResponse() - generalPlanner.setResponse() - deliveryStatistics.setResponse() - alert.setResponse() - userData.setResponse() - userData.setUserDataResponse(UserDetailsResponse.defaultUserResponse) - } - - def cleanupSpec() { - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.invalidateLineItemsRequest) - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.createReportRequest) - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.sendReportRequest) - generalPlanner.reset() - deliveryStatistics.reset() - alert.reset() - userData.reset() - bidder.reset() - } - - protected void updateLineItemsAndWait() { - def initialPlansRequestCount = generalPlanner.recordedPlansRequestCount - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.updateLineItemsRequest) - PBSUtils.waitUntil { generalPlanner.recordedPlansRequestCount == initialPlansRequestCount + 1 } - } -} diff --git a/src/test/groovy/org/prebid/server/functional/tests/pg/CurrencySpec.groovy b/src/test/groovy/org/prebid/server/functional/tests/pg/CurrencySpec.groovy deleted file mode 100644 index 9f2d6a3f540..00000000000 --- a/src/test/groovy/org/prebid/server/functional/tests/pg/CurrencySpec.groovy +++ /dev/null @@ -1,98 +0,0 @@ -package org.prebid.server.functional.tests.pg - -import org.prebid.server.functional.model.deals.lineitem.LineItem -import org.prebid.server.functional.model.deals.lineitem.Price -import org.prebid.server.functional.model.mock.services.currencyconversion.CurrencyConversionRatesResponse -import org.prebid.server.functional.model.mock.services.generalplanner.PlansResponse -import org.prebid.server.functional.model.request.auction.BidRequest -import org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest -import org.prebid.server.functional.model.response.auction.BidResponse -import org.prebid.server.functional.service.PrebidServerService -import org.prebid.server.functional.testcontainers.scaffolding.CurrencyConversion -import org.prebid.server.functional.util.PBSUtils -import spock.lang.Shared - -import static org.prebid.server.functional.model.bidder.BidderName.GENERIC -import static org.prebid.server.functional.testcontainers.Dependencies.networkServiceContainer - -class CurrencySpec extends BasePgSpec { - - private static final CurrencyConversion currencyConversion = new CurrencyConversion(networkServiceContainer).tap { - setCurrencyConversionRatesResponse(CurrencyConversionRatesResponse.defaultCurrencyConversionRatesResponse) - } - - private static final Map pgCurrencyConverterPbsConfig = externalCurrencyConverterConfig + pgConfig.properties - private static final PrebidServerService pgCurrencyConverterPbsService = pbsServiceFactory.getService(pgCurrencyConverterPbsConfig) - - @Shared - BidRequest bidRequest - - def setup() { - bidRequest = BidRequest.defaultBidRequest - bidder.setResponse(bidRequest.id, BidResponse.getDefaultBidResponse(bidRequest)) - pgCurrencyConverterPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.invalidateLineItemsRequest) - } - - def "PBS should convert non-default line item currency to the default one during the bidder auction"() { - given: "Planner Mock line items with the same CPM but different currencies" - def accountId = bidRequest.site.publisher.id - def defaultCurrency = Price.defaultPrice.currency - def nonDefaultCurrency = "EUR" - def defaultCurrencyLineItem = [LineItem.getDefaultLineItem(accountId).tap { price = new Price(cpm: 1, currency: defaultCurrency) }] - def nonDefaultCurrencyLineItems = [LineItem.getDefaultLineItem(accountId).tap { price = new Price(cpm: 1, currency: nonDefaultCurrency) }, - LineItem.getDefaultLineItem(accountId).tap { price = new Price(cpm: 1, currency: nonDefaultCurrency) }, - LineItem.getDefaultLineItem(accountId).tap { price = new Price(cpm: 1, currency: nonDefaultCurrency) }] - def lineItems = defaultCurrencyLineItem + nonDefaultCurrencyLineItems - def plansResponse = new PlansResponse(lineItems: lineItems) - generalPlanner.initPlansResponse(plansResponse) - def nonDefaultCurrencyLineItemIds = nonDefaultCurrencyLineItems.collect { it.lineItemId } - - and: "Line items are fetched by PBS" - def initialPlansRequestCount = generalPlanner.recordedPlansRequestCount - pgCurrencyConverterPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.updateLineItemsRequest) - PBSUtils.waitUntil { generalPlanner.recordedPlansRequestCount == initialPlansRequestCount + 1 } - - when: "Auction is requested" - def auctionResponse = pgCurrencyConverterPbsService.sendAuctionRequest(bidRequest) - - then: "All line items are ready to be served" - assert auctionResponse.ext?.debug?.pgmetrics?.readyToServe?.size() == plansResponse.lineItems.size() - - and: "Line Item with EUR defaultCurrency was sent to bidder as EUR defaultCurrency rate > than USD" - assert auctionResponse.ext?.debug?.pgmetrics?.sentToBidder?.get(GENERIC.value)?.sort() == - nonDefaultCurrencyLineItemIds.sort() - } - - def "PBS should invalidate line item with an unknown for the conversion rate currency"() { - given: "Planner Mock line items with a default currency and unknown currency" - def defaultCurrency = Price.defaultPrice.currency - def unknownCurrency = "UAH" - def defaultCurrencyLineItem = [LineItem.getDefaultLineItem(bidRequest.site.publisher.id).tap { price = new Price(cpm: 1, currency: defaultCurrency) }] - def unknownCurrencyLineItem = [LineItem.getDefaultLineItem(bidRequest.site.publisher.id).tap { price = new Price(cpm: 1, currency: unknownCurrency) }] - def lineItems = defaultCurrencyLineItem + unknownCurrencyLineItem - def plansResponse = new PlansResponse(lineItems: lineItems) - generalPlanner.initPlansResponse(plansResponse) - def defaultCurrencyLineItemId = defaultCurrencyLineItem.collect { it.lineItemId } - - and: "Line items are fetched by PBS" - def initialPlansRequestCount = generalPlanner.recordedPlansRequestCount - pgCurrencyConverterPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.updateLineItemsRequest) - PBSUtils.waitUntil { generalPlanner.recordedPlansRequestCount == initialPlansRequestCount + 1 } - - when: "Auction is requested" - def auctionResponse = pgCurrencyConverterPbsService.sendAuctionRequest(bidRequest) - - then: "Only line item with the default currency is ready to be served and was sent to bidder" - assert auctionResponse.ext?.debug?.pgmetrics?.readyToServe == defaultCurrencyLineItemId as Set - assert auctionResponse.ext?.debug?.pgmetrics?.sentToBidder?.get(GENERIC.value) == - defaultCurrencyLineItemId as Set - } - - private static Map getExternalCurrencyConverterConfig() { - ["currency-converter.external-rates.enabled" : "true", - "currency-converter.external-rates.url" : "$networkServiceContainer.rootUri/currency".toString(), - "currency-converter.external-rates.default-timeout-ms": "4000", - "currency-converter.external-rates.refresh-period-ms" : "900000" - ] - } -} diff --git a/src/test/groovy/org/prebid/server/functional/tests/pg/LineItemStatusSpec.groovy b/src/test/groovy/org/prebid/server/functional/tests/pg/LineItemStatusSpec.groovy deleted file mode 100644 index 77f2c31f603..00000000000 --- a/src/test/groovy/org/prebid/server/functional/tests/pg/LineItemStatusSpec.groovy +++ /dev/null @@ -1,193 +0,0 @@ -package org.prebid.server.functional.tests.pg - -import org.prebid.server.functional.model.deals.lineitem.DeliverySchedule -import org.prebid.server.functional.model.deals.lineitem.LineItem -import org.prebid.server.functional.model.deals.lineitem.Token -import org.prebid.server.functional.model.mock.services.generalplanner.PlansResponse -import org.prebid.server.functional.model.request.auction.BidRequest -import org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest -import org.prebid.server.functional.model.response.auction.BidResponse -import org.prebid.server.functional.service.PrebidServerException -import org.prebid.server.functional.util.ObjectMapperWrapper -import org.prebid.server.functional.util.PBSUtils - -import java.time.ZoneId -import java.time.ZonedDateTime -import java.time.temporal.ChronoUnit - -import static java.time.ZoneOffset.UTC - -class LineItemStatusSpec extends BasePgSpec implements ObjectMapperWrapper { - - def cleanup() { - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.invalidateLineItemsRequest) - } - - def "PBS should return a bad request exception when no 'id' query parameter is provided"() { - when: "Requesting endpoint without 'id' parameter" - pgPbsService.sendLineItemStatusRequest(null) - - then: "PBS throws an exception" - def exception = thrown(PrebidServerException) - assert exception.statusCode == 400 - assert exception.responseBody.contains("id parameter is required") - } - - def "PBS should return a bad request exception when endpoint is requested with not existing line item id"() { - given: "Not existing line item id" - def notExistingLineItemId = PBSUtils.randomString - - when: "Requesting endpoint" - pgPbsService.sendLineItemStatusRequest(notExistingLineItemId) - - then: "PBS throws an exception" - def exception = thrown(PrebidServerException) - assert exception.statusCode == 400 - assert exception.responseBody.contains("LineItem not found: $notExistingLineItemId") - } - - def "PBS should return an empty line item status response when line item doesn't have a scheduled delivery"() { - given: "Line item with no delivery schedule" - def plansResponse = PlansResponse.getDefaultPlansResponse(PBSUtils.randomString).tap { - lineItems[0].deliverySchedules = null - } - def lineItemId = plansResponse.lineItems[0].lineItemId - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Requesting endpoint" - def lineItemStatusReport = pgPbsService.sendLineItemStatusRequest(lineItemId) - - then: "Empty line item status report is returned" - verifyAll(lineItemStatusReport) { - it.lineItemId == lineItemId - !it.deliverySchedule - !it.spentTokens - !it.readyToServeTimestamp - !it.pacingFrequency - !it.accountId - !it.target - } - } - - def "PBS should return filled line item status report when line item has a scheduled delivery"() { - given: "Line item with a scheduled delivery" - def plansResponse = new PlansResponse(lineItems: [LineItem.getDefaultLineItem(PBSUtils.randomString).tap { - deliverySchedules = [DeliverySchedule.defaultDeliverySchedule] - }]) - generalPlanner.initPlansResponse(plansResponse) - def lineItemId = plansResponse.lineItems[0].lineItemId - def lineItem = plansResponse.lineItems[0] - def deliverySchedule = lineItem.deliverySchedules[0] - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Requesting endpoint" - def lineItemStatusReport = pgPbsService.sendLineItemStatusRequest(lineItemId) - - then: "Line item status report is returned" - def reportTimeZone = lineItemStatusReport.deliverySchedule?.planStartTimeStamp?.zone - assert reportTimeZone - - verifyAll(lineItemStatusReport) { - it.lineItemId == lineItemId - it.deliverySchedule?.planId == deliverySchedule.planId - - it.deliverySchedule.planStartTimeStamp == - timeToReportFormat(deliverySchedule.startTimeStamp, reportTimeZone) - it.deliverySchedule?.planExpirationTimeStamp == - timeToReportFormat(deliverySchedule.endTimeStamp, reportTimeZone) - it.deliverySchedule?.planUpdatedTimeStamp == - timeToReportFormat(deliverySchedule.updatedTimeStamp, reportTimeZone) - - it.deliverySchedule?.tokens?.size() == deliverySchedule.tokens.size() - it.deliverySchedule?.tokens?.first()?.priorityClass == deliverySchedule.tokens[0].priorityClass - it.deliverySchedule?.tokens?.first()?.total == deliverySchedule.tokens[0].total - !it.deliverySchedule?.tokens?.first()?.spent - !it.deliverySchedule?.tokens?.first()?.totalSpent - - it.spentTokens == 0 - it.readyToServeTimestamp.isBefore(ZonedDateTime.now()) - it.pacingFrequency == getDeliveryRateMs(deliverySchedule) - it.accountId == lineItem.accountId - encode(it.target) == encode(lineItem.targeting) - } - } - - def "PBS should return line item status report with an active scheduled delivery"() { - given: "Line item with an active and expired scheduled deliveries" - def inactiveDeliverySchedule = DeliverySchedule.defaultDeliverySchedule.tap { - startTimeStamp = ZonedDateTime.now(ZoneId.from(UTC)).minusHours(12) - updatedTimeStamp = ZonedDateTime.now(ZoneId.from(UTC)).minusHours(12) - endTimeStamp = ZonedDateTime.now(ZoneId.from(UTC)).minusHours(6) - } - def activeDeliverySchedule = DeliverySchedule.defaultDeliverySchedule.tap { - startTimeStamp = ZonedDateTime.now(ZoneId.from(UTC)) - updatedTimeStamp = ZonedDateTime.now(ZoneId.from(UTC)) - endTimeStamp = ZonedDateTime.now(ZoneId.from(UTC)).plusHours(12) - } - def plansResponse = new PlansResponse(lineItems: [LineItem.getDefaultLineItem(PBSUtils.randomString).tap { - deliverySchedules = [inactiveDeliverySchedule, activeDeliverySchedule] - }]) - generalPlanner.initPlansResponse(plansResponse) - def lineItemId = plansResponse.lineItems[0].lineItemId - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Requesting endpoint" - def lineItemStatusReport = pgPbsService.sendLineItemStatusRequest(lineItemId) - - then: "Line item status report is returned with an active delivery" - assert lineItemStatusReport.lineItemId == lineItemId - assert lineItemStatusReport.deliverySchedule?.planId == activeDeliverySchedule.planId - } - - def "PBS should return line item status report with increased spent token number when PG auction has happened"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Line item with a scheduled delivery" - def plansResponse = new PlansResponse(lineItems: [LineItem.getDefaultLineItem(bidRequest.site.publisher.id).tap { - deliverySchedules = [DeliverySchedule.defaultDeliverySchedule.tap { - tokens = [Token.defaultToken] - }] - }]) - generalPlanner.initPlansResponse(plansResponse) - def lineItemId = plansResponse.lineItems[0].lineItemId - def spentTokensNumber = 1 - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "PG bid response is set" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "PBS PG auction is requested" - pgPbsService.sendAuctionRequest(bidRequest) - - when: "Requesting line item status endpoint" - def lineItemStatusReport = pgPbsService.sendLineItemStatusRequest(lineItemId) - - then: "Spent token number in line item status report is increased" - assert lineItemStatusReport.lineItemId == lineItemId - assert lineItemStatusReport.spentTokens == spentTokensNumber - assert lineItemStatusReport.deliverySchedule?.tokens?.first()?.spent == spentTokensNumber - } - - private ZonedDateTime timeToReportFormat(ZonedDateTime givenTime, ZoneId reportTimeZone) { - givenTime.truncatedTo(ChronoUnit.MILLIS).withZoneSameInstant(reportTimeZone) - } - - private Integer getDeliveryRateMs(DeliverySchedule deliverySchedule) { - deliverySchedule.tokens[0].total > 0 - ? (deliverySchedule.endTimeStamp.toInstant().toEpochMilli() - - deliverySchedule.startTimeStamp.toInstant().toEpochMilli()) / - deliverySchedule.tokens[0].total - : null - } -} diff --git a/src/test/groovy/org/prebid/server/functional/tests/pg/PgAuctionSpec.groovy b/src/test/groovy/org/prebid/server/functional/tests/pg/PgAuctionSpec.groovy deleted file mode 100644 index 4d7ffec88af..00000000000 --- a/src/test/groovy/org/prebid/server/functional/tests/pg/PgAuctionSpec.groovy +++ /dev/null @@ -1,520 +0,0 @@ -package org.prebid.server.functional.tests.pg - -import org.prebid.server.functional.model.UidsCookie -import org.prebid.server.functional.model.bidder.Generic -import org.prebid.server.functional.model.deals.lineitem.FrequencyCap -import org.prebid.server.functional.model.deals.lineitem.LineItem -import org.prebid.server.functional.model.deals.lineitem.LineItemSize -import org.prebid.server.functional.model.deals.lineitem.Price -import org.prebid.server.functional.model.deals.lineitem.RelativePriority -import org.prebid.server.functional.model.deals.lineitem.targeting.Targeting -import org.prebid.server.functional.model.deals.userdata.UserDetailsResponse -import org.prebid.server.functional.model.mock.services.generalplanner.PlansResponse -import org.prebid.server.functional.model.request.auction.BidRequest -import org.prebid.server.functional.model.request.auction.BidRequestExt -import org.prebid.server.functional.model.request.auction.Bidder -import org.prebid.server.functional.model.request.auction.Imp -import org.prebid.server.functional.model.request.auction.Prebid -import org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest -import org.prebid.server.functional.model.response.auction.BidResponse -import org.prebid.server.functional.util.HttpUtil -import org.prebid.server.functional.util.PBSUtils - -import java.time.ZoneId -import java.time.ZonedDateTime - -import static java.time.ZoneOffset.UTC -import static org.prebid.server.functional.model.bidder.BidderName.GENERIC -import static org.prebid.server.functional.model.deals.lineitem.LineItemStatus.DELETED -import static org.prebid.server.functional.model.deals.lineitem.LineItemStatus.PAUSED -import static org.prebid.server.functional.model.deals.lineitem.RelativePriority.HIGH -import static org.prebid.server.functional.model.deals.lineitem.RelativePriority.LOW -import static org.prebid.server.functional.model.deals.lineitem.RelativePriority.MEDIUM -import static org.prebid.server.functional.model.deals.lineitem.RelativePriority.VERY_HIGH -import static org.prebid.server.functional.model.deals.lineitem.RelativePriority.VERY_LOW -import static org.prebid.server.functional.model.deals.lineitem.targeting.MatchingFunction.IN -import static org.prebid.server.functional.model.deals.lineitem.targeting.MatchingFunction.INTERSECTS -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.AD_UNIT_MEDIA_TYPE -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.AD_UNIT_SIZE -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.DEVICE_REGION -import static org.prebid.server.functional.model.response.auction.MediaType.BANNER -import static org.prebid.server.functional.util.HttpUtil.UUID_REGEX - -class PgAuctionSpec extends BasePgSpec { - - def cleanup() { - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.invalidateLineItemsRequest) - } - - def "PBS should return base response after PG auction"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock line items" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id) - generalPlanner.initPlansResponse(plansResponse) - - and: "Bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "Auction response contains values according to the payload" - verifyAll(auctionResponse) { - auctionResponse.id == bidRequest.id - auctionResponse.cur == pgConfig.currency - !auctionResponse.bidid - !auctionResponse.customdata - !auctionResponse.nbr - } - - and: "Seat bid corresponds to the request seat bid" - assert auctionResponse.seatbid?.size() == bidRequest.imp.size() - def seatBid = auctionResponse.seatbid[0] - assert seatBid.seat == GENERIC - - assert seatBid.bid?.size() == 1 - - verifyAll(seatBid.bid[0]) { bid -> - (bid.id =~ UUID_REGEX).matches() - bid.impid == bidRequest.imp[0].id - bid.price == bidResponse.seatbid[0].bid[0].price - bid.crid == bidResponse.seatbid[0].bid[0].crid - bid.ext?.prebid?.type == BANNER - bid.ext?.origbidcpm == bidResponse.seatbid[0].bid[0].price - } - } - - def "PBS shouldn't process line item with #reason"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock non matched line item" - generalPlanner.initPlansResponse(plansResponse.tap { - it.lineItems[0].accountId = bidRequest.site.publisher.id - }) - - and: "Bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS shouldn't start processing PG deals" - assert !auctionResponse.ext?.debug?.pgmetrics - - where: - reason | plansResponse - - "non matched targeting" | PlansResponse.getDefaultPlansResponse(PBSUtils.randomString).tap { - lineItems[0].targeting = new Targeting.Builder().addTargeting(AD_UNIT_SIZE, INTERSECTS, [LineItemSize.defaultLineItemSize]) - .addTargeting(AD_UNIT_MEDIA_TYPE, INTERSECTS, [BANNER]) - .addTargeting(DEVICE_REGION, IN, [14]) - .build() - } - - "empty targeting" | PlansResponse.getDefaultPlansResponse(PBSUtils.randomString).tap { - lineItems[0].targeting = null - } - - "non matched bidder" | PlansResponse.getDefaultPlansResponse(PBSUtils.randomString).tap { - lineItems[0].source = PBSUtils.randomString - } - - "inactive status" | PlansResponse.getDefaultPlansResponse(PBSUtils.randomString).tap { - lineItems[0].status = DELETED - } - - "paused status" | PlansResponse.getDefaultPlansResponse(PBSUtils.randomString).tap { - lineItems[0].status = PAUSED - } - - "expired lifetime" | PlansResponse.getDefaultPlansResponse(PBSUtils.randomString).tap { - lineItems[0].startTimeStamp = ZonedDateTime.now(ZoneId.from(UTC)).minusMinutes(2) - lineItems[0].endTimeStamp = ZonedDateTime.now(ZoneId.from(UTC)).minusMinutes(1) - lineItems[0].updatedTimeStamp = ZonedDateTime.now(ZoneId.from(UTC)).minusMinutes(2) - } - } - - def "PBS shouldn't process line item with non matched publisher account id"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock non matched publisher account id line item" - def plansResponse = PlansResponse.getDefaultPlansResponse(PBSUtils.randomNumber as String) - generalPlanner.initPlansResponse(plansResponse) - - and: "Bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS shouldn't start processing PG deals" - assert !auctionResponse.ext?.debug?.pgmetrics - } - - def "PBS shouldn't start processing PG deals when there is no any line item"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Bid response" - def bidResponse = BidResponse.getDefaultBidResponse(bidRequest) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Planner Mock no line items" - generalPlanner.initPlansResponse(new PlansResponse(lineItems: [])) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS shouldn't start processing PG deals" - assert !auctionResponse.ext?.debug?.pgmetrics - } - - def "PBS shouldn't allow line item with #reason delivery plan take part in auction"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock line item with expired delivery schedule" - def plansResponse = plansResponseClosure(bidRequest) - generalPlanner.initPlansResponse(plansResponse) - - and: "Bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS shouldn't allow line item take part in auction" - assert auctionResponse.ext?.debug?.pgmetrics?.pacingDeferred == - plansResponse.lineItems.collect { it.lineItemId } as Set - - where: - reason | plansResponseClosure - - "expired" | { BidRequest bidReq -> - PlansResponse.getDefaultPlansResponse(bidReq.site.publisher.id).tap { - lineItems[0].deliverySchedules[0].startTimeStamp = ZonedDateTime.now(ZoneId.from(UTC)).minusDays(2) - lineItems[0].deliverySchedules[0].updatedTimeStamp = ZonedDateTime.now(ZoneId.from(UTC)).minusDays(2) - lineItems[0].deliverySchedules[0].endTimeStamp = ZonedDateTime.now(ZoneId.from(UTC)).minusDays(1) - } - } - - "not set" | { BidRequest bidReq -> - PlansResponse.getDefaultPlansResponse(bidReq.site.publisher.id).tap { - lineItems[0].deliverySchedules = [] - } - } - } - - def "PBS should process only first #maxDealsPerBidder line items among the matched ones"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Publisher account id" - def accountId = bidRequest.site.publisher.id - - and: "Planner Mock line items to return #maxDealsPerBidder + 1 line items" - def maxLineItemsToProcess = pgConfig.maxDealsPerBidder - def plansResponse = new PlansResponse(lineItems: (1..maxLineItemsToProcess + 1).collect { - LineItem.getDefaultLineItem(accountId) - }) - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "There are #maxLineItemsToProcess + 1 line items are matched and ready to serve" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == maxLineItemsToProcess + 1 - assert auctionResponse.ext?.debug?.pgmetrics?.readyToServe?.size() == maxLineItemsToProcess + 1 - - and: "Only #maxLineItemsToProcess were sent to the bidder" - assert auctionResponse.ext?.debug?.pgmetrics?.sentToBidder?.get(GENERIC.value)?.size() == maxLineItemsToProcess - } - - def "PBS should send to bidder only the first line item among line items with identical deal ids"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Deal id" - def dealId = PBSUtils.randomString - - and: "Planner Mock line items with identical deal ids" - def plansResponse = new PlansResponse(lineItems: (1..2).collect { - LineItem.getDefaultLineItem(bidRequest.site.publisher.id).tap { it.dealId = dealId } - }) - generalPlanner.initPlansResponse(plansResponse) - def lineItemsNumber = plansResponse.lineItems.size() - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "There are 2 matched and ready to serve line items" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == lineItemsNumber - assert auctionResponse.ext?.debug?.pgmetrics?.readyToServe?.size() == lineItemsNumber - - and: "Only 1 line item was sent to the bidder" - assert auctionResponse.ext?.debug?.pgmetrics?.sentToBidder?.get(GENERIC.value)?.size() == lineItemsNumber - 1 - } - - def "PBS should allow line item with matched to the request bidder alias take part in auction"() { - given: "Bid request with set bidder alias" - def lineItemSource = PBSUtils.randomString - def bidRequest = BidRequest.defaultBidRequest.tap { - def prebid = new Prebid(aliases: [(lineItemSource): GENERIC], debug: 1) - ext = new BidRequestExt(prebid: prebid) - } - - and: "Planner Mock line items with changed line item source" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].source = lineItemSource - } - generalPlanner.initPlansResponse(plansResponse) - def lineItemCount = plansResponse.lineItems.size() - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "Line item was matched by alias bidder and took part in auction" - def pgMetrics = auctionResponse.ext?.debug?.pgmetrics - assert pgMetrics - assert pgMetrics.sentToBidder?.get(lineItemSource)?.size() == lineItemCount - assert pgMetrics.readyToServe?.size() == lineItemCount - assert pgMetrics.matchedWholeTargeting?.size() == lineItemCount - } - - def "PBS should abandon line items with matched user frequency capped ids take part in auction"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock line items with added frequency cap" - def fcapId = PBSUtils.randomNumber as String - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].frequencyCaps = [FrequencyCap.defaultFrequencyCap.tap { it.fcapId = fcapId }] - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "User Service Response is set to return frequency capped id identical to the line item fcapId" - userData.setUserDataResponse(UserDetailsResponse.defaultUserResponse.tap { - user.ext.fcapIds = [fcapId] - }) - - and: "Cookies header" - def uidsCookie = UidsCookie.defaultUidsCookie - def cookieHeader = HttpUtil.getCookieHeader(uidsCookie) - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest, cookieHeader) - - then: "PBS hasn't started processing PG deals as line item was recognized as frequency capped" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedTargetingFcapped?.size() == plansResponse.lineItems.size() - - cleanup: - userData.setUserDataResponse(UserDetailsResponse.defaultUserResponse) - } - - def "PBS should allow line items with unmatched user frequency capped ids take part in auction"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock line items with added frequency cap" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].frequencyCaps = [FrequencyCap.defaultFrequencyCap.tap { fcapId = PBSUtils.randomNumber as String }] - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "User Service Response is set to return frequency capped id not identical to the line item fcapId" - userData.setUserDataResponse(UserDetailsResponse.defaultUserResponse.tap { - user.ext.fcapIds = [PBSUtils.randomNumber as String] - }) - - and: "Cookies header" - def uidsCookie = UidsCookie.defaultUidsCookie - def cookieHeader = HttpUtil.getCookieHeader(uidsCookie) - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest, cookieHeader) - - then: "PBS hasn't started processing PG deals as line item was recognized as frequency capped" - assert !auctionResponse.ext?.debug?.pgmetrics?.matchedTargetingFcapped - assert auctionResponse.ext?.debug?.pgmetrics?.readyToServe - - cleanup: - userData.setUserDataResponse(UserDetailsResponse.defaultUserResponse) - } - - def "PBS shouldn't use already matched line items by the same bidder during one auction"() { - given: "Bid request with two impressions" - def bidRequest = BidRequest.defaultBidRequest.tap { - imp[0].ext.prebid.bidder = new Bidder(generic: new Generic()) - imp << Imp.defaultImpression - imp[1].ext.prebid.bidder = new Bidder(generic: new Generic()) - } - def accountId = bidRequest.site.publisher.id - - and: "Planner Mock with two line items" - def plansResponse = PlansResponse.getDefaultPlansResponse(accountId).tap { - lineItems << LineItem.getDefaultLineItem(accountId) - } - generalPlanner.initPlansResponse(plansResponse) - def lineItemCount = plansResponse.lineItems.size() - def lineItemIds = plansResponse.lineItems.collect { it.lineItemId } as Set - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is requested" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "Two line items are ready to be served" - assert auctionResponse.ext?.debug?.pgmetrics?.readyToServe?.size() == lineItemCount - - and: "Two (as the number of imps) different line items were sent to the bidder" - def sentToBidder = auctionResponse.ext?.debug?.pgmetrics?.sentToBidder?.get(GENERIC.value) - assert sentToBidder?.size() == lineItemCount - assert sentToBidder.sort() == lineItemIds.sort() - - def sentToBidderAsTopMatch = auctionResponse.ext?.debug?.pgmetrics?.sentToBidderAsTopMatch?.get(GENERIC.value) - assert sentToBidderAsTopMatch?.size() == lineItemCount - assert sentToBidderAsTopMatch.sort() == lineItemIds.sort() - } - - def "PBS should send line items with the highest priority to the bidder during auction"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - def accountId = bidRequest.site.publisher.id - - and: "Planner Mock line items with different priorities" - def lowerPriorityLineItems = [LineItem.getDefaultLineItem(accountId).tap { relativePriority = VERY_LOW }, - LineItem.getDefaultLineItem(accountId).tap { relativePriority = LOW }] - def higherPriorityLineItems = [LineItem.getDefaultLineItem(accountId).tap { relativePriority = MEDIUM }, - LineItem.getDefaultLineItem(accountId).tap { relativePriority = HIGH }, - LineItem.getDefaultLineItem(accountId).tap { relativePriority = VERY_HIGH }] - def lineItems = lowerPriorityLineItems + higherPriorityLineItems - def plansResponse = new PlansResponse(lineItems: lineItems) - def higherPriorityLineItemIds = higherPriorityLineItems.collect { it.lineItemId } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is requested" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "All line items are ready to be served" - assert auctionResponse.ext?.debug?.pgmetrics?.readyToServe?.size() == lineItems.size() - - and: "#maxDealsPerBidder[3] line items were send to bidder" - def sentToBidder = auctionResponse.ext?.debug?.pgmetrics?.sentToBidder?.get(GENERIC.value) - assert sentToBidder?.size() == pgConfig.maxDealsPerBidder - - and: "Those line items with the highest priority were sent" - assert sentToBidder.sort() == higherPriorityLineItemIds.sort() - } - - def "PBS should send line items with the highest CPM to the bidder during auction"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - def accountId = bidRequest.site.publisher.id - - and: "Planner Mock line items with different CPMs" - def currency = Price.defaultPrice.currency - def lowerCpmLineItems = [LineItem.getDefaultLineItem(accountId).tap { price = new Price(cpm: 1, currency: currency) }, - LineItem.getDefaultLineItem(accountId).tap { price = new Price(cpm: 2, currency: currency) }] - def higherCpmLineItems = [LineItem.getDefaultLineItem(accountId).tap { price = new Price(cpm: 3, currency: currency) }, - LineItem.getDefaultLineItem(accountId).tap { price = new Price(cpm: 4, currency: currency) }, - LineItem.getDefaultLineItem(accountId).tap { price = new Price(cpm: 5, currency: currency) }] - def lineItems = lowerCpmLineItems + higherCpmLineItems - def plansResponse = new PlansResponse(lineItems: lineItems) - def higherCpmLineItemIds = higherCpmLineItems.collect { it.lineItemId } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is requested" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "All line items are ready to be served" - assert auctionResponse.ext?.debug?.pgmetrics?.readyToServe?.size() == lineItems.size() - - and: "#maxDealsPerBidder[3] line items were send to bidder" - def sentToBidder = auctionResponse.ext?.debug?.pgmetrics?.sentToBidder?.get(GENERIC.value) - assert sentToBidder?.size() == pgConfig.maxDealsPerBidder - - and: "Those line items with the highest CPM were sent" - assert sentToBidder.sort() == higherCpmLineItemIds.sort() - } - - def "PBS should send line items with the highest priority to the bidder during auction despite the price"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - def accountId = bidRequest.site.publisher.id - - and: "Planner Mock line items with different priorities and CPMs" - def lineItems = RelativePriority.values().collect { relativePriority -> - LineItem.getDefaultLineItem(accountId).tap { - it.relativePriority = relativePriority - it.price = Price.defaultPrice - } - } - - def plansResponse = new PlansResponse(lineItems: lineItems) - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "All line items are ready to be served" - assert auctionResponse.ext?.debug?.pgmetrics?.readyToServe?.size() == lineItems.size() - - and: "#maxDealsPerBidder[3] line items were send to bidder" - def sentToBidder = auctionResponse.ext?.debug?.pgmetrics?.sentToBidder?.get(GENERIC.value) - def dealsPerBidder = pgConfig.maxDealsPerBidder - assert sentToBidder?.size() == dealsPerBidder - - and: "Those line items with the highest priority were sent" - def prioritizedLineItems = lineItems.sort { it.relativePriority.value } - .take(dealsPerBidder) - assert sentToBidder.sort() == prioritizedLineItems.collect { it.lineItemId }.sort() - } -} diff --git a/src/test/groovy/org/prebid/server/functional/tests/pg/PgBidResponseSpec.groovy b/src/test/groovy/org/prebid/server/functional/tests/pg/PgBidResponseSpec.groovy deleted file mode 100644 index 2978fb91e0f..00000000000 --- a/src/test/groovy/org/prebid/server/functional/tests/pg/PgBidResponseSpec.groovy +++ /dev/null @@ -1,211 +0,0 @@ -package org.prebid.server.functional.tests.pg - -import org.prebid.server.functional.model.deals.lineitem.LineItemSize -import org.prebid.server.functional.model.mock.services.generalplanner.PlansResponse -import org.prebid.server.functional.model.request.auction.BidRequest -import org.prebid.server.functional.model.request.auction.Format -import org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest -import org.prebid.server.functional.model.response.auction.BidResponse -import org.prebid.server.functional.util.PBSUtils - -import static org.prebid.server.functional.model.response.auction.ErrorType.GENERIC - -class PgBidResponseSpec extends BasePgSpec { - - def cleanup() { - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.invalidateLineItemsRequest) - } - - def "PBS should allow valid bidder response with deals info continue taking part in auction"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock line items" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id) - generalPlanner.initPlansResponse(plansResponse) - def lineItemCount = plansResponse.lineItems.size() - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Set bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "Bidder returned valid response with deals info during auction" - assert auctionResponse.ext?.debug?.pgmetrics?.sentToClient?.size() == lineItemCount - assert auctionResponse.ext?.debug?.pgmetrics?.sentToClientAsTopMatch?.size() == lineItemCount - } - - def "PBS should invalidate bidder response when bid id doesn't match to the bid request bid id"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock line items" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id) - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Set bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse).tap { - seatbid[0].bid[0].impid = PBSUtils.randomNumber as String - } - bidder.setResponse(bidRequest.id, bidResponse) - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "Bidder response is invalid" - def bidderErrors = auctionResponse.ext?.errors?.get(GENERIC) - def bidId = bidResponse.seatbid[0].bid[0].id - - assert bidderErrors?.size() == 1 - assert bidderErrors[0].message ==~ - /BidId `$bidId` validation messages:.* Error: Bid \"$bidId\" has no corresponding imp in request.*/ - } - - def "PBS should invalidate bidder response when deal id doesn't match to the bid request deal id"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock line items" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id) - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Set bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse).tap { - seatbid[0].bid[0].dealid = PBSUtils.randomNumber as String - } - bidder.setResponse(bidRequest.id, bidResponse) - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "Bidder response is invalid" - def bidderErrors = auctionResponse.ext?.errors?.get(GENERIC) - def bidId = bidResponse.seatbid[0].bid[0].id - - assert bidderErrors?.size() == 1 - assert bidderErrors[0].message ==~ /BidId `$bidId` validation messages:.* Warning: / + - /WARNING: Bid "$bidId" has 'dealid' not present in corresponding imp in request.*/ - } - - def "PBS should invalidate bidder response when non-matched to the bid request size is returned"() { - given: "Bid request with set sizes" - def bidRequest = BidRequest.defaultBidRequest.tap { - imp[0].banner.format = [Format.defaultFormat] - } - def impFormat = bidRequest.imp[0].banner.format[0] - - and: "Planner Mock line items" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id) - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Set bid response with unmatched to the bid request size" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse).tap { - seatbid[0].bid[0].w = PBSUtils.randomNumber - } - def bid = bidResponse.seatbid[0].bid[0] - bidder.setResponse(bidRequest.id, bidResponse) - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "Bidder response is invalid" - assert auctionResponse.ext?.debug?.pgmetrics?.responseInvalidated?.size() == plansResponse.lineItems.size() - - and: "PBS invalidated response as unmatched by size" - def bidderErrors = auctionResponse.ext?.errors?.get(GENERIC) - - assert bidderErrors?.size() == 1 - assert bidderErrors[0].message ==~ /BidId `$bid.id` validation messages:.* Error: / + - /Bid "$bid.id" has 'w' and 'h' not supported by corresponding imp in request\. / + - /Bid dimensions: '${bid.w}x$bid.h', formats in imp: '${impFormat.w}x$impFormat.h'.*/ - } - - def "PBS should invalidate bidder response when non-matched to the PBS line item size response is returned"() { - given: "Bid request" - def newFormat = new Format(w: PBSUtils.randomNumber, h: PBSUtils.randomNumber) - def bidRequest = BidRequest.defaultBidRequest.tap { - imp[0].banner.format = [Format.defaultFormat, newFormat] - } - - and: "Planner Mock line items with a default size" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].sizes = [LineItemSize.defaultLineItemSize] - } - def lineItemSize = plansResponse.lineItems[0].sizes[0] - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Set bid response with non-matched to the line item size" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse).tap { - seatbid[0].bid[0].w = newFormat.w - seatbid[0].bid[0].h = newFormat.h - } - def bid = bidResponse.seatbid[0].bid[0] - bidder.setResponse(bidRequest.id, bidResponse) - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "Bidder response is invalid" - assert auctionResponse.ext?.debug?.pgmetrics?.responseInvalidated?.size() == plansResponse.lineItems.size() - - and: "PBS invalidated response as not matched by size" - def bidderErrors = auctionResponse.ext?.errors?.get(GENERIC) - - assert bidderErrors?.size() == 1 - assert bidderErrors[0].message ==~ /BidId `$bid.id` validation messages:.* Error: / + - /Bid "$bid.id" has 'w' and 'h' not matched to Line Item\. / + - /Bid dimensions: '${bid.w}x$bid.h', Line Item sizes: '${lineItemSize.w}x$lineItemSize.h'.*/ - } - - def "PBS should invalidate bidder response when line items sizes empty"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest.tap { - imp[0].banner.format = [Format.defaultFormat] - } - - and: "Planner Mock line items with a empty sizes" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].sizes = [] - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Set bid response without line items sizes 'h' and 'w' " - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - def bid = bidResponse.seatbid[0].bid[0] - bidder.setResponse(bidRequest.id, bidResponse) - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "Bidder response is invalid" - assert auctionResponse.ext?.debug?.pgmetrics?.responseInvalidated?.size() == plansResponse.lineItems.size() - - and: "PBS invalidated response as line items sizes empty" - def bidderErrors = auctionResponse.ext?.errors?.get(GENERIC) - - assert bidderErrors?.size() == 1 - assert bidderErrors[0].message == "BidId `${bid.id}` validation messages: " + - "Error: Line item sizes were not found for " + - "bidId ${bid.id} and dealId ${plansResponse.getLineItems()[0].dealId}" - } -} diff --git a/src/test/groovy/org/prebid/server/functional/tests/pg/PgBidderRequestSpec.groovy b/src/test/groovy/org/prebid/server/functional/tests/pg/PgBidderRequestSpec.groovy deleted file mode 100644 index 0a0219d34ee..00000000000 --- a/src/test/groovy/org/prebid/server/functional/tests/pg/PgBidderRequestSpec.groovy +++ /dev/null @@ -1,167 +0,0 @@ -package org.prebid.server.functional.tests.pg - -import org.prebid.server.functional.model.UidsCookie -import org.prebid.server.functional.model.bidder.Generic -import org.prebid.server.functional.model.deals.lineitem.LineItem -import org.prebid.server.functional.model.deals.userdata.UserDetailsResponse -import org.prebid.server.functional.model.mock.services.generalplanner.PlansResponse -import org.prebid.server.functional.model.request.auction.BidRequest -import org.prebid.server.functional.model.request.auction.Bidder -import org.prebid.server.functional.model.request.auction.Device -import org.prebid.server.functional.model.request.auction.Imp -import org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest -import org.prebid.server.functional.model.response.auction.BidResponse -import org.prebid.server.functional.util.HttpUtil -import org.prebid.server.functional.util.PBSUtils -import spock.lang.Ignore - -class PgBidderRequestSpec extends BasePgSpec { - - def cleanup() { - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.invalidateLineItemsRequest) - } - - def "PBS should be able to add given device info to the bidder request"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest.tap { - device = new Device(ua: PBSUtils.randomString, - make: PBSUtils.randomString, - model: PBSUtils.randomString) - } - - and: "Planner Mock line items" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id) - generalPlanner.initPlansResponse(plansResponse) - - and: "Bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "User Service response is set" - def userResponse = UserDetailsResponse.defaultUserResponse - userData.setUserDataResponse(userResponse) - - and: "Cookies with user ids" - def uidsCookie = UidsCookie.defaultUidsCookie - def cookieHeader = HttpUtil.getCookieHeader(uidsCookie) - - when: "Sending auction request to PBS" - pgPbsService.sendAuctionRequest(bidRequest, cookieHeader) - - then: "PBS sent a request to the bidder with added device info" - verifyAll(bidder.getBidderRequest(bidRequest.id)) { bidderRequest -> - bidderRequest.user?.ext?.fcapids == userResponse.user.ext.fcapIds - bidderRequest.user.data?.size() == userResponse.user.data.size() - bidderRequest.user.data[0].id == userResponse.user.data[0].name - bidderRequest.user.data[0].segment?.size() == userResponse.user.data[0].segment.size() - bidderRequest.user.data[0].segment[0].id == userResponse.user.data[0].segment[0].id - } - } - - def "PBS should be able to add pmp deals part to the bidder request when PG is enabled"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock line items" - def accountId = bidRequest.site.publisher.id - def plansResponse = new PlansResponse(lineItems: [LineItem.getDefaultLineItem(accountId), LineItem.getDefaultLineItem(accountId)]) - generalPlanner.initPlansResponse(plansResponse) - - and: "Bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Sending auction request to PBS" - pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS sent a request to the bidder with added deals" - def bidderRequest = bidder.getBidderRequest(bidRequest.id) - - assert bidderRequest.imp?.size() == bidRequest.imp.size() - assert bidderRequest.imp[0].pmp?.deals?.size() == plansResponse.lineItems.size() - assert bidderRequest.imp[0].pmp?.deals - assert plansResponse.lineItems.each { lineItem -> - def deal = bidderRequest.imp[0]?.pmp?.deals?.find { it.id == lineItem.dealId } - - assert deal - verifyAll(deal) { - deal?.ext?.line?.lineItemId == lineItem.lineItemId - deal?.ext?.line?.extLineItemId == lineItem.extLineItemId - deal?.ext?.line?.sizes?.size() == lineItem.sizes.size() - deal?.ext?.line?.sizes[0].w == lineItem.sizes[0].w - deal?.ext?.line?.sizes[0].h == lineItem.sizes[0].h - } - } - } - - @Ignore - def "PBS shouldn't add already top matched line item by first impression to the second impression deals bidder request section"() { - given: "Bid request with two impressions" - def bidRequest = BidRequest.defaultBidRequest.tap { - imp[0].ext.prebid.bidder = new Bidder(generic: new Generic()) - imp << Imp.defaultImpression - imp[1].ext.prebid.bidder = new Bidder(generic: new Generic()) - } - - and: "Planner Mock line items" - def accountId = bidRequest.site.publisher.id - def plansResponse = new PlansResponse(lineItems: [LineItem.getDefaultLineItem(accountId), LineItem.getDefaultLineItem(accountId)]) - generalPlanner.initPlansResponse(plansResponse) - - and: "Bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Sending auction request to PBS" - pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS sent a request to the bidder with two impressions" - def bidderRequest = bidder.getBidderRequest(bidRequest.id) - assert bidderRequest.imp?.size() == bidRequest.imp.size() - - and: "First impression contains 2 deals according to the line items" - def firstRequestImp = bidderRequest.imp.find { it.id == bidRequest.imp[0].id } - assert firstRequestImp?.pmp?.deals?.size() == plansResponse.lineItems.size() - assert plansResponse.lineItems.each { lineItem -> - def deal = firstRequestImp.pmp.deals.find { it.id == lineItem.dealId } - - assert deal - verifyAll(deal) { - deal?.ext?.line?.lineItemId == lineItem.lineItemId - deal?.ext?.line?.extLineItemId == lineItem.extLineItemId - deal?.ext?.line?.sizes?.size() == lineItem.sizes.size() - deal?.ext?.line?.sizes[0].w == lineItem.sizes[0].w - deal?.ext?.line?.sizes[0].h == lineItem.sizes[0].h - } - } - - def topMatchLineItemId = firstRequestImp.pmp.deals.first().ext.line.lineItemId - def secondRequestImp = bidderRequest.imp.find { it.id == bidRequest.imp[1].id } - - and: "Second impression contains only 1 deal excluding already top matched line items by the first impression" - assert secondRequestImp.pmp.deals.size() == plansResponse.lineItems.size() - 1 - assert !(secondRequestImp.pmp.deals.collect { it.ext.line.lineItemId } in topMatchLineItemId) - - assert plansResponse.lineItems.findAll { it.lineItemId != topMatchLineItemId }.each { lineItem -> - def deal = secondRequestImp.pmp.deals.find { it.id == lineItem.dealId } - - assert deal - verifyAll(deal) { - deal?.ext?.line?.lineItemId == lineItem.lineItemId - deal?.ext?.line?.extLineItemId == lineItem.extLineItemId - deal?.ext?.line?.sizes?.size() == lineItem.sizes.size() - deal?.ext?.line?.sizes[0].w == lineItem.sizes[0].w - deal?.ext?.line?.sizes[0].h == lineItem.sizes[0].h - } - } - } -} diff --git a/src/test/groovy/org/prebid/server/functional/tests/pg/PgDealsOnlySpec.groovy b/src/test/groovy/org/prebid/server/functional/tests/pg/PgDealsOnlySpec.groovy deleted file mode 100644 index d5677d963cf..00000000000 --- a/src/test/groovy/org/prebid/server/functional/tests/pg/PgDealsOnlySpec.groovy +++ /dev/null @@ -1,190 +0,0 @@ -package org.prebid.server.functional.tests.pg - -import org.prebid.server.functional.model.bidder.BidderName -import org.prebid.server.functional.model.bidder.Generic -import org.prebid.server.functional.model.mock.services.generalplanner.PlansResponse -import org.prebid.server.functional.model.request.auction.BidRequest -import org.prebid.server.functional.model.request.auction.BidRequestExt -import org.prebid.server.functional.model.request.auction.Prebid -import org.prebid.server.functional.model.response.auction.BidResponse -import org.prebid.server.functional.util.PBSUtils - -import static org.prebid.server.functional.model.response.auction.ErrorType.GENERIC -import static org.prebid.server.functional.model.response.auction.ErrorType.PREBID - -class PgDealsOnlySpec extends BasePgSpec { - - def "PBS shouldn't call bidder when bidder pgdealsonly flag is set to true and no available PG line items"() { - given: "Bid request with set pgdealsonly flag" - def bidRequest = BidRequest.defaultBidRequest - bidRequest.imp.first().ext.prebid.bidder.generic = new Generic(pgDealsOnly: true) - def initialBidderRequestCount = bidder.requestCount - - and: "No line items response" - generalPlanner.initPlansResponse(new PlansResponse(lineItems: [])) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS hasn't called bidder during auction" - assert initialBidderRequestCount == bidder.requestCount - - and: "PBS returns a not calling bidder warning" - def auctionWarnings = auctionResponse.ext?.warnings?.get(PREBID) - assert auctionWarnings.size() == 1 - assert auctionWarnings[0].code == 999 - assert auctionWarnings[0].message == - "Not calling $GENERIC.value bidder for impressions ${bidRequest.imp[0].id}" + - " due to pgdealsonly flag and no available PG line items." - } - - def "PBS shouldn't call bidder when bidder alias is set, bidder pgdealsonly flag is set to true and no available PG line items"() { - given: "Bid request with set bidder alias and pgdealsonly flag" - def bidderAliasName = PBSUtils.randomString - def bidRequest = BidRequest.defaultBidRequest.tap { - def prebid = new Prebid(aliases: [(bidderAliasName): BidderName.GENERIC], debug: 1) - ext = new BidRequestExt(prebid: prebid) - } - bidRequest.imp.first().ext.prebid.bidder.generic = new Generic(pgDealsOnly: true) - def initialBidderRequestCount = bidder.requestCount - - and: "No line items response" - generalPlanner.initPlansResponse(new PlansResponse(lineItems: [])) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS hasn't called bidder during auction" - assert initialBidderRequestCount == bidder.requestCount - - and: "PBS returns a not calling bidder warning" - def auctionWarnings = auctionResponse.ext?.warnings?.get(PREBID) - assert auctionWarnings.size() == 1 - assert auctionWarnings[0].code == 999 - assert auctionWarnings[0].message == - "Not calling $GENERIC.value bidder for impressions ${bidRequest.imp[0].id}" + - " due to pgdealsonly flag and no available PG line items." - } - - def "PBS should call bidder when bidder pgdealsonly flag is set to false and no available PG line items"() { - given: "Bid request with set pgdealsonly flag" - def bidRequest = BidRequest.defaultBidRequest - bidRequest.imp.first().ext.prebid.bidder.generic = new Generic(pgDealsOnly: false) - def initialBidderRequestCount = bidder.requestCount - - and: "No line items response" - generalPlanner.initPlansResponse(new PlansResponse(lineItems: [])) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS has called bidder during auction" - assert initialBidderRequestCount + 1 == bidder.requestCount - assert !auctionResponse.ext?.warnings - } - - def "PBS should return an error when bidder dealsonly flag is set to true, no available PG line items and bid response misses 'dealid' field"() { - given: "Bid request with set dealsonly flag" - def bidRequest = BidRequest.defaultBidRequest - bidRequest.imp.first().ext.prebid.bidder.generic = new Generic(dealsOnly: true) - def initialBidderRequestCount = bidder.requestCount - - and: "No line items response" - generalPlanner.initPlansResponse(PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id)) - - and: "Bid response with missing 'dealid' field" - def bidResponse = BidResponse.getDefaultBidResponse(bidRequest) - bidResponse.seatbid[0].bid[0].dealid = null - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "Bidder was requested" - assert initialBidderRequestCount + 1 == bidder.requestCount - - and: "PBS returns an error of missing 'dealid' field in bid" - def bidErrors = auctionResponse.ext?.errors?.get(GENERIC) - def bidId = bidResponse.seatbid[0].bid[0].id - - assert bidErrors?.size() == 1 - assert bidErrors[0].code == 5 - assert bidErrors[0].message ==~ /BidId `$bidId` validation messages:.* Error: / + - /Bid "$bidId" missing required field 'dealid'.*/ - } - - def "PBS should add dealsonly flag when it is not specified and pgdealsonly flag is set to true"() { - given: "Bid request with set pgdealsonly flag, dealsonly is not specified" - def bidRequest = BidRequest.defaultBidRequest - bidRequest.imp.first().ext.prebid.bidder.generic = new Generic(pgDealsOnly: true) - def initialBidderRequestCount = bidder.requestCount - - and: "No line items response" - generalPlanner.initPlansResponse(PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id)) - - and: "Bid response with missing 'dealid' field to check dealsonly flag was added and worked" - def bidResponse = BidResponse.getDefaultBidResponse(bidRequest) - bidResponse.seatbid[0].bid[0].dealid = null - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "Bidder was requested" - assert initialBidderRequestCount + 1 == bidder.requestCount - - and: "PBS added dealsonly flag to the bidder request" - assert auctionResponse.ext?.debug?.resolvedRequest?.imp?.first()?.ext?.prebid?.bidder?.generic?.dealsOnly - - and: "PBS returns an error of missing 'dealid' field in bid" - def bidErrors = auctionResponse.ext?.errors?.get(GENERIC) - def bidId = bidResponse.seatbid[0].bid[0].id - - assert bidErrors?.size() == 1 - assert bidErrors[0].code == 5 - assert bidErrors[0].message ==~ /BidId `$bidId` validation messages:.* Error: / + - /Bid "$bidId" missing required field 'dealid'.*/ - } - - def "PBS shouldn't return an error when bidder dealsonly flag is set to true, no available PG line items and bid response misses 'dealid' field"() { - given: "Bid request with set dealsonly flag" - def bidRequest = BidRequest.defaultBidRequest - bidRequest.imp.first().ext.prebid.bidder.generic = new Generic(dealsOnly: false) - def initialBidderRequestCount = bidder.requestCount - - and: "No line items response" - generalPlanner.initPlansResponse(PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id)) - - and: "Bid response with missing 'dealid' field" - def bidResponse = BidResponse.getDefaultBidResponse(bidRequest) - bidResponse.seatbid[0].bid[0].dealid = null - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "Bidder was requested" - assert initialBidderRequestCount + 1 == bidder.requestCount - - and: "PBS hasn't returned an error" - !auctionResponse.ext?.errors - } -} diff --git a/src/test/groovy/org/prebid/server/functional/tests/pg/PlansSpec.groovy b/src/test/groovy/org/prebid/server/functional/tests/pg/PlansSpec.groovy deleted file mode 100644 index 6d277034751..00000000000 --- a/src/test/groovy/org/prebid/server/functional/tests/pg/PlansSpec.groovy +++ /dev/null @@ -1,57 +0,0 @@ -package org.prebid.server.functional.tests.pg - -import org.prebid.server.functional.model.mock.services.generalplanner.PlansResponse -import org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest -import org.prebid.server.functional.util.HttpUtil -import org.prebid.server.functional.util.PBSUtils - -import static org.mockserver.model.HttpStatusCode.INTERNAL_SERVER_ERROR_500 -import static org.mockserver.model.HttpStatusCode.OK_200 -import static org.prebid.server.functional.testcontainers.PbsPgConfig.PG_ENDPOINT_PASSWORD -import static org.prebid.server.functional.testcontainers.PbsPgConfig.PG_ENDPOINT_USERNAME -import static org.prebid.server.functional.util.HttpUtil.AUTHORIZATION_HEADER -import static org.prebid.server.functional.util.HttpUtil.PG_TRX_ID_HEADER -import static org.prebid.server.functional.util.HttpUtil.UUID_REGEX - -class PlansSpec extends BasePgSpec { - - def "PBS should be able to send a request to General Planner"() { - given: "General Planner response is set" - generalPlanner.initPlansResponse(PlansResponse.getDefaultPlansResponse(PBSUtils.randomString), OK_200) - - when: "PBS sends request to General Planner" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.updateLineItemsRequest) - - then: "Request is sent" - PBSUtils.waitUntil { generalPlanner.recordedPlansRequestCount == 1 } - } - - def "PBS should retry request to General Planner when first request fails"() { - given: "Bad General Planner response" - generalPlanner.initPlansResponse(PlansResponse.getDefaultPlansResponse(PBSUtils.randomString), INTERNAL_SERVER_ERROR_500) - - when: "PBS sends request to General Planner" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.updateLineItemsRequest) - - then: "Request is sent two times" - PBSUtils.waitUntil { generalPlanner.recordedPlansRequestCount == 2 } - } - - def "PBS should send appropriate headers when requests plans from General Planner"() { - when: "PBS sends request to General Planner" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.updateLineItemsRequest) - - then: "Request with headers is sent" - def plansRequestHeaders = generalPlanner.lastRecordedPlansRequestHeaders - assert plansRequestHeaders - - and: "Request has an authorization header with a basic auth token" - def basicAuthToken = HttpUtil.makeBasicAuthHeaderValue(PG_ENDPOINT_USERNAME, PG_ENDPOINT_PASSWORD) - assert plansRequestHeaders.get(AUTHORIZATION_HEADER) == [basicAuthToken] - - and: "Request has a header with uuid value" - def uuidHeader = plansRequestHeaders.get(PG_TRX_ID_HEADER) - assert uuidHeader?.size() == 1 - assert (uuidHeader[0] =~ UUID_REGEX).matches() - } -} diff --git a/src/test/groovy/org/prebid/server/functional/tests/pg/RegisterSpec.groovy b/src/test/groovy/org/prebid/server/functional/tests/pg/RegisterSpec.groovy deleted file mode 100644 index a62a10cd594..00000000000 --- a/src/test/groovy/org/prebid/server/functional/tests/pg/RegisterSpec.groovy +++ /dev/null @@ -1,229 +0,0 @@ -package org.prebid.server.functional.tests.pg - -import org.prebid.server.functional.model.mock.services.generalplanner.PlansResponse -import org.prebid.server.functional.model.request.auction.BidRequest -import org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest -import org.prebid.server.functional.model.response.auction.BidResponse -import org.prebid.server.functional.util.HttpUtil -import org.prebid.server.functional.util.PBSUtils - -import java.time.ZoneId -import java.time.ZonedDateTime - -import static java.time.ZoneOffset.UTC -import static org.prebid.server.functional.testcontainers.PbsPgConfig.PG_ENDPOINT_PASSWORD -import static org.prebid.server.functional.testcontainers.PbsPgConfig.PG_ENDPOINT_USERNAME -import static org.prebid.server.functional.util.HttpUtil.AUTHORIZATION_HEADER -import static org.prebid.server.functional.util.HttpUtil.PG_TRX_ID_HEADER -import static org.prebid.server.functional.util.HttpUtil.UUID_REGEX - -class RegisterSpec extends BasePgSpec { - - def setupSpec() { - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.invalidateLineItemsRequest) - } - - def "PBS should be able to register its instance in Planner on demand"() { - given: "Properties values from PBS config" - def host = pgConfig.hostId - def vendor = pgConfig.vendor - def region = pgConfig.region - - and: "Initial Planner request count" - def initialRequestCount = generalPlanner.requestCount - - when: "PBS sends request to Planner" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.registerInstanceRequest) - - then: "Request counter is increased" - PBSUtils.waitUntil { generalPlanner.requestCount == initialRequestCount + 1 } - - and: "PBS instance is healthy" - def registerRequest = generalPlanner.lastRecordedRegisterRequest - assert registerRequest.healthIndex >= 0 && registerRequest.healthIndex <= 1 - - and: "Host, vendor and region are appropriate to the config" - assert registerRequest.hostInstanceId == host - assert registerRequest.vendor == vendor - assert registerRequest.region == region - - and: "Delivery Statistics Report doesn't have delivery specific data" - verifyAll(registerRequest.status.dealsStatus) { delStatsReport -> - (delStatsReport.reportId =~ UUID_REGEX).matches() - delStatsReport.instanceId == host - delStatsReport.vendor == vendor - delStatsReport.region == region - !delStatsReport.lineItemStatus - !delStatsReport.dataWindowStartTimeStamp - !delStatsReport.dataWindowEndTimeStamp - delStatsReport.reportTimeStamp.isBefore(ZonedDateTime.now(ZoneId.from(UTC))) - } - } - - def "PBS should send a register request with appropriate headers"() { - when: "Initiating PBS to register its instance" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.registerInstanceRequest) - - then: "Request with headers is sent" - def registerRequestHeaders = generalPlanner.lastRecordedRegisterRequestHeaders - assert registerRequestHeaders - - and: "Request has an authorization header with a basic auth token" - def basicAuthToken = HttpUtil.makeBasicAuthHeaderValue(PG_ENDPOINT_USERNAME, PG_ENDPOINT_PASSWORD) - assert registerRequestHeaders.get(AUTHORIZATION_HEADER) == [basicAuthToken] - - and: "Request has a header with uuid value" - def uuidHeader = registerRequestHeaders.get(PG_TRX_ID_HEADER) - assert uuidHeader?.size() == 1 - assert (uuidHeader[0] =~ UUID_REGEX).matches() - } - - def "PBS should be able to register its instance in Planner providing active PBS line items info"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Bid response" - def bidResponse = BidResponse.getDefaultBidResponse(bidRequest) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Planner Mock line items" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id) - def lineItem = plansResponse.lineItems[0] - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Initial Planner request count" - def initialRequestCount = generalPlanner.requestCount - - when: "PBS sends request to Planner" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.registerInstanceRequest) - - then: "Request counter is increased" - PBSUtils.waitUntil { generalPlanner.requestCount == initialRequestCount + 1 } - - and: "Delivery Statistics Report has active line item data" - def registerRequest = generalPlanner.lastRecordedRegisterRequest - def delStatsReport = registerRequest.status?.dealsStatus - assert delStatsReport - def lineItemStatus = delStatsReport.lineItemStatus - - assert lineItemStatus?.size() == plansResponse.lineItems.size() - verifyAll(lineItemStatus) { - lineItemStatus[0].lineItemSource == lineItem.source - lineItemStatus[0].lineItemId == lineItem.lineItemId - lineItemStatus[0].dealId == lineItem.dealId - lineItemStatus[0].extLineItemId == lineItem.extLineItemId - } - - and: "Line item wasn't used in auction" - verifyAll(lineItemStatus) { - !lineItemStatus[0].accountAuctions - !lineItemStatus[0].targetMatched - !lineItemStatus[0].sentToBidder - !lineItemStatus[0].spentTokens - } - - cleanup: - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.invalidateLineItemsRequest) - } - - def "PBS should be able to register its instance in Planner providing line items status after auction"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock line items" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id) - def lineItem = plansResponse.lineItems[0] - def lineItemCount = plansResponse.lineItems.size() as Long - generalPlanner.initPlansResponse(plansResponse) - - and: "Bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Initial Planner request count" - def initialRequestCount = generalPlanner.requestCount - - and: "Auction is requested" - pgPbsService.sendAuctionRequest(bidRequest) - - when: "PBS sends request to Planner" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.registerInstanceRequest) - - then: "Request counter is increased" - PBSUtils.waitUntil { generalPlanner.requestCount == initialRequestCount + 1 } - - and: "Delivery Statistics Report has info about auction" - def registerRequest = generalPlanner.lastRecordedRegisterRequest - def delStatsReport = registerRequest.status.dealsStatus - assert delStatsReport - - and: "Delivery Statistics Report has correct line item status data" - def lineItemStatus = delStatsReport.lineItemStatus - - assert lineItemStatus?.size() as Long == lineItemCount - verifyAll(lineItemStatus) { - lineItemStatus[0].lineItemSource == lineItem.source - lineItemStatus[0].lineItemId == lineItem.lineItemId - lineItemStatus[0].dealId == lineItem.dealId - lineItemStatus[0].extLineItemId == lineItem.extLineItemId - } - - and: "Line item was used in auction" - verifyAll(lineItemStatus) { - lineItemStatus[0].accountAuctions == lineItemCount - lineItemStatus[0].targetMatched == lineItemCount - lineItemStatus[0].sentToBidder == lineItemCount - lineItemStatus[0].spentTokens == lineItemCount - } - - cleanup: - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.invalidateLineItemsRequest) - } - - def "PBS should update auction count when register its instance in Planner after auction"() { - given: "Initial auction count" - def initialRequestCount = generalPlanner.requestCount - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.registerInstanceRequest) - PBSUtils.waitUntil { generalPlanner.requestCount == initialRequestCount + 1 } - def initialAuctionCount = generalPlanner.lastRecordedRegisterRequest?.status?.dealsStatus?.clientAuctions - - and: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock line items" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id) - generalPlanner.initPlansResponse(plansResponse) - - and: "Bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Initial Planner request count" - initialRequestCount = generalPlanner.requestCount - - and: "Auction is requested" - pgPbsService.sendAuctionRequest(bidRequest) - - when: "PBS sends request to Planner" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.registerInstanceRequest) - - then: "Request counter is increased" - PBSUtils.waitUntil { generalPlanner.requestCount == initialRequestCount + 1 } - - and: "Delivery Statistics Report has info about auction" - def registerRequest = generalPlanner.lastRecordedRegisterRequest - assert registerRequest.status?.dealsStatus?.clientAuctions == initialAuctionCount + 1 - - cleanup: - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.invalidateLineItemsRequest) - } -} diff --git a/src/test/groovy/org/prebid/server/functional/tests/pg/ReportSpec.groovy b/src/test/groovy/org/prebid/server/functional/tests/pg/ReportSpec.groovy deleted file mode 100644 index 75c73d0f534..00000000000 --- a/src/test/groovy/org/prebid/server/functional/tests/pg/ReportSpec.groovy +++ /dev/null @@ -1,559 +0,0 @@ -package org.prebid.server.functional.tests.pg - -import org.prebid.server.functional.model.deals.lineitem.DeliverySchedule -import org.prebid.server.functional.model.deals.lineitem.LineItem -import org.prebid.server.functional.model.deals.lineitem.Token -import org.prebid.server.functional.model.mock.services.generalplanner.PlansResponse -import org.prebid.server.functional.model.request.auction.BidRequest -import org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest -import org.prebid.server.functional.model.response.auction.BidResponse -import org.prebid.server.functional.util.HttpUtil -import org.prebid.server.functional.util.PBSUtils - -import java.time.ZoneId -import java.time.ZonedDateTime -import java.time.format.DateTimeFormatter - -import static java.time.ZoneOffset.UTC -import static org.mockserver.model.HttpStatusCode.CONFLICT_409 -import static org.mockserver.model.HttpStatusCode.INTERNAL_SERVER_ERROR_500 -import static org.mockserver.model.HttpStatusCode.OK_200 -import static org.prebid.server.functional.model.deals.lineitem.LineItem.TIME_PATTERN -import static org.prebid.server.functional.testcontainers.PbsPgConfig.PG_ENDPOINT_PASSWORD -import static org.prebid.server.functional.testcontainers.PbsPgConfig.PG_ENDPOINT_USERNAME -import static org.prebid.server.functional.util.HttpUtil.AUTHORIZATION_HEADER -import static org.prebid.server.functional.util.HttpUtil.CHARSET_HEADER_VALUE -import static org.prebid.server.functional.util.HttpUtil.CONTENT_TYPE_HEADER -import static org.prebid.server.functional.util.HttpUtil.CONTENT_TYPE_HEADER_VALUE -import static org.prebid.server.functional.util.HttpUtil.PG_TRX_ID_HEADER -import static org.prebid.server.functional.util.HttpUtil.UUID_REGEX - -class ReportSpec extends BasePgSpec { - - def cleanup() { - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.invalidateLineItemsRequest) - } - - def "PBS shouldn't send delivery statistics when PBS doesn't have reports to send"() { - given: "Initial Delivery Statistics Service request count" - def initialRequestCount = deliveryStatistics.requestCount - - when: "PBS is requested to send a report to Delivery Statistics" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.sendReportRequest) - - then: "Delivery Statistics Service request count is not changed" - PBSUtils.waitUntil { deliveryStatistics.requestCount == initialRequestCount } - } - - def "PBS shouldn't send delivery statistics when delivery report batch is created but doesn't have reports to send"() { - given: "Initial Delivery Statistics Service request count" - def initialRequestCount = deliveryStatistics.requestCount - - and: "PBS generates delivery report batch" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.createReportRequest) - - when: "PBS is requested to send a report to Delivery Statistics" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.sendReportRequest) - - then: "Delivery Statistics Service request count is not changed" - PBSUtils.waitUntil { deliveryStatistics.requestCount == initialRequestCount } - } - - def "PBS should send a report request with appropriate headers"() { - given: "Initial report sent request count is taken" - def initialRequestCount = deliveryStatistics.requestCount - - and: "Line items are fetched" - generalPlanner.initPlansResponse(PlansResponse.getDefaultPlansResponse(PBSUtils.randomString)) - updateLineItemsAndWait() - - and: "Delivery report batch is created" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.createReportRequest) - - when: "PBS is requested to send a report to Delivery Statistics" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.sendReportRequest) - - and: "PBS sends a report request to the Delivery Statistics Service" - PBSUtils.waitUntil { deliveryStatistics.requestCount == initialRequestCount + 1 } - - then: "Request headers corresponds to the payload" - def deliveryRequestHeaders = deliveryStatistics.lastRecordedDeliveryRequestHeaders - assert deliveryRequestHeaders - - and: "Request has an authorization header with a basic auth token" - def basicAuthToken = HttpUtil.makeBasicAuthHeaderValue(PG_ENDPOINT_USERNAME, PG_ENDPOINT_PASSWORD) - assert deliveryRequestHeaders.get(AUTHORIZATION_HEADER) == [basicAuthToken] - - and: "Request has a header with uuid value" - def uuidHeader = deliveryRequestHeaders.get(PG_TRX_ID_HEADER) - assert uuidHeader?.size() == 1 - assert (uuidHeader[0] =~ UUID_REGEX).matches() - - and: "Request has a content type header" - assert deliveryRequestHeaders.get(CONTENT_TYPE_HEADER) == ["$CONTENT_TYPE_HEADER_VALUE;$CHARSET_HEADER_VALUE"] - } - - def "PBS should send delivery statistics report when delivery progress report with one line item is created"() { - given: "Initial Delivery Statistics Service request count" - def initialRequestCount = deliveryStatistics.requestCount - - and: "Time before report is sent" - def startTime = ZonedDateTime.now(UTC) - - and: "Set Planner response to return one line item" - def plansResponse = PlansResponse.getDefaultPlansResponse(PBSUtils.randomString) - def lineItem = plansResponse.lineItems[0] - generalPlanner.initPlansResponse(plansResponse) - - and: "PBS requests Planner line items" - updateLineItemsAndWait() - - and: "PBS generates delivery report batch" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.createReportRequest) - - when: "PBS is requested to send a report to Delivery Statistics" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.sendReportRequest) - - then: "PBS sends a report request to the Delivery Statistics Service" - PBSUtils.waitUntil { deliveryStatistics.requestCount == initialRequestCount + 1 } - - and: "Report request should correspond to the payload" - def reportRequest = deliveryStatistics.lastRecordedDeliveryStatisticsReportRequest - def endTime = ZonedDateTime.now(ZoneId.from(UTC)) - - verifyAll(reportRequest) { - (reportRequest.reportId =~ UUID_REGEX).matches() - reportRequest.instanceId == pgConfig.hostId - reportRequest.vendor == pgConfig.vendor - reportRequest.region == pgConfig.region - !reportRequest.clientAuctions - - reportRequest.reportTimeStamp.isBefore(endTime) - reportRequest.dataWindowStartTimeStamp.isBefore(startTime) - reportRequest.dataWindowEndTimeStamp.isAfter(startTime) - reportRequest.dataWindowEndTimeStamp.isBefore(endTime) - reportRequest.reportTimeStamp.isAfter(reportRequest.dataWindowEndTimeStamp) - } - - and: "Report line items should have an appropriate to the initially set line items info" - assert reportRequest.lineItemStatus?.size() == 1 - def lineItemStatus = reportRequest.lineItemStatus[0] - - verifyAll(lineItemStatus) { - lineItemStatus.lineItemSource == lineItem.source - lineItemStatus.lineItemId == lineItem.lineItemId - lineItemStatus.dealId == lineItem.dealId - lineItemStatus.extLineItemId == lineItem.extLineItemId - !lineItemStatus.accountAuctions - !lineItemStatus.domainMatched - !lineItemStatus.targetMatched - !lineItemStatus.targetMatchedButFcapped - !lineItemStatus.targetMatchedButFcapLookupFailed - !lineItemStatus.pacingDeferred - !lineItemStatus.sentToBidder - !lineItemStatus.sentToBidderAsTopMatch - !lineItemStatus.receivedFromBidder - !lineItemStatus.receivedFromBidderInvalidated - !lineItemStatus.sentToClient - !lineItemStatus.sentToClientAsTopMatch - !lineItemStatus.lostToLineItems - !lineItemStatus.events - !lineItemStatus.readyAt - !lineItemStatus.spentTokens - !lineItemStatus.pacingFrequency - - lineItemStatus.deliverySchedule?.size() == 1 - } - - def timeFormatter = DateTimeFormatter.ofPattern(TIME_PATTERN) - def deliverySchedule = lineItemStatus.deliverySchedule[0] - - verifyAll(deliverySchedule) { - deliverySchedule.planId == lineItem.deliverySchedules[0].planId - timeFormatter.format(deliverySchedule.planStartTimeStamp) == - timeFormatter.format(lineItem.deliverySchedules[0].startTimeStamp) - timeFormatter.format(deliverySchedule.planUpdatedTimeStamp) == - timeFormatter.format(lineItem.deliverySchedules[0].updatedTimeStamp) - timeFormatter.format(deliverySchedule.planExpirationTimeStamp) == - timeFormatter.format(lineItem.deliverySchedules[0].endTimeStamp) - - deliverySchedule.tokens?.size() == 1 - } - - verifyAll(deliverySchedule.tokens[0]) { tokens -> - tokens.priorityClass == lineItem.deliverySchedules[0].tokens[0].priorityClass - tokens.total == lineItem.deliverySchedules[0].tokens[0].total - tokens.spent == 0 - tokens.totalSpent == 0 - } - } - - def "PBS should send a correct delivery statistics report when auction with one line item is happened"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Bid response" - def bidResponse = BidResponse.getDefaultBidResponse(bidRequest) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Initial Delivery Statistics Service request count" - def initialRequestCount = deliveryStatistics.requestCount - - and: "Time before report is sent" - def startTime = ZonedDateTime.now(UTC) - - and: "Set Planner response to return one line item" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id) - generalPlanner.initPlansResponse(plansResponse) - def lineItem = plansResponse.lineItems[0] - def lineItemCount = plansResponse.lineItems.size() as Long - - and: "PBS requests Planner line items" - updateLineItemsAndWait() - - when: "Auction request to PBS is sent" - pgPbsService.sendAuctionRequest(bidRequest) - - and: "PBS generates delivery report batch" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.createReportRequest) - - and: "PBS is requested to send a report to Delivery Statistics" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.sendReportRequest) - - then: "PBS sends a report request to the Delivery Statistics Service" - PBSUtils.waitUntil { deliveryStatistics.requestCount == initialRequestCount + 1 } - - and: "Report request should be sent after the test start" - def reportRequest = deliveryStatistics.lastRecordedDeliveryStatisticsReportRequest - assert reportRequest.reportTimeStamp.isAfter(startTime) - - and: "Request should contain correct number of client auctions made" - assert reportRequest.clientAuctions == 1 - - and: "Report line items should have an appropriate to the initially set line item info" - assert reportRequest.lineItemStatus?.size() == 1 - def lineItemStatus = reportRequest.lineItemStatus[0] - - verifyAll(lineItemStatus) { - lineItemStatus.lineItemSource == lineItem.source - lineItemStatus.lineItemId == lineItem.lineItemId - lineItemStatus.dealId == lineItem.dealId - lineItemStatus.extLineItemId == lineItem.extLineItemId - } - - and: "Report should have the right PG metrics info" - verifyAll(lineItemStatus) { - lineItemStatus?.accountAuctions == lineItemCount - lineItemStatus?.targetMatched == lineItemCount - lineItemStatus?.sentToBidder == lineItemCount - lineItemStatus?.sentToBidderAsTopMatch == lineItemCount - } - - and: "Report line item should have a delivery schedule" - assert lineItemStatus.deliverySchedule?.size() == 1 - assert lineItemStatus.deliverySchedule[0].planId == lineItem.deliverySchedules[0].planId - } - - def "PBS should use line item token with the highest priority"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Initial Delivery Statistics Service request count" - def initialRequestCount = deliveryStatistics.requestCount - - and: "Time before report is sent" - def startTime = ZonedDateTime.now(UTC) - - and: "Set Planner response to return one line item" - def highestPriorityToken = new Token(priorityClass: 1, total: 2) - def lowerPriorityToken = new Token(priorityClass: 3, total: 2) - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - def tokens = [highestPriorityToken, lowerPriorityToken] - lineItems[0].deliverySchedules[0].tokens = tokens - } - def tokens = plansResponse.lineItems[0].deliverySchedules[0].tokens - generalPlanner.initPlansResponse(plansResponse) - - and: "Bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "PBS requests Planner line items" - updateLineItemsAndWait() - - when: "Auction request to PBS is sent" - pgPbsService.sendAuctionRequest(bidRequest) - - and: "PBS generates delivery report batch" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.createReportRequest) - - and: "PBS is requested to send a report to Delivery Statistics" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.sendReportRequest) - - then: "PBS sends a report request to the Delivery Statistics Service" - PBSUtils.waitUntil { deliveryStatistics.requestCount == initialRequestCount + 1 } - - and: "Report request should be sent after the test start" - def reportRequest = deliveryStatistics.lastRecordedDeliveryStatisticsReportRequest - assert reportRequest.reportTimeStamp.isAfter(startTime) - - and: "Token with the highest priority was used" - def reportTokens = reportRequest.lineItemStatus?.first()?.deliverySchedule?.first()?.tokens - assert reportTokens - assert reportTokens.size() == tokens.size() - def usedToken = reportTokens.find { it.priorityClass == highestPriorityToken.priorityClass } - assert usedToken?.total == highestPriorityToken.total - assert usedToken?.spent == 1 - assert usedToken?.totalSpent == 1 - - and: "Token with a lower priority wasn't used" - def notUsedToken = reportTokens.find { it.priorityClass == lowerPriorityToken.priorityClass } - assert notUsedToken?.total == lowerPriorityToken.total - assert notUsedToken?.spent == 0 - assert notUsedToken?.totalSpent == 0 - } - - def "PBS shouldn't consider line item as used when bidder responds with non-deals specific info"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Initial Delivery Statistics Service request count" - def initialRequestCount = deliveryStatistics.requestCount - - and: "Time before report is sent" - def startTime = ZonedDateTime.now(UTC) - - and: "Set Planner response to return one line item" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id) - generalPlanner.initPlansResponse(plansResponse) - - and: "Non-deals bid response" - def bidResponse = BidResponse.getDefaultBidResponse(bidRequest) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "PBS requests Planner line items" - updateLineItemsAndWait() - - when: "Auction request to PBS is sent" - pgPbsService.sendAuctionRequest(bidRequest) - - and: "PBS generates delivery report batch" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.createReportRequest) - - and: "PBS is requested to send a report to Delivery Statistics" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.sendReportRequest) - - then: "PBS sends a report request to the Delivery Statistics Service" - PBSUtils.waitUntil { deliveryStatistics.requestCount == initialRequestCount + 1 } - - and: "Report request should be sent after the test start" - def reportRequest = deliveryStatistics.lastRecordedDeliveryStatisticsReportRequest - assert reportRequest.reportTimeStamp.isAfter(startTime) - - and: "Line item token wasn't used" - def reportTokens = reportRequest.lineItemStatus?.first()?.deliverySchedule?.first()?.tokens - assert reportTokens?.size() == plansResponse.lineItems[0].deliverySchedules[0].tokens.size() - assert reportTokens[0].spent == 0 - assert reportTokens[0].totalSpent == 0 - } - - def "PBS should send additional report when line items number exceeds PBS 'line-items-per-report' property"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - def accountId = bidRequest.site.publisher.id - - and: "Bid response" - def bidResponse = BidResponse.getDefaultBidResponse(bidRequest) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Already recorded request count is reset" - deliveryStatistics.resetRecordedRequests() - deliveryStatistics.setResponse() - - and: "Initial Delivery Statistics Service request count" - def initialRequestCount = deliveryStatistics.requestCount - - and: "Set Planner response to return #lineItemsPerReport + 1 line items" - def lineItemsPerReport = pgConfig.lineItemsPerReport - def plansResponse = new PlansResponse(lineItems: (1..lineItemsPerReport + 1).collect { - LineItem.getDefaultLineItem(accountId) - }) - generalPlanner.initPlansResponse(plansResponse) - - and: "PBS requests Planner line items" - updateLineItemsAndWait() - - when: "PBS generates delivery report batch" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.createReportRequest) - - and: "PBS is requested to send a report to Delivery Statistics" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.sendReportRequest) - - then: "PBS sends two report requests to the Delivery Statistics Service" - PBSUtils.waitUntil { deliveryStatistics.requestCount == initialRequestCount + 2 } - - and: "Two reports are sent" - def reportRequests = deliveryStatistics.recordedDeliveryStatisticsReportRequests - assert reportRequests.size() == 2 - - and: "Two reports were sent with #lineItemsPerReport and 1 number of line items" - assert [reportRequests[-2].lineItemStatus.size(), reportRequests[-1].lineItemStatus.size()].sort() == - [lineItemsPerReport, 1].sort() - } - - def "PBS should save reports for later sending when response from Delivery Statistics was unsuccessful"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - def accountId = bidRequest.site.publisher.id - - and: "Bid response" - def bidResponse = BidResponse.getDefaultBidResponse(bidRequest) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Set Planner response to return 1 line item" - def plansResponse = PlansResponse.getDefaultPlansResponse(accountId) - generalPlanner.initPlansResponse(plansResponse) - - and: "PBS requests Planner line items" - updateLineItemsAndWait() - - and: "PBS generates delivery report batch" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.createReportRequest) - - and: "Delivery Statistics Service response is set to return a bad status code" - deliveryStatistics.reset() - deliveryStatistics.setResponse(INTERNAL_SERVER_ERROR_500) - - when: "PBS is requested to send a report to Delivery Statistics" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.sendReportRequest) - - then: "PBS sends a report to Delivery Statistics" - PBSUtils.waitUntil { deliveryStatistics.requestCount == 1 } - - when: "Delivery Statistics Service response is set to return a success response" - deliveryStatistics.reset() - deliveryStatistics.setResponse(OK_200) - - and: "PBS is requested to send a report to Delivery Statistics for the second time" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.sendReportRequest) - - then: "PBS for the second time sends the same report to the Delivery Statistics Service" - PBSUtils.waitUntil { deliveryStatistics.requestCount == 1 } - } - - def "PBS shouldn't save reports for later sending when Delivery Statistics response is Conflict 409"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - def accountId = bidRequest.site.publisher.id - - and: "Set Planner response to return 1 line item" - def plansResponse = PlansResponse.getDefaultPlansResponse(accountId) - generalPlanner.initPlansResponse(plansResponse) - - and: "PBS requests Planner line items" - updateLineItemsAndWait() - - and: "PBS generates delivery report batch" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.createReportRequest) - - and: "Delivery Statistics Service response is set to return a Conflict status code" - deliveryStatistics.reset() - deliveryStatistics.setResponse(CONFLICT_409) - - and: "Initial Delivery Statistics Service request count" - def initialRequestCount = deliveryStatistics.requestCount - - when: "PBS is requested to send a report to Delivery Statistics" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.sendReportRequest) - - then: "PBS sends a report to Delivery Statistics" - PBSUtils.waitUntil { deliveryStatistics.requestCount == initialRequestCount + 1 } - - and: "PBS is requested to send a report to Delivery Statistics for the second time" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.sendReportRequest) - - then: "PBS doesn't request Delivery Statistics Service for the second time" - assert deliveryStatistics.requestCount == initialRequestCount + 1 - } - - def "PBS should change active delivery plan when the current plan lifetime expires"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - def accountId = bidRequest.site.publisher.id - - and: "Initial Delivery Statistics Service request count" - def initialRequestCount = deliveryStatistics.requestCount - def auctionCount = 2 - - and: "Current delivery plan which expires in 2 seconds" - def currentPlanTimeToLive = 2 - def currentDeliverySchedule = new DeliverySchedule(planId: PBSUtils.randomNumber as String, - startTimeStamp: ZonedDateTime.now(ZoneId.from(UTC)), - updatedTimeStamp: ZonedDateTime.now(ZoneId.from(UTC)), - endTimeStamp: ZonedDateTime.now(ZoneId.from(UTC)).plusSeconds(currentPlanTimeToLive), - tokens: [new Token(priorityClass: 1, total: 1000)]) - - and: "Next delivery plan" - def nextDeliverySchedule = new DeliverySchedule(planId: PBSUtils.randomNumber as String, - startTimeStamp: ZonedDateTime.now(ZoneId.from(UTC)).plusSeconds(currentPlanTimeToLive), - updatedTimeStamp: ZonedDateTime.now(ZoneId.from(UTC)).plusSeconds(currentPlanTimeToLive), - endTimeStamp: ZonedDateTime.now(ZoneId.from(UTC)).plusHours(1), - tokens: [new Token(priorityClass: 1, total: 500)]) - - and: "Set Planner response to return line item with two delivery plans" - def plansResponse = PlansResponse.getDefaultPlansResponse(accountId).tap { - lineItems[0].deliverySchedules = [currentDeliverySchedule, nextDeliverySchedule] - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "PBS requests Planner line items" - updateLineItemsAndWait() - - and: "Auction request to PBS is sent for the first time" - pgPbsService.sendAuctionRequest(bidRequest) - - when: "Current delivery plan lifetime is expired" - PBSUtils.waitUntil({ ZonedDateTime.now(ZoneId.from(UTC)).isAfter(currentDeliverySchedule.endTimeStamp) }, - (currentPlanTimeToLive * 1000) + 1000) - - and: "PBS requests Planner line items which also forces current PBS line items to be updated" - generalPlanner.initPlansResponse(plansResponse) - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.updateLineItemsRequest) - - and: "Auction request to PBS is sent for the second time" - bidder.setResponse(bidRequest.id, bidResponse) - pgPbsService.sendAuctionRequest(bidRequest) - - and: "PBS generates delivery report batch" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.createReportRequest) - - and: "PBS is requested to send a report to Delivery Statistics" - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.sendReportRequest) - - then: "PBS sends a report to Delivery Statistics" - PBSUtils.waitUntil { deliveryStatistics.requestCount == initialRequestCount + 1 } - - and: "Report has info about 2 happened auctions" - def reportRequest = deliveryStatistics.lastRecordedDeliveryStatisticsReportRequest - assert reportRequest.clientAuctions == auctionCount - assert reportRequest.lineItemStatus?.size() == plansResponse.lineItems.size() - assert reportRequest.lineItemStatus[0].accountAuctions == auctionCount - - and: "One line item during each auction was sent to the bidder" - assert reportRequest.lineItemStatus[0].sentToBidder == auctionCount - - and: "Report contains two delivery plans info" - def reportDeliverySchedules = reportRequest.lineItemStatus[0].deliverySchedule - assert reportDeliverySchedules?.size() == plansResponse.lineItems[0].deliverySchedules.size() - - and: "One token was used during the first auction by the first delivery plan" - assert reportDeliverySchedules.find { it.planId == currentDeliverySchedule.planId }?.tokens[0].spent == 1 - - and: "One token was used from another delivery plan during the second auction after first delivery plan lifetime expired" - assert reportDeliverySchedules.find { it.planId == nextDeliverySchedule.planId }?.tokens[0].spent == 1 - } -} diff --git a/src/test/groovy/org/prebid/server/functional/tests/pg/TargetingFirstPartyDataSpec.groovy b/src/test/groovy/org/prebid/server/functional/tests/pg/TargetingFirstPartyDataSpec.groovy deleted file mode 100644 index a1552071a8d..00000000000 --- a/src/test/groovy/org/prebid/server/functional/tests/pg/TargetingFirstPartyDataSpec.groovy +++ /dev/null @@ -1,707 +0,0 @@ -package org.prebid.server.functional.tests.pg - -import org.prebid.server.functional.model.deals.lineitem.targeting.Targeting -import org.prebid.server.functional.model.mock.services.generalplanner.PlansResponse -import org.prebid.server.functional.model.request.auction.AppExt -import org.prebid.server.functional.model.request.auction.AppExtData -import org.prebid.server.functional.model.request.auction.Banner -import org.prebid.server.functional.model.request.auction.BidRequest -import org.prebid.server.functional.model.request.auction.BidRequestExt -import org.prebid.server.functional.model.request.auction.BidderConfig -import org.prebid.server.functional.model.request.auction.BidderConfigOrtb -import org.prebid.server.functional.model.request.auction.DoohExt -import org.prebid.server.functional.model.request.auction.DoohExtData -import org.prebid.server.functional.model.request.auction.ExtPrebidBidderConfig -import org.prebid.server.functional.model.request.auction.Imp -import org.prebid.server.functional.model.request.auction.ImpExtContext -import org.prebid.server.functional.model.request.auction.ImpExtContextData -import org.prebid.server.functional.model.request.auction.Prebid -import org.prebid.server.functional.model.request.auction.Site -import org.prebid.server.functional.model.request.auction.SiteExt -import org.prebid.server.functional.model.request.auction.SiteExtData -import org.prebid.server.functional.model.request.auction.User -import org.prebid.server.functional.model.request.auction.UserExt -import org.prebid.server.functional.model.request.auction.UserExtData -import org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest -import org.prebid.server.functional.service.PrebidServerException -import org.prebid.server.functional.util.PBSUtils -import spock.lang.Shared - -import static org.prebid.server.functional.model.bidder.BidderName.APPNEXUS -import static org.prebid.server.functional.model.bidder.BidderName.GENERIC_CAMEL_CASE -import static org.prebid.server.functional.model.bidder.BidderName.GENERIC -import static org.prebid.server.functional.model.deals.lineitem.targeting.MatchingFunction.IN -import static org.prebid.server.functional.model.deals.lineitem.targeting.MatchingFunction.INTERSECTS -import static org.prebid.server.functional.model.deals.lineitem.targeting.MatchingFunction.MATCHES -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.SFPD_BUYER_ID -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.SFPD_BUYER_IDS -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.SFPD_KEYWORDS -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.SFPD_LANGUAGE -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.UFPD_BUYER_UID -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.UFPD_BUYER_UIDS -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.UFPD_KEYWORDS -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.UFPD_YOB -import static org.prebid.server.functional.model.request.auction.DistributionChannel.APP -import static org.prebid.server.functional.model.request.auction.DistributionChannel.DOOH -import static org.prebid.server.functional.model.request.auction.DistributionChannel.SITE - -class TargetingFirstPartyDataSpec extends BasePgSpec { - - @Shared - String stringTargetingValue = PBSUtils.randomString - @Shared - Integer integerTargetingValue = PBSUtils.randomNumber - - def cleanup() { - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.invalidateLineItemsRequest) - } - - def "PBS should support both scalar and array String inputs by '#ufpdTargetingType' for INTERSECTS matching function"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest.tap { - user = User.defaultUser.tap { - ext = new UserExt(data: userExtData) - } - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(ufpdTargetingType, INTERSECTS, [stringTargetingValue]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - - where: - ufpdTargetingType | userExtData - UFPD_BUYER_UID | new UserExtData(buyeruid: stringTargetingValue) - UFPD_KEYWORDS | new UserExtData(keywords: [stringTargetingValue]) - } - - def "PBS should support both scalar and array Integer inputs by '#ufpdTargetingType' for INTERSECTS matching function"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest.tap { - user = User.defaultUser.tap { - ext = new UserExt(data: userExtData) - } - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(ufpdTargetingType, INTERSECTS, [stringTargetingValue]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - - where: - ufpdTargetingType | userExtData - UFPD_BUYER_UID | new UserExtData(buyeruid: stringTargetingValue) - UFPD_BUYER_UIDS | new UserExtData(buyeruids: [stringTargetingValue]) - } - - def "PBS should support taking Site First Party Data from #place source"() { - given: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.getAccountId()).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(SFPD_LANGUAGE, INTERSECTS, [stringTargetingValue]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - - where: - place | bidRequest - "imp[].ext.context" | BidRequest.defaultBidRequest.tap { - imp = [Imp.defaultImpression.tap { - ext.context = new ImpExtContext(data: new ImpExtContextData(language: stringTargetingValue)) - }] - } - "site" | BidRequest.defaultBidRequest.tap { - site = Site.defaultSite.tap { - ext = new SiteExt(data: new SiteExtData(language: stringTargetingValue)) - } - } - "imp[].ext.data" | BidRequest.defaultBidRequest.tap { - imp = [Imp.defaultImpression.tap { - ext.data = new ImpExtContextData(language: stringTargetingValue) - }] - } - } - - def "PBS should support String array input for Site First Party Data to be matched by INTERSECTS matching function"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest.tap { - imp = [Imp.defaultImpression.tap { - banner = Banner.defaultBanner - ext.context = new ImpExtContext(data: new ImpExtContextData(keywords: [stringTargetingValue])) - }] - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(SFPD_KEYWORDS, INTERSECTS, [stringTargetingValue]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - } - - def "PBS should support both scalar and array Integer inputs in Site First Party Data ('#targetingType') by INTERSECTS matching function"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest.tap { - imp = [Imp.defaultImpression.tap { - banner = Banner.defaultBanner - ext.context = new ImpExtContext(data: impExtContextData) - }] - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(targetingType, INTERSECTS, [integerTargetingValue]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - - where: - targetingType | impExtContextData - SFPD_BUYER_ID | new ImpExtContextData(buyerId: integerTargetingValue) - SFPD_BUYER_IDS | new ImpExtContextData(buyerIds: [integerTargetingValue]) - } - - def "PBS shouldn't throw a NPE for Site First Party Data when its Ext is absent and targeting INTERSECTS matching type is selected"() { - given: "Bid request with set site first party data in bidRequest.site" - def bidRequest = BidRequest.defaultBidRequest.tap { - site = Site.defaultSite.tap { - keywords = stringTargetingValue - } - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(SFPD_KEYWORDS, INTERSECTS, [stringTargetingValue]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS successfully processed request" - notThrown(PrebidServerException) - - and: "PBS hasn't had PG auction as request targeting is not specified in the right place" - assert !auctionResponse.ext?.debug?.pgmetrics - } - - def "PBS should support taking User FPD from bidRequest.user by #matchingFunction matching function"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest.tap { - user = User.defaultUser.tap { - updateUserFieldGeneric(it) - } - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(ufpdTargetingType, matchingFunction, [targetingValue]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - - where: - ufpdTargetingType | updateUserFieldGeneric | targetingValue | matchingFunction - UFPD_BUYER_UID | { it.buyeruid = stringTargetingValue } | stringTargetingValue | INTERSECTS - UFPD_BUYER_UID | { it.buyeruid = stringTargetingValue } | stringTargetingValue | IN - UFPD_YOB | { it.yob = integerTargetingValue } | integerTargetingValue | INTERSECTS - UFPD_YOB | { it.yob = integerTargetingValue } | integerTargetingValue | IN - } - - def "PBS should support taking User FPD from bidRequest.user by MATCHES matching function"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest.tap { - user = User.defaultUser.tap { - it.buyeruid = stringTargetingValue - } - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(UFPD_BUYER_UID, MATCHES, stringTargetingValue) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - } - - def "PBS should be able to match site FPD targeting taken from different sources by INTERSECTS matching function"() { - given: "Bid request with set site FPD in different request places" - def bidRequest = getSiteFpdBidRequest(siteLanguage, appLanguage, doohLanguage, impLanguage) - - and: "Planner response with INTERSECTS 1 of site FPD values" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.getAccountId()).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(SFPD_LANGUAGE, INTERSECTS, [stringTargetingValue, PBSUtils.randomString]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - - where: - siteLanguage | appLanguage | doohLanguage | impLanguage - stringTargetingValue | null | null | PBSUtils.randomString - null | stringTargetingValue | null | PBSUtils.randomString - null | null | stringTargetingValue | stringTargetingValue - } - - def "PBS should be able to match site FPD targeting taken from different sources by MATCHES matching function"() { - given: "Bid request with set site FPD in different request places" - def bidRequest = getSiteFpdBidRequest(siteLanguage, appLanguage, doohLanguage, impLanguage) - - and: "Planner response with MATCHES 1 of site FPD values" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.getAccountId()).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(SFPD_LANGUAGE, MATCHES, stringTargetingValue) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - - where: - siteLanguage | appLanguage | doohLanguage | impLanguage - stringTargetingValue | null | null | PBSUtils.randomString - null | stringTargetingValue | null | PBSUtils.randomString - null | null | stringTargetingValue | stringTargetingValue - } - - def "PBS should be able to match site FPD targeting taken from different sources by IN matching function"() { - given: "Bid request with set site FPD in different request places" - def siteLanguage = PBSUtils.randomString - def appLanguage = PBSUtils.randomString - def doohLanguage = PBSUtils.randomString - def impLanguage = PBSUtils.randomString - def bidRequest = getSiteFpdBidRequest(siteLanguage, appLanguage, doohLanguage, impLanguage) - - and: "Planner response with IN all of site FPD values" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(SFPD_LANGUAGE, IN, [siteLanguage, appLanguage, impLanguage, PBSUtils.randomString]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - } - - def "PBS should be able to match user FPD targeting taken from different sources by MATCHES matching function"() { - given: "Bid request with set user FPD in different request places" - def bidRequest = getUserFpdBidRequest(userBuyerUid, userExtDataBuyerUid) - - and: "Planner response with MATCHES 1 of user FPD values" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(UFPD_BUYER_UID, MATCHES, stringTargetingValue) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - def lineItemSize = plansResponse.lineItems.size() - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == lineItemSize - - where: - userBuyerUid | userExtDataBuyerUid - stringTargetingValue | PBSUtils.randomString - PBSUtils.randomString | stringTargetingValue - } - - def "PBS should be able to match user FPD targeting taken from different sources by IN matching function"() { - given: "Bid request with set user FPD in different request places" - def userBuyerUid = PBSUtils.randomString - def userExtDataBuyerUid = PBSUtils.randomString - def bidRequest = getUserFpdBidRequest(userBuyerUid, userExtDataBuyerUid) - - and: "Planner response with IN all of user FPD values" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(UFPD_BUYER_UID, IN, [userBuyerUid, userExtDataBuyerUid, PBSUtils.randomString]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - def lineItemSize = plansResponse.lineItems.size() - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == lineItemSize - } - - def "PBS should support targeting by SITE First Party Data when request ext prebid bidder config is given"() { - given: "Bid request with set Site specific bidder config" - def bidRequest = BidRequest.defaultBidRequest.tap { - def site = new Site().tap { - ext = new SiteExt(data: new SiteExtData(language: stringTargetingValue)) - } - def bidderConfig = new ExtPrebidBidderConfig(bidders: [GENERIC], - config: new BidderConfig(ortb2: new BidderConfigOrtb(site: site))) - ext = new BidRequestExt(prebid: new Prebid(debug: 1, bidderConfig: [bidderConfig])) - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(SFPD_LANGUAGE, matchingFunction, matchingValue) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - - where: - matchingFunction | matchingValue - INTERSECTS | [stringTargetingValue, PBSUtils.randomString] - MATCHES | stringTargetingValue - } - - def "PBS should support targeting by USER First Party Data when request ext prebid bidder config is given"() { - given: "Bid request with set User specific bidder config" - def bidRequest = BidRequest.defaultBidRequest.tap { - def user = new User().tap { - ext = new UserExt(data: new UserExtData(buyeruid: stringTargetingValue)) - } - def bidderConfig = new ExtPrebidBidderConfig(bidders: [GENERIC], - config: new BidderConfig(ortb2: new BidderConfigOrtb(user: user))) - ext = new BidRequestExt(prebid: new Prebid(debug: 1, bidderConfig: [bidderConfig])) - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(UFPD_BUYER_UID, matchingFunction, matchingValue) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - - where: - matchingFunction | matchingValue - INTERSECTS | [stringTargetingValue, PBSUtils.randomString] - MATCHES | stringTargetingValue - } - - def "PBS shouldn't target by SITE First Party Data when request ext prebid bidder config with not matched bidder is given"() { - given: "Bid request with request not matched bidder" - def notMatchedBidder = APPNEXUS - def bidRequest = BidRequest.defaultBidRequest.tap { - def site = new Site().tap { - ext = new SiteExt(data: new SiteExtData(language: stringTargetingValue)) - } - def bidderConfig = new ExtPrebidBidderConfig(bidders: [notMatchedBidder], - config: new BidderConfig(ortb2: new BidderConfigOrtb(site: site))) - ext = new BidRequestExt(prebid: new Prebid(debug: 1, bidderConfig: [bidderConfig])) - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(SFPD_LANGUAGE, matchingFunction, matchingValue) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS hasn't had PG auction" - assert !auctionResponse.ext?.debug?.pgmetrics - - where: - matchingFunction | matchingValue - INTERSECTS | [stringTargetingValue, PBSUtils.randomString] - MATCHES | stringTargetingValue - } - - def "PBS shouldn't target by USER First Party Data when request ext prebid bidder config with not matched bidder is given"() { - given: "Bid request with request not matched bidder" - def notMatchedBidder = APPNEXUS - def bidRequest = BidRequest.defaultBidRequest.tap { - def user = new User().tap { - ext = new UserExt(data: new UserExtData(buyeruid: stringTargetingValue)) - } - def bidderConfig = new ExtPrebidBidderConfig(bidders: [notMatchedBidder], - config: new BidderConfig(ortb2: new BidderConfigOrtb(user: user))) - ext = new BidRequestExt(prebid: new Prebid(debug: 1, bidderConfig: [bidderConfig])) - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(UFPD_BUYER_UID, matchingFunction, matchingValue) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS hasn't had PG auction" - assert !auctionResponse.ext?.debug?.pgmetrics - - where: - matchingFunction | matchingValue - INTERSECTS | [stringTargetingValue, PBSUtils.randomString] - MATCHES | stringTargetingValue - } - - def "PBS should support targeting by SITE First Party Data when a couple of request ext prebid bidder configs are given"() { - given: "Bid request with 1 not matched Site specific bidder config and 1 matched" - def bidRequest = BidRequest.defaultBidRequest.tap { - def bidderConfigSite = new Site().tap { - ext = new SiteExt(data: new SiteExtData(language: stringTargetingValue)) - } - def bidderConfig = new ExtPrebidBidderConfig(bidders: [GENERIC], - config: new BidderConfig(ortb2: new BidderConfigOrtb(site: bidderConfigSite))) - ext = new BidRequestExt(prebid: new Prebid(debug: 1, bidderConfig: [bidderConfig])) - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(SFPD_LANGUAGE, matchingFunction, matchingValue) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - - where: - matchingFunction | matchingValue - INTERSECTS | [stringTargetingValue, PBSUtils.randomString] - MATCHES | stringTargetingValue - } - - def "PBS should support targeting by USER First Party Data when a couple of request ext prebid bidder configs are given"() { - given: "Bid request with 1 not matched User specific bidder config and 1 matched" - def bidRequest = BidRequest.defaultBidRequest.tap { - def bidderConfigUser = new User().tap { - ext = new UserExt(data: new UserExtData(buyeruid: stringTargetingValue)) - } - def bidderConfig = new ExtPrebidBidderConfig(bidders: [GENERIC], - config: new BidderConfig(ortb2: new BidderConfigOrtb(user: bidderConfigUser))) - ext = new BidRequestExt(prebid: new Prebid(debug: 1, bidderConfig: [bidderConfig])) - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(UFPD_BUYER_UID, matchingFunction, matchingValue) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - - where: - matchingFunction | matchingValue - INTERSECTS | [stringTargetingValue, PBSUtils.randomString] - MATCHES | stringTargetingValue - } - - def "PBS shouldn't rely on bidder name case strategy when bidder name in another case stately"() { - given: "Bid request with 1 not matched User specific bidder config and 1 matched" - def bidRequest = BidRequest.defaultBidRequest.tap { - def bidderConfigUser = new User().tap { - ext = new UserExt(data: new UserExtData(buyeruid: stringTargetingValue)) - } - def bidderConfig = new ExtPrebidBidderConfig(bidders: [bidders], - config: new BidderConfig(ortb2: new BidderConfigOrtb(user: bidderConfigUser))) - ext = new BidRequestExt(prebid: new Prebid(debug: 1, bidderConfig: [bidderConfig])) - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(UFPD_BUYER_UID, MATCHES, stringTargetingValue) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - - where: - bidders << [GENERIC, GENERIC_CAMEL_CASE] - } - - private BidRequest getSiteFpdBidRequest(String siteLanguage, String appLanguage, String doohLanguage, String impLanguage) { - def bidRequest - if (siteLanguage != null) { - bidRequest = BidRequest.getDefaultBidRequest(SITE).tap { - site.ext = new SiteExt(data: new SiteExtData(language: siteLanguage)) - } - } else if (appLanguage != null) { - bidRequest = BidRequest.getDefaultBidRequest(APP).tap { - app.ext = new AppExt(data: new AppExtData(language: appLanguage)) - } - } else { - bidRequest = BidRequest.getDefaultBidRequest(DOOH).tap { - dooh.ext = new DoohExt(data: new DoohExtData(language: doohLanguage)) - } - } - bidRequest.imp[0].tap { - ext.context = new ImpExtContext(data: new ImpExtContextData(language: impLanguage)) - } - bidRequest - } - - private BidRequest getUserFpdBidRequest(String userBuyerUid, String userExtDataBuyerUid) { - BidRequest.defaultBidRequest.tap { - user = User.defaultUser.tap { - buyeruid = userBuyerUid - ext = new UserExt(data: new UserExtData(buyeruid: userExtDataBuyerUid)) - } - } - } -} diff --git a/src/test/groovy/org/prebid/server/functional/tests/pg/TargetingSpec.groovy b/src/test/groovy/org/prebid/server/functional/tests/pg/TargetingSpec.groovy deleted file mode 100644 index 882860a9e5b..00000000000 --- a/src/test/groovy/org/prebid/server/functional/tests/pg/TargetingSpec.groovy +++ /dev/null @@ -1,560 +0,0 @@ -package org.prebid.server.functional.tests.pg - -import org.prebid.server.functional.model.bidder.Rubicon -import org.prebid.server.functional.model.deals.lineitem.LineItemSize -import org.prebid.server.functional.model.deals.lineitem.targeting.BooleanOperator -import org.prebid.server.functional.model.deals.lineitem.targeting.Targeting -import org.prebid.server.functional.model.mock.services.generalplanner.PlansResponse -import org.prebid.server.functional.model.request.auction.App -import org.prebid.server.functional.model.request.auction.Banner -import org.prebid.server.functional.model.request.auction.BidRequest -import org.prebid.server.functional.model.request.auction.Bidder -import org.prebid.server.functional.model.request.auction.Device -import org.prebid.server.functional.model.request.auction.Geo -import org.prebid.server.functional.model.request.auction.GeoExt -import org.prebid.server.functional.model.request.auction.GeoExtGeoProvider -import org.prebid.server.functional.model.request.auction.Imp -import org.prebid.server.functional.model.request.auction.ImpExt -import org.prebid.server.functional.model.request.auction.ImpExtContext -import org.prebid.server.functional.model.request.auction.ImpExtContextData -import org.prebid.server.functional.model.request.auction.ImpExtContextDataAdServer -import org.prebid.server.functional.model.request.auction.Publisher -import org.prebid.server.functional.model.request.auction.User -import org.prebid.server.functional.model.request.auction.UserExt -import org.prebid.server.functional.model.request.auction.UserTime -import org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest -import org.prebid.server.functional.util.PBSUtils -import spock.lang.Shared - -import java.time.ZoneId -import java.time.ZonedDateTime - -import static java.time.ZoneOffset.UTC -import static java.time.temporal.WeekFields.SUNDAY_START -import static org.prebid.server.functional.model.bidder.BidderName.RUBICON -import static org.prebid.server.functional.model.deals.lineitem.targeting.BooleanOperator.NOT -import static org.prebid.server.functional.model.deals.lineitem.targeting.BooleanOperator.OR -import static org.prebid.server.functional.model.deals.lineitem.targeting.BooleanOperator.UPPERCASE_AND -import static org.prebid.server.functional.model.deals.lineitem.targeting.MatchingFunction.IN -import static org.prebid.server.functional.model.deals.lineitem.targeting.MatchingFunction.INTERSECTS -import static org.prebid.server.functional.model.deals.lineitem.targeting.MatchingFunction.MATCHES -import static org.prebid.server.functional.model.deals.lineitem.targeting.MatchingFunction.WITHIN -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.AD_UNIT_AD_SLOT -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.AD_UNIT_MEDIA_TYPE -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.AD_UNIT_SIZE -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.APP_BUNDLE -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.BIDP_ACCOUNT_ID -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.DEVICE_METRO -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.DEVICE_REGION -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.DOW -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.HOUR -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.INVALID -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.PAGE_POSITION -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.REFERRER -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.SITE_DOMAIN -import static org.prebid.server.functional.model.deals.lineitem.targeting.TargetingType.UFPD_BUYER_UID -import static org.prebid.server.functional.model.request.auction.DistributionChannel.APP -import static org.prebid.server.functional.model.response.auction.MediaType.BANNER -import static org.prebid.server.functional.model.response.auction.MediaType.VIDEO - -class TargetingSpec extends BasePgSpec { - - @Shared - String stringTargetingValue = PBSUtils.randomString - @Shared - Integer integerTargetingValue = PBSUtils.randomNumber - - def cleanup() { - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.invalidateLineItemsRequest) - } - - def "PBS should invalidate line items when targeting has #reason"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = targeting - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS hasn't had PG deals auction as line item hasn't passed validation" - assert !auctionResponse.ext?.debug?.pgmetrics - - where: - reason | targeting - - "two root nodes" | Targeting.invalidTwoRootNodesTargeting - - "invalid boolean operator" | new Targeting.Builder(BooleanOperator.INVALID).addTargeting(AD_UNIT_SIZE, INTERSECTS, [LineItemSize.defaultLineItemSize]) - .addTargeting(AD_UNIT_MEDIA_TYPE, INTERSECTS, [BANNER]) - .build() - - "uppercase boolean operator" | new Targeting.Builder(UPPERCASE_AND).addTargeting(AD_UNIT_SIZE, INTERSECTS, [LineItemSize.defaultLineItemSize]) - .addTargeting(AD_UNIT_MEDIA_TYPE, INTERSECTS, [BANNER]) - .build() - - "invalid targeting type" | Targeting.defaultTargetingBuilder - .addTargeting(INVALID, INTERSECTS, [PBSUtils.randomString]) - .build() - - "'in' matching type value as not list" | new Targeting.Builder().addTargeting(AD_UNIT_SIZE, INTERSECTS, [LineItemSize.defaultLineItemSize]) - .addTargeting(AD_UNIT_MEDIA_TYPE, IN, BANNER) - .build() - - "'intersects' matching type value as not list" | new Targeting.Builder().addTargeting(AD_UNIT_SIZE, INTERSECTS, [LineItemSize.defaultLineItemSize]) - .addTargeting(AD_UNIT_MEDIA_TYPE, INTERSECTS, BANNER) - .build() - - "'within' matching type value as not list" | new Targeting.Builder().addTargeting(AD_UNIT_SIZE, INTERSECTS, [LineItemSize.defaultLineItemSize]) - .addTargeting(AD_UNIT_MEDIA_TYPE, WITHIN, BANNER) - .build() - - "'matches' matching type value as list" | new Targeting.Builder().addTargeting(AD_UNIT_SIZE, INTERSECTS, [LineItemSize.defaultLineItemSize]) - .addTargeting(AD_UNIT_MEDIA_TYPE, MATCHES, [BANNER]) - .build() - - "null targeting height and width" | new Targeting.Builder().addTargeting(AD_UNIT_SIZE, INTERSECTS, [new LineItemSize(w: null, h: null)]) - .addTargeting(AD_UNIT_MEDIA_TYPE, INTERSECTS, [BANNER]) - .build() - } - - def "PBS should invalidate line items with not supported '#matchingFunction' matching function by '#targetingType' targeting type"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(targetingType, matchingFunction, [PBSUtils.randomString]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS hasn't had PG deals auction as line item hasn't passed validation" - assert !auctionResponse.ext?.debug?.pgmetrics - - where: - matchingFunction | targetingType - INTERSECTS | SITE_DOMAIN - WITHIN | SITE_DOMAIN - INTERSECTS | REFERRER - WITHIN | REFERRER - INTERSECTS | APP_BUNDLE - WITHIN | APP_BUNDLE - INTERSECTS | AD_UNIT_AD_SLOT - WITHIN | AD_UNIT_AD_SLOT - } - - def "PBS should support line item targeting by string '#targetingType' targeting type"() { - given: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.getAccountId()).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(targetingType, MATCHES, stringTargetingValue) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - - where: - targetingType | bidRequest - - REFERRER | BidRequest.defaultBidRequest.tap { - site.page = stringTargetingValue - } - - APP_BUNDLE | BidRequest.getDefaultBidRequest(APP).tap { - app = App.defaultApp.tap { - bundle = stringTargetingValue - } - } - - UFPD_BUYER_UID | BidRequest.defaultBidRequest.tap { - user = User.defaultUser.tap { - buyeruid = stringTargetingValue - } - } - } - - def "PBS should support targeting matching by bidder parameters"() { - given: "Bid request with specified bidder parameter" - def bidRequest = BidRequest.defaultBidRequest.tap { - imp = [Imp.defaultImpression.tap { - banner = Banner.defaultBanner - ext = ImpExt.defaultImpExt - ext.prebid.bidder = new Bidder(rubicon: Rubicon.defaultRubicon.tap { accountId = integerTargetingValue }) - }] - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].source = RUBICON.name().toLowerCase() - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(BIDP_ACCOUNT_ID, INTERSECTS, [integerTargetingValue]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - } - - def "PBS should support line item targeting by page position targeting type"() { - given: "Bid request and bid response" - def bidRequest = BidRequest.defaultBidRequest.tap { - imp[0].banner.pos = integerTargetingValue - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(PAGE_POSITION, IN, [integerTargetingValue]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - } - - def "PBS should support line item targeting by userdow targeting type"() { - given: "Bid request and bid response" - def bidRequest = BidRequest.defaultBidRequest.tap { - def weekDay = ZonedDateTime.now(ZoneId.from(UTC)).dayOfWeek.get(SUNDAY_START.dayOfWeek()) - user = User.defaultUser.tap { - ext = new UserExt(time: new UserTime(userdow: weekDay)) - } - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(DOW, IN, [ZonedDateTime.now(ZoneId.from(UTC)).dayOfWeek.get(SUNDAY_START.dayOfWeek())]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - } - - def "PBS should support line item targeting by userhour targeting type"() { - given: "Bid request and bid response" - def bidRequest = BidRequest.defaultBidRequest.tap { - def hour = ZonedDateTime.now(ZoneId.from(UTC)).hour - user = User.defaultUser.tap { - ext = new UserExt(time: new UserTime(userhour: hour)) - } - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(HOUR, IN, [ZonedDateTime.now(ZoneId.from(UTC)).hour]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - } - - def "PBS should support line item targeting by '#targetingType' targeting type"() { - given: "Bid request and bid response" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(HOUR, IN, [ZonedDateTime.now(ZoneId.from(UTC)).hour]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - - where: - targetingType | targetingValue - - "'\$or' root node with one match" | new Targeting.Builder(OR).addTargeting(AD_UNIT_SIZE, INTERSECTS, [LineItemSize.defaultLineItemSize]) - .addTargeting(AD_UNIT_MEDIA_TYPE, INTERSECTS, [VIDEO]) - .build() - - "'\$not' root node without matches" | new Targeting.Builder(NOT).buildNotBooleanOperatorTargeting(AD_UNIT_MEDIA_TYPE, INTERSECTS, [VIDEO]) - } - - def "PBS should support line item domain targeting by #domainTargetingType"() { - given: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(SITE_DOMAIN, MATCHES, stringTargetingValue) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - def lineItemSize = plansResponse.lineItems.size() - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == lineItemSize - - and: "Targeting recorded as matched" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedDomainTargeting?.size() == lineItemSize - - where: - domainTargetingType | bidRequest - - "site domain" | BidRequest.defaultBidRequest.tap { - site.domain = stringTargetingValue - } - - "site publisher domain" | BidRequest.defaultBidRequest.tap { - site.publisher = Publisher.defaultPublisher.tap { domain = stringTargetingValue } - } - } - - def "PBS should support line item domain targeting"() { - given: "Bid response" - def bidRequest = BidRequest.defaultBidRequest.tap { - site.domain = siteDomain - site.publisher = Publisher.defaultPublisher.tap { domain = sitePublisherDomain } - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(SITE_DOMAIN, IN, [siteDomain]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - def lineItemSize = plansResponse.lineItems.size() - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == lineItemSize - - and: "Targeting recorded as matched" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedDomainTargeting?.size() == lineItemSize - - where: - siteDomain | sitePublisherDomain - "www.example.com" | null - "https://www.example.com" | null - "www.example.com" | "example.com" - } - - def "PBS should appropriately match '\$or', '\$not' line items targeting root node rules"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = targeting - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS hasn't had PG deals auction as targeting differs" - assert !auctionResponse.ext?.debug?.pgmetrics - - where: - targeting << [new Targeting.Builder(OR).addTargeting(AD_UNIT_SIZE, INTERSECTS, [new LineItemSize(w: PBSUtils.randomNumber, h: PBSUtils.randomNumber)]) - .addTargeting(AD_UNIT_MEDIA_TYPE, INTERSECTS, [VIDEO]) - .build(), - new Targeting.Builder(NOT).buildNotBooleanOperatorTargeting(AD_UNIT_SIZE, INTERSECTS, [LineItemSize.defaultLineItemSize])] - } - - def "PBS should support line item targeting by device geo region, metro when request region, metro as int or str value are given"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest.tap { - device = new Device(geo: new Geo(ext: new GeoExt(geoProvider: new GeoExtGeoProvider(region: requestValue, - metro: requestValue)))) - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(DEVICE_REGION, IN, [lineItemValue]) - .addTargeting(DEVICE_METRO, IN, [lineItemValue]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - assert auctionResponse.ext.debug.pgmetrics.matchedWholeTargeting.first() == plansResponse.lineItems.first().lineItemId - - where: - requestValue | lineItemValue - stringTargetingValue | stringTargetingValue - integerTargetingValue | integerTargetingValue as String - } - - def "PBS should be able to match Ad Slot targeting taken from different sources by MATCHES matching function"() { - given: "Bid request with set ad slot info in different request places" - def bidRequest = BidRequest.defaultBidRequest.tap { - imp = [Imp.defaultImpression.tap { - tagId = impTagId - ext.gpid = impExtGpid - ext.data = new ImpExtContextData(pbAdSlot: adSlot, - adServer: new ImpExtContextDataAdServer(adSlot: adServerAdSlot)) - }] - } - - and: "Planner response with MATCHES one of Ad Slot values" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(AD_UNIT_AD_SLOT, MATCHES, stringTargetingValue) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - def lineItemSize = plansResponse.lineItems.size() - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == lineItemSize - - where: - impTagId | impExtGpid | adSlot | adServerAdSlot - stringTargetingValue | PBSUtils.randomString | PBSUtils.randomString | PBSUtils.randomString - PBSUtils.randomString | stringTargetingValue | PBSUtils.randomString | PBSUtils.randomString - null | null | stringTargetingValue | PBSUtils.randomString - null | null | PBSUtils.randomString | stringTargetingValue - } - - def "PBS should be able to match Ad Slot targeting taken from different sources by IN matching function"() { - given: "Bid request with set ad slot info in different request places" - def contextAdSlot = PBSUtils.randomString - def contextAdServerAdSlot = PBSUtils.randomString - def adSlot = PBSUtils.randomString - def adServerAdSlot = PBSUtils.randomString - def bidRequest = BidRequest.defaultBidRequest.tap { - imp = [Imp.defaultImpression.tap { - ext.context = new ImpExtContext(data: new ImpExtContextData(pbAdSlot: contextAdSlot, - adServer: new ImpExtContextDataAdServer(adSlot: contextAdServerAdSlot))) - ext.data = new ImpExtContextData(pbAdSlot: adSlot, - adServer: new ImpExtContextDataAdServer(adSlot: adServerAdSlot)) - }] - } - - and: "Planner response with IN all of Ad Slot values" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = Targeting.defaultTargetingBuilder - .addTargeting(AD_UNIT_AD_SLOT, IN, [contextAdSlot, contextAdServerAdSlot, adSlot, adServerAdSlot, PBSUtils.randomString]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - def lineItemSize = plansResponse.lineItems.size() - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == lineItemSize - } - - def "PBS should be able to match video size targeting taken from imp[].video sources by INTERSECTS matching function"() { - given: "Default video bid request" - def lineItemSize = LineItemSize.defaultLineItemSize - def bidRequest = BidRequest.defaultVideoRequest.tap { - imp[0].video.w = lineItemSize.w - imp[0].video.h = lineItemSize.h - } - - and: "Planner response" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].targeting = new Targeting.Builder().addTargeting(AD_UNIT_SIZE, INTERSECTS, [lineItemSize]) - .addTargeting(AD_UNIT_MEDIA_TYPE, INTERSECTS, [VIDEO]) - .build() - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS had PG auction" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedWholeTargeting?.size() == plansResponse.lineItems.size() - } -} diff --git a/src/test/groovy/org/prebid/server/functional/tests/pg/TokenSpec.groovy b/src/test/groovy/org/prebid/server/functional/tests/pg/TokenSpec.groovy deleted file mode 100644 index 672db59e438..00000000000 --- a/src/test/groovy/org/prebid/server/functional/tests/pg/TokenSpec.groovy +++ /dev/null @@ -1,317 +0,0 @@ -package org.prebid.server.functional.tests.pg - -import org.prebid.server.functional.model.deals.lineitem.LineItem -import org.prebid.server.functional.model.deals.lineitem.Token -import org.prebid.server.functional.model.mock.services.generalplanner.PlansResponse -import org.prebid.server.functional.model.request.auction.BidRequest -import org.prebid.server.functional.model.request.dealsupdate.ForceDealsUpdateRequest -import org.prebid.server.functional.model.response.auction.BidResponse -import org.prebid.server.functional.util.HttpUtil - -import java.time.ZoneId -import java.time.ZonedDateTime - -import static java.time.ZoneOffset.UTC -import static org.prebid.server.functional.model.bidder.BidderName.GENERIC - -class TokenSpec extends BasePgSpec { - - def cleanup() { - pgPbsService.sendForceDealsUpdateRequest(ForceDealsUpdateRequest.invalidateLineItemsRequest) - } - - def "PBS should start using line item in auction when its expired tokens number is increased"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock zero tokens line item" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].deliverySchedules[0].tokens[0].total = 0 - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is requested" - def firstAuctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS shouldn't start processing PG deals" - assert firstAuctionResponse.ext?.debug?.pgmetrics?.pacingDeferred == - [plansResponse.lineItems[0].lineItemId] as Set - assert !firstAuctionResponse.ext?.debug?.pgmetrics?.sentToBidder - - when: "Line item tokens are updated" - plansResponse.lineItems[0].deliverySchedules[0].tokens[0].total = 1 - plansResponse.lineItems[0].deliverySchedules[0].updatedTimeStamp = ZonedDateTime.now(ZoneId.from(UTC)).plusSeconds(1) - generalPlanner.initPlansResponse(plansResponse) - - and: "Updated line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Auction is requested for the second time" - bidder.setResponse(bidRequest.id, bidResponse) - def secondAuctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS should process PG deals" - def sentToBidder = secondAuctionResponse.ext?.debug?.pgmetrics?.sentToBidder?.get(GENERIC.value) - assert sentToBidder?.size() == plansResponse.lineItems.size() - assert sentToBidder[0] == plansResponse.lineItems[0].lineItemId - } - - def "PBS shouldn't allow line items with zero token number take part in auction"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock zero tokens line item" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].deliverySchedules[0].tokens[0].total = 0 - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS should recognize line items with pacing deferred" - assert auctionResponse.ext?.debug?.pgmetrics?.pacingDeferred == [plansResponse.lineItems[0].lineItemId] as Set - } - - def "PBS should allow line item take part in auction when it has at least one unspent token among all expired tokens"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock line item with zero and 1 available tokens" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - def deliverySchedules = lineItems[0].deliverySchedules[0] - deliverySchedules.tokens[0].total = 0 - deliverySchedules.tokens << new Token(priorityClass: 2, total: 0) - deliverySchedules.tokens << new Token(priorityClass: 3, total: 1) - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - def lineItemCount = plansResponse.lineItems.size() - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS should process PG deals" - assert !auctionResponse.ext?.debug?.pgmetrics?.pacingDeferred - assert auctionResponse.ext?.debug?.pgmetrics?.readyToServe?.size() == lineItemCount - def sentToBidder = auctionResponse.ext?.debug?.pgmetrics?.sentToBidder?.get(GENERIC.value) - assert sentToBidder?.size() == lineItemCount - assert sentToBidder[0] == plansResponse.lineItems[0].lineItemId - } - - def "PBS shouldn't allow line item take part in auction when all its tokens are spent"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock with 1 token to spend line item" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].deliverySchedules[0].tokens[0].total = 1 - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Auction is happened for the first time" - pgPbsService.sendAuctionRequest(bidRequest) - - when: "Requesting auction for the second time" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS shouldn't start PG processing" - assert auctionResponse.ext?.debug?.pgmetrics?.pacingDeferred == [plansResponse.lineItems[0].lineItemId] as Set - } - - def "PBS should take only the first token among tokens with the same priority class"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock line item with 2 tokens of the same priority but the first has zero total number" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - def tokens = [new Token(priorityClass: 1, total: 0), new Token(priorityClass: 1, total: 1)] - lineItems[0].deliverySchedules[0].tokens = tokens - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is happened" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS shouldn't start PG processing as it was processed only the first token with 0 total number" - assert auctionResponse.ext?.debug?.pgmetrics?.pacingDeferred == [plansResponse.lineItems[0].lineItemId] as Set - } - - def "PBS shouldn't allow line item take part in auction when its number of available impressions is ahead of the scheduled time"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock line item to have max 2 impressions during one week" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].deliverySchedules[0].tokens[0].total = 2 - lineItems[0].startTimeStamp = ZonedDateTime.now(ZoneId.from(UTC)) - lineItems[0].updatedTimeStamp = ZonedDateTime.now(ZoneId.from(UTC)) - lineItems[0].endTimeStamp = ZonedDateTime.now(ZoneId.from(UTC)).plusWeeks(1) - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is requested for the first time" - def firstAuctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS processed PG deals" - def sentToBidder = firstAuctionResponse.ext?.debug?.pgmetrics?.sentToBidder?.get(GENERIC.value) - assert sentToBidder?.size() == plansResponse.lineItems.size() - assert sentToBidder[0] == plansResponse.lineItems[0].lineItemId - - when: "Auction is requested for the second time" - def secondAuctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS hasn't allowed line item take part in auction as it has only one impression left to be shown during the week" - assert secondAuctionResponse.ext?.debug?.pgmetrics?.pacingDeferred == - [plansResponse.lineItems[0].lineItemId] as Set - assert !secondAuctionResponse.ext?.debug?.pgmetrics?.sentToBidder - } - - def "PBS should abandon line item with updated zero available token number take part in auction"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock with not null tokens number line item" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].deliverySchedules[0].tokens[0].total = 2 - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - when: "Auction is requested" - def firstAuctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS processed PG deals" - def sentToBidder = firstAuctionResponse.ext?.debug?.pgmetrics?.sentToBidder?.get(GENERIC.value) - assert sentToBidder?.size() == plansResponse.lineItems.size() - assert sentToBidder[0] == plansResponse.lineItems[0].lineItemId - - when: "Line item tokens are updated to have no available tokens" - plansResponse.lineItems[0].deliverySchedules[0].tokens[0].total = 0 - plansResponse.lineItems[0].deliverySchedules[0].updatedTimeStamp = ZonedDateTime.now(ZoneId.from(UTC)) - - generalPlanner.initPlansResponse(plansResponse) - - and: "Updated line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Auction is requested for the second time" - def secondAuctionResponse = pgPbsService.sendAuctionRequest(bidRequest) - - then: "PBS shouldn't start processing PG deals" - assert secondAuctionResponse.ext?.debug?.pgmetrics?.pacingDeferred == - [plansResponse.lineItems[0].lineItemId] as Set - assert !secondAuctionResponse.ext?.debug?.pgmetrics?.sentToBidder - } - - def "PBS should ignore line item pacing when ignore pacing header is present in the request"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock zero tokens line item" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].deliverySchedules[0].tokens[0].total = 0 - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Pg ignore pacing header" - def pgIgnorePacingHeader = ["${HttpUtil.PG_IGNORE_PACING_HEADER}": "1"] - - when: "Auction is requested" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest, pgIgnorePacingHeader) - - then: "PBS should process PG deals" - def pgMetrics = auctionResponse.ext?.debug?.pgmetrics - def sentToBidder = pgMetrics?.sentToBidder[GENERIC.value] - assert sentToBidder?.size() == plansResponse.lineItems.size() - assert sentToBidder[0] == plansResponse.lineItems[0].lineItemId - assert pgMetrics.readyToServe == [plansResponse.lineItems[0].lineItemId] as Set - } - - def "PBS should prioritize line item when pg ignore pacing and #reason"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock with additional lineItem" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems.add(updateLineItem(bidRequest.site.publisher.id)) - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Pg ignore pacing header" - def pgIgnorePacingHeader = ["${HttpUtil.PG_IGNORE_PACING_HEADER}": "1"] - - when: "Auction is requested" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest, pgIgnorePacingHeader) - - then: "PBS should process PG deals" - def pgMetrics = auctionResponse.ext?.debug?.pgmetrics - assert pgMetrics?.readyToServe?.size() == plansResponse.lineItems.size() - assert pgMetrics.readyToServe.eachWithIndex { id, index -> - id == plansResponse.lineItems[index].lineItemId } - - where: - reason | updateLineItem - "cpm is null" | {siteId -> LineItem.getDefaultLineItem(siteId).tap { - price.cpm = null - }} - "relative priority is null" | {siteId -> LineItem.getDefaultLineItem(siteId).tap { - relativePriority = null - }} - "no tokens unspent" | {siteId -> LineItem.getDefaultLineItem(siteId).tap { - deliverySchedules[0].tokens[0].total = 0 - }} - "delivery plan is null" | {siteId -> LineItem.getDefaultLineItem(siteId).tap { - deliverySchedules = null - }} - } -} diff --git a/src/test/groovy/org/prebid/server/functional/tests/pg/UserDetailsSpec.groovy b/src/test/groovy/org/prebid/server/functional/tests/pg/UserDetailsSpec.groovy deleted file mode 100644 index a61907af8ae..00000000000 --- a/src/test/groovy/org/prebid/server/functional/tests/pg/UserDetailsSpec.groovy +++ /dev/null @@ -1,343 +0,0 @@ -package org.prebid.server.functional.tests.pg - -import org.prebid.server.functional.model.UidsCookie -import org.prebid.server.functional.model.deals.lineitem.FrequencyCap -import org.prebid.server.functional.model.deals.userdata.UserDetailsResponse -import org.prebid.server.functional.model.mock.services.generalplanner.PlansResponse -import org.prebid.server.functional.model.mock.services.httpsettings.HttpAccountsResponse -import org.prebid.server.functional.model.request.auction.BidRequest -import org.prebid.server.functional.model.request.event.EventRequest -import org.prebid.server.functional.model.response.auction.BidResponse -import org.prebid.server.functional.testcontainers.Dependencies -import org.prebid.server.functional.testcontainers.scaffolding.HttpSettings -import org.prebid.server.functional.util.HttpUtil -import org.prebid.server.functional.util.PBSUtils -import spock.lang.Shared - -import java.time.format.DateTimeFormatter - -import static org.mockserver.model.HttpStatusCode.INTERNAL_SERVER_ERROR_500 -import static org.mockserver.model.HttpStatusCode.NOT_FOUND_404 -import static org.mockserver.model.HttpStatusCode.NO_CONTENT_204 -import static org.prebid.server.functional.model.bidder.BidderName.GENERIC -import static org.prebid.server.functional.model.deals.lineitem.LineItem.TIME_PATTERN - -class UserDetailsSpec extends BasePgSpec { - - private static final String USER_SERVICE_NAME = "userservice" - - @Shared - HttpSettings httpSettings = new HttpSettings(Dependencies.networkServiceContainer) - - def "PBS should send user details request to the User Service during deals auction"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock line items" - generalPlanner.initPlansResponse(PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id)) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Initial user details request count is taken" - def initialRequestCount = userData.recordedUserDetailsRequestCount - - and: "Cookies with user ids" - def uidsCookie = UidsCookie.defaultUidsCookie - def cookieHeader = HttpUtil.getCookieHeader(uidsCookie) - - when: "Sending auction request to PBS" - pgPbsService.sendAuctionRequest(bidRequest, cookieHeader) - - then: "PBS sends a request to the User Service" - def updatedRequestCount = userData.recordedUserDetailsRequestCount - assert updatedRequestCount == initialRequestCount + 1 - - and: "Request corresponds to the payload" - def userDetailsRequest = userData.recordedUserDetailsRequest - assert userDetailsRequest.ids?.size() == 1 - assert userDetailsRequest.ids[0].id == uidsCookie.tempUIDs.get(GENERIC).uid - assert userDetailsRequest.ids[0].type == pgConfig.userIdType - } - - def "PBS should validate bad user details response status code #statusCode"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Bid response" - def bidResponse = BidResponse.getDefaultBidResponse(bidRequest) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Planner Mock line items" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id) - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "User Service response is set" - userData.setUserDataResponse(UserDetailsResponse.defaultUserResponse, statusCode) - - and: "Initial user details request count is taken" - def initialRequestCount = userData.recordedUserDetailsRequestCount - - and: "Cookies with user ids" - def uidsCookie = UidsCookie.defaultUidsCookie - def cookieHeader = HttpUtil.getCookieHeader(uidsCookie) - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest, cookieHeader) - - then: "PBS sends a request to the User Service during auction" - assert userData.recordedUserDetailsRequestCount == initialRequestCount + 1 - def userServiceCall = auctionResponse.ext?.debug?.httpcalls?.get(USER_SERVICE_NAME) - assert userServiceCall?.size() == 1 - - assert !userServiceCall[0].status - assert !userServiceCall[0].responseBody - - cleanup: - userData.setUserDataResponse(UserDetailsResponse.defaultUserResponse) - - where: - statusCode << [NO_CONTENT_204, NOT_FOUND_404, INTERNAL_SERVER_ERROR_500] - } - - def "PBS should invalidate user details response body when response has absent #fieldName field"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Bid response" - def bidResponse = BidResponse.getDefaultBidResponse(bidRequest) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Planner Mock line items" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id) - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Initial user details request count is taken" - def initialRequestCount = userData.recordedUserDetailsRequestCount - - and: "User Service response is set" - userData.setUserDataResponse(userDataResponse) - - and: "Cookies with user ids" - def uidsCookie = UidsCookie.defaultUidsCookie - def cookieHeader = HttpUtil.getCookieHeader(uidsCookie) - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest, cookieHeader) - - then: "PBS sends a request to the User Service" - assert userData.recordedUserDetailsRequestCount == initialRequestCount + 1 - - and: "Call to the user service was made" - assert auctionResponse.ext?.debug?.httpcalls?.get(USER_SERVICE_NAME)?.size() == 1 - - and: "Data from the user service response wasn't added to the bid request by PBS" - assert !auctionResponse.ext?.debug?.resolvedRequest?.user?.data - assert !auctionResponse.ext?.debug?.resolvedRequest?.user?.ext?.fcapids - - cleanup: - userData.setUserDataResponse(UserDetailsResponse.defaultUserResponse) - - where: - fieldName | userDataResponse - "user" | new UserDetailsResponse(user: null) - "user.data" | UserDetailsResponse.defaultUserResponse.tap { user.data = null } - "user.ext" | UserDetailsResponse.defaultUserResponse.tap { user.ext = null } - } - - def "PBS should abandon line items with user fCap ids take part in auction when user details response failed"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Planner Mock line items with added frequency cap" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id).tap { - lineItems[0].frequencyCaps = [FrequencyCap.defaultFrequencyCap.tap { fcapId = PBSUtils.randomNumber as String }] - } - generalPlanner.initPlansResponse(plansResponse) - - and: "Bid response" - def bidResponse = BidResponse.getDefaultPgBidResponse(bidRequest, plansResponse) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Bad User Service Response is set" - userData.setUserDataResponse(new UserDetailsResponse(user: null)) - - and: "Cookies header" - def uidsCookie = UidsCookie.defaultUidsCookie - def cookieHeader = HttpUtil.getCookieHeader(uidsCookie) - - when: "Sending auction request to PBS" - def auctionResponse = pgPbsService.sendAuctionRequest(bidRequest, cookieHeader) - - then: "PBS hasn't started processing PG deals as line item targeting frequency capped lookup failed" - assert auctionResponse.ext?.debug?.pgmetrics?.matchedTargetingFcapLookupFailed?.size() == - plansResponse.lineItems.size() - - cleanup: - userData.setUserDataResponse(UserDetailsResponse.defaultUserResponse) - } - - def "PBS should send win notification request to the User Service on bidder wins"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Bid response" - def bidResponse = BidResponse.getDefaultBidResponse(bidRequest) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Planner Mock line items" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id) - def lineItemId = plansResponse.lineItems[0].lineItemId - def lineItemUpdateTime = plansResponse.lineItems[0].updatedTimeStamp - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Initial win notification request count" - def initialRequestCount = userData.requestCount - - and: "Enabled event request" - def winEventRequest = EventRequest.defaultEventRequest.tap { - it.lineItemId = lineItemId - analytics = 0 - } - - and: "Default account response" - def httpSettingsResponse = HttpAccountsResponse.getDefaultHttpAccountsResponse(winEventRequest.accountId.toString()) - httpSettings.setResponse(winEventRequest.accountId.toString(), httpSettingsResponse) - - and: "Cookies header" - def uidsCookie = UidsCookie.defaultUidsCookie - def cookieHeader = HttpUtil.getCookieHeader(uidsCookie) - - when: "Sending auction request to PBS where the winner is instantiated" - pgPbsService.sendAuctionRequest(bidRequest) - - and: "Sending event request to PBS" - pgPbsService.sendEventRequest(winEventRequest, cookieHeader) - - then: "PBS sends a win notification to the User Service" - PBSUtils.waitUntil { userData.requestCount == initialRequestCount + 1 } - - and: "Win request corresponds to the payload" - def timeFormatter = DateTimeFormatter.ofPattern(TIME_PATTERN) - - verifyAll(userData.recordedWinEventRequest) { winNotificationRequest -> - winNotificationRequest.bidderCode == GENERIC.value - winNotificationRequest.bidId == winEventRequest.bidId - winNotificationRequest.lineItemId == lineItemId - winNotificationRequest.region == pgConfig.region - winNotificationRequest.userIds?.size() == 1 - winNotificationRequest.userIds[0].id == uidsCookie.tempUIDs.get(GENERIC).uid - winNotificationRequest.userIds[0].type == pgConfig.userIdType - timeFormatter.format(winNotificationRequest.lineUpdatedDateTime) == timeFormatter.format(lineItemUpdateTime) - winNotificationRequest.winEventDateTime.isAfter(winNotificationRequest.lineUpdatedDateTime) - !winNotificationRequest.frequencyCaps - } - } - - def "PBS shouldn't send win notification request to the User Service when #reason line item id is given"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Bid response" - def bidResponse = BidResponse.getDefaultBidResponse(bidRequest) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Planner Mock line items" - generalPlanner.initPlansResponse(PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id)) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Initial win notification request count" - def initialRequestCount = userData.requestCount - - and: "Enabled event request" - def eventRequest = EventRequest.defaultEventRequest.tap { - it.lineItemId = lineItemId - analytics = 0 - } - - and: "Default account response" - def httpSettingsResponse = HttpAccountsResponse.getDefaultHttpAccountsResponse(eventRequest.accountId.toString()) - httpSettings.setResponse(eventRequest.accountId.toString(), httpSettingsResponse) - - and: "Cookies header" - def uidsCookie = UidsCookie.defaultUidsCookie - def cookieHeader = HttpUtil.getCookieHeader(uidsCookie) - - when: "Sending auction request to PBS where the winner is instantiated" - pgPbsService.sendAuctionRequest(bidRequest) - - and: "Sending event request to PBS" - pgPbsService.sendEventRequest(eventRequest, cookieHeader) - - then: "PBS hasn't sent a win notification to the User Service" - assert userData.requestCount == initialRequestCount - - where: - reason | lineItemId - "null" | null - "non-existent" | PBSUtils.randomNumber as String - } - - def "PBS shouldn't send win notification request to the User Service when #reason cookies header was given"() { - given: "Bid request" - def bidRequest = BidRequest.defaultBidRequest - - and: "Bid response" - def bidResponse = BidResponse.getDefaultBidResponse(bidRequest) - bidder.setResponse(bidRequest.id, bidResponse) - - and: "Planner Mock line items" - def plansResponse = PlansResponse.getDefaultPlansResponse(bidRequest.site.publisher.id) - def lineItemId = plansResponse.lineItems[0].lineItemId - generalPlanner.initPlansResponse(plansResponse) - - and: "Line items are fetched by PBS" - updateLineItemsAndWait() - - and: "Initial win notification request count" - def initialRequestCount = userData.requestCount - - and: "Enabled event request" - def eventRequest = EventRequest.defaultEventRequest.tap { - it.lineItemId = lineItemId - analytics = 0 - } - - and: "Default account response" - def httpSettingsResponse = HttpAccountsResponse.getDefaultHttpAccountsResponse(eventRequest.accountId.toString()) - httpSettings.setResponse(eventRequest.accountId.toString(), httpSettingsResponse) - - when: "Sending auction request to PBS where the winner is instantiated" - pgPbsService.sendAuctionRequest(bidRequest) - - and: "Sending event request to PBS" - pgPbsService.sendEventRequest(eventRequest, HttpUtil.getCookieHeader(uidsCookie)) - - then: "PBS hasn't sent a win notification to the User Service" - assert userData.requestCount == initialRequestCount - - where: - reason | uidsCookie - - "empty cookie" | new UidsCookie() - - "empty uids cookie" | UidsCookie.defaultUidsCookie.tap { - uids = null - tempUIDs = null - } - } -} diff --git a/src/test/groovy/org/prebid/server/functional/tests/privacy/PrivacyBaseSpec.groovy b/src/test/groovy/org/prebid/server/functional/tests/privacy/PrivacyBaseSpec.groovy index 0b917c50055..6c274fb7ab4 100644 --- a/src/test/groovy/org/prebid/server/functional/tests/privacy/PrivacyBaseSpec.groovy +++ b/src/test/groovy/org/prebid/server/functional/tests/privacy/PrivacyBaseSpec.groovy @@ -20,7 +20,6 @@ import org.prebid.server.functional.model.request.auction.RegsExt import org.prebid.server.functional.model.request.auction.User import org.prebid.server.functional.model.request.auction.UserExt import org.prebid.server.functional.service.PrebidServerService -import org.prebid.server.functional.testcontainers.PbsPgConfig import org.prebid.server.functional.testcontainers.scaffolding.VendorList import org.prebid.server.functional.tests.BaseSpec import org.prebid.server.functional.util.PBSUtils @@ -59,10 +58,9 @@ abstract class PrivacyBaseSpec extends BaseSpec { static final Map GDPR_VENDOR_LIST_CONFIG = ["gdpr.vendorlist.v2.http-endpoint-template": "$networkServiceContainer.rootUri/v2/vendor-list.json".toString(), "gdpr.vendorlist.v3.http-endpoint-template": "$networkServiceContainer.rootUri/v3/vendor-list.json".toString()] private static final Map SETTING_CONFIG = ["settings.enforce-valid-account": 'true'] - private static final PbsPgConfig pgConfig = new PbsPgConfig(networkServiceContainer) protected static final Map PBS_CONFIG = OPENX_CONFIG + OPENX_COOKIE_SYNC_CONFIG + - GENERIC_COOKIE_SYNC_CONFIG + pgConfig.properties + GDPR_VENDOR_LIST_CONFIG + SETTING_CONFIG + GENERIC_COOKIE_SYNC_CONFIG + GDPR_VENDOR_LIST_CONFIG + SETTING_CONFIG protected static final String VALID_VALUE_FOR_GPC_HEADER = "1" protected static final GppConsent SIMPLE_GPC_DISALLOW_LOGIC = new UspNatV1Consent.Builder().setGpc(true).build() protected static final VendorList vendorListResponse = new VendorList(networkServiceContainer) diff --git a/src/test/groovy/org/prebid/server/functional/util/HttpUtil.groovy b/src/test/groovy/org/prebid/server/functional/util/HttpUtil.groovy index 2e7d6a2d0a1..c1f60516abf 100644 --- a/src/test/groovy/org/prebid/server/functional/util/HttpUtil.groovy +++ b/src/test/groovy/org/prebid/server/functional/util/HttpUtil.groovy @@ -7,11 +7,7 @@ import static java.nio.charset.StandardCharsets.UTF_8 class HttpUtil implements ObjectMapperWrapper { - public static final String UUID_REGEX = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/ - public static final String PG_TRX_ID_HEADER = "pg-trx-id" - public static final String PG_IGNORE_PACING_HEADER = "X-Prebid-PG-ignore-pacing" - public static final String AUTHORIZATION_HEADER = "Authorization" public static final String ACCEPT_HEADER = "Authorization" public static final String CONTENT_TYPE_HEADER = "Content-Type" public static final String COOKIE_HEADER = "cookie" @@ -21,13 +17,6 @@ class HttpUtil implements ObjectMapperWrapper { public static final String SET_COOKIE_HEADER = 'Set-Cookie' public static final String COOKIE_DEPRECATION_HEADER = 'Sec-Cookie-Deprecation' - public static final String CONTENT_TYPE_HEADER_VALUE = "application/json" - public static final String CHARSET_HEADER_VALUE = "charset=utf-8" - - static String makeBasicAuthHeaderValue(String username, String password) { - "Basic ${encodeWithBase64("$username:$password")}" - } - static HashMap getCookieHeader(UidsCookie uidsCookie) { [(COOKIE_HEADER): makeUidsCookieHeaderValue(encode(uidsCookie))] } diff --git a/src/test/java/org/prebid/server/analytics/reporter/pubstack/PubstackEventHandlerTest.java b/src/test/java/org/prebid/server/analytics/reporter/pubstack/PubstackEventHandlerTest.java index 12ee628c670..98fd998571b 100644 --- a/src/test/java/org/prebid/server/analytics/reporter/pubstack/PubstackEventHandlerTest.java +++ b/src/test/java/org/prebid/server/analytics/reporter/pubstack/PubstackEventHandlerTest.java @@ -17,8 +17,6 @@ import org.prebid.server.auction.model.AuctionContext; import org.prebid.server.auction.model.TimeoutContext; import org.prebid.server.cookie.UidsCookie; -import org.prebid.server.deals.model.DeepDebugLog; -import org.prebid.server.deals.model.TxnLog; import org.prebid.server.execution.Timeout; import org.prebid.server.vertx.http.HttpClient; import org.prebid.server.vertx.http.model.HttpClientResponse; @@ -161,8 +159,6 @@ public void handleShouldBeAbleToEncodeAuctionEvent() { .auctionContext(AuctionContext.builder() .uidsCookie(mock(UidsCookie.class)) .timeoutContext(TimeoutContext.of(0, mock(Timeout.class), 0)) - .txnLog(mock(TxnLog.class)) - .deepDebugLog(mock(DeepDebugLog.class)) .build()) .build(); diff --git a/src/test/java/org/prebid/server/auction/AdjustmentFactorResolverTest.java b/src/test/java/org/prebid/server/auction/AdjustmentFactorResolverTest.java deleted file mode 100644 index 7640e81eaab..00000000000 --- a/src/test/java/org/prebid/server/auction/AdjustmentFactorResolverTest.java +++ /dev/null @@ -1,159 +0,0 @@ -package org.prebid.server.auction; - -import org.junit.Before; -import org.junit.Test; -import org.prebid.server.proto.openrtb.ext.request.ExtRequestBidAdjustmentFactors; -import org.prebid.server.proto.openrtb.ext.request.ImpMediaType; - -import java.math.BigDecimal; -import java.util.EnumMap; -import java.util.Map; - -import static org.assertj.core.api.Assertions.assertThat; - -public class AdjustmentFactorResolverTest { - - private AdjustmentFactorResolver adjustmentFactorResolver; - - @Before - public void setUp() { - adjustmentFactorResolver = new AdjustmentFactorResolver(); - } - - @Test - public void resolveShouldReturnOneIfAdjustmentsByMediaTypeAndBidderAreAbsent() { - // when - final BigDecimal result = adjustmentFactorResolver.resolve( - ImpMediaType.video, - ExtRequestBidAdjustmentFactors.builder().build(), - "bidder"); - - // then - assertThat(result).isEqualTo(BigDecimal.ONE); - } - - @Test - public void resolveShouldReturnBidderAdjustmentFactorIfAdjustmentsByTypeAreAbsent() { - // given - final ExtRequestBidAdjustmentFactors adjustmentFactors = - ExtRequestBidAdjustmentFactors.builder().build(); - adjustmentFactors.addFactor("bidder", BigDecimal.valueOf(3.456)); - - // when - final BigDecimal result = adjustmentFactorResolver.resolve(ImpMediaType.video, adjustmentFactors, "bidder"); - - // then - assertThat(result).isEqualTo(BigDecimal.valueOf(3.456)); - } - - @Test - public void resolveShouldReturnSmallestAdjustmentByMediaTypeIfPresent() { - // given - final EnumMap> adjustmentFactorsByMediaType = new EnumMap<>(Map.of( - ImpMediaType.video, Map.of("bidder", BigDecimal.valueOf(1.234)), - ImpMediaType.video_outstream, Map.of("bidder", BigDecimal.valueOf(2.345)), - ImpMediaType.banner, Map.of("bidder", BigDecimal.valueOf(3.456)))); - - final ExtRequestBidAdjustmentFactors adjustmentFactors = - ExtRequestBidAdjustmentFactors.builder() - .mediatypes(adjustmentFactorsByMediaType) - .build(); - - // when - final BigDecimal result = adjustmentFactorResolver.resolve(ImpMediaType.video, adjustmentFactors, "bidder"); - - // then - assertThat(result).isEqualTo(BigDecimal.valueOf(1.234)); - } - - @Test - public void resolveShouldReturnAdjustmentByMediaTypeIfPresentIgnoringCaseOfBidderName() { - // given - final EnumMap> adjustmentFactorsByMediaType = new EnumMap<>(Map.of( - ImpMediaType.video, Map.of("bIdDeR", BigDecimal.valueOf(1.234)), - ImpMediaType.video_outstream, Map.of("bidder", BigDecimal.valueOf(2.345)), - ImpMediaType.banner, Map.of("bidder", BigDecimal.valueOf(3.456)))); - - final ExtRequestBidAdjustmentFactors adjustmentFactors = - ExtRequestBidAdjustmentFactors.builder() - .mediatypes(adjustmentFactorsByMediaType) - .build(); - - // when - final BigDecimal result = adjustmentFactorResolver.resolve(ImpMediaType.video, adjustmentFactors, "bidder"); - - // then - assertThat(result).isEqualTo(BigDecimal.valueOf(1.234)); - } - - @Test - public void resolveShouldReturnSmallestAdjustmentBetweenMediaTypeAndBidderChosen() { - // given - final EnumMap> adjustmentFactorsByMediaType = new EnumMap<>(Map.of( - ImpMediaType.video, Map.of("bidder", BigDecimal.valueOf(1.234)))); - - final ExtRequestBidAdjustmentFactors adjustmentFactors = ExtRequestBidAdjustmentFactors.builder() - .mediatypes(adjustmentFactorsByMediaType) - .build(); - adjustmentFactors.addFactor("bidder", BigDecimal.valueOf(0.123)); - - // when - final BigDecimal result = adjustmentFactorResolver.resolve(ImpMediaType.video, adjustmentFactors, "bidder"); - - // then - assertThat(result).isEqualTo(BigDecimal.valueOf(0.123)); - } - - @Test - public void resolveShouldReturnMediaTypeAdjustmentWhenBidderAdjustmentIsAbsent() { - // given - final EnumMap> adjustmentFactorsByMediaType = new EnumMap<>(Map.of( - ImpMediaType.video, Map.of("bidder", BigDecimal.valueOf(1.234)))); - - final ExtRequestBidAdjustmentFactors adjustmentFactors = ExtRequestBidAdjustmentFactors.builder() - .mediatypes(adjustmentFactorsByMediaType) - .build(); - - // when - final BigDecimal result = adjustmentFactorResolver.resolve(ImpMediaType.video, adjustmentFactors, "bidder"); - - // then - assertThat(result).isEqualTo(BigDecimal.valueOf(1.234)); - } - - @Test - public void resolveShouldReturnBidderAdjustmentWhenMediaTypeAdjustmentIsAbsent() { - // given - final EnumMap> adjustmentFactorsByMediaType = new EnumMap<>(Map.of( - ImpMediaType.video, Map.of("bidder", BigDecimal.valueOf(1.234)))); - - final ExtRequestBidAdjustmentFactors adjustmentFactors = ExtRequestBidAdjustmentFactors.builder() - .mediatypes(adjustmentFactorsByMediaType) - .build(); - adjustmentFactors.addFactor("bidder", BigDecimal.valueOf(3.456)); - - // when - final BigDecimal result = adjustmentFactorResolver.resolve(ImpMediaType.banner, adjustmentFactors, "bidder"); - - // then - assertThat(result).isEqualTo(BigDecimal.valueOf(3.456)); - } - - @Test - public void resolveShouldReturnOneWhenAppropriateBidderAdjustmentAndMediaTypeAdjustmentAreAbsent() { - // given - final EnumMap> adjustmentFactorsByMediaType = new EnumMap<>(Map.of( - ImpMediaType.video, Map.of("bidder", BigDecimal.valueOf(1.234)))); - - final ExtRequestBidAdjustmentFactors adjustmentFactors = ExtRequestBidAdjustmentFactors.builder() - .mediatypes(adjustmentFactorsByMediaType) - .build(); - adjustmentFactors.addFactor("bidder1", BigDecimal.valueOf(3.456)); - - // when - final BigDecimal result = adjustmentFactorResolver.resolve(ImpMediaType.banner, adjustmentFactors, "bidder"); - - // then - assertThat(result).isEqualTo(BigDecimal.ONE); - } -} diff --git a/src/test/java/org/prebid/server/auction/BidResponseCreatorTest.java b/src/test/java/org/prebid/server/auction/BidResponseCreatorTest.java index 67d7725c535..4271870a983 100644 --- a/src/test/java/org/prebid/server/auction/BidResponseCreatorTest.java +++ b/src/test/java/org/prebid/server/auction/BidResponseCreatorTest.java @@ -58,8 +58,6 @@ import org.prebid.server.cache.model.CacheInfo; import org.prebid.server.cache.model.CacheServiceResult; import org.prebid.server.cache.model.DebugHttpCall; -import org.prebid.server.deals.model.DeepDebugLog; -import org.prebid.server.deals.model.TxnLog; import org.prebid.server.events.EventsContext; import org.prebid.server.events.EventsService; import org.prebid.server.exception.InvalidRequestException; @@ -95,7 +93,6 @@ import org.prebid.server.proto.openrtb.ext.response.ExtBidResponse; import org.prebid.server.proto.openrtb.ext.response.ExtBidResponsePrebid; import org.prebid.server.proto.openrtb.ext.response.ExtBidderError; -import org.prebid.server.proto.openrtb.ext.response.ExtDebugPgmetrics; import org.prebid.server.proto.openrtb.ext.response.ExtDebugTrace; import org.prebid.server.proto.openrtb.ext.response.ExtHttpCall; import org.prebid.server.proto.openrtb.ext.response.ExtResponseCache; @@ -105,7 +102,6 @@ import org.prebid.server.proto.openrtb.ext.response.ExtTraceActivityInvocationDefaultResult; import org.prebid.server.proto.openrtb.ext.response.ExtTraceActivityInvocationResult; import org.prebid.server.proto.openrtb.ext.response.ExtTraceActivityRule; -import org.prebid.server.proto.openrtb.ext.response.ExtTraceDeal; import org.prebid.server.proto.openrtb.ext.response.FledgeAuctionConfig; import org.prebid.server.proto.openrtb.ext.response.seatnonbid.NonBid; import org.prebid.server.proto.openrtb.ext.response.seatnonbid.SeatNonBid; @@ -122,7 +118,6 @@ import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; -import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -136,7 +131,6 @@ import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; -import static java.util.Collections.singleton; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static java.util.function.UnaryOperator.identity; @@ -162,8 +156,6 @@ import static org.prebid.server.proto.openrtb.ext.response.BidType.banner; import static org.prebid.server.proto.openrtb.ext.response.BidType.video; import static org.prebid.server.proto.openrtb.ext.response.BidType.xNative; -import static org.prebid.server.proto.openrtb.ext.response.ExtTraceDeal.Category.pacing; -import static org.prebid.server.proto.openrtb.ext.response.ExtTraceDeal.Category.targeting; public class BidResponseCreatorTest extends VertxTest { @@ -551,7 +543,7 @@ public void shouldRequestCacheServiceWithVideoBidsToModify() { .with(toAuctionParticipant(bidderResponses)); final String modifiedAdm = "modifiedAdm"; - given(vastModifier.createBidVastXml(any(), any(), any(), any(), any(), any(), any(), any())) + given(vastModifier.createBidVastXml(any(), any(), any(), any(), any(), any(), any())) .willReturn(modifiedAdm); // just a stub to get through method call chain @@ -569,8 +561,14 @@ public void shouldRequestCacheServiceWithVideoBidsToModify() { .build(); verify(vastModifier) - .createBidVastXml(eq(bidder1), eq(null), eq(BID_NURL), eq(bidId1), - eq(accountId), eq(expectedEventContext), eq(emptyList()), eq(null)); + .createBidVastXml( + eq(bidder1), + eq(null), + eq(BID_NURL), + eq(bidId1), + eq(accountId), + eq(expectedEventContext), + eq(emptyList())); final ArgumentCaptor> bidInfoCaptor = ArgumentCaptor.forClass(List.class); verify(cacheService).cacheBidsOpenrtb( @@ -609,8 +607,7 @@ public void shouldModifyBidAdmWhenBidVideoAndVastModifierReturnValue() { final String modifiedVast = "modifiedVast"; given(vastModifier - .createBidVastXml(anyString(), anyString(), anyString(), - anyString(), anyString(), any(), any(), any())) + .createBidVastXml(anyString(), anyString(), anyString(), anyString(), anyString(), any(), any())) .willReturn(modifiedVast); // when @@ -623,8 +620,7 @@ public void shouldModifyBidAdmWhenBidVideoAndVastModifierReturnValue() { .containsOnly(modifiedVast); verify(vastModifier) - .createBidVastXml(eq(bidder), eq(BID_ADM), eq(BID_NURL), eq(bidId), eq("accountId"), any(), any(), - any()); + .createBidVastXml(eq(bidder), eq(BID_ADM), eq(BID_NURL), eq(bidId), eq("accountId"), any(), any()); } @SuppressWarnings("unchecked") @@ -840,14 +836,18 @@ public void shouldUseGeneratedBidIdForEventAndCacheWhenIdGeneratorIsUUIDAndEvent final BidRequestCacheInfo cacheInfo = BidRequestCacheInfo.builder().doCaching(true).build(); givenCacheServiceResult(singletonList(CacheInfo.of("id", null, null, null))); final Events events = Events.of("http://event-type-win", "http://event-type-view"); - given(eventsService.createEvent(anyString(), anyString(), anyString(), anyString(), anyBoolean(), any())) + given(eventsService.createEvent(anyString(), anyString(), anyString(), anyBoolean(), any())) .willReturn(events); // when bidResponseCreator.create(auctionContext, cacheInfo, MULTI_BIDS).result(); // then - final ExtBidPrebid extBidPrebid = ExtBidPrebid.builder().bidid(generatedBidId).type(banner).build(); + final ExtBidPrebid extBidPrebid = ExtBidPrebid.builder() + .bidid(generatedBidId) + .type(banner) + .events(events) + .build(); final Bid expectedBid = bid.toBuilder() .ext(mapper.createObjectNode().set("prebid", mapper.valueToTree(extBidPrebid))) .build(); @@ -855,7 +855,7 @@ public void shouldUseGeneratedBidIdForEventAndCacheWhenIdGeneratorIsUUIDAndEvent final BidInfo expectedBidInfo = toBidInfo(expectedBid, imp, bidder, banner, true); verify(cacheService).cacheBidsOpenrtb(eq(singletonList(expectedBidInfo)), any(), any(), any()); - verify(eventsService).createEvent(eq(generatedBidId), anyString(), anyString(), any(), anyBoolean(), any()); + verify(eventsService).createEvent(eq(generatedBidId), anyString(), anyString(), anyBoolean(), any()); } @SuppressWarnings("unchecked") @@ -1920,88 +1920,6 @@ public void shouldPopulateTargetingKeywordsForWinningBidsAndWinningBidsByBidder( verify(cacheService, never()).cacheBidsOpenrtb(anyList(), any(), any(), any()); } - @Test - public void shouldPopulateAuctionLostToMetricByWinningDealBid() { - // given - final String dealId1 = "dealId1"; - final String dealId2 = "dealId2"; - final String lineItemId1 = "lineItemId1"; - final String lineItemId2 = "lineItemId2"; - final BidRequest bidRequest = givenBidRequest( - identity(), - extBuilder -> extBuilder.targeting(givenTargeting()), - Imp.builder() - .id(IMP_ID) - .pmp(Pmp.builder() - // Order defines winning bid - .deals(asList( - Deal.builder().id("dealId1") - .ext(mapper.valueToTree(ExtDeal.of(ExtDealLine.of( - "lineItemId1", null, null, null)))).build(), - Deal.builder().id("dealId2") - .ext(mapper.valueToTree(ExtDeal.of(ExtDealLine.of( - "lineItemId2", null, null, null)))).build())) - .build()) - .build()); - - final Bid firstBid = Bid.builder().id("bidId1").impid(IMP_ID).price(BigDecimal.valueOf(5.67)) - .dealid(dealId1).build(); - final Bid secondBid = Bid.builder().id("bidId2").impid(IMP_ID).price(BigDecimal.valueOf(4.98)) - .dealid(dealId2).build(); - - final List bidderResponses = asList( - BidderResponse.of("bidder1", givenSeatBid(BidderBid.of(firstBid, banner, null)), 100), - BidderResponse.of("bidder2", givenSeatBid(BidderBid.of(secondBid, banner, null)), 100)); - - final AuctionContext auctionContext = givenAuctionContext( - bidRequest, - contextBuilder -> contextBuilder.auctionParticipations(toAuctionParticipant(bidderResponses))); - - // when - bidResponseCreator.create(auctionContext, CACHE_INFO, MULTI_BIDS).result(); - - // then - assertThat(auctionContext.getTxnLog().lostAuctionToLineItems().entrySet()) - .extracting(Map.Entry::getKey, Map.Entry::getValue) - .containsOnly(tuple(lineItemId2, singleton(lineItemId1))); - } - - @Test - public void shouldIncreaseLineItemSentToClientAsTopMatchMetricInTransactionLog() { - // given - final BidRequest bidRequest = givenBidRequest( - identity(), - extBuilder -> extBuilder.targeting(givenTargeting()), - givenImp(Collections.singletonMap("dealId", "lineItemId1"))); - - final Bid bid = Bid.builder() - .id("bidId1") - .impid(IMP_ID) - .price(BigDecimal.valueOf(5.67)) - .dealid("dealId") - .build(); - final List bidderResponses = singletonList( - BidderResponse.of("bidder1", givenSeatBid(BidderBid.of(bid, banner, null)), 100)); - - final AuctionContext auctionContext = givenAuctionContext( - bidRequest, - context -> context - .debugContext(DebugContext.of(true, true, null)) - .auctionParticipations(toAuctionParticipant(bidderResponses))); - - // when - final BidResponse bidResponse = bidResponseCreator.create(auctionContext, CACHE_INFO, MULTI_BIDS).result(); - - // then - final ExtBidResponse responseExt = bidResponse.getExt(); - - assertThat(responseExt.getDebug()).isNotNull(); - assertThat(responseExt.getDebug().getPgmetrics()).isNotNull(); - assertThat(singletonList(responseExt.getDebug().getPgmetrics())) - .flatExtracting(ExtDebugPgmetrics::getSentToClientAsTopMatch) - .containsOnly("lineItemId1"); - } - @Test public void shouldPopulateTargetingKeywordsFromMediaTypePriceGranularities() { // given @@ -2159,43 +2077,6 @@ public void shouldPopulateTargetingKeywordsIfBidWasCachedAndAdmWasRemoved() { .doesNotContainNull(); } - @Test - public void shouldCallEventsServiceWhenEventsDisabledByRequestButBidWithLineItem() { - // given - final Account account = Account.builder() - .id("accountId") - .auction(AccountAuctionConfig.builder() - .events(AccountEventsConfig.of(true)) - .build()) - .build(); - final BidRequest bidRequest = givenBidRequest( - identity(), - extBuilder -> extBuilder.targeting(givenTargeting()), - givenImp(Collections.singletonMap("dealId", "lineItemId"))); - - final Bid bid = Bid.builder() - .id("bidId") - .price(BigDecimal.valueOf(5.67)) - .impid(IMP_ID) - .dealid("dealId") - .build(); - final List bidderResponses = singletonList(BidderResponse.of("bidder1", - givenSeatBid(BidderBid.of(bid, banner, "USD")), 100)); - - final AuctionContext auctionContext = givenAuctionContext( - bidRequest, - contextBuilder -> contextBuilder - .account(account) - .auctionParticipations(toAuctionParticipant(bidderResponses))); - - // when - bidResponseCreator.create(auctionContext, CACHE_INFO, MULTI_BIDS).result(); - - // then - verify(eventsService).createEvent( - anyString(), anyString(), anyString(), eq("lineItemId"), eq(false), any()); - } - @Test public void shouldAddExtPrebidEventsIfEventsAreEnabledAndExtRequestPrebidEventPresent() { // given @@ -2227,7 +2108,7 @@ public void shouldAddExtPrebidEventsIfEventsAreEnabledAndExtRequestPrebidEventPr .auctionParticipations(toAuctionParticipant(bidderResponses))); final Events events = Events.of("http://event-type-win", "http://event-type-view"); - given(eventsService.createEvent(anyString(), anyString(), anyString(), any(), anyBoolean(), any())) + given(eventsService.createEvent(anyString(), anyString(), anyString(), anyBoolean(), any())) .willReturn(events); final BidRequestCacheInfo cacheInfo = BidRequestCacheInfo.builder().doCaching(true).build(); @@ -2284,7 +2165,7 @@ public void shouldAddExtPrebidEventsIfEventsAreEnabledAndAccountSupportEventsFor .auctionParticipations(toAuctionParticipant(bidderResponses))); final Events events = Events.of("http://event-type-win", "http://event-type-view"); - given(eventsService.createEvent(anyString(), anyString(), anyString(), any(), anyBoolean(), any())) + given(eventsService.createEvent(anyString(), anyString(), anyString(), anyBoolean(), any())) .willReturn(events); // when @@ -2331,7 +2212,7 @@ public void shouldAddExtPrebidEventsIfEventsAreEnabledAndDefaultAccountAnalytics .auctionParticipations(toAuctionParticipant(bidderResponses))); final Events events = Events.of("http://event-type-win", "http://event-type-view"); - given(eventsService.createEvent(anyString(), anyString(), anyString(), any(), anyBoolean(), any())) + given(eventsService.createEvent(anyString(), anyString(), anyString(), anyBoolean(), any())) .willReturn(events); // when @@ -2762,7 +2643,6 @@ public void shouldPopulateBidResponseExtension() { assertThat(responseExt.getDebug()).isNull(); assertThat(responseExt.getWarnings()) .containsEntry("bidder1", singletonList(ExtBidderError.of(999, "some_warning"))); - assertThat(responseExt.getUsersync()).isNull(); assertThat(responseExt.getTmaxrequest()).isEqualTo(1000L); assertThat(responseExt.getErrors()).hasSize(2).containsOnly( @@ -3089,7 +2969,7 @@ public void shouldPassIntegrationToCacheServiceAndBidEvents() { givenCacheServiceResult(singletonList(CacheInfo.empty())); - given(eventsService.createEvent(anyString(), anyString(), anyString(), any(), anyBoolean(), any())) + given(eventsService.createEvent(anyString(), anyString(), anyString(), anyBoolean(), any())) .willReturn(Events.of( "http://win-url?param=value&int=integration", "http://imp-url?param=value&int=integration")); @@ -3109,41 +2989,6 @@ public void shouldPassIntegrationToCacheServiceAndBidEvents() { "http://imp-url?param=value&int=integration")); } - @Test - public void shouldPopulateExtensionResponseDebugAndDeepDebugLogIfEnabled() { - // given - final DeepDebugLog deepDebugLog = DeepDebugLog.create(true, clock); - deepDebugLog.add("line-item-id-1", pacing, () -> "test-1"); - deepDebugLog.add("line-item-id-2", targeting, () -> "test-2"); - deepDebugLog.add("", targeting, () -> "test-3"); - - final Bid bid = Bid.builder().id("bidId1").price(BigDecimal.valueOf(5.67)).impid(IMP_ID).build(); - final List bidderResponses = singletonList(BidderResponse.of("bidder1", - givenSeatBid(BidderBid.of(bid, banner, "USD")), 100)); - - final AuctionContext auctionContext = givenAuctionContext( - givenBidRequest(givenImp()), - builder -> builder - .deepDebugLog(deepDebugLog) - .auctionParticipations(toAuctionParticipant(bidderResponses))); - - // when - final BidResponse bidResponse = bidResponseCreator.create(auctionContext, CACHE_INFO, MULTI_BIDS).result(); - - // then - final ExtDebugTrace extDebugTrace = bidResponse.getExt().getDebug().getTrace(); - - assertThat(extDebugTrace.getDeals()) - .containsExactly(ExtTraceDeal.of("", ZonedDateTime.now(clock), targeting, "test-3")); - - assertThat(extDebugTrace.getLineItems()) - .containsExactly( - entry("line-item-id-1", List.of(ExtTraceDeal.of("line-item-id-1", - ZonedDateTime.now(clock), pacing, "test-1"))), - entry("line-item-id-2", List.of(ExtTraceDeal.of("line-item-id-2", - ZonedDateTime.now(clock), targeting, "test-2")))); - } - @Test public void shouldPopulateActivityInfrastructureTraceLogOnSpecifiedTraceLevel() { // given @@ -3184,26 +3029,6 @@ public void shouldPopulateActivityInfrastructureTraceLogOnSpecifiedTraceLevel() .isEqualTo(traceLog); } - @Test - public void shouldBidResponseDebugReturnNullIfDeepDebugLogIsEnabledAndNotPopulated() { - // given - final Bid bid = Bid.builder().id("bidId1").price(BigDecimal.valueOf(5.67)).impid(IMP_ID).build(); - final List bidderResponses = singletonList(BidderResponse.of("bidder1", - givenSeatBid(BidderBid.of(bid, banner, "USD")), 100)); - - final AuctionContext auctionContext = givenAuctionContext( - givenBidRequest(givenImp()), - builder -> builder - .deepDebugLog(DeepDebugLog.create(true, clock)) - .auctionParticipations(toAuctionParticipant(bidderResponses))); - - // when - final BidResponse bidResponse = bidResponseCreator.create(auctionContext, CACHE_INFO, MULTI_BIDS).result(); - - // then - assertThat(bidResponse.getExt().getDebug()).isNull(); - } - @Test public void shouldPopulateBidResponseExtErrorIfImpExtIsInvalid() { // given @@ -3398,7 +3223,7 @@ public void shouldPopulateEventsContextForRequestIfEventsEnabledForRequest() { final Events givenEvents = Events.of( "http://win-url?auctionId=123×tamp=1000", "http://imp-url?auctionId=123×tamp=1000"); - given(eventsService.createEvent(anyString(), anyString(), anyString(), any(), anyBoolean(), any())) + given(eventsService.createEvent(anyString(), anyString(), anyString(), anyBoolean(), any())) .willReturn(givenEvents); // when @@ -3767,18 +3592,13 @@ public void shouldPopulateBidExtWhenExtMediaTypePriceGranularityHasValidxNativeE .includebidderkeys(true) .build(); - final TxnLog txnLog = TxnLog.create(); - txnLog.lineItemsSentToBidder(); - final Bid bid = Bid.builder().id("bidId").price(BigDecimal.valueOf(5.67)).impid(IMP_ID).build(); final List bidderResponses = singletonList(BidderResponse.of("bidder1", givenSeatBid(BidderBid.of(bid, banner, "USD")), 100)); - final AuctionContext auctionContext = givenAuctionContext(givenBidRequest( - identity(), extBuilder -> extBuilder.targeting(targeting), givenImp()), - auctionContextBuilder -> auctionContextBuilder - .txnLog(txnLog) - .auctionParticipations(toAuctionParticipant(bidderResponses))); + final AuctionContext auctionContext = givenAuctionContext( + givenBidRequest(identity(), extBuilder -> extBuilder.targeting(targeting), givenImp()), + context -> context.auctionParticipations(toAuctionParticipant(bidderResponses))); // when final BidResponse bidResponse = bidResponseCreator.create(auctionContext, CACHE_INFO, MULTI_BIDS).result(); @@ -3880,10 +3700,8 @@ private AuctionContext givenAuctionContext(BidRequest bidRequest, final AuctionContext.AuctionContextBuilder auctionContextBuilder = AuctionContext.builder() .account(Account.empty("accountId")) .bidRequest(bidRequest) - .txnLog(TxnLog.create()) .timeoutContext(TimeoutContext.of(0, timeout, 0)) .debugContext(DebugContext.empty()) - .deepDebugLog(DeepDebugLog.create(false, clock)) .debugHttpCalls(new HashMap<>()) .debugWarnings(emptyList()) .auctionParticipations(emptyList()) diff --git a/src/test/java/org/prebid/server/auction/ExchangeServiceTest.java b/src/test/java/org/prebid/server/auction/ExchangeServiceTest.java index e0aa389eb79..08651a9ed12 100644 --- a/src/test/java/org/prebid/server/auction/ExchangeServiceTest.java +++ b/src/test/java/org/prebid/server/auction/ExchangeServiceTest.java @@ -1,7 +1,6 @@ package org.prebid.server.auction; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.BooleanNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; import com.iab.openrtb.request.App; @@ -32,7 +31,6 @@ import com.iab.openrtb.response.SeatBid; import io.vertx.core.Future; import org.apache.commons.collections4.MapUtils; -import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -69,10 +67,6 @@ import org.prebid.server.bidder.model.BidderSeatBid; import org.prebid.server.cookie.UidsCookie; import org.prebid.server.currency.CurrencyConversionService; -import org.prebid.server.deals.DealsService; -import org.prebid.server.deals.events.ApplicationEventService; -import org.prebid.server.deals.model.DeepDebugLog; -import org.prebid.server.deals.model.TxnLog; import org.prebid.server.exception.InvalidRequestException; import org.prebid.server.exception.PreBidException; import org.prebid.server.execution.Timeout; @@ -109,8 +103,6 @@ import org.prebid.server.proto.openrtb.ext.request.ExtAppPrebid; import org.prebid.server.proto.openrtb.ext.request.ExtBidderConfig; import org.prebid.server.proto.openrtb.ext.request.ExtBidderConfigOrtb; -import org.prebid.server.proto.openrtb.ext.request.ExtDeal; -import org.prebid.server.proto.openrtb.ext.request.ExtDealLine; import org.prebid.server.proto.openrtb.ext.request.ExtDooh; import org.prebid.server.proto.openrtb.ext.request.ExtGranularityRange; import org.prebid.server.proto.openrtb.ext.request.ExtImpAuctionEnvironment; @@ -197,7 +189,6 @@ import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.ArgumentMatchers.same; import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.willReturn; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyList; import static org.mockito.Mockito.doAnswer; @@ -224,9 +215,6 @@ public class ExchangeServiceTest extends VertxTest { @Mock private StoredResponseProcessor storedResponseProcessor; - @Mock - private DealsService dealsService; - @Mock private PrivacyEnforcementService privacyEnforcementService; @@ -272,9 +260,6 @@ public class ExchangeServiceTest extends VertxTest { @Mock private HookStageExecutor hookStageExecutor; - @Mock - private ApplicationEventService applicationEventService; - @Mock private HttpInteractionLogger httpInteractionLogger; @@ -394,9 +379,6 @@ public void setUp() { given(storedResponseProcessor.updateStoredBidResponse(any())) .willAnswer(inv -> inv.getArgument(0)); - given(dealsService.matchAndPopulateDeals(any(), any(), any())) - .willAnswer(inv -> inv.getArgument(0)); - given(priceFloorEnforcer.enforce(any(), any(), any(), any())).willAnswer(inv -> inv.getArgument(1)); given(dsaEnforcer.enforce(any(), any(), any())).willAnswer(inv -> inv.getArgument(1)); given(priceFloorAdjuster.adjustForImp(any(), any(), any(), any())) @@ -697,88 +679,6 @@ public void shouldPassRequestModifiedByRawBidderResponseHooks() { .containsOnly(hookChangedBid); } - @Test - public void shouldFilterPgDealsOnlyBiddersWithoutDeals() { - // given - final Bidder bidder1 = mock(Bidder.class); - final Bidder bidder2 = mock(Bidder.class); - givenBidder("bidder1", bidder1, givenEmptySeatBid()); - givenBidder("bidder2", bidder2, givenEmptySeatBid()); - - final BidRequest bidRequest = givenBidRequest(asList( - givenImp( - Map.of( - "bidder1", mapper.valueToTree("traceToken"), - "bidder2", mapper.createObjectNode().set("pgdealsonly", BooleanNode.getTrue())), - imp -> imp.id("imp1")), - givenImp( - singletonMap("bidder2", mapper.createObjectNode().set("pgdealsonly", BooleanNode.getTrue())), - imp -> imp.id("imp2")))); - - // when - final Future result = target.holdAuction(givenRequestContext(bidRequest)); - - // then - final ArgumentCaptor bidRequestCaptor = ArgumentCaptor.forClass(BidderRequest.class); - verify(httpBidderRequester, times(1)) - .requestBids(any(), bidRequestCaptor.capture(), any(), any(), any(), any(), anyBoolean()); - - assertThat(bidRequestCaptor.getValue().getBidRequest().getImp()).hasSize(1) - .extracting(imp -> imp.getExt().get("bidder").asText()) - .containsExactly("traceToken"); - - assertThat(result.result().getDebugWarnings()).containsExactly(""" - Not calling bidder2 bidder for impressions imp1, imp2 \ - due to pgdealsonly flag and no available PG line items."""); - } - - @Test - public void shouldFillAuctionContextWithMatchedDeals() { - // given - final Bidder bidder1 = mock(Bidder.class); - final Bidder bidder2 = mock(Bidder.class); - givenBidder("bidder1", bidder1, givenEmptySeatBid()); - givenBidder("bidder2", bidder2, givenEmptySeatBid()); - - final BidRequest bidRequest = givenBidRequest(asList( - givenImp(singletonMap("bidder1", mapper.createObjectNode()), imp -> imp.id("imp1")), - givenImp(singletonMap("bidder2", mapper.createObjectNode()), imp -> imp.id("imp2")))); - - given(dealsService.matchAndPopulateDeals(any(), any(), any())) - .willAnswer(arguments -> { - final BidderRequest bidderRequest = arguments.getArgument(0); - final Map> impIdToDeals = switch (bidderRequest.getBidder()) { - case "bidder1" -> singletonMap("imp1", singletonList(Deal.builder().id("deal1").build())); - case "bidder2" -> singletonMap("imp2", singletonList(Deal.builder().id("deal2").build())); - default -> null; - }; - - return bidderRequest.toBuilder().impIdToDeals(impIdToDeals).build(); - }); - - // when - final Future result = target.holdAuction(givenRequestContext(bidRequest)); - - // then - assertThat(result.result()) - .extracting(AuctionContext::getBidRequest) - .extracting(BidRequest::getImp) - .satisfies(imps -> { - assertThat(imps.get(0)) - .extracting(Imp::getPmp) - .extracting(Pmp::getDeals) - .asInstanceOf(InstanceOfAssertFactories.list(Deal.class)) - .containsExactly(Deal.builder().id("deal1").build()); - - assertThat(imps.get(1)) - .extracting(Imp::getPmp) - .extracting(Pmp::getDeals) - .asInstanceOf(InstanceOfAssertFactories.list(Deal.class)) - .containsExactly(Deal.builder().id("deal2").build()); - }); - - } - @Test public void shouldPassRequestWithExtPrebidToDefinedBidder() { // given @@ -1382,7 +1282,7 @@ public void shouldOverrideDebugEnabledFlag() { .willReturn(Future.succeededFuture( BidResponse.builder() .ext(ExtBidResponse.builder() - .debug(ExtResponseDebug.of(null, null, null, null)) + .debug(ExtResponseDebug.of(null, null, null)) .build()) .build())); @@ -1412,7 +1312,7 @@ public void shouldAddDebugInfoIfDebugEnabledAndPublisherAndBidderAllowedDebug() .willReturn(Future.succeededFuture( BidResponse.builder() .ext(ExtBidResponse.builder() - .debug(ExtResponseDebug.of(null, null, null, null)) + .debug(ExtResponseDebug.of(null, null, null)) .build()) .build())); @@ -2792,12 +2692,12 @@ public void shouldUseConcreteOverGeneralSiteWithExtPrebidBidderConfigIgnoringCas final ObjectNode siteWithPage = mapper.valueToTree(Site.builder().page("testPage").build()); final ExtBidderConfig extBidderConfig = ExtBidderConfig.of( - null, ExtBidderConfigOrtb.of(siteWithPage, null, null, null)); + ExtBidderConfigOrtb.of(siteWithPage, null, null, null)); final ExtRequestPrebidBidderConfig concreteFpdConfig = ExtRequestPrebidBidderConfig.of( singletonList("SoMeBiDdEr"), extBidderConfig); final ObjectNode siteWithDomain = mapper.valueToTree(Site.builder().domain("notUsed").build()); final ExtBidderConfig allExtBidderConfig = ExtBidderConfig.of( - null, ExtBidderConfigOrtb.of(siteWithDomain, null, null, null)); + ExtBidderConfigOrtb.of(siteWithDomain, null, null, null)); final ExtRequestPrebidBidderConfig allFpdConfig = ExtRequestPrebidBidderConfig.of(singletonList("*"), allExtBidderConfig); @@ -2839,12 +2739,12 @@ public void shouldUseConcreteOverGeneralDoohWithExtPrebidBidderConfig() { final ObjectNode doohWithVenueType = mapper.valueToTree(Dooh.builder().venuetype(List.of("venuetype")).build()); final ExtBidderConfig extBidderConfig = ExtBidderConfig.of( - null, ExtBidderConfigOrtb.of(null, null, doohWithVenueType, null)); + ExtBidderConfigOrtb.of(null, null, doohWithVenueType, null)); final ExtRequestPrebidBidderConfig concreteFpdConfig = ExtRequestPrebidBidderConfig.of( singletonList("someBidder"), extBidderConfig); final ObjectNode doohWithDomain = mapper.valueToTree(Dooh.builder().domain("notUsed").build()); final ExtBidderConfig allExtBidderConfig = ExtBidderConfig.of( - null, ExtBidderConfigOrtb.of(null, null, doohWithDomain, null)); + ExtBidderConfigOrtb.of(null, null, doohWithDomain, null)); final ExtRequestPrebidBidderConfig allFpdConfig = ExtRequestPrebidBidderConfig.of( singletonList("*"), allExtBidderConfig); @@ -2888,7 +2788,7 @@ public void shouldUseConcreteOverGeneralAppWithExtPrebidBidderConfigIgnoringCase final Publisher publisherWithId = Publisher.builder().id("testId").build(); final ObjectNode appWithPublisherId = mapper.valueToTree(App.builder().publisher(publisherWithId).build()); final ExtBidderConfig extBidderConfig = ExtBidderConfig.of( - null, ExtBidderConfigOrtb.of(null, appWithPublisherId, null, null)); + ExtBidderConfigOrtb.of(null, appWithPublisherId, null, null)); final ExtRequestPrebidBidderConfig concreteFpdConfig = ExtRequestPrebidBidderConfig.of( singletonList("SoMeBiDdEr"), extBidderConfig); @@ -2896,7 +2796,7 @@ public void shouldUseConcreteOverGeneralAppWithExtPrebidBidderConfigIgnoringCase final ObjectNode appWithUpdatedPublisher = mapper.valueToTree( App.builder().publisher(publisherWithIdAndDomain).build()); final ExtBidderConfig allExtBidderConfig = ExtBidderConfig.of( - null, ExtBidderConfigOrtb.of(null, appWithUpdatedPublisher, null, null)); + ExtBidderConfigOrtb.of(null, appWithUpdatedPublisher, null, null)); final ExtRequestPrebidBidderConfig allFpdConfig = ExtRequestPrebidBidderConfig.of(singletonList("*"), allExtBidderConfig); @@ -2935,13 +2835,13 @@ public void shouldUseConcreteOverGeneralUserWithExtPrebidBidderConfig() { givenBidder("someBidder", bidder, givenEmptySeatBid()); final ObjectNode bidderConfigUser = mapper.valueToTree(User.builder().id("userFromConfig").build()); final ExtBidderConfig extBidderConfig = ExtBidderConfig.of( - null, ExtBidderConfigOrtb.of(null, null, null, bidderConfigUser)); + ExtBidderConfigOrtb.of(null, null, null, bidderConfigUser)); final ExtRequestPrebidBidderConfig concreteFpdConfig = ExtRequestPrebidBidderConfig.of( singletonList("SomMeBiDdEr"), extBidderConfig); final ObjectNode emptyUser = mapper.valueToTree(User.builder().build()); final ExtBidderConfig allExtBidderConfig = ExtBidderConfig.of( - null, ExtBidderConfigOrtb.of(null, null, null, emptyUser)); + ExtBidderConfigOrtb.of(null, null, null, emptyUser)); final ExtRequestPrebidBidderConfig allFpdConfig = ExtRequestPrebidBidderConfig.of(singletonList("*"), allExtBidderConfig); final User requestUser = User.builder().id("erased").buyeruid("testBuyerId").build(); @@ -4466,74 +4366,6 @@ public void shouldIncrementHooksGlobalAndAccountMetrics() { verify(metrics).updateAccountModuleDurationMetric(any(), eq("module3"), eq(8L)); } - @Test - public void shouldTolerateBidWithDealThatHasNoLineItemAssociated() { - // given - givenBidder(givenSingleSeatBid(givenBidderBid( - Bid.builder().impid("impId").dealid("dealId").price(BigDecimal.ONE).build()))); - - final BidRequest bidRequest = givenBidRequest(givenSingleImp(singletonMap("someBidder", 1)), identity()); - final AuctionContext auctionContext = givenRequestContext(bidRequest); - - // when - target.holdAuction(auctionContext); - - // then - final ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(AuctionContext.class); - verify(applicationEventService).publishAuctionEvent(argumentCaptor.capture()); - final TxnLog txnLog = argumentCaptor.getValue().getTxnLog(); - - assertThat(txnLog).isEqualTo(TxnLog.create()); - } - - @Test - public void shouldRecordLineItemMetricsInTransactionLog() { - // given - givenBidder(givenSeatBid(asList( - givenBidderBid(Bid.builder().impid("impId").dealid("dealId1").price(BigDecimal.ONE).build()), - givenBidderBid(Bid.builder().impid("impId").dealid("dealId2").price(BigDecimal.ONE).build())))); - - willReturn(ValidationResult.success()).given(responseBidValidator) - .validate(argThat(bid -> bid.getBid().getDealid().equals("dealId1")), any(), any(), any()); - willReturn(ValidationResult.error("validation error")).given(responseBidValidator) - .validate(argThat(bid -> bid.getBid().getDealid().equals("dealId2")), any(), any(), any()); - - final List deals = asList( - Deal.builder() - .id("dealId1") - .ext(mapper.valueToTree(ExtDeal.of( - ExtDealLine.of("lineItemId1", null, null, "someBidder")))) - .build(), - Deal.builder() - .id("dealId2") - .ext(mapper.valueToTree(ExtDeal.of( - ExtDealLine.of("lineItemId2", null, null, "someBidder")))) - .build()); - final Imp imp = givenImp( - singletonMap("someBidder", 1), - builder -> builder - .id("impId") - .pmp(Pmp.builder() - .deals(deals) - .build())); - final BidRequest bidRequest = givenBidRequest(singletonList(imp), identity()); - final AuctionContext auctionContext = givenRequestContext(bidRequest); - - // when - target.holdAuction(auctionContext); - - // then - final ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(AuctionContext.class); - verify(applicationEventService).publishAuctionEvent(argumentCaptor.capture()); - final TxnLog txnLog = argumentCaptor.getValue().getTxnLog(); - - final TxnLog expectedTxnLog = TxnLog.create(); - expectedTxnLog.lineItemsReceivedFromBidder().get("someBidder").addAll(asList("lineItemId1", "lineItemId2")); - expectedTxnLog.lineItemsResponseInvalidated().add("lineItemId2"); - - assertThat(txnLog).isEqualTo(expectedTxnLog); - } - @Test public void shouldProperPopulateImpExtPrebidEvenIfInExtImpPrebidContainNotCorrectField() { // given @@ -4621,27 +4453,6 @@ public void shouldReturnsSourceWithCorrespondingRequestExtPrebidSchainsIfSchainI .isEqualTo(givenSourceSchain); } - @Test - public void shouldNotModifyOriginalDealsIfDealsFromLineItemServiceAreMissing() { - // given - final Pmp pmp = Pmp.builder() - .deals(singletonList(Deal.builder().id("dealId1").build())) // deal from prebid request (not from PG) - .build(); - final BidRequest bidRequest = givenBidRequest(singletonList(givenImp(singletonMap("someBidder", 1), - builder -> builder.pmp(pmp))), identity()); - final AuctionContext auctionContext = givenRequestContext(bidRequest).toBuilder() - .build(); - - // when - target.holdAuction(auctionContext); - - // then - final BidRequest capturedBidRequest = captureBidRequest(); - assertThat(capturedBidRequest.getImp()) - .extracting(Imp::getPmp) - .containsExactly(pmp); - } - @Test public void shouldReduceBidsHavingDealIdWithSameImpIdByBidderWithToleratingNotObtainedBidWithTopDeal() { // given @@ -4807,7 +4618,6 @@ private void givenTarget(boolean enabledStrictAppSiteDoohValidation) { 0, bidderCatalog, storedResponseProcessor, - dealsService, privacyEnforcementService, fpdResolver, supplyChainResolver, @@ -4823,7 +4633,6 @@ private void givenTarget(boolean enabledStrictAppSiteDoohValidation) { bidResponseCreator, bidResponsePostProcessor, hookStageExecutor, - applicationEventService, httpInteractionLogger, priceFloorAdjuster, priceFloorEnforcer, @@ -4858,8 +4667,6 @@ private AuctionContext givenRequestContext(BidRequest bidRequest, Account accoun .timeoutContext(TimeoutContext.of(clock.millis(), timeout, 90)) .hookExecutionContext(HookExecutionContext.of(Endpoint.openrtb2_auction)) .debugContext(DebugContext.empty()) - .txnLog(TxnLog.create()) - .deepDebugLog(DeepDebugLog.create(false, clock)) .bidRejectionTrackers(new HashMap<>()) .activityInfrastructure(activityInfrastructure) .build(); diff --git a/src/test/java/org/prebid/server/auction/ImplicitParametersExtractorTest.java b/src/test/java/org/prebid/server/auction/ImplicitParametersExtractorTest.java index 7e411d08191..4a02223cc7e 100644 --- a/src/test/java/org/prebid/server/auction/ImplicitParametersExtractorTest.java +++ b/src/test/java/org/prebid/server/auction/ImplicitParametersExtractorTest.java @@ -163,39 +163,6 @@ public void uaFromShouldReturnUaFromUserAgentHeader() { assertThat(extractor.uaFrom(httpRequest)).isEqualTo("user agent"); } - @Test - public void secureFromShouldReturnOneIfXForwardedProtoIsHttps() { - // given - final HttpRequestContext httpRequest = HttpRequestContext.builder() - .headers(CaseInsensitiveMultiMap.builder() - .add("X-Forwarded-Proto", "https") - .build()) - .build(); - - // when and then - assertThat(extractor.secureFrom(httpRequest)).isEqualTo(1); - } - - @Test - public void secureFromShouldReturnOneIfConnectedViaSSL() { - // given - final HttpRequestContext httpRequest = HttpRequestContext.builder() - .headers(CaseInsensitiveMultiMap.empty()) - .scheme("https") - .build(); - - // when and then - assertThat(extractor.secureFrom(httpRequest)).isEqualTo(1); - } - - @Test - public void secureFromShouldReturnNull() { - final HttpRequestContext httpRequest = HttpRequestContext.builder() - .headers(CaseInsensitiveMultiMap.empty()) - .build(); - assertThat(extractor.secureFrom(httpRequest)).isNull(); - } - @Test public void gpcFromShouldReturn1OnInteger() { // given diff --git a/src/test/java/org/prebid/server/auction/WinningBidComparatorFactoryTest.java b/src/test/java/org/prebid/server/auction/WinningBidComparatorFactoryTest.java index 57d5ecbea2a..3716bc7b92e 100644 --- a/src/test/java/org/prebid/server/auction/WinningBidComparatorFactoryTest.java +++ b/src/test/java/org/prebid/server/auction/WinningBidComparatorFactoryTest.java @@ -1,18 +1,14 @@ package org.prebid.server.auction; -import com.iab.openrtb.request.Deal; import com.iab.openrtb.request.Imp; -import com.iab.openrtb.request.Pmp; import com.iab.openrtb.response.Bid; import org.junit.Test; import org.prebid.server.auction.model.BidInfo; import java.math.BigDecimal; -import java.util.Arrays; import java.util.List; -import static java.util.Collections.emptyList; -import static java.util.Collections.singletonList; +import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; public class WinningBidComparatorFactoryTest { @@ -60,10 +56,10 @@ public void preferDealsComparatorCompareShouldReturnZeroWhenPriceAreEqualForNonD } @Test - public void preferDealsComparatorCompareShouldReturnMoreThanZeroWhenFirstHasNonPgDeal() { + public void preferDealsComparatorCompareShouldReturnMoreThanZeroWhenFirstHasDeal() { // given - final BidInfo dealPriceBidInfo = givenBidInfo(5.0f, "dealId", emptyList()); - final BidInfo higherPriceBidInfo = givenBidInfo(10.0f, null, emptyList()); + final BidInfo dealPriceBidInfo = givenBidInfo(1.0f, "dealId"); + final BidInfo higherPriceBidInfo = givenBidInfo(5.0f); // when final int result = winningBidComparatorFactory.create(true).compare(dealPriceBidInfo, higherPriceBidInfo); @@ -73,10 +69,10 @@ public void preferDealsComparatorCompareShouldReturnMoreThanZeroWhenFirstHasNonP } @Test - public void preferDealsComparatorCompareShouldReturnLessThanZeroWhenFirstHasNoDeal() { + public void preferDealsComparatorCompareShouldReturnLessThanZeroWhenSecondHasDeal() { // given - final BidInfo higherPriceBidInfo = givenBidInfo(10.0f, null, emptyList()); - final BidInfo dealPriceBidInfo = givenBidInfo(5.0f, "dealId", emptyList()); + final BidInfo higherPriceBidInfo = givenBidInfo(5.0f); + final BidInfo dealPriceBidInfo = givenBidInfo(1.0f, "dealId"); // when final int result = winningBidComparatorFactory.create(true).compare(higherPriceBidInfo, dealPriceBidInfo); @@ -86,117 +82,64 @@ public void preferDealsComparatorCompareShouldReturnLessThanZeroWhenFirstHasNoDe } @Test - public void preferDealsComparatorCompareShouldReturnZeroWhenBothHaveNonPgDeals() { - // given - final BidInfo bidInfo1 = givenBidInfo(5.0f, "dealId", emptyList()); - final BidInfo bidInfo2 = givenBidInfo(5.0f, "dealId", emptyList()); - - // when - final int result = winningBidComparatorFactory.create(true).compare(bidInfo1, bidInfo2); - - // then - assertThat(result).isEqualTo(0); - } - - @Test - public void preferDealsComparatorCompareShouldReturnZeroWhenBothHaveSamePgDealIdAndHasSamePrice() { + public void preferDealsComparatorCompareShouldReturnMoreThanZeroWhenBothHaveDealsAndFirstHasHigherPrice() { // given - final List impDeals = singletonList("dealId"); - final BidInfo bidInfo1 = givenBidInfo(5.0f, "dealId", impDeals); - final BidInfo bidInfo2 = givenBidInfo(5.0f, "dealId", impDeals); + final BidInfo higherPriceBidInfo = givenBidInfo(5.0f, "dealId1"); + final BidInfo lowerPriceBidInfo = givenBidInfo(1.0f, "dealId2"); // when - final int result = winningBidComparatorFactory.create(true).compare(bidInfo1, bidInfo2); - - // then - assertThat(result).isEqualTo(0); - } - - @Test - public void preferDealsComparatorCompareShouldReturnMoreThanZeroWhenBothHaveSamePgDealIdAndFirstHasHigherPrice() { - // given - final List impDeals = singletonList("dealId"); - final BidInfo bidInfo1 = givenBidInfo(10.0f, "dealId", impDeals); - final BidInfo bidInfo2 = givenBidInfo(5.0f, "dealId", impDeals); - - // when - final int result = winningBidComparatorFactory.create(true).compare(bidInfo1, bidInfo2); + final int result = winningBidComparatorFactory.create(true).compare(higherPriceBidInfo, lowerPriceBidInfo); // then assertThat(result).isGreaterThan(0); } @Test - public void preferDealsComparatorShouldReturnLessThanZeroWhenFirstHasHigherPriceAndSecondHasLessImpPgDealIndex() { - // given - final List impDeals = Arrays.asList("dealId1", "dealId2"); - final BidInfo bidInfo1 = givenBidInfo(10.0f, "dealId2", impDeals); - final BidInfo bidInfo2 = givenBidInfo(5.0f, "dealId1", impDeals); - - // when - final int result = winningBidComparatorFactory.create(true).compare(bidInfo1, bidInfo2); - - // then - assertThat(result).isLessThan(0); - } - - @Test - public void preferDealsComparatorShouldReturnLessThanZeroWhenFirstIsNonPgDealWithHigherPriceAndSecondPgDeal() { + public void preferDealsComparatorCompareShouldReturnLessThanZeroWhenBothHaveDealsAndFirstHasLowerPrice() { // given - final List impDeals = singletonList("dealId1"); - final BidInfo bidInfo1 = givenBidInfo(10.0f, "dealId2", impDeals); - final BidInfo bidInfo2 = givenBidInfo(5.0f, "dealId1", impDeals); + final BidInfo lowerPriceBidInfo = givenBidInfo(1.0f, "dealId1"); + final BidInfo higherPriceBidInfo = givenBidInfo(5.0f, "dealId2"); // when - final int result = winningBidComparatorFactory.create(true).compare(bidInfo1, bidInfo2); + final int result = winningBidComparatorFactory.create(true).compare(lowerPriceBidInfo, higherPriceBidInfo); // then assertThat(result).isLessThan(0); } @Test - public void preferDealsComparatorShouldReturnGreaterThanZeroWhenFirstPgDealAndSecondMonPgDeal() { + public void preferDealsComparatorCompareShouldReturnZeroWhenBothHaveDealsAndPriceAreEqual() { // given - final List impDeals = singletonList("dealId2"); - final BidInfo bidInfo1 = givenBidInfo(5.0f, "dealId2", impDeals); - final BidInfo bidInfo2 = givenBidInfo(10.0f, "dealId1", impDeals); + final BidInfo bidInfo1 = givenBidInfo(5.0f, "dealId1"); + final BidInfo bidInfo2 = givenBidInfo(5.0f, "dealId2"); // when final int result = winningBidComparatorFactory.create(true).compare(bidInfo1, bidInfo2); // then - assertThat(result).isGreaterThan(0); + assertThat(result).isEqualTo(0); } @Test public void preferDealsComparatorSortShouldReturnExpectedSortedResultWithDeals() { // given - final String dealId1 = "pgDealId1"; - final String dealId2 = "pgDealId2"; - final List impDeals = Arrays.asList(dealId1, dealId2); - - final BidInfo bidInfo1 = givenBidInfo(1.0f, dealId1, impDeals); // pg deal with lower price - final BidInfo bidInfo2 = givenBidInfo(2.0f, dealId1, impDeals); // pg deal with middle price - final BidInfo bidInfo3 = givenBidInfo(4.1f, dealId2, impDeals); // pg deal with higher price - final BidInfo bidInfo4 = givenBidInfo(5.0f, null, impDeals); // non deal with lower price - final BidInfo bidInfo5 = givenBidInfo(100.1f, null, impDeals); // non deal with higher price - final BidInfo bidInfo6 = givenBidInfo(0.5f, "dealId1", impDeals); // non pg deal with lower price - final BidInfo bidInfo7 = givenBidInfo(1f, "dealId2", impDeals); // non pg deal with middle price - final BidInfo bidInfo8 = givenBidInfo(4.4f, "dealId3", impDeals); // non pg deal with higher price - - final List bidInfos = Arrays.asList(bidInfo5, bidInfo3, bidInfo1, bidInfo2, bidInfo1, bidInfo4, - bidInfo6, bidInfo7, bidInfo8); + final BidInfo bidInfo1 = givenBidInfo(5.0f); // non deal with lower price + final BidInfo bidInfo2 = givenBidInfo(100.1f); // non deal with higher price + final BidInfo bidInfo3 = givenBidInfo(0.5f, "dealId1"); // deal with lower price + final BidInfo bidInfo4 = givenBidInfo(1f, "dealId2"); // deal with middle price + final BidInfo bidInfo5 = givenBidInfo(6f, "dealId3"); // deal with higher price + + final List bidInfos = asList(bidInfo5, bidInfo4, bidInfo2, bidInfo3, bidInfo1, bidInfo2); // when bidInfos.sort(winningBidComparatorFactory.create(true)); // then - assertThat(bidInfos).containsOnly(bidInfo4, bidInfo5, bidInfo6, bidInfo7, bidInfo8, bidInfo3, bidInfo2, - bidInfo1, bidInfo1); + assertThat(bidInfos).containsExactly(bidInfo1, bidInfo2, bidInfo2, bidInfo3, bidInfo4, bidInfo5); } @Test - public void priceComparatorCompareShouldReturnMoreThatZeroWhenFirstHasHigherPriceForNonDealsBids() { + public void priceComparatorCompareShouldReturnMoreThatZeroWhenFirstHasHigherPrice() { // given final BidInfo higherPriceBidInfo = givenBidInfo(5.0f); final BidInfo lowerPriceBidInfo = givenBidInfo(1.0f); @@ -209,7 +152,7 @@ public void priceComparatorCompareShouldReturnMoreThatZeroWhenFirstHasHigherPric } @Test - public void priceComparatorCompareShouldReturnLessThatZeroWhenFirstHasLowerPriceForNonDealsBids() { + public void priceComparatorCompareShouldReturnLessThatZeroWhenFirstHasLowerPrice() { // given final BidInfo lowerPriceBidInfo = givenBidInfo(1.0f); final BidInfo higherPriceBidInfo = givenBidInfo(5.0f); @@ -234,140 +177,22 @@ public void priceComparatorCompareShouldReturnZeroWhenPriceAreEqualForNonDealsBi assertThat(result).isEqualTo(0); } - @Test - public void preferPriceComparatorCompareShouldReturnLessThanZeroWhenFirstHasNonPgDeal() { - // given - final BidInfo dealPriceBidInfo = givenBidInfo(5.0f, "dealId", emptyList()); - final BidInfo higherPriceBidInfo = givenBidInfo(10.0f, null, emptyList()); - - // when - final int result = winningBidComparatorFactory.create(false).compare(dealPriceBidInfo, higherPriceBidInfo); - - // then - assertThat(result).isLessThan(0); - } - - @Test - public void preferPriceComparatorCompareShouldReturnGreaterThanZeroWhenFirstHasNoDeal() { - // given - final BidInfo higherPriceBidInfo = givenBidInfo(10.0f, null, emptyList()); - final BidInfo dealPriceBidInfo = givenBidInfo(5.0f, "dealId", emptyList()); - - // when - final int result = winningBidComparatorFactory.create(false).compare(higherPriceBidInfo, dealPriceBidInfo); - - // then - assertThat(result).isGreaterThan(0); - } - - @Test - public void preferPriceComparatorCompareShouldReturnZeroWhenBothHaveNonPgDeals() { - // given - final BidInfo bidInfo1 = givenBidInfo(5.0f, "dealId", emptyList()); - final BidInfo bidInfo2 = givenBidInfo(5.0f, "dealId", emptyList()); - - // when - final int result = winningBidComparatorFactory.create(false).compare(bidInfo1, bidInfo2); - - // then - assertThat(result).isEqualTo(0); - } - - @Test - public void preferPriceComparatorCompareShouldReturnZeroWhenBothHaveSamePgDealIdAndHasSamePrice() { - // given - final List impDeals = singletonList("dealId"); - final BidInfo bidInfo1 = givenBidInfo(5.0f, "dealId", impDeals); - final BidInfo bidInfo2 = givenBidInfo(5.0f, "dealId", impDeals); - - // when - final int result = winningBidComparatorFactory.create(false).compare(bidInfo1, bidInfo2); - - // then - assertThat(result).isEqualTo(0); - } - - @Test - public void preferPriceComparatorCompareShouldReturnMoreThanZeroWhenBothHaveSamePgDealIdAndFirstHasHigherPrice() { - // given - final List impDeals = singletonList("dealId"); - final BidInfo bidInfo1 = givenBidInfo(10.0f, "dealId", impDeals); - final BidInfo bidInfo2 = givenBidInfo(5.0f, "dealId", impDeals); - - // when - final int result = winningBidComparatorFactory.create(false).compare(bidInfo1, bidInfo2); - - // then - assertThat(result).isGreaterThan(0); - } - - @Test - public void preferPriceComparatorShouldReturnLessThanZeroWhenFirstHasHigherPriceAndSecondHasLessImpPgDealIndex() { - // given - final List impDeals = Arrays.asList("dealId1", "dealId2"); - final BidInfo bidInfo1 = givenBidInfo(10.0f, "dealId2", impDeals); - final BidInfo bidInfo2 = givenBidInfo(5.0f, "dealId1", impDeals); - - // when - final int result = winningBidComparatorFactory.create(false).compare(bidInfo1, bidInfo2); - - // then - assertThat(result).isLessThan(0); - } - - @Test - public void preferPriceComparatorShouldReturnLessThanZeroWhenFirstIsNonPgDealWithHigherPriceAndSecondPgDeal() { - // given - final List impDeals = singletonList("dealId1"); - final BidInfo bidInfo1 = givenBidInfo(10.0f, "dealId2", impDeals); - final BidInfo bidInfo2 = givenBidInfo(5.0f, "dealId1", impDeals); - - // when - final int result = winningBidComparatorFactory.create(false).compare(bidInfo1, bidInfo2); - - // then - assertThat(result).isLessThan(0); - } - - @Test - public void preferPriceComparatorShouldReturnGreaterThanZeroWhenFirstPgDealAndSecondMonPgDeal() { - // given - final List impDeals = singletonList("dealId2"); - final BidInfo bidInfo1 = givenBidInfo(5.0f, "dealId2", impDeals); - final BidInfo bidInfo2 = givenBidInfo(10.0f, "dealId1", impDeals); - - // when - final int result = winningBidComparatorFactory.create(false).compare(bidInfo1, bidInfo2); - - // then - assertThat(result).isGreaterThan(0); - } - @Test public void preferPriceComparatorSortShouldReturnExpectedSortedResultWithDeals() { // given - final String dealId1 = "pgDealId1"; - final String dealId2 = "pgDealId2"; - final List impDeals = Arrays.asList(dealId1, dealId2); - - final BidInfo bidInfo1 = givenBidInfo(1.0f, dealId1, impDeals); // pg deal with lower price - final BidInfo bidInfo2 = givenBidInfo(2.0f, dealId1, impDeals); // pg deal with middle price - final BidInfo bidInfo3 = givenBidInfo(4.1f, dealId2, impDeals); // pg deal with higher price - final BidInfo bidInfo4 = givenBidInfo(5.0f, null, impDeals); // non deal with lower price - final BidInfo bidInfo5 = givenBidInfo(100.1f, null, impDeals); // non deal with higher price - final BidInfo bidInfo6 = givenBidInfo(0.5f, "dealId1", impDeals); // non pg deal with lower price - final BidInfo bidInfo7 = givenBidInfo(1f, "dealId2", impDeals); // non pg deal with middle price - final BidInfo bidInfo8 = givenBidInfo(4.4f, "dealId3", impDeals); // non pg deal with higher price - - final List bidInfos = Arrays.asList(bidInfo5, bidInfo3, bidInfo1, bidInfo2, bidInfo1, bidInfo4, - bidInfo6, bidInfo7, bidInfo8); + final BidInfo bidInfo1 = givenBidInfo(5.0f, null); // non deal with lower price + final BidInfo bidInfo2 = givenBidInfo(100.1f, null); // non deal with higher price + final BidInfo bidInfo3 = givenBidInfo(0.5f, "dealId1"); // deal with lower price + final BidInfo bidInfo4 = givenBidInfo(1f, "dealId2"); // deal with middle price + final BidInfo bidInfo5 = givenBidInfo(6f, "dealId3"); // deal with higher price + + final List bidInfos = asList(bidInfo5, bidInfo4, bidInfo2, bidInfo3, bidInfo1, bidInfo2); // when bidInfos.sort(winningBidComparatorFactory.create(false)); // then - assertThat(bidInfos).containsOnly(bidInfo6, bidInfo7, bidInfo8, bidInfo4, bidInfo5, bidInfo1, - bidInfo1, bidInfo2, bidInfo3); + assertThat(bidInfos).containsExactly(bidInfo3, bidInfo4, bidInfo1, bidInfo5, bidInfo2, bidInfo2); } private static BidInfo givenBidInfo(float price) { @@ -381,16 +206,4 @@ private static BidInfo givenBidInfo(float price, String dealId) { .correspondingImp(Imp.builder().id(IMP_ID).build()) .build(); } - - private static BidInfo givenBidInfo(float price, String dealId, List impDealIds) { - final List impDeals = impDealIds.stream() - .map(impDealId -> Deal.builder().id(impDealId).build()) - .toList(); - final Pmp pmp = Pmp.builder().deals(impDeals).build(); - - return BidInfo.builder() - .bid(Bid.builder().impid(IMP_ID).price(BigDecimal.valueOf(price)).dealid(dealId).build()) - .correspondingImp(Imp.builder().id(IMP_ID).pmp(pmp).build()) - .build(); - } } diff --git a/src/test/java/org/prebid/server/auction/adjustment/FloorAdjustmentFactorResolverTest.java b/src/test/java/org/prebid/server/auction/adjustment/FloorAdjustmentFactorResolverTest.java index 496c46f072b..2834c874a12 100644 --- a/src/test/java/org/prebid/server/auction/adjustment/FloorAdjustmentFactorResolverTest.java +++ b/src/test/java/org/prebid/server/auction/adjustment/FloorAdjustmentFactorResolverTest.java @@ -9,6 +9,7 @@ import java.util.EnumMap; import java.util.Map; +import static java.util.Collections.singleton; import static org.assertj.core.api.Assertions.assertThat; public class FloorAdjustmentFactorResolverTest { @@ -24,9 +25,7 @@ public void setUp() { public void resolveShouldReturnOneIfAdjustmentsByMediaTypeAndBidderAreAbsent() { // when final BigDecimal result = floorAdjustmentFactorResolver.resolve( - ImpMediaType.video, - ExtRequestBidAdjustmentFactors.builder().build(), - "bidder"); + singleton(ImpMediaType.video), ExtRequestBidAdjustmentFactors.builder().build(), "bidder"); // then assertThat(result).isEqualTo(BigDecimal.ONE); @@ -35,13 +34,12 @@ public void resolveShouldReturnOneIfAdjustmentsByMediaTypeAndBidderAreAbsent() { @Test public void resolveShouldReturnBidderAdjustmentFactorIfAdjustmentsByTypeAreAbsentIgnoringCase() { // given - final ExtRequestBidAdjustmentFactors adjustmentFactors = - ExtRequestBidAdjustmentFactors.builder().build(); + final ExtRequestBidAdjustmentFactors adjustmentFactors = ExtRequestBidAdjustmentFactors.builder().build(); adjustmentFactors.addFactor("BIDder", BigDecimal.valueOf(3.456)); // when final BigDecimal result = floorAdjustmentFactorResolver.resolve( - ImpMediaType.video, adjustmentFactors, "bidDER"); + singleton(ImpMediaType.video), adjustmentFactors, "bidDER"); // then assertThat(result).isEqualTo(BigDecimal.valueOf(3.456)); @@ -55,14 +53,13 @@ public void resolveShouldReturnSmallestAdjustmentByMediaTypeIfPresentIgnoringCas ImpMediaType.video_outstream, Map.of("bidder", BigDecimal.valueOf(2.345)), ImpMediaType.banner, Map.of("bidder", BigDecimal.valueOf(3.456)))); - final ExtRequestBidAdjustmentFactors adjustmentFactors = - ExtRequestBidAdjustmentFactors.builder() - .mediatypes(adjustmentFactorsByMediaType) - .build(); + final ExtRequestBidAdjustmentFactors adjustmentFactors = ExtRequestBidAdjustmentFactors.builder() + .mediatypes(adjustmentFactorsByMediaType) + .build(); // when final BigDecimal result = floorAdjustmentFactorResolver.resolve( - ImpMediaType.video, adjustmentFactors, "bidDER"); + singleton(ImpMediaType.video), adjustmentFactors, "bidDER"); // then assertThat(result).isEqualTo(BigDecimal.valueOf(1.234)); @@ -81,7 +78,7 @@ public void resolveShouldReturnSmallestAdjustmentBetweenMediaTypeAndBidderChosen // when final BigDecimal result = floorAdjustmentFactorResolver.resolve( - ImpMediaType.video, adjustmentFactors, "bidder"); + singleton(ImpMediaType.video), adjustmentFactors, "bidder"); // then assertThat(result).isEqualTo(BigDecimal.valueOf(0.123)); @@ -99,7 +96,7 @@ public void resolveShouldReturnMediaTypeAdjustmentWhenBidderAdjustmentIsAbsent() // when final BigDecimal result = floorAdjustmentFactorResolver.resolve( - ImpMediaType.video, adjustmentFactors, "bidder"); + singleton(ImpMediaType.video), adjustmentFactors, "bidder"); // then assertThat(result).isEqualTo(BigDecimal.valueOf(1.234)); @@ -118,7 +115,7 @@ public void resolveShouldReturnBidderAdjustmentWhenMediaTypeAdjustmentIsAbsent() // when final BigDecimal result = floorAdjustmentFactorResolver.resolve( - ImpMediaType.banner, adjustmentFactors, "bidder"); + singleton(ImpMediaType.banner), adjustmentFactors, "bidder"); // then assertThat(result).isEqualTo(BigDecimal.valueOf(3.456)); @@ -137,7 +134,7 @@ public void resolveShouldReturnOneWhenAppropriateBidderAdjustmentAndMediaTypeAdj // when final BigDecimal result = floorAdjustmentFactorResolver.resolve( - ImpMediaType.banner, adjustmentFactors, "bidder"); + singleton(ImpMediaType.banner), adjustmentFactors, "bidder"); // then assertThat(result).isEqualTo(BigDecimal.ONE); diff --git a/src/test/java/org/prebid/server/auction/requestfactory/AmpRequestFactoryTest.java b/src/test/java/org/prebid/server/auction/requestfactory/AmpRequestFactoryTest.java index a81e971a019..26ba2d77e5e 100644 --- a/src/test/java/org/prebid/server/auction/requestfactory/AmpRequestFactoryTest.java +++ b/src/test/java/org/prebid/server/auction/requestfactory/AmpRequestFactoryTest.java @@ -152,7 +152,7 @@ public void setUp() { given(ortb2RequestFactory.restoreResultFromRejection(any())) .willAnswer(invocation -> Future.failedFuture((Throwable) invocation.getArgument(0))); given(ortb2RequestFactory.enrichWithPriceFloors(any())).willAnswer(invocation -> invocation.getArgument(0)); - given(ortb2RequestFactory.updateTimeout(any(), anyLong())).willAnswer(invocation -> invocation.getArgument(0)); + given(ortb2RequestFactory.updateTimeout(any())).willAnswer(invocation -> invocation.getArgument(0)); given(fpdResolver.resolveApp(any(), any())) .willAnswer(invocationOnMock -> invocationOnMock.getArgument(0)); @@ -161,8 +161,6 @@ public void setUp() { given(fpdResolver.resolveUser(any(), any())) .willAnswer(invocationOnMock -> invocationOnMock.getArgument(0)); given(fpdResolver.resolveImpExt(any(), any())).willAnswer(invocationOnMock -> invocationOnMock.getArgument(0)); - given(ortb2RequestFactory.populateUserAdditionalInfo(any())) - .willAnswer(invocationOnMock -> Future.succeededFuture(invocationOnMock.getArgument(0))); given(ortb2RequestFactory.activityInfrastructureFrom(any())) .willReturn(Future.succeededFuture()); @@ -1665,7 +1663,7 @@ public void shouldUpdateTimeout() { // given givenBidRequest(); - given(ortb2RequestFactory.updateTimeout(any(), anyLong())) + given(ortb2RequestFactory.updateTimeout(any())) .willAnswer(invocation -> { final AuctionContext auctionContext = invocation.getArgument(0); return auctionContext.with(auctionContext.getBidRequest().toBuilder().tmax(10000L).build()); @@ -1707,7 +1705,8 @@ private void givenBidRequest( .willAnswer(invocation -> Future.succeededFuture((BidRequest) invocation.getArgument(0))); given(ortb2RequestFactory.enrichBidRequestWithAccountAndPrivacyData(any())) - .willAnswer(invocation -> ((AuctionContext) invocation.getArgument(0)).getBidRequest()); + .willAnswer(invocation -> Future.succeededFuture( + ((AuctionContext) invocation.getArgument(0)).getBidRequest())); given(ortb2RequestFactory.executeProcessedAuctionRequestHooks(any())) .willAnswer(invocation -> Future.succeededFuture( ((AuctionContext) invocation.getArgument(0)).getBidRequest())); diff --git a/src/test/java/org/prebid/server/auction/requestfactory/AuctionRequestFactoryTest.java b/src/test/java/org/prebid/server/auction/requestfactory/AuctionRequestFactoryTest.java index 60dc83c3438..0f9f2da493d 100644 --- a/src/test/java/org/prebid/server/auction/requestfactory/AuctionRequestFactoryTest.java +++ b/src/test/java/org/prebid/server/auction/requestfactory/AuctionRequestFactoryTest.java @@ -159,7 +159,7 @@ public void setUp() { given(ortb2RequestFactory.validateRequest(any(), any(), any())) .willAnswer(invocationOnMock -> Future.succeededFuture((BidRequest) invocationOnMock.getArgument(0))); given(ortb2RequestFactory.enrichWithPriceFloors(any())).willAnswer(invocation -> invocation.getArgument(0)); - given(ortb2RequestFactory.updateTimeout(any(), anyLong())).willAnswer(invocation -> invocation.getArgument(0)); + given(ortb2RequestFactory.updateTimeout(any())).willAnswer(invocation -> invocation.getArgument(0)); given(paramsResolver.resolve(any(), any(), any(), anyBoolean())) .will(invocationOnMock -> invocationOnMock.getArgument(0)); @@ -171,12 +171,11 @@ public void setUp() { .willReturn(Future.succeededFuture(defaultPrivacyContext)); given(ortb2RequestFactory.enrichBidRequestWithAccountAndPrivacyData(any())) - .willAnswer(invocation -> ((AuctionContext) invocation.getArgument(0)).getBidRequest()); + .willAnswer(invocation -> Future.succeededFuture( + ((AuctionContext) invocation.getArgument(0)).getBidRequest())); given(ortb2RequestFactory.executeProcessedAuctionRequestHooks(any())) .willAnswer(invocation -> Future.succeededFuture( ((AuctionContext) invocation.getArgument(0)).getBidRequest())); - given(ortb2RequestFactory.populateUserAdditionalInfo(any())) - .willAnswer(invocationOnMock -> Future.succeededFuture(invocationOnMock.getArgument(0))); given(ortb2RequestFactory.restoreResultFromRejection(any())) .willAnswer(invocation -> Future.failedFuture((Throwable) invocation.getArgument(0))); given(ortb2RequestFactory.activityInfrastructureFrom(any())) @@ -734,7 +733,7 @@ public void shouldUpdateTimeout() { // given givenValidBidRequest(); - given(ortb2RequestFactory.updateTimeout(any(), anyLong())) + given(ortb2RequestFactory.updateTimeout(any())) .willAnswer(invocation -> { final AuctionContext auctionContext = invocation.getArgument(0); return auctionContext.with(auctionContext.getBidRequest().toBuilder().tmax(10000L).build()); diff --git a/src/test/java/org/prebid/server/auction/requestfactory/Ortb2ImplicitParametersResolverTest.java b/src/test/java/org/prebid/server/auction/requestfactory/Ortb2ImplicitParametersResolverTest.java index 022cb2f33e3..d8b7d45abd5 100644 --- a/src/test/java/org/prebid/server/auction/requestfactory/Ortb2ImplicitParametersResolverTest.java +++ b/src/test/java/org/prebid/server/auction/requestfactory/Ortb2ImplicitParametersResolverTest.java @@ -950,10 +950,9 @@ public void shouldNotSetDeviceLmtForIos14Minor3AndAttsNull() { } @Test - public void shouldUpdateImpsWithSecurityOneIfRequestIsSecuredAndImpSecurityNotDefined() { + public void shouldUpdateImpsWithSecurityOneIfImpSecurityNotDefined() { // given final BidRequest bidRequest = BidRequest.builder().imp(singletonList(Imp.builder().build())).build(); - given(paramsExtractor.secureFrom(any())).willReturn(1); // when final BidRequest result = target.resolve(bidRequest, auctionContext, ENDPOINT, false); @@ -963,14 +962,12 @@ public void shouldUpdateImpsWithSecurityOneIfRequestIsSecuredAndImpSecurityNotDe } @Test - public void shouldNotUpdateImpsWithSecurityOneIfRequestIsSecureAndImpSecurityIsZero() { + public void shouldNotUpdateImpsWithSecurityOneIfImpSecurityIsZero() { // given final List imps = singletonList(Imp.builder().id("someImpId").secure(0).build()); final BidRequest bidRequest = BidRequest.builder().imp(imps).build(); - given(paramsExtractor.secureFrom(any())).willReturn(1); - // when final BidRequest result = target.resolve(bidRequest, auctionContext, ENDPOINT, false); @@ -979,12 +976,11 @@ public void shouldNotUpdateImpsWithSecurityOneIfRequestIsSecureAndImpSecurityIsZ } @Test - public void shouldUpdateImpsOnlyWithNotDefinedSecurityWithSecurityOneIfRequestIsSecure() { + public void shouldUpdateImpsOnlyWithNotDefinedSecurityWithSecurityOne() { // given final BidRequest bidRequest = BidRequest.builder() .imp(asList(Imp.builder().build(), Imp.builder().secure(0).build())) .build(); - given(paramsExtractor.secureFrom(any())).willReturn(1); // when final BidRequest result = target.resolve(bidRequest, auctionContext, ENDPOINT, false); @@ -993,22 +989,6 @@ public void shouldUpdateImpsOnlyWithNotDefinedSecurityWithSecurityOneIfRequestIs assertThat(result.getImp()).extracting(Imp::getSecure).containsOnly(1, 0); } - @Test - public void shouldNotUpdateImpsWithSecurityOneIfRequestIsNotSecureAndImpSecurityIsNotDefined() { - // given - final List imps = singletonList(Imp.builder().id("someImpId").secure(1).build()); - - final BidRequest bidRequest = BidRequest.builder().imp(imps).build(); - - given(paramsExtractor.secureFrom(any())).willReturn(0); - - // when - final BidRequest result = target.resolve(bidRequest, auctionContext, ENDPOINT, false); - - // then - assertThat(result.getImp()).isSameAs(imps); - } - @Test public void shouldGenerateImpIdIfEmpty() { // given @@ -1838,8 +1818,6 @@ public void shouldAddNewBidderToImpBidderParamsWhenRequestLevelHasNotSharedBidde .set("bidder1", mapper.createObjectNode().put("key1", "value1"))))) .build())).build(); - given(paramsExtractor.secureFrom(any())).willReturn(0); - // when final BidRequest result = target.resolve(bidRequest, auctionContext, ENDPOINT, false); @@ -1870,8 +1848,6 @@ public void shouldMergeImpAndRequestBidderParamsForSharedBidderWithImpPriority() given(jsonMerger.merge(any(), any())).willReturn(mapper.createObjectNode().put("key1", "value1-imp") .put("key2", "value2")); - given(paramsExtractor.secureFrom(any())).willReturn(0); - // when final BidRequest result = target.resolve(bidRequest, auctionContext, ENDPOINT, false); @@ -1901,8 +1877,6 @@ public void shouldNotRemoveImpBidderParamsThatWasNotParticipateInMerge() { given(jsonMerger.merge(any(), any())).willReturn(mapper.createObjectNode().put("key1", "value1") .put("key2", "value2")); - given(paramsExtractor.secureFrom(any())).willReturn(0); - // when final BidRequest result = target.resolve(bidRequest, auctionContext, ENDPOINT, false); @@ -1934,8 +1908,6 @@ public void shouldNotAddContextAndPrebidAsBidderParamsIfDefinedInRequest() { .set("bidder1", mapper.createObjectNode().put("key1", "value1"))))) .build())).build(); - given(paramsExtractor.secureFrom(any())).willReturn(0); - // when final BidRequest result = target.resolve(bidRequest, auctionContext, ENDPOINT, false); @@ -1963,8 +1935,6 @@ public void shouldNotMergeContextAndPrebidAsBidderParamsIfDefinedInRequest() { .imp(singletonList(Imp.builder() .ext(impBidderParams).build())).build(); - given(paramsExtractor.secureFrom(any())).willReturn(0); - // when final BidRequest result = target.resolve(bidRequest, auctionContext, ENDPOINT, false); diff --git a/src/test/java/org/prebid/server/auction/requestfactory/Ortb2RequestFactoryTest.java b/src/test/java/org/prebid/server/auction/requestfactory/Ortb2RequestFactoryTest.java index c57edaf4d02..0c6374e3218 100644 --- a/src/test/java/org/prebid/server/auction/requestfactory/Ortb2RequestFactoryTest.java +++ b/src/test/java/org/prebid/server/auction/requestfactory/Ortb2RequestFactoryTest.java @@ -33,9 +33,6 @@ import org.prebid.server.cookie.UidsCookie; import org.prebid.server.cookie.UidsCookieService; import org.prebid.server.cookie.proto.Uids; -import org.prebid.server.deals.UserAdditionalInfoService; -import org.prebid.server.deals.model.DeepDebugLog; -import org.prebid.server.deals.model.TxnLog; import org.prebid.server.exception.BlacklistedAccountException; import org.prebid.server.exception.InvalidRequestException; import org.prebid.server.exception.PreBidException; @@ -80,7 +77,6 @@ import org.prebid.server.validation.RequestValidator; import org.prebid.server.validation.model.ValidationResult; -import java.time.Clock; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -131,16 +127,12 @@ public class Ortb2RequestFactoryTest extends VertxTest { @Mock private HookStageExecutor hookStageExecutor; @Mock - private UserAdditionalInfoService userAdditionalInfoService; - @Mock private PriceFloorProcessor priceFloorProcessor; @Mock private CountryCodeMapper countryCodeMapper; @Mock private Metrics metrics; - private final Clock clock = Clock.systemDefaultZone(); - private Ortb2RequestFactory target; @Mock @@ -179,9 +171,6 @@ public void setUp() { false, AuctionRequestPayloadImpl.of(invocation.getArgument(0))))); - given(userAdditionalInfoService.populate(any())) - .willAnswer(invocationOnMock -> Future.succeededFuture(invocationOnMock.getArgument(0))); - givenTarget(false, 90); } @@ -703,7 +692,6 @@ public void createAuctionContextShouldReturnExpectedAuctionContext() { .hookExecutionContext(hookExecutionContext) .debugContext(DebugContext.empty()) .requestRejected(false) - .txnLog(TxnLog.create()) .debugHttpCalls(emptyMap()) .bidRejectionTrackers(new HashMap<>()) .build()); @@ -734,7 +722,6 @@ public void enrichAuctionContextShouldReturnExpectedAuctionContext() { .prebidErrors(new ArrayList<>()) .debugWarnings(new ArrayList<>()) .hookExecutionContext(hookExecutionContext) - .txnLog(TxnLog.create()) .debugHttpCalls(emptyMap()) .build(), httpRequest, @@ -756,8 +743,6 @@ public void enrichAuctionContextShouldReturnExpectedAuctionContext() { .prebidErrors(new ArrayList<>()) .debugWarnings(new ArrayList<>()) .hookExecutionContext(hookExecutionContext) - .txnLog(TxnLog.create()) - .deepDebugLog(DeepDebugLog.create(false, clock)) .debugHttpCalls(new HashMap<>()) .build()); } @@ -777,38 +762,6 @@ public void enrichAuctionContextShouldSetDebugOff() { assertThat(result.getDebugContext()).isEqualTo(DebugContext.empty()); } - @Test - public void enrichAuctionContextShouldReturnAuctionContextWithDeepDebugLogWhenDeepDebugIsOff() { - // when - final AuctionContext auctionContext = target.enrichAuctionContext( - AuctionContext.builder().build(), - httpRequest, - BidRequest.builder().build(), - 100); - - // then - assertThat(auctionContext.getDeepDebugLog()).isNotNull().returns(false, DeepDebugLog::isDeepDebugEnabled); - } - - @Test - public void enrichAuctionContextShouldReturnAuctionContextWithDeepDebugLogWhenDeepDebugIsOn() { - // given - final BidRequest bidRequest = BidRequest.builder() - .ext(ExtRequest.of( - ExtRequestPrebid.builder().trace(TraceLevel.verbose).build())) - .build(); - - // when - final AuctionContext auctionContext = target.enrichAuctionContext( - AuctionContext.builder().build(), - httpRequest, - bidRequest, - 100); - - // then - assertThat(auctionContext.getDeepDebugLog()).isNotNull().returns(true, DeepDebugLog::isDeepDebugEnabled); - } - @Test public void validateRequestShouldThrowInvalidRequestExceptionIfRequestIsInvalid() { // given @@ -902,7 +855,7 @@ public void enrichBidRequestWithAccountAndPrivacyDataShouldReturnSameBidRequest( .build(); // when - final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext); + final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext).result(); // then assertThat(result) @@ -956,7 +909,7 @@ public void enrichBidRequestWithAccountAndPrivacyDataShouldReturnBidRequestWithA .build(); // when - final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext); + final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext).result(); // then assertThat(result) @@ -1001,7 +954,7 @@ public void enrichBidRequestWithAccountAndPrivacyDataShouldAddCountryFromPrivacy .build(); // when - final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext); + final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext).result(); // then assertThat(List.of(result)) @@ -1041,7 +994,7 @@ public void enrichBidRequestWithAccountAndPrivacyDataShouldAddRegionFromPrivacy( .build(); // when - final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext); + final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext).result(); // then assertThat(result) @@ -1074,7 +1027,7 @@ public void enrichBidRequestWithAccountAndPrivacyDataShouldMakeRegionUpperCasedW .build(); // when - final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext); + final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext).result(); // then assertThat(result) @@ -1104,11 +1057,12 @@ public void enrichBidRequestWithAccountAndPrivacyDataShouldAddIpAddressV4FromPri // when final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData( - AuctionContext.builder() - .bidRequest(bidRequest) - .account(account) - .privacyContext(privacyContext) - .build()); + AuctionContext.builder() + .bidRequest(bidRequest) + .account(account) + .privacyContext(privacyContext) + .build()) + .result(); // then assertThat(Collections.singleton(result)) @@ -1137,11 +1091,12 @@ public void enrichBidRequestWithAccountAndPrivacyDataShouldAddIpAddressV6FromPri // when final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData( - AuctionContext.builder() - .bidRequest(bidRequest) - .account(account) - .privacyContext(privacyContext) - .build()); + AuctionContext.builder() + .bidRequest(bidRequest) + .account(account) + .privacyContext(privacyContext) + .build()) + .result(); // then assertThat(Collections.singleton(result)) @@ -1348,7 +1303,7 @@ public void updateTimeoutShouldReturnSameContextIfNoNeedUpdates() { .build(); // when - final AuctionContext result = target.updateTimeout(auctionContext, 0L); + final AuctionContext result = target.updateTimeout(auctionContext); // then assertThat(result).isSameAs(auctionContext); @@ -1371,7 +1326,7 @@ public void updateTimeoutShouldReturnContextWithUpdatedTimeout() { .build(); // when - final AuctionContext result = target.updateTimeout(auctionContext, 0L); + final AuctionContext result = target.updateTimeout(auctionContext); // then assertThat(result.getBidRequest()).isSameAs(auctionContext.getBidRequest()); @@ -1392,7 +1347,7 @@ public void updateTimeoutShouldReturnContextWithUpdatedBidRequestTmax() { .build(); // when - final AuctionContext result = target.updateTimeout(auctionContext, 0L); + final AuctionContext result = target.updateTimeout(auctionContext); // then assertThat(result.getBidRequest()).isEqualTo(givenBidRequest(request -> request.tmax(500L))); @@ -1416,7 +1371,7 @@ public void updateTimeoutShouldReturnContextWithUpdatedTimeoutAndBidRequestTmax( .build(); // when - final AuctionContext result = target.updateTimeout(auctionContext, 0L); + final AuctionContext result = target.updateTimeout(auctionContext); // then assertThat(result.getBidRequest()).isEqualTo(givenBidRequest(request -> request.tmax(500L))); @@ -1465,7 +1420,7 @@ public void enrichBidRequestWithAccountAndPrivacyDataShouldSetDsaFromAccountWhen .build(); // when - final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext); + final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext).result(); // then assertThat(result) @@ -1522,7 +1477,7 @@ public void enrichBidRequestWithAccountAndPrivacyDataShouldNotSetDsaFromAccountW .build(); // when - final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext); + final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext).result(); // then assertThat(result) @@ -1585,7 +1540,7 @@ public void enrichBidRequestWithAccountAndPrivacyDataShouldNotSetDsaFromAccountW .build(); // when - final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext); + final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext).result(); // then assertThat(result) @@ -1644,7 +1599,7 @@ public void enrichBidRequestWithAccountAndPrivacyDataShouldSetDsaFromAccountWhen .build(); // when - final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext); + final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext).result(); // then assertThat(result) @@ -1705,7 +1660,7 @@ public void enrichBidRequestWithAccountAndPrivacyDataShouldNotSetDsaFromAccountW .build(); // when - final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext); + final BidRequest result = target.enrichBidRequestWithAccountAndPrivacyData(auctionContext).result(); // then assertThat(result) @@ -1732,11 +1687,9 @@ private void givenTarget(boolean enforceValidAccount, int timeoutAdjustmentFacto applicationSettings, ipAddressHelper, hookStageExecutor, - userAdditionalInfoService, priceFloorProcessor, countryCodeMapper, - metrics, - clock); + metrics); } private static String bidRequestToString(BidRequest bidRequest) { diff --git a/src/test/java/org/prebid/server/auction/requestfactory/VideoRequestFactoryTest.java b/src/test/java/org/prebid/server/auction/requestfactory/VideoRequestFactoryTest.java index 71eb233b2f4..4e1f9ff20c9 100644 --- a/src/test/java/org/prebid/server/auction/requestfactory/VideoRequestFactoryTest.java +++ b/src/test/java/org/prebid/server/auction/requestfactory/VideoRequestFactoryTest.java @@ -101,7 +101,7 @@ public void setUp() { given(ortb2RequestFactory.restoreResultFromRejection(any())) .willAnswer(invocation -> Future.failedFuture((Throwable) invocation.getArgument(0))); given(ortb2RequestFactory.enrichWithPriceFloors(any())).willAnswer(invocation -> invocation.getArgument(0)); - given(ortb2RequestFactory.updateTimeout(any(), anyLong())).willAnswer(invocation -> invocation.getArgument(0)); + given(ortb2RequestFactory.updateTimeout(any())).willAnswer(invocation -> invocation.getArgument(0)); given(ortb2RequestFactory.activityInfrastructureFrom(any())) .willReturn(Future.succeededFuture()); @@ -127,9 +127,6 @@ public void setUp() { given(privacyEnforcementService.contextFromBidRequest(any())) .willReturn(Future.succeededFuture(defaultPrivacyContext)); - given(ortb2RequestFactory.populateUserAdditionalInfo(any())) - .willAnswer(invocationOnMock -> Future.succeededFuture(invocationOnMock.getArgument(0))); - target = new VideoRequestFactory( Integer.MAX_VALUE, false, @@ -406,7 +403,8 @@ private void givenBidRequest(BidRequest bidRequest, List podErrors) { .willAnswer(answerWithFirstArgument()); given(ortb2RequestFactory.enrichBidRequestWithAccountAndPrivacyData(any())) - .willAnswer(invocation -> ((AuctionContext) invocation.getArgument(0)).getBidRequest()); + .willAnswer(invocation -> Future.succeededFuture( + ((AuctionContext) invocation.getArgument(0)).getBidRequest())); given(ortb2RequestFactory.executeProcessedAuctionRequestHooks(any())) .willAnswer(invocation -> Future.succeededFuture( ((AuctionContext) invocation.getArgument(0)).getBidRequest())); @@ -489,7 +487,7 @@ public void shouldUpdateTimeout() throws JsonProcessingException { // given prepareMinimumSuccessfulConditions(); - given(ortb2RequestFactory.updateTimeout(any(), anyLong())) + given(ortb2RequestFactory.updateTimeout(any())) .willAnswer(invocation -> { final AuctionContext auctionContext = invocation.getArgument(0); return auctionContext.with(auctionContext.getBidRequest().toBuilder().tmax(10000L).build()); diff --git a/src/test/java/org/prebid/server/auction/versionconverter/down/BidRequestOrtb26To25ConverterTest.java b/src/test/java/org/prebid/server/auction/versionconverter/down/BidRequestOrtb26To25ConverterTest.java index 4a53da795c9..0457e1a234c 100644 --- a/src/test/java/org/prebid/server/auction/versionconverter/down/BidRequestOrtb26To25ConverterTest.java +++ b/src/test/java/org/prebid/server/auction/versionconverter/down/BidRequestOrtb26To25ConverterTest.java @@ -38,8 +38,8 @@ import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; +import static java.util.function.UnaryOperator.identity; import static org.assertj.core.api.Assertions.assertThat; -import static org.prebid.server.hooks.v1.PayloadUpdate.identity; public class BidRequestOrtb26To25ConverterTest extends VertxTest { diff --git a/src/test/java/org/prebid/server/bidder/HttpBidderRequesterTest.java b/src/test/java/org/prebid/server/bidder/HttpBidderRequesterTest.java index 88a99caf1bb..125a5252c5e 100644 --- a/src/test/java/org/prebid/server/bidder/HttpBidderRequesterTest.java +++ b/src/test/java/org/prebid/server/bidder/HttpBidderRequesterTest.java @@ -50,6 +50,7 @@ import java.util.List; import java.util.Map; import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.UnaryOperator; import static java.util.Arrays.asList; @@ -459,8 +460,28 @@ public void shouldCompressRequestBodyIfContentEncodingHeaderIsGzip() { @Test public void shouldNotWaitForResponsesWhenAllDealsIsGathered() throws JsonProcessingException { // given - target = new HttpBidderRequester(httpClient, new DealsBidderRequestCompletionTrackerFactory(), - bidderErrorNotifier, requestEnricher, jacksonMapper); + target = new HttpBidderRequester( + httpClient, + bidRequest -> new BidderRequestCompletionTracker() { + + private final AtomicInteger waitAllDeals = new AtomicInteger(2); + private final Promise promise = Promise.promise(); + + @Override + public Future future() { + return promise.future(); + } + + @Override + public void processBids(List bids) { + if (waitAllDeals.decrementAndGet() == 0) { + promise.complete(); + } + } + }, + bidderErrorNotifier, + requestEnricher, + jacksonMapper); final BidRequest bidRequest = bidRequestWithDeals("deal1", "deal2"); final BidderRequest bidderRequest = BidderRequest.builder() @@ -512,16 +533,15 @@ public void shouldNotWaitForResponsesWhenAllDealsIsGathered() throws JsonProcess CompositeBidderResponse.withBids(singletonList(bidderBidDeal2), emptyList())); // when - final BidderSeatBid bidderSeatBid = - target.requestBids( - bidder, - bidderRequest, - bidRejectionTracker, - timeout, - CaseInsensitiveMultiMap.empty(), - bidderAliases, - false) - .result(); + final BidderSeatBid bidderSeatBid = target.requestBids( + bidder, + bidderRequest, + bidRejectionTracker, + timeout, + CaseInsensitiveMultiMap.empty(), + bidderAliases, + false) + .result(); // then verify(bidder).makeHttpRequests(any()); diff --git a/src/test/java/org/prebid/server/bidder/adrino/AdrinoBidderTest.java b/src/test/java/org/prebid/server/bidder/adrino/AdrinoBidderTest.java index f1f58954407..92990680616 100644 --- a/src/test/java/org/prebid/server/bidder/adrino/AdrinoBidderTest.java +++ b/src/test/java/org/prebid/server/bidder/adrino/AdrinoBidderTest.java @@ -17,8 +17,6 @@ import org.prebid.server.bidder.model.HttpRequest; import org.prebid.server.bidder.model.HttpResponse; import org.prebid.server.bidder.model.Result; -import org.prebid.server.proto.openrtb.ext.ExtPrebid; -import org.prebid.server.proto.openrtb.ext.request.adrino.ExtImpAdrino; import org.prebid.server.proto.openrtb.ext.response.BidType; import java.util.List; @@ -69,16 +67,9 @@ public void makeHttpRequestsShouldReturnHttpRequestWithCorrectBodyHeadersAndMeth public void makeHttpRequestShouldReturnSingleHttpRequestsWhenTwoImpsHasDifferentSourceId() { // given final BidRequest bidRequest = BidRequest.builder() - .imp(asList(Imp.builder() - .xNative(Native.builder().build()) - .ext(mapper.valueToTree( - ExtPrebid.of(null, ExtImpAdrino.of("test")))) - .build(), - Imp.builder() - .xNative(Native.builder().build()) - .ext(mapper.valueToTree( - ExtPrebid.of(null, ExtImpAdrino.of("test")))) - .build())) + .imp(asList( + Imp.builder().xNative(Native.builder().build()).build(), + Imp.builder().xNative(Native.builder().build()).build())) .build(); // when diff --git a/src/test/java/org/prebid/server/bidder/adtrgtme/AdtrgtmeBidderTest.java b/src/test/java/org/prebid/server/bidder/adtrgtme/AdtrgtmeBidderTest.java index 12497eee40d..b1f09b5a9fe 100644 --- a/src/test/java/org/prebid/server/bidder/adtrgtme/AdtrgtmeBidderTest.java +++ b/src/test/java/org/prebid/server/bidder/adtrgtme/AdtrgtmeBidderTest.java @@ -21,7 +21,6 @@ import org.prebid.server.bidder.model.HttpResponse; import org.prebid.server.bidder.model.Result; import org.prebid.server.proto.openrtb.ext.ExtPrebid; -import org.prebid.server.proto.openrtb.ext.request.adrino.ExtImpAdrino; import org.prebid.server.proto.openrtb.ext.request.adtrgtme.ExtImpAdtrgtme; import org.prebid.server.util.HttpUtil; @@ -129,9 +128,9 @@ public void makeHttpRequestsShouldSplitRequestIntoMultipleRequests() { // given final BidRequest bidRequest = BidRequest.builder().site(Site.builder().id("site_id").build()) .imp(asList(givenImp(impBuilder -> impBuilder.xNative(Native.builder().build()) - .ext(mapper.valueToTree(ExtPrebid.of(null, ExtImpAdrino.of("test"))))), + .ext(mapper.valueToTree(ExtPrebid.of(null, ExtImpAdtrgtme.of(1))))), givenImp(impBuilder -> impBuilder.xNative(Native.builder().build()) - .ext(mapper.valueToTree(ExtPrebid.of(null, ExtImpAdrino.of("test"))))))).build(); + .ext(mapper.valueToTree(ExtPrebid.of(null, ExtImpAdtrgtme.of(1))))))).build(); // when final Result>> result = target.makeHttpRequests(bidRequest); diff --git a/src/test/java/org/prebid/server/bidder/adxcg/AdxcgBidderTest.java b/src/test/java/org/prebid/server/bidder/adxcg/AdxcgBidderTest.java index 74fe9481780..e8c1ccba374 100644 --- a/src/test/java/org/prebid/server/bidder/adxcg/AdxcgBidderTest.java +++ b/src/test/java/org/prebid/server/bidder/adxcg/AdxcgBidderTest.java @@ -16,8 +16,6 @@ import org.prebid.server.bidder.model.HttpRequest; import org.prebid.server.bidder.model.HttpResponse; import org.prebid.server.bidder.model.Result; -import org.prebid.server.proto.openrtb.ext.ExtPrebid; -import org.prebid.server.proto.openrtb.ext.request.adxcg.ExtImpAdxcg; import java.util.Collections; import java.util.List; @@ -48,9 +46,7 @@ public void creationShouldFailOnInvalidEndpointUrl() { public void makeHttpRequestsShouldNotModifyIncomingRequest() { // given final BidRequest bidRequest = BidRequest.builder() - .imp(singletonList(Imp.builder() - .ext(mapper.valueToTree(ExtPrebid.of(null, ExtImpAdxcg.of("adZoneId")))) - .build())) + .imp(singletonList(Imp.builder().build())) .id("request_id") .build(); @@ -246,9 +242,7 @@ private static BidRequest givenBidRequest( private static Imp givenImp(Function impCustomizer) { return impCustomizer.apply(Imp.builder() .id("123") - .banner(Banner.builder().id("banner_id").build()) - .ext(mapper.valueToTree(ExtPrebid.of(null, - ExtImpAdxcg.of("adzoneid"))))) + .banner(Banner.builder().id("banner_id").build())) .build(); } } diff --git a/src/test/java/org/prebid/server/bidder/bidmyadz/BidmyadzBidderTest.java b/src/test/java/org/prebid/server/bidder/bidmyadz/BidmyadzBidderTest.java index 4a41cece487..61f7b637c8c 100644 --- a/src/test/java/org/prebid/server/bidder/bidmyadz/BidmyadzBidderTest.java +++ b/src/test/java/org/prebid/server/bidder/bidmyadz/BidmyadzBidderTest.java @@ -16,8 +16,6 @@ import org.prebid.server.bidder.model.HttpRequest; import org.prebid.server.bidder.model.HttpResponse; import org.prebid.server.bidder.model.Result; -import org.prebid.server.proto.openrtb.ext.ExtPrebid; -import org.prebid.server.proto.openrtb.ext.request.bidmyadz.ExtImpBidmyadz; import org.prebid.server.proto.openrtb.ext.response.BidType; import org.prebid.server.util.HttpUtil; @@ -228,11 +226,7 @@ private static BidRequest givenBidRequest( } private static Imp givenImp(Function impCustomizer) { - return impCustomizer.apply(Imp.builder() - .id("123") - .ext(mapper.valueToTree(ExtPrebid.of(null, - ExtImpBidmyadz.of("placementId"))))) - .build(); + return impCustomizer.apply(Imp.builder().id("123")).build(); } private static BidResponse givenBidResponse(Function bidCustomizer) { diff --git a/src/test/java/org/prebid/server/bidder/ccx/CcxBidderTest.java b/src/test/java/org/prebid/server/bidder/ccx/CcxBidderTest.java index d88f12400fb..f9da8cc6b5d 100644 --- a/src/test/java/org/prebid/server/bidder/ccx/CcxBidderTest.java +++ b/src/test/java/org/prebid/server/bidder/ccx/CcxBidderTest.java @@ -18,8 +18,6 @@ import org.prebid.server.bidder.model.HttpRequest; import org.prebid.server.bidder.model.HttpResponse; import org.prebid.server.bidder.model.Result; -import org.prebid.server.proto.openrtb.ext.ExtPrebid; -import org.prebid.server.proto.openrtb.ext.request.ccx.ExtImpCcx; import java.util.List; import java.util.function.Function; @@ -61,20 +59,17 @@ public void makeHttpRequestsShouldCreateExpectedUrl() { @Test public void makeHttpRequestsShouldHaveTheSameIncomingAndOutGoingBidRequest() { // given - final BidRequest bidRequest = givenBidRequest(impCustomizer -> impCustomizer - .ext(mapper.valueToTree(ExtPrebid.of(null, - ExtImpCcx.of(123456789))))); + final BidRequest bidRequest = givenBidRequest(identity()); // when final Result>> result = target.makeHttpRequests(bidRequest); // then assertThat(result.getErrors()).isEmpty(); assertThat(result.getValue()) + .hasSize(1) + .element(0) .extracting(HttpRequest::getPayload) - .flatExtracting(BidRequest::getImp) - .extracting(Imp::getExt) - .containsExactly(mapper.valueToTree(ExtPrebid.of(null, - ExtImpCcx.of(123456789)))); + .isSameAs(bidRequest); } @Test @@ -215,11 +210,7 @@ private static BidRequest givenBidRequest( } private static Imp givenImp(Function impCustomizer) { - return impCustomizer.apply(Imp.builder() - .id("123") - .ext(mapper.valueToTree(ExtPrebid.of(null, - ExtImpCcx.of(123456789))))) - .build(); + return impCustomizer.apply(Imp.builder().id("123")).build(); } private static BidResponse givenBidResponse(Function bidCustomizer) { diff --git a/src/test/java/org/prebid/server/bidder/jixie/JixieBidderTest.java b/src/test/java/org/prebid/server/bidder/jixie/JixieBidderTest.java index 13fed975622..18f78d15c80 100644 --- a/src/test/java/org/prebid/server/bidder/jixie/JixieBidderTest.java +++ b/src/test/java/org/prebid/server/bidder/jixie/JixieBidderTest.java @@ -19,8 +19,6 @@ import org.prebid.server.bidder.model.HttpRequest; import org.prebid.server.bidder.model.HttpResponse; import org.prebid.server.bidder.model.Result; -import org.prebid.server.proto.openrtb.ext.ExtPrebid; -import org.prebid.server.proto.openrtb.ext.request.jixie.ExtImpJixie; import org.prebid.server.util.HttpUtil; import java.util.Arrays; @@ -204,10 +202,8 @@ private static BidRequest givenBidRequest( private static Imp givenImp(Function impCustomizer) { return impCustomizer.apply(Imp.builder() - .id("123")) - .banner(Banner.builder().build()) - .ext(mapper.valueToTree(ExtPrebid.of(null, - ExtImpJixie.of("unit", "accountId", "jxProp1", "jxProp2")))) + .id("123") + .banner(Banner.builder().build())) .build(); } diff --git a/src/test/java/org/prebid/server/bidder/kargo/KargoBidderTest.java b/src/test/java/org/prebid/server/bidder/kargo/KargoBidderTest.java index 1e38a1a1a04..199ef42c808 100644 --- a/src/test/java/org/prebid/server/bidder/kargo/KargoBidderTest.java +++ b/src/test/java/org/prebid/server/bidder/kargo/KargoBidderTest.java @@ -15,8 +15,6 @@ import org.prebid.server.bidder.model.HttpRequest; import org.prebid.server.bidder.model.HttpResponse; import org.prebid.server.bidder.model.Result; -import org.prebid.server.proto.openrtb.ext.ExtPrebid; -import org.prebid.server.proto.openrtb.ext.request.kargo.ExtImpKargo; import java.util.List; import java.util.function.UnaryOperator; @@ -217,11 +215,7 @@ private static BidRequest givenBidRequest(UnaryOperator impCustomizer) { - return impCustomizer.apply(Imp.builder() - .id("123") - .ext(mapper.valueToTree(ExtPrebid.of(null, - ExtImpKargo.of("placementId", "adSlotId"))))) - .build(); + return impCustomizer.apply(Imp.builder().id("123")).build(); } private static BidResponse givenBidResponse(UnaryOperator bidCustomizer) { diff --git a/src/test/java/org/prebid/server/bidder/loopme/LoopmeBidderTest.java b/src/test/java/org/prebid/server/bidder/loopme/LoopmeBidderTest.java index 7fd6fca1073..ec6a599c8bb 100644 --- a/src/test/java/org/prebid/server/bidder/loopme/LoopmeBidderTest.java +++ b/src/test/java/org/prebid/server/bidder/loopme/LoopmeBidderTest.java @@ -16,8 +16,6 @@ import org.prebid.server.bidder.model.HttpRequest; import org.prebid.server.bidder.model.HttpResponse; import org.prebid.server.bidder.model.Result; -import org.prebid.server.proto.openrtb.ext.ExtPrebid; -import org.prebid.server.proto.openrtb.ext.request.loopme.ExtImpLoopme; import java.util.Arrays; import java.util.List; @@ -167,7 +165,6 @@ private static Imp givenImp(Function impCustomiz .id("123")) .banner(Banner.builder().build()) .video(Video.builder().build()) - .ext(mapper.valueToTree(ExtPrebid.of(null, ExtImpLoopme.of("somePubId")))) .build(); } diff --git a/src/test/java/org/prebid/server/bidder/visx/VisxBidderTest.java b/src/test/java/org/prebid/server/bidder/visx/VisxBidderTest.java index 011b70efd86..54c95450277 100644 --- a/src/test/java/org/prebid/server/bidder/visx/VisxBidderTest.java +++ b/src/test/java/org/prebid/server/bidder/visx/VisxBidderTest.java @@ -20,11 +20,8 @@ import org.prebid.server.bidder.visx.model.VisxBid; import org.prebid.server.bidder.visx.model.VisxResponse; import org.prebid.server.bidder.visx.model.VisxSeatBid; -import org.prebid.server.proto.openrtb.ext.ExtPrebid; -import org.prebid.server.proto.openrtb.ext.request.visx.ExtImpVisx; import java.math.BigDecimal; -import java.util.Arrays; import java.util.List; import java.util.function.UnaryOperator; @@ -50,10 +47,7 @@ public void creationShouldFailOnInvalidEndpointUrl() { public void makeHttpRequestsShouldNotModifyIncomingRequest() { // given final BidRequest bidRequest = BidRequest.builder() - .imp(singletonList(Imp.builder() - .ext(mapper.valueToTree(ExtPrebid.of(null, - ExtImpVisx.of(123, Arrays.asList(10, 20))))) - .build())) + .imp(singletonList(Imp.builder().build())) .id("request_id") .cur(singletonList("USD")) .build(); diff --git a/src/test/java/org/prebid/server/bidder/vrtcal/VrtcalBidderTest.java b/src/test/java/org/prebid/server/bidder/vrtcal/VrtcalBidderTest.java index 5115023feb0..00bcb948f3d 100644 --- a/src/test/java/org/prebid/server/bidder/vrtcal/VrtcalBidderTest.java +++ b/src/test/java/org/prebid/server/bidder/vrtcal/VrtcalBidderTest.java @@ -15,8 +15,6 @@ import org.prebid.server.bidder.model.HttpRequest; import org.prebid.server.bidder.model.HttpResponse; import org.prebid.server.bidder.model.Result; -import org.prebid.server.proto.openrtb.ext.ExtPrebid; -import org.prebid.server.proto.openrtb.ext.request.vrtcal.ExtImpVrtcal; import org.prebid.server.util.HttpUtil; import java.util.List; @@ -46,8 +44,7 @@ public void creationShouldFailOnInvalidEndpointUrl() { @Test public void makeHttpRequestsShouldNotModifyIncomingRequest() { // given - final BidRequest bidRequest = givenBidRequest(impBuilder -> - impBuilder.ext(mapper.valueToTree(ExtPrebid.of(null, ExtImpVrtcal.of("JustAnUnusedVrtcalParam"))))); + final BidRequest bidRequest = givenBidRequest(identity()); // when final Result>> result = target.makeHttpRequests(bidRequest); @@ -189,9 +186,7 @@ private static BidRequest givenBidRequest(Function impCustomizer) { - return impCustomizer.apply(Imp.builder() - .ext(mapper.valueToTree(ExtPrebid.of(null, ExtImpVrtcal.of("JustAnUnusedVrtcalParam"))))) - .build(); + return impCustomizer.apply(Imp.builder()).build(); } private static String givenBidResponse(Bid... bids) throws JsonProcessingException { diff --git a/src/test/java/org/prebid/server/cache/CacheServiceTest.java b/src/test/java/org/prebid/server/cache/CacheServiceTest.java index 74feaf189af..4e4410b7b1c 100644 --- a/src/test/java/org/prebid/server/cache/CacheServiceTest.java +++ b/src/test/java/org/prebid/server/cache/CacheServiceTest.java @@ -232,8 +232,7 @@ public void cacheBidsOpenrtbShouldStoreWinUrl() { .build(); // when cacheService.cacheBidsOpenrtb( - singletonList(givenBidInfo(builder -> builder.id("bidId1"), BidType.banner, "bidder", - "lineItemId")), + singletonList(givenBidInfo(builder -> builder.id("bidId1"), BidType.banner, "bidder")), givenAuctionContext(), CacheContext.builder() .shouldCacheBids(true) @@ -241,9 +240,16 @@ public void cacheBidsOpenrtbShouldStoreWinUrl() { eventsContext); // then - verify(eventsService).winUrl(eq("bidId1"), eq("bidder"), eq("accountId"), eq("lineItemId"), eq(true), - eq(EventsContext.builder().enabledForAccount(true).enabledForRequest(true) - .auctionId("auctionId").build())); + verify(eventsService).winUrl( + eq("bidId1"), + eq("bidder"), + eq("accountId"), + eq(true), + eq(EventsContext.builder() + .enabledForAccount(true) + .enabledForRequest(true) + .auctionId("auctionId") + .build())); } @Test @@ -790,8 +796,8 @@ public void cacheBidsOpenrtbShouldUpdateVastXmlPutObjectWithKeyWhenBidHasCategor // given final Imp imp1 = givenImp(builder -> builder.id("impId1").video(Video.builder().build())); - final BidInfo bidInfo1 = givenBidInfo(builder -> builder.id("bid1").adm("adm"), - BidType.video, "bidder", null) + final BidInfo bidInfo1 = givenBidInfo( + builder -> builder.id("bid1").adm("adm"), BidType.video, "bidder") .toBuilder().category("bid1Category").build(); given(idGenerator.generateId()).willReturn("randomId"); @@ -820,10 +826,10 @@ public void cacheBidsOpenrtbShouldUpdateVastXmlPutObjectWithKeyWhenBidHasCategor public void cacheBidsOpenrtbShouldNotUpdateVastXmlPutObjectWithKeyWhenDoesNotHaveCatDur() throws IOException { // given final Imp imp1 = givenImp(builder -> builder.id("impId1").video(Video.builder().build())); - final BidInfo bidInfo1 = givenBidInfo(builder -> builder.id("bid1").impid("impId1").adm("adm"), - BidType.video, "bidder", null); + final BidInfo bidInfo1 = givenBidInfo( + builder -> builder.id("bid1").impid("impId1").adm("adm"), BidType.video, "bidder"); - given(vastModifier.createBidVastXml(any(), any(), any(), any(), any(), any(), any(), any())).willReturn("adm"); + given(vastModifier.createBidVastXml(any(), any(), any(), any(), any(), any(), any())).willReturn("adm"); // when cacheService.cacheBidsOpenrtb( @@ -1015,16 +1021,6 @@ private static BidInfo givenBidInfo(UnaryOperator bidCustomizer, .build(); } - private static BidInfo givenBidInfo(UnaryOperator bidCustomizer, - BidType bidType, - String bidder, - String lineItemId) { - - return givenBidInfo(bidCustomizer, bidType, bidder).toBuilder() - .lineItemId(lineItemId) - .build(); - } - private static Imp givenImp(UnaryOperator impCustomizer) { return impCustomizer.apply(Imp.builder()).build(); } diff --git a/src/test/java/org/prebid/server/deals/AdminCentralServiceTest.java b/src/test/java/org/prebid/server/deals/AdminCentralServiceTest.java deleted file mode 100644 index 7ff33ff7cd6..00000000000 --- a/src/test/java/org/prebid/server/deals/AdminCentralServiceTest.java +++ /dev/null @@ -1,437 +0,0 @@ -package org.prebid.server.deals; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.iab.openrtb.request.BidRequest; -import com.iab.openrtb.request.Imp; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.VertxTest; -import org.prebid.server.deals.model.AdminAccounts; -import org.prebid.server.deals.model.AdminCentralResponse; -import org.prebid.server.deals.model.AdminLineItems; -import org.prebid.server.deals.model.Command; -import org.prebid.server.deals.model.LogCriteriaFilter; -import org.prebid.server.deals.model.LogTracer; -import org.prebid.server.deals.model.ServicesCommand; -import org.prebid.server.log.CriteriaManager; -import org.prebid.server.settings.CachingApplicationSettings; -import org.prebid.server.settings.SettingsCache; -import org.prebid.server.settings.proto.request.InvalidateSettingsCacheRequest; -import org.prebid.server.settings.proto.request.UpdateSettingsCacheRequest; - -import java.util.Collections; - -import static java.util.Arrays.asList; -import static java.util.Collections.singletonList; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -public class AdminCentralServiceTest extends VertxTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - private AdminCentralService adminCentralService; - - @Mock - private LineItemService lineItemService; - - @Mock - private DeliveryProgressService deliveryProgressService; - - @Mock - private CriteriaManager criteriaManager; - - @Mock - private SettingsCache settingsCache; - - @Mock - private SettingsCache ampSettingsCache; - - @Mock - private CachingApplicationSettings cachingApplicationSettings; - - @Mock - private Suspendable suspendable; - - @Before - public void setUp() { - adminCentralService = new AdminCentralService(criteriaManager, lineItemService, deliveryProgressService, - settingsCache, ampSettingsCache, cachingApplicationSettings, - jacksonMapper, singletonList(suspendable)); - } - - @Test - public void processAdminCentralEventShouldAddCriteriaWhenTraceLogAndCriteriaFilterArePresentAndCmdIsStart() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of( - LogTracer.of("start", false, 800L, LogCriteriaFilter.of(null, null, null)), null, null, null, null, - null); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verify(criteriaManager).addCriteria(any(), anyLong()); - } - - @Test - public void processAdminCentralEventShouldAddCriteriaWhenTraceLogAndCriteriaFilterArePresentAndCmdIsStop() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(LogTracer.of("stop", false, 0L, null), - null, null, null, null, null); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verify(criteriaManager).stop(); - } - - @Test - public void processAdminCentralEventShouldStopServicesWhenServicesStopCommandIsPresent() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, null, null, null, null, - ServicesCommand.of("stop")); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verify(suspendable).suspend(); - } - - @Test - public void processAdminCentralEventShouldNotStopServicesWhenServicesCommandIsNotStop() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, null, null, null, null, - ServicesCommand.of("invalid")); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verifyNoInteractions(suspendable); - } - - @Test - public void processAdminCentralEventShouldAddCriteriaAndStopServices() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of( - LogTracer.of("start", false, 800L, LogCriteriaFilter.of(null, null, null)), null, null, null, null, - ServicesCommand.of("stop")); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verify(suspendable).suspend(); - verify(criteriaManager).addCriteria(any(), anyLong()); - } - - @Test - public void processAdminCentralEventShouldNotCallCriteriaManagerWhenCommandIsNull() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of( - LogTracer.of(null, false, 800L, LogCriteriaFilter.of(null, null, null)), null, null, null, null, null); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verifyNoInteractions(criteriaManager); - } - - @Test - public void processAdminCentralEventShouldNotCallCriteriaManagerWhenItIsNotStartOrStop() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of( - LogTracer.of("invalid", false, 800L, LogCriteriaFilter.of(null, null, null)), null, null, - null, null, null); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verifyNoInteractions(criteriaManager); - } - - @Test - public void processAdminCentralEventShouldNotCallSettingsCacheWhenCommandWasNotDefined() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, Command.of(null, null), - Command.of(null, null), null, null, null); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verifyNoInteractions(settingsCache); - verifyNoInteractions(ampSettingsCache); - } - - @Test - public void processAdminCentralEventShouldNotCallSettingsCacheWhenBodyWasNotDefined() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, Command.of("save", null), - Command.of("save", null), null, null, null); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verifyNoInteractions(settingsCache); - verifyNoInteractions(ampSettingsCache); - } - - @Test - public void processAdminCentralEventShouldCallSettings() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, Command.of("save", null), - Command.of("save", null), null, null, null); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verifyNoInteractions(settingsCache); - verifyNoInteractions(ampSettingsCache); - } - - @Test - public void processAdminCentralEventShouldCallSaveAmpSettingsCache() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, null, - Command.of("save", jacksonMapper.mapper().valueToTree(UpdateSettingsCacheRequest - .of(Collections.emptyMap(), Collections.emptyMap()))), null, null, null); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verify(ampSettingsCache).save(any(), any()); - } - - @Test - public void processAdminCentralEventShouldCallInvalidateAmpSettingsCache() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, null, - Command.of("invalidate", jacksonMapper.mapper().valueToTree(InvalidateSettingsCacheRequest - .of(Collections.emptyList(), Collections.emptyList()))), null, null, null); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verify(ampSettingsCache).invalidate(any(), any()); - } - - @Test - public void processAdminCentralEventShouldNotCallAmpSettingsCacheWhenCantParseBody() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, null, - Command.of("save", jacksonMapper.mapper().createObjectNode().put("requests", 1)), null, null, null); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verifyNoInteractions(ampSettingsCache); - } - - @Test - public void processAdminCentralEventShouldCallSaveSettingsCache() throws JsonProcessingException { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, - Command.of("save", jacksonMapper.mapper().valueToTree(UpdateSettingsCacheRequest - .of(Collections.singletonMap("requestId", - jacksonMapper.mapper().writeValueAsString(BidRequest.builder().id("requestId") - .build())), - Collections.singletonMap("impId", - jacksonMapper.mapper().writeValueAsString(Imp.builder().id("impId") - .build()))))), - null, null, null, null); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verify(settingsCache).save(any(), any()); - } - - @Test - public void processAdminCentralEventShouldCallInvalidateSettingsCache() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, - Command.of("invalidate", jacksonMapper.mapper().valueToTree(InvalidateSettingsCacheRequest - .of(Collections.emptyList(), Collections.emptyList()))), null, null, null, null); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verify(settingsCache).invalidate(any(), any()); - } - - @Test - public void processAdminCentralEventShouldNotCallSettingsCacheWhenCantParseBody() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, - Command.of("save", jacksonMapper.mapper().createObjectNode().put("requests", 1)), null, null, null, - null); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verifyNoInteractions(settingsCache); - } - - @Test - public void processAdminCentralEventShouldCallInvalidateLineItemsById() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, - null, null, Command.of("invalidate", jacksonMapper.mapper() - .valueToTree(AdminLineItems.of(singletonList("lineItemId")))), null, null); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verify(lineItemService).invalidateLineItemsByIds(eq(singletonList("lineItemId"))); - verify(deliveryProgressService).invalidateLineItemsByIds(eq(singletonList("lineItemId"))); - } - - @Test - public void processAdminCentralEventShouldCallInvalidateAllLineItems() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, - null, null, Command.of("invalidate", null), null, null); - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verify(lineItemService).invalidateLineItems(); - verify(deliveryProgressService).invalidateLineItems(); - } - - @Test - public void processAdminCentralEventShouldNotCallInvalidateWhenCmdNotDefined() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, - null, null, Command.of(null, null), null, null); - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verifyNoMoreInteractions(lineItemService); - verifyNoMoreInteractions(deliveryProgressService); - } - - @Test - public void processAdminCentralEventShouldNotCallInvalidateWhenCmdHasValueOtherToInvalidate() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, - null, null, Command.of("save", null), null, null); - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verifyNoMoreInteractions(lineItemService); - verifyNoMoreInteractions(deliveryProgressService); - } - - @Test - public void processAdminCentralEventShouldNotCallInvalidateWhenCantParseBody() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, - null, null, Command.of("invalidate", mapper.createObjectNode() - .set("ids", mapper.valueToTree(AdminLineItems.of(singletonList("5"))))), null, - null); - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verifyNoMoreInteractions(lineItemService); - verifyNoMoreInteractions(deliveryProgressService); - } - - @Test - public void processAdminCentralEventShouldNotCallInvalidateAccountsWhenCommandIsNotDefined() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, - null, null, null, Command.of(null, mapper.createObjectNode() - .set("ids", mapper.valueToTree(AdminAccounts.of(singletonList("1001"))))), null); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verifyNoInteractions(cachingApplicationSettings); - } - - @Test - public void processAdminCentralEventShouldNotCallInvalidateAccountsWhenInvalidCommandValue() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, - null, null, null, Command.of("invalid", mapper.valueToTree(AdminAccounts.of(singletonList("1001")))), - null); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verifyNoInteractions(cachingApplicationSettings); - } - - @Test - public void processAdminCentralEventShouldNotCallInvalidateAccountsCantParseBody() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, - null, null, null, Command.of("invalidate", mapper.createObjectNode() - .set("accounts", mapper.valueToTree(AdminAccounts.of(singletonList("5"))))), null); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verifyNoInteractions(cachingApplicationSettings); - } - - @Test - public void processAdminCentralEventShouldInvalidateAccounts() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, - null, null, null, Command.of("invalidate", - mapper.valueToTree(AdminAccounts.of(asList("1001", "1002")))), null); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verify(cachingApplicationSettings).invalidateAccountCache(eq("1001")); - verify(cachingApplicationSettings).invalidateAccountCache(eq("1002")); - } - - @Test - public void processAdminCentralEventShouldInvalidateAllAccounts() { - // given - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, - null, null, null, Command.of("invalidate", mapper.createObjectNode() - .set("ids", mapper.valueToTree(AdminAccounts.of(null)))), null); - - // when - adminCentralService.processAdminCentralEvent(adminCentralResponse); - - // then - verify(cachingApplicationSettings).invalidateAllAccountCache(); - } -} diff --git a/src/test/java/org/prebid/server/deals/AlertHttpServiceTest.java b/src/test/java/org/prebid/server/deals/AlertHttpServiceTest.java deleted file mode 100644 index 3dd501bed23..00000000000 --- a/src/test/java/org/prebid/server/deals/AlertHttpServiceTest.java +++ /dev/null @@ -1,233 +0,0 @@ -package org.prebid.server.deals; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import io.vertx.core.Future; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.VertxTest; -import org.prebid.server.deals.model.AlertEvent; -import org.prebid.server.deals.model.AlertPriority; -import org.prebid.server.deals.model.AlertProxyProperties; -import org.prebid.server.deals.model.AlertSource; -import org.prebid.server.deals.model.DeploymentProperties; -import org.prebid.server.vertx.http.HttpClient; - -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.util.HashMap; -import java.util.List; -import java.util.stream.IntStream; - -import static java.util.Collections.emptyMap; -import static java.util.Collections.singletonList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; - -public class AlertHttpServiceTest extends VertxTest { - - @Rule - public final MockitoRule rule = MockitoJUnit.rule(); - - @Mock - private HttpClient httpClient; - - private ZonedDateTime now; - - private Clock clock; - - private AlertHttpService alertHttpService; - - @Before - public void setUp() { - clock = Clock.fixed(Instant.parse("2019-07-26T10:00:00Z"), ZoneOffset.UTC); - now = ZonedDateTime.now(clock); - final HashMap servicesAlertPeriod = new HashMap<>(); - servicesAlertPeriod.put("pbs-error", 3L); - alertHttpService = new AlertHttpService(jacksonMapper, httpClient, clock, DeploymentProperties.builder() - .pbsVendor("pbsVendor") - .pbsRegion("pbsRegion").pbsHostId("pbsHostId").subSystem("pbsSubSystem").system("pbsSystem") - .dataCenter("pbsDataCenter").infra("pbsInfra").profile("pbsProfile").build(), - AlertProxyProperties.builder().password("password").username("username").timeoutSec(5) - .url("http://localhost") - .alertTypes(servicesAlertPeriod).enabled(true).build()); - } - - @Test - public void alertShouldNotSendAlertWhenServiceIsNotEnabled() { - // given - alertHttpService = new AlertHttpService(jacksonMapper, httpClient, clock, DeploymentProperties.builder() - .pbsVendor("pbsVendor").pbsRegion("pbsRegion").pbsHostId("pbsHostId").subSystem("pbsSubSystem") - .system("pbsSystem").dataCenter("pbsDataCenter").infra("pbsInfra").profile("pbsProfile").build(), - AlertProxyProperties.builder().password("password").username("username").timeoutSec(5) - .alertTypes(emptyMap()) - .url("http://localhost").enabled(false).build()); - - // when - alertHttpService.alert("pbs", AlertPriority.HIGH, "errorMessage"); - - // then - verifyNoInteractions(httpClient); - } - - @Test - public void alertShouldSendAlertWhenServiceIsEnabled() throws JsonProcessingException { - // given - given(httpClient.post(anyString(), any(), anyString(), anyLong())) - .willReturn(Future.succeededFuture()); - - // when - alertHttpService.alert("pbs", AlertPriority.HIGH, "errorMessage"); - - // then - final List requestPayloadObject = getRequestPayload(); - final String id = requestPayloadObject.get(0).getId(); - assertThat(requestPayloadObject) - .isEqualTo(singletonList(AlertEvent.builder().id(id).action("RAISE").priority(AlertPriority.HIGH) - .updatedAt(now).name("pbs").details("errorMessage") - .source(AlertSource.builder().env("pbsProfile").dataCenter("pbsDataCenter").region("pbsRegion") - .system("pbsSystem").subSystem("pbsSubSystem").hostId("pbsHostId").build()).build())); - } - - @Test - public void alertWithPeriodShouldSendAlertFirstTimeWithPassedAlertPriority() throws JsonProcessingException { - // given - given(httpClient.post(anyString(), any(), anyString(), anyLong())) - .willReturn(Future.succeededFuture()); - - // when - alertHttpService.alertWithPeriod("pbs", "pbs-error", AlertPriority.MEDIUM, "errorMessage"); - - // then - final List requestPayloadObject = getRequestPayload(); - final String id = requestPayloadObject.get(0).getId(); - assertThat(requestPayloadObject) - .isEqualTo(singletonList(AlertEvent.builder().id(id).action("RAISE").priority(AlertPriority.MEDIUM) - .updatedAt(now).name("pbs-error").details("Service pbs failed to send request 1 time(s) " - + "with error message : errorMessage") - .source(AlertSource.builder().env("pbsProfile").dataCenter("pbsDataCenter").region("pbsRegion") - .system("pbsSystem").subSystem("pbsSubSystem").hostId("pbsHostId").build()).build())); - } - - @Test - public void alertWithPeriodShouldSendAlertWithPassedPriorityAndWithHighPriorityAfterPeriodLimitReached() - throws JsonProcessingException { - // given - given(httpClient.post(anyString(), any(), anyString(), anyLong())) - .willReturn(Future.succeededFuture()); - - // when - IntStream.range(0, 3).forEach(ignored -> - alertHttpService.alertWithPeriod("pbs", "pbs-error", AlertPriority.MEDIUM, "errorMessage")); - - // then - final ArgumentCaptor requestBodyCaptor = ArgumentCaptor.forClass(String.class); - verify(httpClient, times(2)).post(anyString(), any(), requestBodyCaptor.capture(), anyLong()); - - final List requests = requestBodyCaptor.getAllValues(); - final List alertEvents1 = parseAlertEvents(requests.get(0)); - - final String id = alertEvents1.get(0).getId(); - - assertThat(alertEvents1) - .isEqualTo(singletonList(AlertEvent.builder().id(id).action("RAISE").priority(AlertPriority.MEDIUM) - .updatedAt(now).name("pbs-error").details("Service pbs failed to send request 1 time(s) " - + "with error message : errorMessage") - .source(AlertSource.builder().env("pbsProfile").dataCenter("pbsDataCenter").region("pbsRegion") - .system("pbsSystem").subSystem("pbsSubSystem").hostId("pbsHostId").build()).build())); - - final List alertEvents2 = parseAlertEvents(requests.get(1)); - final String id2 = alertEvents2.get(0).getId(); - - assertThat(alertEvents2) - .isEqualTo(singletonList(AlertEvent.builder().id(id2).action("RAISE").priority(AlertPriority.HIGH) - .updatedAt(now).name("pbs-error").details("Service pbs failed to send request 3 time(s) " - + "with error message : errorMessage") - .source(AlertSource.builder().env("pbsProfile").dataCenter("pbsDataCenter").region("pbsRegion") - .system("pbsSystem").subSystem("pbsSubSystem").hostId("pbsHostId").build()).build())); - } - - @Test - public void alertWithPeriodShouldSendAlertTwoTimesForUnknownServiceWithDefaultPeriod() - throws JsonProcessingException { - // given - given(httpClient.post(anyString(), any(), anyString(), anyLong())) - .willReturn(Future.succeededFuture()); - - // when - IntStream.range(0, 15).forEach(ignored -> - alertHttpService.alertWithPeriod("unknown", "unknown-error", AlertPriority.MEDIUM, "errorMessage")); - - // then - final ArgumentCaptor requestBodyCaptor = ArgumentCaptor.forClass(String.class); - verify(httpClient, times(2)).post(anyString(), any(), requestBodyCaptor.capture(), anyLong()); - - final List requests = requestBodyCaptor.getAllValues(); - final List alertEvents1 = parseAlertEvents(requests.get(0)); - - final String id = alertEvents1.get(0).getId(); - - assertThat(alertEvents1) - .isEqualTo(singletonList(AlertEvent.builder().id(id).action("RAISE").priority(AlertPriority.MEDIUM) - .updatedAt(now).name("unknown-error").details("Service unknown failed to send request" - + " 1 time(s) with error message : errorMessage") - .source(AlertSource.builder().env("pbsProfile").dataCenter("pbsDataCenter").region("pbsRegion") - .system("pbsSystem").subSystem("pbsSubSystem").hostId("pbsHostId").build()).build())); - - final List alertEvents2 = parseAlertEvents(requests.get(1)); - final String id2 = alertEvents2.get(0).getId(); - - assertThat(alertEvents2) - .isEqualTo(singletonList(AlertEvent.builder().id(id2).action("RAISE").priority(AlertPriority.HIGH) - .updatedAt(now).name("unknown-error").details("Service unknown failed to send request" - + " 15 time(s) with error message : errorMessage") - .source(AlertSource.builder().env("pbsProfile").dataCenter("pbsDataCenter").region("pbsRegion") - .system("pbsSystem").subSystem("pbsSubSystem").hostId("pbsHostId").build()).build())); - } - - @Test - public void alertWithPeriodShouldSendAlertFirstTimeWithPassedAlertPriorityForUnknownService() - throws JsonProcessingException { - // given - given(httpClient.post(anyString(), any(), anyString(), anyLong())) - .willReturn(Future.succeededFuture()); - - // when - alertHttpService.alertWithPeriod("unknown", "unknown-error", AlertPriority.MEDIUM, "errorMessage"); - - // then - final List requestPayloadObject = getRequestPayload(); - final String id = requestPayloadObject.get(0).getId(); - assertThat(requestPayloadObject) - .isEqualTo(singletonList(AlertEvent.builder().id(id).action("RAISE").priority(AlertPriority.MEDIUM) - .updatedAt(now).name("unknown-error").details("Service unknown failed to send request " - + "1 time(s) with error message : errorMessage") - .source(AlertSource.builder().env("pbsProfile").dataCenter("pbsDataCenter").region("pbsRegion") - .system("pbsSystem").subSystem("pbsSubSystem").hostId("pbsHostId").build()).build())); - } - - private List getRequestPayload() throws JsonProcessingException { - final ArgumentCaptor requestBodyCaptor = ArgumentCaptor.forClass(String.class); - verify(httpClient).post(anyString(), any(), requestBodyCaptor.capture(), anyLong()); - return parseAlertEvents(requestBodyCaptor.getValue()); - } - - private List parseAlertEvents(String row) throws JsonProcessingException { - return mapper.readValue(row, - new TypeReference<>() { - }); - } -} diff --git a/src/test/java/org/prebid/server/deals/DealsServiceTest.java b/src/test/java/org/prebid/server/deals/DealsServiceTest.java deleted file mode 100644 index 4bbd4d8a008..00000000000 --- a/src/test/java/org/prebid/server/deals/DealsServiceTest.java +++ /dev/null @@ -1,403 +0,0 @@ -package org.prebid.server.deals; - -import com.iab.openrtb.request.Banner; -import com.iab.openrtb.request.BidRequest; -import com.iab.openrtb.request.Deal; -import com.iab.openrtb.request.Device; -import com.iab.openrtb.request.Format; -import com.iab.openrtb.request.Imp; -import com.iab.openrtb.request.Pmp; -import org.assertj.core.api.InstanceOfAssertFactories; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.VertxTest; -import org.prebid.server.auction.BidderAliases; -import org.prebid.server.auction.model.AuctionContext; -import org.prebid.server.auction.model.AuctionParticipation; -import org.prebid.server.auction.model.BidderRequest; -import org.prebid.server.bidder.BidderCatalog; -import org.prebid.server.deals.lineitem.LineItem; -import org.prebid.server.deals.model.MatchLineItemsResult; -import org.prebid.server.deals.proto.LineItemMetaData; -import org.prebid.server.deals.proto.LineItemSize; -import org.prebid.server.log.CriteriaLogManager; -import org.prebid.server.proto.openrtb.ext.request.ExtDeal; -import org.prebid.server.proto.openrtb.ext.request.ExtDealLine; -import org.prebid.server.settings.model.Account; - -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.function.UnaryOperator; - -import static java.util.Arrays.asList; -import static java.util.Collections.emptyList; -import static java.util.Collections.emptyMap; -import static java.util.Collections.singletonList; -import static java.util.Collections.singletonMap; -import static java.util.function.UnaryOperator.identity; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.BDDMockito.given; - -public class DealsServiceTest extends VertxTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private LineItemService lineItemService; - @Mock - private CriteriaLogManager criteriaLogManager; - @Mock - private BidderCatalog bidderCatalog; - - private BidderAliases bidderAliases; - private DealsService dealsService; - - private static final Clock CLOCK = Clock.fixed(Instant.parse("2019-10-10T00:01:00Z"), ZoneOffset.UTC); - - @Before - public void setUp() { - given(lineItemService.accountHasDeals(any())).willReturn(true); - given(lineItemService.findMatchingLineItems(any(), any(), anyString(), any(), any())) - .willReturn(MatchLineItemsResult.of(emptyList())); - - bidderAliases = BidderAliases.of(emptyMap(), emptyMap(), bidderCatalog); - dealsService = new DealsService(lineItemService, jacksonMapper, criteriaLogManager); - } - - @Test - public void matchAndPopulateDealsShouldReturnOriginalBidderRequestIfAccountHasNoDeals() { - // given - given(lineItemService.accountHasDeals(any())).willReturn(false); - - final BidderRequest bidderRequest = givenBidderRequest(request -> request - .imp(singletonList(givenImp(identity())))); - final AuctionContext auctionContext = givenAuctionContext(identity()); - - // when - final BidderRequest result = dealsService.matchAndPopulateDeals(bidderRequest, bidderAliases, auctionContext); - - // then - assertThat(result).isEqualTo(bidderRequest.toBuilder().impIdToDeals(emptyMap()).build()); - } - - @Test - public void matchAndPopulateDealsShouldEnrichImpWithDeals() { - // given - given(lineItemService.findMatchingLineItems(any(), any(), anyString(), any(), any())) - .willReturn(MatchLineItemsResult.of(singletonList(LineItem.of( - LineItemMetaData.builder() - .lineItemId("lineItemId") - .extLineItemId("extLineItemId") - .source("bidder") - .dealId("dealId") - .build(), - null, - null, - ZonedDateTime.now(CLOCK))))); - - final BidderRequest bidderRequest = givenBidderRequest(request -> request - .device(Device.builder().ip("ip").ua("ua").build()) - .imp(singletonList(givenImp(imp -> imp - .id("impId") - .pmp(Pmp.builder() - .deals(singletonList(Deal.builder().id("existingDealId").build())) - .build()))))); - final AuctionContext auctionContext = givenAuctionContext(identity()); - - // when - final BidderRequest result = dealsService.matchAndPopulateDeals(bidderRequest, bidderAliases, auctionContext); - - // then - assertThat(result).satisfies(request -> { - assertThat(request.getImpIdToDeals()) - .containsExactlyEntriesOf(Map.of("impId", singletonList(Deal.builder() - .id("dealId") - .ext(mapper.valueToTree( - ExtDeal.of(ExtDealLine.of("lineItemId", "extLineItemId", null, "bidder")))) - .build()))); - - assertThat(request.getBidRequest()) - .extracting(BidRequest::getImp) - .asInstanceOf(InstanceOfAssertFactories.list(Imp.class)) - .extracting(Imp::getPmp) - .flatExtracting(Pmp::getDeals) - .containsExactly( - Deal.builder().id("existingDealId").build(), - Deal.builder() - .id("dealId") - .ext(mapper.valueToTree( - ExtDeal.of(ExtDealLine.of("lineItemId", "extLineItemId", null, null)))) - .build()); - }); - } - - @Test - public void matchAndPopulateDealsShouldEnrichImpWithDealsAndAddLineItemSizesIfSizesIntersectionMatched() { - // given - given(lineItemService.findMatchingLineItems(any(), any(), anyString(), any(), any())) - .willReturn(MatchLineItemsResult.of(singletonList(LineItem.of( - LineItemMetaData.builder() - .lineItemId("lineItemId") - .extLineItemId("extLineItemId") - .sizes(singletonList(LineItemSize.of(200, 20))) - .source("bidder") - .dealId("dealId") - .build(), - null, - null, - ZonedDateTime.now(CLOCK))))); - - final BidderRequest bidderRequest = givenBidderRequest(request -> request - .device(Device.builder().ip("ip").ua("ua").build()) - .imp(singletonList(givenImp(imp -> imp - .id("impId") - .banner(Banner.builder() - .format(asList( - Format.builder().w(100).h(10).build(), - Format.builder().w(200).h(20).build())) - .build()))))); - final AuctionContext auctionContext = givenAuctionContext(identity()); - - // when - final BidderRequest result = dealsService.matchAndPopulateDeals(bidderRequest, bidderAliases, auctionContext); - - // then - assertThat(result).satisfies(request -> { - assertThat(request.getImpIdToDeals()) - .containsExactlyEntriesOf(Map.of("impId", singletonList(Deal.builder() - .id("dealId") - .ext(mapper.valueToTree(ExtDeal.of(ExtDealLine.of( - "lineItemId", - "extLineItemId", - singletonList(Format.builder().w(200).h(20).build()), - "bidder")))) - .build()))); - - assertThat(request.getBidRequest()) - .extracting(BidRequest::getImp) - .asInstanceOf(InstanceOfAssertFactories.list(Imp.class)) - .extracting(Imp::getPmp) - .flatExtracting(Pmp::getDeals) - .containsExactly( - Deal.builder() - .id("dealId") - .ext(mapper.valueToTree(ExtDeal.of(ExtDealLine.of( - "lineItemId", - "extLineItemId", - singletonList(Format.builder().w(200).h(20).build()), - null)))) - .build()); - }); - } - - @Test - public void matchAndPopulateDealsShouldEnrichImpWithDealsAndNotAddLineItemSizesIfSizesIntersectionNotMatched() { - // given - given(lineItemService.findMatchingLineItems(any(), any(), anyString(), any(), any())) - .willReturn(MatchLineItemsResult.of(singletonList(LineItem.of( - LineItemMetaData.builder() - .lineItemId("lineItemId") - .extLineItemId("extLineItemId") - .sizes(singletonList(LineItemSize.of(200, 20))) - .source("bidder") - .dealId("dealId") - .build(), - null, - null, - ZonedDateTime.now(CLOCK))))); - - final BidderRequest bidderRequest = givenBidderRequest(request -> request - .device(Device.builder().ip("ip").ua("ua").build()) - .imp(singletonList(givenImp(imp -> imp - .id("impId") - .banner(Banner.builder() - .format(singletonList(Format.builder().w(100).h(10).build())) - .build()))))); - final AuctionContext auctionContext = givenAuctionContext(identity()); - - // when - final BidderRequest result = dealsService.matchAndPopulateDeals(bidderRequest, bidderAliases, auctionContext); - - // then - assertThat(result).satisfies(request -> { - assertThat(request.getImpIdToDeals()) - .containsExactlyEntriesOf(Map.of("impId", singletonList(Deal.builder() - .id("dealId") - .ext(mapper.valueToTree(ExtDeal.of(ExtDealLine.of( - "lineItemId", - "extLineItemId", - null, - "bidder")))) - .build()))); - - assertThat(request.getBidRequest()) - .extracting(BidRequest::getImp) - .asInstanceOf(InstanceOfAssertFactories.list(Imp.class)) - .extracting(Imp::getPmp) - .flatExtracting(Pmp::getDeals) - .containsExactly( - Deal.builder() - .id("dealId") - .ext(mapper.valueToTree(ExtDeal.of(ExtDealLine.of( - "lineItemId", - "extLineItemId", - null, - null)))) - .build()); - }); - } - - @Test - public void matchAndPopulateDealsShouldFilterExistingDeals() { - // given - given(lineItemService.findMatchingLineItems(any(), any(), anyString(), any(), any())) - .willReturn(MatchLineItemsResult.of(emptyList())); - - final BidderRequest bidderRequest = givenBidderRequest(request -> request - .device(Device.builder().ip("ip").ua("ua").build()) - .imp(singletonList(givenImp(imp -> imp - .id("impId") - .pmp(Pmp.builder() - .deals(asList( - Deal.builder().id("deal1").build(), - Deal.builder() - .id("deal2") - .ext(mapper.valueToTree(ExtDeal.of(ExtDealLine.of( - null, - null, - null, - "anotherBidder")))) - .build(), - Deal.builder() - .id("deal3") - .ext(mapper.valueToTree(ExtDeal.of(ExtDealLine.of( - null, - null, - null, - "bidder")))) - .build())) - .build()))))); - final AuctionContext auctionContext = givenAuctionContext(identity()); - - // when - final BidderRequest result = dealsService.matchAndPopulateDeals(bidderRequest, bidderAliases, auctionContext); - - // then - assertThat(result).satisfies(request -> { - assertThat(request.getImpIdToDeals()).isEmpty(); - - assertThat(request.getBidRequest()) - .extracting(BidRequest::getImp) - .asInstanceOf(InstanceOfAssertFactories.list(Imp.class)) - .extracting(Imp::getPmp) - .flatExtracting(Pmp::getDeals) - .containsExactly( - Deal.builder().id("deal1").build(), - Deal.builder().id("deal3").build()); - }); - } - - @Test - public void removePgDealsOnlyImpsWithoutDealsShouldRemovePgDealsOnlyImpsWithoutMatchedDeals() { - // given - final List auctionParticipations = asList( - givenAuctionParticipation(givenBidderRequest( - "bidder1", - request -> request.imp(asList( - givenImp(imp -> imp.id("imp1").ext(mapper.createObjectNode())), - givenImp(imp -> imp.id("imp2").ext(mapper.createObjectNode())))), - null)), - givenAuctionParticipation(givenBidderRequest( - "bidder2", - request -> request.imp(asList( - givenImp(imp -> imp - .id("imp1") - .ext(mapper.valueToTree(Map.of("bidder", Map.of("pgdealsonly", true))))), - givenImp(imp -> imp - .id("imp2") - .ext(mapper.valueToTree(Map.of("bidder", Map.of("pgdealsonly", true))))))), - emptyMap())), - givenAuctionParticipation(givenBidderRequest( - "bidder3", - request -> request.imp(asList( - givenImp(imp -> imp - .id("imp1") - .ext(mapper.valueToTree(Map.of("bidder", Map.of("pgdealsonly", true))))), - givenImp(imp -> imp - .id("imp2") - .ext(mapper.valueToTree(Map.of("bidder", Map.of("pgdealsonly", true))))))), - singletonMap("imp2", singletonList(Deal.builder().build()))))); - final AuctionContext auctionContext = givenAuctionContext(identity()); - - // when - final List result = DealsService.removePgDealsOnlyImpsWithoutDeals( - auctionParticipations, auctionContext); - - // then - assertThat(result).containsExactly( - givenAuctionParticipation(givenBidderRequest( - "bidder1", - request -> request.imp(asList( - givenImp(imp -> imp.id("imp1").ext(mapper.createObjectNode())), - givenImp(imp -> imp.id("imp2").ext(mapper.createObjectNode())))), - null)), - givenAuctionParticipation(givenBidderRequest( - "bidder3", - request -> request.imp(singletonList( - givenImp(imp -> imp - .id("imp2") - .ext(mapper.valueToTree(Map.of("bidder", Map.of("pgdealsonly", true))))))), - singletonMap("imp2", singletonList(Deal.builder().build()))))); - assertThat(auctionContext.getDebugWarnings()).containsExactly( - """ - Not calling bidder2 bidder for impressions imp1, imp2 \ - due to pgdealsonly flag and no available PG line items.""", - """ - Not calling bidder3 bidder for impressions imp1 \ - due to pgdealsonly flag and no available PG line items."""); - } - - private static Imp givenImp(UnaryOperator customizer) { - return customizer.apply(Imp.builder()).build(); - } - - private static BidderRequest givenBidderRequest(UnaryOperator customizer) { - return BidderRequest.builder() - .bidder("bidder") - .bidRequest(customizer.apply(BidRequest.builder()).build()) - .build(); - } - - private static BidderRequest givenBidderRequest(String bidder, - UnaryOperator customizer, - Map> impIdToDeals) { - - return BidderRequest.builder() - .bidder(bidder) - .bidRequest(customizer.apply(BidRequest.builder()).build()) - .impIdToDeals(impIdToDeals) - .build(); - } - - private static AuctionParticipation givenAuctionParticipation(BidderRequest bidderRequest) { - return AuctionParticipation.builder().bidderRequest(bidderRequest).build(); - } - - private static AuctionContext givenAuctionContext(UnaryOperator customizer) { - return AuctionContext.builder() - .account(customizer.apply(Account.builder().id("accountId")).build()) - .debugWarnings(new ArrayList<>()) - .build(); - } -} diff --git a/src/test/java/org/prebid/server/deals/DeliveryProgressReportFactoryTest.java b/src/test/java/org/prebid/server/deals/DeliveryProgressReportFactoryTest.java deleted file mode 100644 index ef9daed10eb..00000000000 --- a/src/test/java/org/prebid/server/deals/DeliveryProgressReportFactoryTest.java +++ /dev/null @@ -1,201 +0,0 @@ -package org.prebid.server.deals; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.VertxTest; -import org.prebid.server.deals.lineitem.DeliveryProgress; -import org.prebid.server.deals.lineitem.LineItem; -import org.prebid.server.deals.lineitem.LineItemStatus; -import org.prebid.server.deals.lineitem.LostToLineItem; -import org.prebid.server.deals.model.DeploymentProperties; -import org.prebid.server.deals.proto.DeliverySchedule; -import org.prebid.server.deals.proto.LineItemMetaData; -import org.prebid.server.deals.proto.Token; -import org.prebid.server.deals.proto.report.DeliveryProgressReport; -import org.prebid.server.deals.proto.report.DeliveryProgressReportBatch; - -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.LongAdder; - -import static java.util.Collections.singleton; -import static java.util.Collections.singletonList; -import static java.util.Collections.singletonMap; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.tuple; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - -public class DeliveryProgressReportFactoryTest extends VertxTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private LineItemService lineItemService; - - private DeliveryProgressReportFactory deliveryProgressReportFactory; - - private ZonedDateTime now; - - @Before - public void setUp() { - deliveryProgressReportFactory = new DeliveryProgressReportFactory( - DeploymentProperties.builder().pbsHostId("pbsHost").pbsRegion("pbsRegion") - .pbsVendor("pbsVendor").build(), 2, lineItemService); - - now = ZonedDateTime.now(Clock.fixed(Instant.parse("2019-07-26T10:00:00Z"), ZoneOffset.UTC)); - } - - @Test - public void fromDeliveryProgressShouldCreateReportWithTop2Competitors() { - // given - given(lineItemService.getLineItemById(anyString())) - .willReturn(LineItem.of( - LineItemMetaData.builder() - .accountId("accountId") - .deliverySchedules(singletonList(DeliverySchedule.builder() - .startTimeStamp(now.minusHours(1)) - .endTimeStamp(now.plusHours(1)) - .updatedTimeStamp(now.minusHours(1)) - .build())) - .source("rubicon") - .build(), - null, null, now)); - - final DeliveryProgress deliveryProgress = DeliveryProgress.of(now.minusHours(3), lineItemService); - deliveryProgress.setEndTimeStamp(now.minusHours(2)); - - final Map lostTo = new ConcurrentHashMap<>(); - lostTo.put("lineItemId1", LostToLineItem.of("lineItemId1", makeLongAdderWithValue(100L))); - lostTo.put("lineItemId2", LostToLineItem.of("lineItemId2", makeLongAdderWithValue(50L))); - lostTo.put("lineItemId3", LostToLineItem.of("lineItemId3", makeLongAdderWithValue(80L))); - lostTo.put("lineItemId4", LostToLineItem.of("lineItemId4", makeLongAdderWithValue(120L))); - deliveryProgress.getLineItemIdToLost().put("lineItemId5", lostTo); - deliveryProgress.getLineItemStatuses().put("lineItemId5", LineItemStatus.of("lineItemId5")); - - // when - final DeliveryProgressReport deliveryProgressReport = deliveryProgressReportFactory - .fromDeliveryProgress(deliveryProgress, now, false); - - // then - assertThat(deliveryProgressReport.getLineItemStatus()) - .flatExtracting(org.prebid.server.deals.proto.report.LineItemStatus::getLostToLineItems) - .extracting(org.prebid.server.deals.proto.report.LostToLineItem::getLineItemSource, - org.prebid.server.deals.proto.report.LostToLineItem::getLineItemId, - org.prebid.server.deals.proto.report.LostToLineItem::getCount) - .containsOnly( - tuple("rubicon", "lineItemId4", 120L), - tuple("rubicon", "lineItemId1", 100L)); - } - - @Test - public void fromDeliveryProgressShouldCreateOverallReport() { - // given - given(lineItemService.getLineItemById(anyString())) - .willReturn(LineItem.of( - LineItemMetaData.builder() - .accountId("accountId") - .deliverySchedules(singletonList(DeliverySchedule.builder() - .startTimeStamp(now.minusHours(1)) - .endTimeStamp(now.plusHours(1)) - .updatedTimeStamp(now.minusHours(1)) - .tokens(singleton(Token.of(1, 100))) - .build())) - .source("rubicon") - .build(), - null, null, now)); - - final DeliveryProgress deliveryProgress = mock(DeliveryProgress.class); - given(deliveryProgress.getRequests()).willReturn(new LongAdder()); - given(deliveryProgress.getLineItemStatuses()).willReturn(singletonMap("lineItemId1", - LineItemStatus.of("lineItemId1"))); - deliveryProgress.setEndTimeStamp(now.minusHours(2)); - - // when - final DeliveryProgressReport deliveryProgressReport = deliveryProgressReportFactory - .fromDeliveryProgress(deliveryProgress, now, true); - - // then - assertThat(deliveryProgressReport.getLineItemStatus()) - .extracting(org.prebid.server.deals.proto.report.LineItemStatus::getReadyAt, - org.prebid.server.deals.proto.report.LineItemStatus::getPacingFrequency, - org.prebid.server.deals.proto.report.LineItemStatus::getSpentTokens) - .containsOnly(tuple("2019-07-26T10:00:00.000Z", 72000L, 0L)); - } - - @Test - public void fromDeliveryProgressShouldDropLineItemsWithoutDeliverySchedule() { - // given - given(lineItemService.getLineItemById(anyString())) - .willReturn(LineItem.of( - LineItemMetaData.builder() - .accountId("accountId") - .source("rubicon") - .build(), - null, null, now)); - - final DeliveryProgress deliveryProgress = DeliveryProgress.of(now.minusHours(3), lineItemService); - deliveryProgress.setEndTimeStamp(now.minusHours(2)); - - // when - final DeliveryProgressReport deliveryProgressReport = deliveryProgressReportFactory - .fromDeliveryProgress(deliveryProgress, now, false); - - // then - assertThat(deliveryProgressReport.getLineItemStatus()).isEmpty(); - } - - @Test - public void batchFromDeliveryProgressShouldCreateTwoReportsInBatchWithSameId() { - // given - given(lineItemService.getLineItemById(anyString())) - .willReturn(LineItem.of( - LineItemMetaData.builder() - .accountId("accountId") - .deliverySchedules(singletonList(DeliverySchedule.builder() - .startTimeStamp(now.minusHours(1)) - .endTimeStamp(now.plusHours(1)) - .updatedTimeStamp(now.minusHours(1)) - .build())) - .source("rubicon") - .build(), - null, null, now)); - - final DeliveryProgress deliveryProgress = DeliveryProgress.of(now.minusHours(3), lineItemService); - deliveryProgress.setEndTimeStamp(now.minusHours(2)); - - deliveryProgress.getLineItemStatuses().put("lineItemId1", LineItemStatus.of("lineItemId1")); - deliveryProgress.getLineItemStatuses().put("lineItemId2", LineItemStatus.of("lineItemId2")); - deliveryProgress.getLineItemStatuses().put("lineItemId3", LineItemStatus.of("lineItemId3")); - - // when - final DeliveryProgressReportBatch deliveryProgressReportBatch = deliveryProgressReportFactory - .batchFromDeliveryProgress(deliveryProgress, null, now, 2, false); - - // then - final Set reports = deliveryProgressReportBatch.getReports(); - assertThat(reports).hasSize(2) - .extracting(DeliveryProgressReport::getReportId) - .containsOnly(deliveryProgressReportBatch.getReportId()); - assertThat(reports) - .extracting(deliveryProgressReport -> deliveryProgressReport.getLineItemStatus().size()) - .containsOnly(1, 2); - } - - private static LongAdder makeLongAdderWithValue(Long value) { - final LongAdder longAdder = new LongAdder(); - longAdder.add(value); - return longAdder; - } -} diff --git a/src/test/java/org/prebid/server/deals/DeliveryProgressServiceTest.java b/src/test/java/org/prebid/server/deals/DeliveryProgressServiceTest.java deleted file mode 100644 index 2981b1bc179..00000000000 --- a/src/test/java/org/prebid/server/deals/DeliveryProgressServiceTest.java +++ /dev/null @@ -1,426 +0,0 @@ -package org.prebid.server.deals; - -import org.assertj.core.api.iterable.ThrowingExtractor; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.VertxTest; -import org.prebid.server.auction.model.AuctionContext; -import org.prebid.server.deals.lineitem.DeliveryPlan; -import org.prebid.server.deals.lineitem.DeliveryProgress; -import org.prebid.server.deals.lineitem.DeliveryToken; -import org.prebid.server.deals.lineitem.LineItem; -import org.prebid.server.deals.lineitem.LineItemStatus; -import org.prebid.server.deals.lineitem.LostToLineItem; -import org.prebid.server.deals.model.DeliveryProgressProperties; -import org.prebid.server.deals.model.TxnLog; -import org.prebid.server.deals.proto.DeliverySchedule; -import org.prebid.server.deals.proto.LineItemMetaData; -import org.prebid.server.deals.proto.Price; -import org.prebid.server.deals.proto.Token; -import org.prebid.server.deals.proto.report.Event; -import org.prebid.server.deals.proto.report.LineItemStatusReport; -import org.prebid.server.log.CriteriaLogManager; -import org.prebid.server.settings.model.Account; - -import java.math.BigDecimal; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.LongAdder; -import java.util.function.UnaryOperator; -import java.util.stream.IntStream; - -import static java.util.Arrays.asList; -import static java.util.Collections.singleton; -import static java.util.Collections.singletonList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.tuple; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.verify; - -public class DeliveryProgressServiceTest extends VertxTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private LineItemService lineItemService; - @Mock - private DeliveryStatsService deliveryStatsService; - @Mock - private DeliveryProgressReportFactory deliveryProgressReportFactory; - @Mock - private CriteriaLogManager criteriaLogManager; - - private DeliveryProgressService deliveryProgressService; - - private final Clock clock = Clock.fixed(Instant.parse("2019-07-26T10:00:00Z"), ZoneOffset.UTC); - private ZonedDateTime now; - - @Before - public void setUp() { - now = ZonedDateTime.now(clock); - - deliveryProgressService = new DeliveryProgressService( - DeliveryProgressProperties.of(200L, 20), - lineItemService, - deliveryStatsService, - deliveryProgressReportFactory, - clock, - criteriaLogManager); - } - - @Test - public void updateLineItemsShouldUpdateCurrentDeliveryReportIfUpdatedPlanUpdateTimeStampIsInFuture() { - // given - final LineItemMetaData firstPlanResponse = givenLineItemMetaData( - now, - lineItemMetaData -> lineItemMetaData - .lineItemId("lineItem1") - .accountId("1001") - .source("rubicon") - .deliverySchedules(singletonList( - givenDeliverySchedule( - "planId1", - now.minusHours(1), - now.plusHours(1), - now, - singleton(Token.of(1, 100)))))); - final LineItemMetaData secondPlanResponse = givenLineItemMetaData( - now, - lineItemMetaData -> lineItemMetaData - .lineItemId("lineItem1") - .accountId("1001") - .source("rubicon") - .deliverySchedules(singletonList( - givenDeliverySchedule( - "planId1", - now.minusHours(1), - now.plusHours(1), - now.plusMinutes(1), - singleton(Token.of(1, 200)))))); - - final LineItem lineItem1 = LineItem.of(firstPlanResponse, null, null, now); - final LineItem lineItem12 = LineItem.of(secondPlanResponse, null, null, now); - - given(lineItemService.getLineItems()).willReturn( - singletonList(lineItem1), - singletonList(lineItem12)); - - given(lineItemService.getLineItemById(anyString())).willReturn( - lineItem12); - - // when - deliveryProgressService.processDeliveryProgressUpdateEvent(); - recordLineItemsServed(40, "lineItem1"); - deliveryProgressService.processDeliveryProgressUpdateEvent(); - - // then - // trigger overall progress passing to report factory - deliveryProgressService.getOverallDeliveryProgressReport(); - - final ArgumentCaptor overallProgressCaptor = ArgumentCaptor.forClass(DeliveryProgress.class); - verify(deliveryProgressReportFactory).fromDeliveryProgress(overallProgressCaptor.capture(), any(), - anyBoolean()); - - final DeliveryProgress overallProgress = overallProgressCaptor.getValue(); - assertThat(overallProgress).isNotNull(); - assertThat(overallProgress.getLineItemStatuses()).isNotNull(); - assertThat(overallProgress.getLineItemStatuses().keySet()) - .containsOnly("lineItem1"); - final LineItemStatus overallLineItemStatus = overallProgress.getLineItemStatuses().get("lineItem1"); - assertThat(overallLineItemStatus).isNotNull(); - assertThat(overallLineItemStatus.getDeliveryPlans()) - .extracting(DeliveryPlan::getPlanId, DeliveryPlan::getStartTimeStamp, DeliveryPlan::getEndTimeStamp, - DeliveryPlan::getUpdatedTimeStamp) - .containsOnly(tuple("planId1", now.minusHours(1), now.plusHours(1), now.plusMinutes(1))); - assertThat(overallLineItemStatus.getDeliveryPlans()) - .flatExtracting(DeliveryPlan::getDeliveryTokens) - .extracting(DeliveryToken::getPriorityClass, DeliveryToken::getTotal, token -> token.getSpent().sum()) - .containsOnly(tuple(1, 200, 40L)); - - // trigger current progress passing to delivery stats - deliveryProgressService.shutdown(); - - final ArgumentCaptor currentProgressCaptor = ArgumentCaptor.forClass(DeliveryProgress - .class); - verify(deliveryStatsService).addDeliveryProgress(currentProgressCaptor.capture(), any()); - - final DeliveryProgress currentProgress = currentProgressCaptor.getValue(); - assertThat(currentProgress).isNotNull(); - assertThat(currentProgress.getLineItemStatuses()).isNotNull(); - final LineItemStatus currentLineItemStatus = currentProgress.getLineItemStatuses().get("lineItem1"); - assertThat(currentLineItemStatus).isNotNull(); - assertThat(currentLineItemStatus.getDeliveryPlans()) - .extracting(DeliveryPlan::getPlanId, DeliveryPlan::getStartTimeStamp, DeliveryPlan::getEndTimeStamp, - DeliveryPlan::getUpdatedTimeStamp) - .containsOnly(tuple("planId1", now.minusHours(1), now.plusHours(1), now.plusMinutes(1))); - assertThat(currentLineItemStatus.getDeliveryPlans()) - .flatExtracting(DeliveryPlan::getDeliveryTokens) - .extracting(DeliveryToken::getPriorityClass, DeliveryToken::getTotal, token -> token.getSpent().sum()) - .containsOnly(tuple(1, 200, 40L)); - } - - @Test - public void processAuctionEventShouldUpdateCurrentPlan() { - // given - final String lineItemId1 = "lineItemId1"; - final String lineItemId2 = "lineItemId2"; - - final LineItem lineItem1 = LineItem.of( - givenLineItemMetaData( - now, - lineItemMetaData -> lineItemMetaData - .lineItemId(lineItemId1) - .accountId("1001") - .source("rubicon") - .deliverySchedules(singletonList( - givenDeliverySchedule( - "plan1", - now.minusHours(1), - now.plusHours(1), - Set.of(Token.of(1, 100), Token.of(2, 100)))))), - null, - null, - now); - final LineItem lineItem2 = LineItem.of( - givenLineItemMetaData( - now, - lineItemMetaData -> lineItemMetaData - .lineItemId(lineItemId2) - .accountId("1001") - .source("rubicon") - .deliverySchedules(singletonList( - givenDeliverySchedule( - "plan2", - now.minusHours(1), - now.plusHours(1), - Set.of(Token.of(1, 100), Token.of(2, 100)))))), - null, - null, - now); - - given(lineItemService.getLineItemById(eq(lineItemId1))).willReturn(lineItem1); - given(lineItemService.getLineItemById(eq(lineItemId2))).willReturn(lineItem2); - - recordLineItemsServed(150, lineItemId1); - - final TxnLog txnLog = TxnLog.create(); - txnLog.lineItemSentToClientAsTopMatch().addAll(asList(lineItemId1, lineItemId2)); - txnLog.lineItemsSentToClient().addAll(asList(lineItemId1, lineItemId2)); - txnLog.lineItemsMatchedDomainTargeting().addAll(asList(lineItemId1, lineItemId2)); - txnLog.lineItemsMatchedWholeTargeting().addAll(asList(lineItemId1, lineItemId2)); - txnLog.lineItemsMatchedTargetingFcapped().addAll(asList(lineItemId1, lineItemId2)); - txnLog.lineItemsMatchedTargetingFcapLookupFailed().addAll(asList(lineItemId1, lineItemId2)); - txnLog.lineItemsSentToBidder().put("rubicon", new HashSet<>(asList(lineItemId1, lineItemId2))); - txnLog.lineItemsSentToBidderAsTopMatch().put("rubicon", singleton(lineItemId1)); - txnLog.lineItemsSentToBidderAsTopMatch().put("appnexus", singleton(lineItemId2)); - txnLog.lineItemsReceivedFromBidder().put("rubicon", new HashSet<>(asList(lineItemId1, lineItemId2))); - txnLog.lineItemsResponseInvalidated().addAll(asList(lineItemId1, lineItemId2)); - txnLog.lostMatchingToLineItems().put(lineItemId1, singleton(lineItemId2)); - - // when and then - deliveryProgressService.processAuctionEvent(AuctionContext.builder() - .account(Account.empty("1001")) - .txnLog(txnLog) - .build()); - deliveryProgressService.createDeliveryProgressReports(now); - - final ArgumentCaptor deliveryProgressReportCaptor = - ArgumentCaptor.forClass(DeliveryProgress.class); - verify(deliveryStatsService).addDeliveryProgress(deliveryProgressReportCaptor.capture(), any()); - final DeliveryProgress deliveryProgress = deliveryProgressReportCaptor.getValue(); - assertThat(deliveryProgress.getRequests().sum()).isEqualTo(151); - - final Set lineItemStatuses = new HashSet<>(deliveryProgress.getLineItemStatuses().values()); - - checkLineItemStatusStats(lineItemStatuses, LineItemStatus::getDomainMatched, 1L, 1L); - checkLineItemStatusStats(lineItemStatuses, LineItemStatus::getTargetMatched, 1L, 1L); - checkLineItemStatusStats(lineItemStatuses, LineItemStatus::getTargetMatchedButFcapped, 1L, 1L); - checkLineItemStatusStats(lineItemStatuses, LineItemStatus::getTargetMatchedButFcapLookupFailed, 1L, 1L); - checkLineItemStatusStats(lineItemStatuses, LineItemStatus::getSentToBidder, 1L, 1L); - checkLineItemStatusStats(lineItemStatuses, LineItemStatus::getReceivedFromBidder, 1L, 1L); - checkLineItemStatusStats(lineItemStatuses, LineItemStatus::getReceivedFromBidderInvalidated, 1L, 1L); - checkLineItemStatusStats(lineItemStatuses, LineItemStatus::getSentToClientAsTopMatch, 151L, 1L); - checkLineItemStatusStats(lineItemStatuses, LineItemStatus::getSentToBidderAsTopMatch, 1L, 1L); - checkLineItemStatusStats(lineItemStatuses, LineItemStatus::getSentToClient, 1L, 1L); - - assertThat(deliveryProgress.getLineItemIdToLost()) - .extracting(lineItemId1) - .extracting(lineItemId2) - .extracting(lostToLineItem -> ((LostToLineItem) lostToLineItem).getCount().sum()) - .isEqualTo(1L); - - assertThat(lineItemStatuses) - .flatExtracting(LineItemStatus::getDeliveryPlans) - .flatExtracting(DeliveryPlan::getDeliveryTokens) - .extracting(DeliveryToken::getPriorityClass, DeliveryToken::getTotal, - deliveryToken -> deliveryToken.getSpent().sum()) - .containsOnly( - tuple(1, 100, 100L), - tuple(2, 100, 51L), - tuple(1, 100, 1L), - tuple(2, 100, 0L)); - - assertThat(lineItem1.getActiveDeliveryPlan().getDeliveryTokens()) - .extracting(DeliveryToken::getPriorityClass, DeliveryToken::getTotal, token -> token.getSpent().sum()) - .containsExactly( - tuple(1, 100, 100L), - tuple(2, 100, 51L)); - - assertThat(lineItem2.getActiveDeliveryPlan().getDeliveryTokens()) - .extracting(DeliveryToken::getPriorityClass, DeliveryToken::getTotal, token -> token.getSpent().sum()) - .containsExactly( - tuple(1, 100, 1L), - tuple(2, 100, 0L)); - } - - @Test - public void trackWinEventShouldCreateLineItemStatusAndUpdateWinEventsMetric() { - // given - final LineItem lineItem = LineItem.of( - givenLineItemMetaData( - now, - lineItemMetaData -> lineItemMetaData - .lineItemId("lineItemId1") - .accountId("1001") - .source("rubicon") - .deliverySchedules(singletonList( - givenDeliverySchedule( - "plan1", - now.minusHours(1), - now.plusHours(1), - Set.of(Token.of(1, 100), Token.of(2, 100)))))), - null, - null, - now); - - given(lineItemService.getLineItemById(eq("lineItemId1"))).willReturn(lineItem); - - // when - deliveryProgressService.processLineItemWinEvent("lineItemId1"); - - // then - // trigger current progress passing to delivery stats - deliveryProgressService.shutdown(); - - final ArgumentCaptor currentProgressCaptor = ArgumentCaptor.forClass(DeliveryProgress.class); - verify(deliveryStatsService).addDeliveryProgress(currentProgressCaptor.capture(), any()); - - final DeliveryProgress currentProgress = currentProgressCaptor.getValue(); - assertThat(currentProgress).isNotNull(); - assertThat(currentProgress.getLineItemStatuses().entrySet()).hasSize(1) - .extracting(Map.Entry::getValue) - .flatExtracting(LineItemStatus::getEvents) - .extracting(Event::getType, event -> event.getCount().sum()) - .containsOnly(tuple("win", 1L)); - } - - @Test - public void getLineItemStatusReportShouldReturnExpectedResult() { - // given - final LineItem lineItem = LineItem.of( - givenLineItemMetaData( - now, - lineItemMetaData -> lineItemMetaData - .lineItemId("lineItemId1") - .accountId("1001") - .source("rubicon") - .deliverySchedules(singletonList( - givenDeliverySchedule( - "plan1", - now.minusHours(1), - now.plusHours(1), - singleton(Token.of(1, 100))))) - .targeting(mapper.createObjectNode().put("targetingField", "targetingValue"))), - null, - null, - now); - given(lineItemService.getLineItemById(anyString())).willReturn(lineItem); - - // when - final LineItemStatusReport report = deliveryProgressService.getLineItemStatusReport("lineItemId1"); - - // then - assertThat(report).isEqualTo(LineItemStatusReport.builder() - .lineItemId("lineItemId1") - .deliverySchedule(org.prebid.server.deals.proto.report.DeliverySchedule.builder() - .planId("plan1") - .planStartTimeStamp("2019-07-26T09:00:00.000Z") - .planExpirationTimeStamp("2019-07-26T11:00:00.000Z") - .planUpdatedTimeStamp("2019-07-26T09:00:00.000Z") - .tokens(singleton(org.prebid.server.deals.proto.report.Token.of(1, 100, 0L, null))) - .build()) - .readyToServeTimestamp(now) - .spentTokens(0L) - .pacingFrequency(72000L) - .accountId("1001") - .target(mapper.createObjectNode().put("targetingField", "targetingValue")) - .build()); - } - - private static LineItemMetaData givenLineItemMetaData( - ZonedDateTime now, - UnaryOperator lineItemMetaDataCustomizer) { - - return lineItemMetaDataCustomizer - .apply(LineItemMetaData.builder() - .dealId("dealId") - .status("active") - .price(Price.of(BigDecimal.ONE, "USD")) - .relativePriority(5) - .startTimeStamp(now.minusHours(1)) - .endTimeStamp(now.plusHours(1)) - .updatedTimeStamp(now)) - .build(); - } - - private static DeliverySchedule givenDeliverySchedule(String planId, ZonedDateTime start, ZonedDateTime end, - ZonedDateTime updated, Set tokens) { - return DeliverySchedule.builder() - .planId(planId) - .startTimeStamp(start) - .endTimeStamp(end) - .updatedTimeStamp(updated) - .tokens(tokens) - .build(); - } - - private static DeliverySchedule givenDeliverySchedule(String planId, ZonedDateTime start, ZonedDateTime end, - Set tokens) { - return givenDeliverySchedule(planId, start, end, start, tokens); - } - - private static void checkLineItemStatusStats(Set lineItemStatuses, - ThrowingExtractor stat, - Long... values) { - assertThat(lineItemStatuses) - .extracting(stat) - .extracting(LongAdder::sum) - .containsOnly(values); - } - - private void recordLineItemsServed(int times, String... lineItemIds) { - final TxnLog txnLog = TxnLog.create(); - final AuctionContext auctionContext = AuctionContext.builder() - .account(Account.empty("1001")) - .txnLog(txnLog) - .build(); - txnLog.lineItemSentToClientAsTopMatch().addAll(asList(lineItemIds)); - IntStream.range(0, times).forEach(i -> deliveryProgressService.processAuctionEvent(auctionContext)); - - } -} diff --git a/src/test/java/org/prebid/server/deals/DeliveryStatsServiceTest.java b/src/test/java/org/prebid/server/deals/DeliveryStatsServiceTest.java deleted file mode 100644 index 07badbbc5c3..00000000000 --- a/src/test/java/org/prebid/server/deals/DeliveryStatsServiceTest.java +++ /dev/null @@ -1,428 +0,0 @@ -package org.prebid.server.deals; - -import com.fasterxml.jackson.core.JsonProcessingException; -import io.vertx.core.Future; -import io.vertx.core.MultiMap; -import io.vertx.core.Vertx; -import org.apache.http.HttpHeaders; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.VertxTest; -import org.prebid.server.deals.lineitem.DeliveryProgress; -import org.prebid.server.deals.model.AlertPriority; -import org.prebid.server.deals.model.DeliveryStatsProperties; -import org.prebid.server.deals.proto.report.DeliveryProgressReport; -import org.prebid.server.deals.proto.report.DeliveryProgressReportBatch; -import org.prebid.server.deals.proto.report.LineItemStatus; -import org.prebid.server.metric.Metrics; -import org.prebid.server.vertx.http.HttpClient; -import org.prebid.server.vertx.http.model.HttpClientResponse; -import org.springframework.test.util.ReflectionTestUtils; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.util.HashSet; -import java.util.NavigableSet; -import java.util.concurrent.TimeoutException; -import java.util.zip.GZIPInputStream; - -import static java.util.Arrays.asList; -import static java.util.Collections.emptyMap; -import static java.util.Collections.emptySet; -import static java.util.Collections.singleton; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; - -public class DeliveryStatsServiceTest extends VertxTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private DeliveryProgressReportFactory deliveryProgressReportFactory; - @Mock - private AlertHttpService alertHttpService; - @Mock - private HttpClient httpClient; - @Mock - private Clock clock; - @Mock - private Metrics metrics; - - @Mock - private Vertx vertx; - - private DeliveryStatsService deliveryStatsService; - - private ZonedDateTime now; - - @Mock - private LineItemService lineItemService; - - @Before - public void setUp() { - now = ZonedDateTime.now(Clock.fixed(Instant.parse("2019-07-26T10:00:00Z"), ZoneOffset.UTC)); - given(clock.instant()).willReturn(now.toInstant()); - given(clock.getZone()).willReturn(ZoneOffset.UTC); - - deliveryStatsService = new DeliveryStatsService( - DeliveryStatsProperties.builder() - .endpoint("localhost/delivery") - .cachedReportsNumber(3) - .timeoutMs(500L) - .reportsIntervalMs(0) - .batchesIntervalMs(0) - .username("username") - .password("password") - .build(), - deliveryProgressReportFactory, - alertHttpService, - httpClient, - metrics, - clock, - vertx, - jacksonMapper); - } - - @SuppressWarnings("unchecked") - @Test - public void sendDeliveryProgressReportShouldSendBothBatches() { - // given - givenDeliveryProgressHttpResponse(httpClient, 200, null); - - given(deliveryProgressReportFactory.batchFromDeliveryProgress(any(), any(), any(), anyInt(), anyBoolean())) - .willReturn( - DeliveryProgressReportBatch.of(singleton(DeliveryProgressReport.builder().reportId("1") - .lineItemStatus(emptySet()) - .dataWindowEndTimeStamp(now.minusHours(2).toString()).build()), "1", - now.minusHours(2).toString()), - DeliveryProgressReportBatch.of(singleton(DeliveryProgressReport.builder().reportId("2") - .lineItemStatus(emptySet()) - .dataWindowEndTimeStamp(now.minusHours(1).toString()).build()), "2", - now.minusHours(1).toString())); - - final DeliveryProgress deliveryProgress1 = DeliveryProgress.of(now.minusHours(3), lineItemService); - final DeliveryProgress deliveryProgress2 = DeliveryProgress.of(now.minusHours(2), lineItemService); - - // when - deliveryStatsService.addDeliveryProgress(deliveryProgress1, emptyMap()); - deliveryStatsService.addDeliveryProgress(deliveryProgress2, emptyMap()); - deliveryStatsService.sendDeliveryProgressReports(); - - // then - verify(httpClient, times(2)).post(anyString(), any(), anyString(), anyLong()); - final NavigableSet reports = (NavigableSet) - ReflectionTestUtils.getField(deliveryStatsService, "requiredBatches"); - assertThat(reports).isEmpty(); - verify(metrics, times(2)).updateDeliveryRequestMetric(eq(true)); - } - - @SuppressWarnings("unchecked") - @Test - public void sendDeliveryProgressReportShouldSendOneBatchAndCacheFailedBatch() { - // given - final DeliveryProgress deliveryProgress1 = DeliveryProgress.of(now.minusHours(3), lineItemService); - final DeliveryProgress deliveryProgress2 = DeliveryProgress.of(now.minusHours(2), lineItemService); - - given(deliveryProgressReportFactory.batchFromDeliveryProgress(any(), any(), any(), anyInt(), anyBoolean())) - .willReturn( - DeliveryProgressReportBatch.of(singleton(DeliveryProgressReport.builder().reportId("1") - .lineItemStatus(emptySet()) - .dataWindowEndTimeStamp(now.minusHours(2).toString()).build()), "1", - now.minusHours(2).toString()), - DeliveryProgressReportBatch.of(singleton(DeliveryProgressReport.builder().reportId("2") - .lineItemStatus(emptySet()) - .dataWindowEndTimeStamp(now.minusHours(1).toString()).build()), "2", - now.minusHours(1).toString())); - - deliveryStatsService.addDeliveryProgress(deliveryProgress1, null); - deliveryStatsService.addDeliveryProgress(deliveryProgress2, null); - - given(httpClient.post(anyString(), any(), anyString(), anyLong())) - .willReturn(Future.succeededFuture(HttpClientResponse.of(200, null, null)), - Future.failedFuture(new TimeoutException())); - - deliveryStatsService.sendDeliveryProgressReports(); - - // when and then - verify(httpClient, times(2)).post(anyString(), any(), anyString(), anyLong()); - final NavigableSet reports = (NavigableSet) - ReflectionTestUtils.getField(deliveryStatsService, "requiredBatches"); - assertThat(reports).hasSize(1); - verify(metrics).updateDeliveryRequestMetric(eq(true)); - verify(metrics).updateDeliveryRequestMetric(eq(false)); - } - - @Test - public void sendDeliveryProgressReportShouldSendFirstReportFromFirstBatchFailOnSecondsAndCacheOther() { - // given - final DeliveryProgress deliveryProgress1 = DeliveryProgress.of(now.minusHours(3), lineItemService); - final DeliveryProgress deliveryProgress2 = DeliveryProgress.of(now.minusHours(2), lineItemService); - - given(deliveryProgressReportFactory.batchFromDeliveryProgress(any(), any(), any(), anyInt(), anyBoolean())) - .willReturn( - DeliveryProgressReportBatch.of( - new HashSet<>(asList(DeliveryProgressReport.builder().reportId("1") - .lineItemStatus(singleton(LineItemStatus.builder().lineItemId("1") - .build())) - .dataWindowEndTimeStamp(now.minusHours(2).toString()).build(), - DeliveryProgressReport.builder().reportId("1") - .lineItemStatus(singleton(LineItemStatus.builder().lineItemId("2") - .build())) - .dataWindowEndTimeStamp(now.minusHours(2).toString()).build())), - "1", now.minusHours(2).toString()), - DeliveryProgressReportBatch.of( - new HashSet<>(asList(DeliveryProgressReport.builder().reportId("2") - .lineItemStatus(singleton(LineItemStatus.builder().lineItemId("1") - .build())) - .dataWindowEndTimeStamp(now.minusHours(3).toString()).build(), - DeliveryProgressReport.builder().reportId("2") - .lineItemStatus(singleton(LineItemStatus.builder().lineItemId("2") - .build())) - .dataWindowEndTimeStamp(now.minusHours(3).toString()).build())), - "2", now.minusHours(3).toString())); - - deliveryStatsService.addDeliveryProgress(deliveryProgress1, null); - deliveryStatsService.addDeliveryProgress(deliveryProgress2, null); - - given(httpClient.post(anyString(), any(), anyString(), anyLong())) - .willReturn(Future.succeededFuture(HttpClientResponse.of(200, null, null)), - Future.failedFuture(new TimeoutException())); - - deliveryStatsService.sendDeliveryProgressReports(); - - // when and then - verify(httpClient, times(2)).post(anyString(), any(), anyString(), anyLong()); - final NavigableSet reports = (NavigableSet) - ReflectionTestUtils.getField(deliveryStatsService, "requiredBatches"); - assertThat(reports).hasSize(2) - .flatExtracting(DeliveryProgressReportBatch::getReports) - .hasSize(3); - verify(metrics).updateDeliveryRequestMetric(eq(true)); - verify(metrics).updateDeliveryRequestMetric(eq(false)); - } - - @Test - public void sendDeliveryProgressReportShouldHandleFailedBatchesCacheLimitWhenResponseStatusIsBadRequest() { - // given - given(deliveryProgressReportFactory.batchFromDeliveryProgress(any(), any(), any(), anyInt(), anyBoolean())) - .willReturn( - DeliveryProgressReportBatch.of(singleton(DeliveryProgressReport.builder().reportId("1") - .dataWindowEndTimeStamp(now.minusHours(4).toString()).build()), "1", - now.minusHours(4).toString()), - DeliveryProgressReportBatch.of(singleton(DeliveryProgressReport.builder().reportId("2") - .dataWindowEndTimeStamp(now.minusHours(3).toString()).build()), "2", - now.minusHours(3).toString()), - DeliveryProgressReportBatch.of(singleton(DeliveryProgressReport.builder().reportId("3") - .dataWindowEndTimeStamp(now.minusHours(2).toString()).build()), "3", - now.minusHours(2).toString()), - DeliveryProgressReportBatch.of(singleton(DeliveryProgressReport.builder().reportId("4") - .dataWindowEndTimeStamp(now.minusHours(1).toString()).build()), "4", - now.minusHours(1).toString())); - - final DeliveryProgress deliveryProgress1 = DeliveryProgress.of(now.minusHours(5), lineItemService); - final DeliveryProgress deliveryProgress2 = DeliveryProgress.of(now.minusHours(4), lineItemService); - final DeliveryProgress deliveryProgress3 = DeliveryProgress.of(now.minusHours(3), lineItemService); - final DeliveryProgress deliveryProgress4 = DeliveryProgress.of(now.minusHours(2), lineItemService); - - deliveryStatsService.addDeliveryProgress(deliveryProgress1, null); - deliveryStatsService.addDeliveryProgress(deliveryProgress2, null); - deliveryStatsService.addDeliveryProgress(deliveryProgress3, null); - deliveryStatsService.addDeliveryProgress(deliveryProgress4, null); - - given(httpClient.post(anyString(), any(), anyString(), anyLong())) - .willReturn(Future.succeededFuture(HttpClientResponse.of(400, null, null))); - - deliveryStatsService.sendDeliveryProgressReports(); - - // when and then - verify(httpClient).post(anyString(), any(), anyString(), anyLong()); - @SuppressWarnings("unchecked") final NavigableSet reports = (NavigableSet) - ReflectionTestUtils.getField(deliveryStatsService, "requiredBatches"); - assertThat(reports).hasSize(3); - } - - @Test - public void sendDeliveryProgressReportShouldShouldRemoveReportFromQueueWhenDelStatsRespondWith409Conflict() { - // given - givenDeliveryProgressHttpResponse(httpClient, 409, null); - - given(deliveryProgressReportFactory.batchFromDeliveryProgress(any(), any(), any(), anyInt(), anyBoolean())) - .willReturn(DeliveryProgressReportBatch.of(singleton(DeliveryProgressReport.builder().reportId("1") - .lineItemStatus(emptySet()) - .dataWindowEndTimeStamp(now.minusHours(2).toString()).build()), "1", - now.minusHours(2).toString())); - - final DeliveryProgress deliveryProgress = DeliveryProgress.of(now.minusHours(3), lineItemService); - - // when - deliveryStatsService.addDeliveryProgress(deliveryProgress, emptyMap()); - deliveryStatsService.sendDeliveryProgressReports(); - - // then - final NavigableSet reports = - (NavigableSet) ReflectionTestUtils.getField(deliveryStatsService, "requiredBatches"); - assertThat(reports).isEmpty(); - } - - @Test - public void sendDeliveryProgressReportShouldCallAlertServiceWhenRequestFailed() { - // given - given(deliveryProgressReportFactory.batchFromDeliveryProgress(any(), any(), any(), anyInt(), anyBoolean())) - .willReturn(DeliveryProgressReportBatch.of(singleton(DeliveryProgressReport.builder().reportId("1") - .dataWindowEndTimeStamp(now.minusHours(2).toString()).build()), "1", - now.minusHours(2).toString())); - - final DeliveryProgress deliveryProgress = DeliveryProgress.of(now.minusHours(3), lineItemService); - - deliveryStatsService.addDeliveryProgress(deliveryProgress, emptyMap()); - - given(httpClient.post(anyString(), any(), anyString(), anyLong())) - .willReturn(Future.failedFuture(new TimeoutException("Timeout"))); - - // when - deliveryStatsService.sendDeliveryProgressReports(); - - // then - verify(alertHttpService).alertWithPeriod(eq("deliveryStats"), eq("pbs-delivery-stats-client-error"), - eq(AlertPriority.MEDIUM), - eq("Report was not send to delivery stats service with a reason: Sending report with id = 1 failed" - + " in a reason: Timeout")); - } - - @Test - public void sendDeliveryProgressReportShouldCallAlertServiceResetWhenRequestWasSuccessful() { - // given - givenDeliveryProgressHttpResponse(httpClient, 200, null); - - given(deliveryProgressReportFactory.batchFromDeliveryProgress(any(), any(), any(), anyInt(), anyBoolean())) - .willReturn(DeliveryProgressReportBatch.of(singleton(DeliveryProgressReport.builder().reportId("1") - .lineItemStatus(emptySet()) - .dataWindowEndTimeStamp(now.minusHours(2).toString()).build()), "1", - now.minusHours(2).toString())); - - final DeliveryProgress deliveryProgress = DeliveryProgress.of(now.minusHours(3), lineItemService); - - // when - deliveryStatsService.addDeliveryProgress(deliveryProgress, emptyMap()); - deliveryStatsService.sendDeliveryProgressReports(); - - // then - verify(alertHttpService).resetAlertCount(eq("pbs-delivery-stats-client-error")); - } - - @Test - public void suspendShouldSetSuspendFlagAndReportShouldNotBeSent() { - // given - given(deliveryProgressReportFactory.batchFromDeliveryProgress(any(), any(), any(), anyInt(), anyBoolean())) - .willReturn(DeliveryProgressReportBatch.of(singleton(DeliveryProgressReport.builder().reportId("1") - .dataWindowEndTimeStamp(now.minusHours(4).toString()).build()), "1", - now.minusHours(4).toString())); - - final DeliveryProgress deliveryProgress = DeliveryProgress.of(now.minusHours(5), lineItemService); - - deliveryStatsService.addDeliveryProgress(deliveryProgress, null); - - // when - deliveryStatsService.suspend(); - deliveryStatsService.sendDeliveryProgressReports(); - - // then - verifyNoInteractions(httpClient); - } - - @Test - public void sendDeliveryProgressReportShouldSendGzippedBody() throws JsonProcessingException { - // given - final DeliveryStatsService deliveryStatsService = new DeliveryStatsService( - DeliveryStatsProperties.builder() - .endpoint("localhost/delivery") - .cachedReportsNumber(3) - .timeoutMs(500L) - .reportsIntervalMs(0) - .requestCompressionEnabled(true) - .username("username") - .password("password") - .build(), - deliveryProgressReportFactory, - alertHttpService, - httpClient, - metrics, - clock, - vertx, - jacksonMapper); - - givenDeliveryProgressHttpResponse(httpClient, 200, null); - - final DeliveryProgressReport deliveryProgressReport = DeliveryProgressReport.builder().reportId("1") - .lineItemStatus(emptySet()) - .dataWindowEndTimeStamp(now.minusHours(2).toString()).build(); - given(deliveryProgressReportFactory.updateReportTimeStamp(any(), any())).willReturn(deliveryProgressReport); - given(deliveryProgressReportFactory.batchFromDeliveryProgress(any(), any(), any(), anyInt(), anyBoolean())) - .willReturn( - DeliveryProgressReportBatch.of(singleton(deliveryProgressReport), "1", - now.minusHours(2).toString())); - - final DeliveryProgress deliveryProgress = DeliveryProgress.of(now.minusHours(3), lineItemService); - - // when - deliveryStatsService.addDeliveryProgress(deliveryProgress, emptyMap()); - deliveryStatsService.sendDeliveryProgressReports(); - - // then - final ArgumentCaptor bodyCaptor = ArgumentCaptor.forClass(byte[].class); - final ArgumentCaptor headerCaptor = ArgumentCaptor.forClass(MultiMap.class); - verify(httpClient).request(any(), anyString(), headerCaptor.capture(), bodyCaptor.capture(), anyLong()); - // verify body was compressed well - final byte[] compressedRequestBody = bodyCaptor.getValue(); - final String decompressedRequestBody = decompress(compressedRequestBody); - assertThat(mapper.readValue(decompressedRequestBody, DeliveryProgressReport.class)) - .isEqualTo(deliveryProgressReport); - // verify Content-encoding header was added - final MultiMap headers = headerCaptor.getValue(); - assertThat(headers.get(HttpHeaders.CONTENT_ENCODING)).isEqualTo("gzip"); - } - - private static String decompress(byte[] byteArray) { - final StringBuilder body = new StringBuilder(); - try ( - GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(byteArray)); - BufferedReader bufferedReader = - new BufferedReader(new InputStreamReader(gzipInputStream, StandardCharsets.UTF_8))) { - String line; - while ((line = bufferedReader.readLine()) != null) { - body.append(line); - } - return body.toString(); - } catch (IOException e) { - throw new RuntimeException("Error occurred while decompressing gzipped body"); - } - } - - private static void givenDeliveryProgressHttpResponse(HttpClient httpClient, int statusCode, String response) { - final HttpClientResponse httpClientResponse = HttpClientResponse.of(statusCode, null, response); - given(httpClient.post(anyString(), any(), anyString(), anyLong())) - .willReturn(Future.succeededFuture(httpClientResponse)); - } -} diff --git a/src/test/java/org/prebid/server/deals/LineItemServiceTest.java b/src/test/java/org/prebid/server/deals/LineItemServiceTest.java deleted file mode 100644 index 07fade4e37e..00000000000 --- a/src/test/java/org/prebid/server/deals/LineItemServiceTest.java +++ /dev/null @@ -1,2076 +0,0 @@ -package org.prebid.server.deals; - -import com.fasterxml.jackson.databind.node.TextNode; -import com.iab.openrtb.request.BidRequest; -import com.iab.openrtb.request.Imp; -import com.iab.openrtb.request.User; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.mockito.stubbing.Answer; -import org.prebid.server.VertxTest; -import org.prebid.server.auction.BidderAliases; -import org.prebid.server.auction.model.AuctionContext; -import org.prebid.server.bidder.BidderCatalog; -import org.prebid.server.currency.CurrencyConversionService; -import org.prebid.server.deals.events.ApplicationEventService; -import org.prebid.server.deals.lineitem.DeliveryPlan; -import org.prebid.server.deals.lineitem.DeliveryToken; -import org.prebid.server.deals.lineitem.LineItem; -import org.prebid.server.deals.model.DeepDebugLog; -import org.prebid.server.deals.model.MatchLineItemsResult; -import org.prebid.server.deals.model.TxnLog; -import org.prebid.server.deals.proto.DeliverySchedule; -import org.prebid.server.deals.proto.FrequencyCap; -import org.prebid.server.deals.proto.LineItemMetaData; -import org.prebid.server.deals.proto.Price; -import org.prebid.server.deals.proto.Token; -import org.prebid.server.deals.targeting.TargetingDefinition; -import org.prebid.server.log.CriteriaLogManager; -import org.prebid.server.model.CaseInsensitiveMultiMap; -import org.prebid.server.model.HttpRequestContext; -import org.prebid.server.proto.openrtb.ext.request.ExtRequest; -import org.prebid.server.proto.openrtb.ext.request.ExtRequestPrebid; -import org.prebid.server.proto.openrtb.ext.request.ExtUser; -import org.prebid.server.proto.openrtb.ext.response.ExtTraceDeal; -import org.prebid.server.proto.openrtb.ext.response.ExtTraceDeal.Category; -import org.prebid.server.settings.model.Account; -import org.prebid.server.util.HttpUtil; - -import java.math.BigDecimal; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.IntStream; - -import static java.util.Arrays.asList; -import static java.util.Collections.emptyList; -import static java.util.Collections.emptyMap; -import static java.util.Collections.emptySet; -import static java.util.Collections.singleton; -import static java.util.Collections.singletonList; -import static java.util.Collections.singletonMap; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.tuple; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyMap; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class LineItemServiceTest extends VertxTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private TargetingService targetingService; - @Mock - private BidderCatalog bidderCatalog; - @Mock - private CurrencyConversionService conversionService; - @Mock - private ApplicationEventService applicationEventService; - @Mock - private Clock clock; - @Mock - private CriteriaLogManager criteriaLogManager; - - private BidderAliases bidderAliases; - - private LineItemService lineItemService; - - private ZonedDateTime now; - - @Before - public void setUp() { - now = ZonedDateTime.now(Clock.fixed(Instant.parse("2019-07-26T10:00:00Z"), ZoneOffset.UTC)); - - given(clock.instant()).willReturn(now.toInstant()); - given(clock.getZone()).willReturn(ZoneOffset.UTC); - - given(conversionService.convertCurrency(any(), anyMap(), anyString(), anyString(), any())) - .willReturn(BigDecimal.ONE); - - bidderAliases = BidderAliases.of(Map.of("rubiAlias", "rubicon"), emptyMap(), bidderCatalog); - - lineItemService = new LineItemService( - 2, - targetingService, - conversionService, - applicationEventService, - "USD", - clock, - criteriaLogManager); - } - - @Test - public void updateLineItemsShouldRemoveLineItemIfItIsNotActiveFromPlannerResponse() { - // given - final List firstPlanResponse = asList( - givenLineItemMetaData("lineItem1", now, "1", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), now, singleton(Token.of(1, 100)))), Function.identity()), - givenLineItemMetaData("lineItem2", now, "2", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), now, singleton(Token.of(1, 100)))), Function.identity())); - - final List secondPlanResponse = asList( - givenLineItemMetaData("lineItem1", now, "1", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), now, singleton(Token.of(1, 100)))), - builder -> builder.status("inactive")), - givenLineItemMetaData("lineItem2", now, "2", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), now, singleton(Token.of(1, 100)))), Function.identity())); - - // when and then - lineItemService.updateLineItems(firstPlanResponse, true); - assertThat(lineItemService.getLineItemById("lineItem1")).isNotNull(); - assertThat(lineItemService.getLineItemById("lineItem2")).isNotNull(); - lineItemService.updateLineItems(secondPlanResponse, true); - assertThat(lineItemService.getLineItemById("lineItem1")).isNull(); - assertThat(lineItemService.getLineItemById("lineItem2")).isNotNull(); - } - - @Test - public void updateLineItemsShouldRemoveLineItemIfItHasEndTimeInPastInPlannerResponse() { - // given - final List firstPlanResponse = asList( - givenLineItemMetaData("lineItem1", now, "1", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), now, singleton(Token.of(1, 100)))), Function.identity()), - givenLineItemMetaData("lineItem2", now, "2", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), now, singleton(Token.of(1, 100)))), Function.identity())); - - final List secondPlanResponse = asList( - givenLineItemMetaData("lineItem1", now, "1", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), now, singleton(Token.of(1, 100)))), - builder -> builder.endTimeStamp(now.minusHours(1))), - givenLineItemMetaData("lineItem2", now, "2", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), now, singleton(Token.of(1, 100)))), Function.identity())); - - // when and then - lineItemService.updateLineItems(firstPlanResponse, true); - assertThat(lineItemService.getLineItemById("lineItem1")).isNotNull(); - assertThat(lineItemService.getLineItemById("lineItem2")).isNotNull(); - lineItemService.updateLineItems(secondPlanResponse, true); - assertThat(lineItemService.getLineItemById("lineItem1")).isNull(); - assertThat(lineItemService.getLineItemById("lineItem2")).isNotNull(); - } - - @Test - public void updateLineItemsShouldRemoveLineItemIfItHasEndTimeInPastInMemory() { - // given - final List firstPlanResponse = asList( - givenLineItemMetaData("lineItem1", now, "1", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), now, singleton(Token.of(1, 100)))), - builder -> builder.endTimeStamp(now.plusSeconds(1))), - givenLineItemMetaData("lineItem2", now, "2", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), now, singleton(Token.of(1, 100)))), Function.identity())); - - // when and then - lineItemService.updateLineItems(firstPlanResponse, true, now); - assertThat(lineItemService.getLineItemById("lineItem1")).isNotNull(); - assertThat(lineItemService.getLineItemById("lineItem2")).isNotNull(); - lineItemService.updateLineItems(emptyList(), true, now.plusSeconds(2)); - assertThat(lineItemService.getLineItemById("lineItem1")).isNull(); - assertThat(lineItemService.getLineItemById("lineItem2")).isNotNull(); - } - - @Test - public void updateLineItemsShouldNotRemoveLineItemIfItWasMissedInPlannerResponse() { - // given - final List firstPlanResponse = asList( - givenLineItemMetaData("lineItem1", "1001", "rubicon", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), now, singleton(Token.of(1, 100)))), now), - givenLineItemMetaData("lineItem2", "1001", "rubicon", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), now, singleton(Token.of(1, 100)))), now)); - - final List secondPlanResponse = singletonList( - givenLineItemMetaData("lineItem1", "1001", "rubicon", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), now, singleton(Token.of(1, 100)))), now)); - - // when and then - lineItemService.updateLineItems(firstPlanResponse, true); - assertThat(lineItemService.getLineItemById("lineItem1")).isNotNull(); - assertThat(lineItemService.getLineItemById("lineItem2")).isNotNull(); - lineItemService.updateLineItems(secondPlanResponse, true); - assertThat(lineItemService.getLineItemById("lineItem1")).isNotNull(); - assertThat(lineItemService.getLineItemById("lineItem2")).isNotNull(); - } - - @Test - public void updateLineItemShouldSaveLineItemIfItHasEmptyDeliverySchedules() { - // given - final List firstPlanResponse = singletonList( - givenLineItemMetaData("lineItem1", "1001", "rubicon", emptyList(), now)); - - // when and then - lineItemService.updateLineItems(firstPlanResponse, true); - assertThat(lineItemService.getLineItemById("lineItem1")).isNotNull(); - } - - @Test - public void updateLineItemShouldSaveLineItemIfItDoesNotHaveDeliverySchedules() { - // given - final List firstPlanResponse = singletonList( - givenLineItemMetaData("lineItem1", "1001", "rubicon", null, now)); - - // when and then - lineItemService.updateLineItems(firstPlanResponse, true); - assertThat(lineItemService.getLineItemById("lineItem1")).isNotNull(); - } - - @Test - public void updateLineItemsShouldUpdateCurrentPlanIfUpdatedPlanUpdateTimeStampIsInFuture() { - // given - final List firstPlanResponse = singletonList( - givenLineItemMetaData("lineItem1", "1001", "rubicon", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), now, singleton(Token.of(1, 100)))), now)); - - final List secondPlanResponse = singletonList( - givenLineItemMetaData("lineItem1", "1001", "rubicon", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), now.plusMinutes(1), singleton(Token.of(1, 200)))), now)); - - // when - lineItemService.updateLineItems(firstPlanResponse, true); - incSpentTokens(10, "lineItem1"); - lineItemService.updateLineItems(secondPlanResponse, true); - - // then - final LineItem lineItem = lineItemService.getLineItemById("lineItem1"); - assertThat(lineItem).isNotNull(); - - final DeliveryPlan activeDeliveryPlan = lineItem.getActiveDeliveryPlan(); - - assertThat(activeDeliveryPlan).isNotNull() - .extracting(DeliveryPlan::getPlanId, DeliveryPlan::getStartTimeStamp, DeliveryPlan::getEndTimeStamp, - DeliveryPlan::getUpdatedTimeStamp) - .containsOnly("planId1", now.minusHours(1), now.plusHours(1), now.plusMinutes(1)); - assertThat(activeDeliveryPlan.getDeliveryTokens()) - .extracting(DeliveryToken::getPriorityClass, DeliveryToken::getTotal, token -> token.getSpent().sum()) - .containsOnly(tuple(1, 200, 10L)); - - // 6 minutes after plan started - assertThat(lineItem.getReadyAt()).isEqualTo(now.minusHours(1).plusMinutes(6)); - } - - @Test - public void updateLineItemsShouldUpdateReadyAtBasedOnPlanStartTime() { - // given - final List firstPlanResponse = singletonList( - givenLineItemMetaData("lineItem1", "1001", "rubicon", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), now, singleton(Token.of(1, 100)))), now)); - - // when - lineItemService.updateLineItems(firstPlanResponse, true); - incSpentTokens(1, "lineItem1"); - - // then - final LineItem lineItem = lineItemService.getLineItemById("lineItem1"); - assertThat(lineItem).isNotNull(); - - // 1 * (120 * 60 * 1000) \ 100 tokens = 72,000 millis = 1 minute 12 seconds shift from plan startTime - assertThat(lineItem.getReadyAt()).isEqualTo(now.minusHours(1).plusMinutes(1).plusSeconds(12)); - } - - @Test - public void updateLineItemsShouldConvertPriceWhenLineItemMetaDataCurrencyIsDifferent() { - // given - final String defaultCurrency = "RUB"; - lineItemService = new LineItemService( - 2, - targetingService, - conversionService, - applicationEventService, - defaultCurrency, - clock, - criteriaLogManager); - - final List planResponse = asList( - givenLineItemMetaData("lineItem1", null, null, - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), now.plusHours(1), - emptySet())), now), - givenLineItemMetaData("lineItem2", null, null, - singletonList(givenDeliverySchedule("planId2", now.minusHours(1), now.plusHours(1), - emptySet())), now)); - - final BigDecimal updatedCmp = BigDecimal.TEN; - given(conversionService.convertCurrency(any(), anyMap(), anyString(), anyString(), any())) - .willReturn(updatedCmp); - - // when - lineItemService.updateLineItems(planResponse, true); - - // then - final LineItem lineItem1 = lineItemService.getLineItemById("lineItem1"); - assertThat(lineItem1.getCpm()).isEqualTo(updatedCmp); - assertThat(lineItem1.getCurrency()).isEqualTo(defaultCurrency); - - final LineItem lineItem2 = lineItemService.getLineItemById("lineItem2"); - assertThat(lineItem2.getCpm()).isEqualTo(updatedCmp); - assertThat(lineItem2.getCurrency()).isEqualTo(defaultCurrency); - } - - @Test - public void updateLineItemsShouldCreateLineItemsWhenPlannerIsResponsive() { - // given - final List planResponse = asList( - givenLineItemMetaData("lineItem1", "1001", "rubicon", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), singleton(Token.of(1, 100)))), now), - givenLineItemMetaData("lineItem2", "1002", "rubicon", - singletonList(givenDeliverySchedule("planId2", now.plusHours(1), - now.plusHours(2), singleton(Token.of(1, 100)))), now)); - - // when - lineItemService.updateLineItems(planResponse, true); - - // then - final LineItem lineItem1 = lineItemService.getLineItemById("lineItem1"); - assertThat(lineItem1).isNotNull(); - - final DeliveryPlan activeDeliveryPlan = lineItem1.getActiveDeliveryPlan(); - assertThat(activeDeliveryPlan).isNotNull() - .extracting(DeliveryPlan::getPlanId, DeliveryPlan::getStartTimeStamp, DeliveryPlan::getEndTimeStamp) - .containsOnly("planId1", now.minusHours(1), now.plusHours(1)); - assertThat(activeDeliveryPlan.getDeliveryTokens()) - .extracting(DeliveryToken::getPriorityClass, DeliveryToken::getTotal) - .containsOnly(tuple(1, 100)); - - assertThat(lineItem1.getReadyAt()).isEqualTo(now); - - final LineItem lineItem2 = lineItemService.getLineItemById("lineItem2"); - assertThat(lineItem2).isNotNull(); - assertThat(lineItem2.getActiveDeliveryPlan()).isNull(); - assertThat(lineItem2.getReadyAt()).isNull(); - } - - @Test - public void updateLineItemsShouldCreateLineItemsWithNullTargetingIfCantParse() { - // given - final List planResponse = singletonList( - LineItemMetaData.builder() - .lineItemId("lineItem1") - .status("active") - .dealId("dealId") - .accountId("1001") - .source("rubicon") - .price(Price.of(BigDecimal.ONE, "USD")) - .relativePriority(5) - .startTimeStamp(now.minusHours(1)) - .endTimeStamp(now.plusHours(1)) - .updatedTimeStamp(now) - .targeting(mapper.createObjectNode().set("$invalid", new TextNode("invalid"))) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), singleton(Token.of(1, 100))))) - .build()); - - // when - lineItemService.updateLineItems(planResponse, true); - - // then - final LineItem lineItem = lineItemService.getLineItemById("lineItem1"); - assertThat(lineItem).isNotNull(); - assertThat(lineItem.getTargetingDefinition()).isNull(); - } - - @Test - public void updateLineItemsShouldNotUpdateCurrentPlanIfUpdatedPlanUpdateTimeStampIsNotInFuture() { - // given - final List firstPlanResponse = singletonList( - givenLineItemMetaData("lineItem1", "1001", "rubicon", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), singleton(Token.of(1, 100)))), now)); - - final List secondPlanResponse = singletonList( - givenLineItemMetaData("lineItem1", "1001", "rubicon", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusHours(1), singleton(Token.of(1, 200)))), now)); - - // when - lineItemService.updateLineItems(firstPlanResponse, true); - incSpentTokens(10, "lineItem1"); - lineItemService.updateLineItems(secondPlanResponse, true); - - // then - final LineItem lineItem = lineItemService.getLineItemById("lineItem1"); - assertThat(lineItem).isNotNull(); - - final DeliveryPlan activeDeliveryPlan = lineItem.getActiveDeliveryPlan(); - assertThat(activeDeliveryPlan).isNotNull() - .extracting(DeliveryPlan::getPlanId, DeliveryPlan::getStartTimeStamp, DeliveryPlan::getEndTimeStamp) - .containsOnly("planId1", now.minusHours(1), now.plusHours(1)); - assertThat(activeDeliveryPlan.getDeliveryTokens()) - .extracting(DeliveryToken::getPriorityClass, DeliveryToken::getTotal, token -> token.getSpent().sum()) - .containsOnly(tuple(1, 100, 10L)); - - // should be ready at 12 minutes after plan start - assertThat(lineItem.getReadyAt()).isEqualTo(now.minusHours(1).plusMinutes(12)); - } - - @Test - public void updateLineItemsShouldMergeLineItemsWhenPlannerIsNotResponsive() { - // given - given(clock.instant()).willReturn(now.toInstant(), now.toInstant(), now.plusSeconds(2).toInstant()); - given(clock.getZone()).willReturn(ZoneOffset.UTC); - - final Set expiredTokens = new HashSet<>(); - expiredTokens.add(Token.of(1, 100)); - expiredTokens.add(Token.of(3, 300)); - expiredTokens.add(Token.of(4, 400)); - expiredTokens.add(Token.of(5, 500)); - - final Set newActiveTokens = new HashSet<>(); - newActiveTokens.add(Token.of(1, 100)); - newActiveTokens.add(Token.of(2, 200)); - newActiveTokens.add(Token.of(3, 300)); - newActiveTokens.add(Token.of(4, 400)); - - final List planResponse = singletonList(givenLineItemMetaData( - "lineItem1", "1001", "rubicon", - asList( - givenDeliverySchedule("planId1", now.minusHours(1), now.plusSeconds(1), expiredTokens), - givenDeliverySchedule("planId2", now.plusSeconds(1), now.plusHours(1), newActiveTokens)), - now)); - - // when and then - lineItemService.updateLineItems(planResponse, true); - incSpentTokens(240, "lineItem1"); - lineItemService.updateLineItems(null, false); - lineItemService.advanceToNextPlan(now.plusSeconds(1)); - - verify(clock, times(2)).instant(); - - final LineItem lineItem = lineItemService.getLineItemById("lineItem1"); - - final DeliveryPlan activeDeliveryPlan = lineItem.getActiveDeliveryPlan(); - assertThat(activeDeliveryPlan).isNotNull(); - assertThat(activeDeliveryPlan.getDeliveryTokens()) - .extracting(DeliveryToken::getPriorityClass, DeliveryToken::getTotal, - deliveryToken -> deliveryToken.getSpent().sum()) - .containsExactly( - tuple(1, 200, 100L), - tuple(2, 200, 0L), - tuple(3, 600, 140L), - tuple(4, 800, 0L), - tuple(5, 500, 0L)); - } - - @Test - public void updateLineItemShouldUpdatePlanWithoutActiveCurrentDeliveryPlan() { - // given - given(clock.instant()).willReturn(now.toInstant(), now.toInstant(), now.plusSeconds(3).toInstant()); - given(clock.getZone()).willReturn(ZoneOffset.UTC); - - final List planResponse = singletonList(givenLineItemMetaData( - "lineItem1", "1001", "rubicon", - asList( - givenDeliverySchedule("planId1", now.minusHours(2), - now.minusHours(1), singleton(Token.of(1, 100))), - givenDeliverySchedule("planId2", now.plusSeconds(2), - now.plusHours(1), singleton(Token.of(1, 100)))), - now)); - - // when and then - lineItemService.updateLineItems(planResponse, true); - lineItemService.updateLineItems(null, false); - lineItemService.advanceToNextPlan(now.plusSeconds(2)); - - verify(clock, times(2)).instant(); - - final LineItem lineItem = lineItemService.getLineItemById("lineItem1"); - - final DeliveryPlan activeDeliveryPlan = lineItem.getActiveDeliveryPlan(); - assertThat(activeDeliveryPlan).isNotNull(); - assertThat(activeDeliveryPlan.getDeliveryTokens()) - .extracting(DeliveryToken::getPriorityClass, DeliveryToken::getTotal, - deliveryToken -> deliveryToken.getSpent().sum()) - .containsExactly(tuple(1, 100, 0L)); - } - - @Test - public void accountHasDealsShouldReturnTrue() { - // given - final List planResponse = singletonList( - givenLineItemMetaData("lineItem1", "1001", "rubicon", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), now.plusHours(1), - emptySet())), now)); - lineItemService.updateLineItems(planResponse, true); - - // when and then - assertThat(lineItemService.accountHasDeals(AuctionContext.builder() - .account(Account.builder().id("1001").build()).build())) - .isTrue(); - } - - @Test - public void accountHasDealsShouldReturnFalseWhenAccountIsEmptyString() { - // given - final List planResponse = singletonList( - givenLineItemMetaData("lineItem1", "1001", "rubicon", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), now.plusHours(1), - emptySet())), now)); - lineItemService.updateLineItems(planResponse, true); - - // when and then - assertThat(lineItemService.accountHasDeals(AuctionContext.builder().account(Account.builder().id("").build()) - .build())).isFalse(); - } - - @Test - public void accountHasDealsShouldReturnFalseWhenNoMatchingLineItemWereFound() { - // given - final List planResponse = singletonList( - givenLineItemMetaData("lineItem1", "3003", "rubicon", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), now.plusHours(1), - emptySet())), now)); - lineItemService.updateLineItems(planResponse, true); - - // when and then - assertThat(lineItemService.accountHasDeals(AuctionContext.builder().account(Account.builder().id("1001") - .build()).build())).isFalse(); - } - - @Test - public void accountHasDealsShouldReturnFalseWhenMatchedLineItemIsNotActive() { - // given - final List planResponse = singletonList( - givenLineItemMetaData("lineItem1", "1001", "rubicon", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), now.plusHours(1), - emptySet())), now)); - lineItemService.updateLineItems(planResponse, true); - given(clock.instant()).willReturn(now.plusHours(2).toInstant()); - - // when and then - assertThat(lineItemService.accountHasDeals(AuctionContext.builder().account(Account.builder().id("1001") - .build()).build())).isFalse(); - } - - @Test - public void findMatchingLineItemsShouldReturnEmptyListWhenLineItemsIsEmpty() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).isEmpty(); - } - - @Test - public void findMatchingLineItemsShouldReturnEmptyListWhenNoLineItemsForAccount() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = singletonList( - givenLineItemMetaData("lineItem1", "accountIdUnknown", "rubicon", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100)))), now)); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).isEmpty(); - } - - @Test - public void findMatchingLineItemsShouldReturnEmptyListWhenNoBiddersMatched() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = singletonList( - givenLineItemMetaData("lineItem1", "accountId", "rubicon", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), now.plusMinutes(1), - singleton(Token.of(1, 100)))), now)); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "pubmatic", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).isEmpty(); - } - - @Test - public void findMatchingLineItemsShouldReturnLineItemsForMatchingBidder() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = singletonList( - givenLineItemMetaData("lineItem1", "accountId", "rubicon", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), now.plusMinutes(1), - singleton(Token.of(1, 100)))), now)); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).containsOnly("lineItem1"); - } - - @Test - public void findMatchingLineItemsShouldReturnLineItemsWhenLineItemsBidderIsAlias() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = singletonList( - givenLineItemMetaData("lineItem1", "accountId", "rubiAlias", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), now.plusMinutes(1), - singleton(Token.of(1, 100)))), now)); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).containsOnly("lineItem1"); - } - - @Test - public void findMatchingLineItemsShouldReturnLineItemsWhenBidderFromInputBiddersIsAlias() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = singletonList( - givenLineItemMetaData("lineItem1", "accountId", "rubicon", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), now.plusMinutes(1), - singleton(Token.of(1, 100)))), now)); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubiAlias", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).containsOnly("lineItem1"); - } - - @Test - public void findMatchingLineItemsShouldReturnEmptyListWhenAccountIsEmptyString() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()) - .toBuilder().account(Account.builder().id("").build()).build(); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = singletonList( - givenLineItemMetaData("lineItem1", "accountId", "rubicon", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), now.plusMinutes(1), - singleton(Token.of(1, 100)))), now)); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).isEmpty(); - } - - @Test - public void findMatchingLineItemsShouldFilterNotMatchingTargeting() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()); - - given(targetingService.parseTargetingDefinition(any(), eq("id1"))) - .willReturn(TargetingDefinition.of(context -> false)); - given(targetingService.parseTargetingDefinition(any(), eq("id2"))) - .willReturn(TargetingDefinition.of(context -> true)); - given(targetingService.matchesTargeting(any(), any(), any(), any())) - .willAnswer(withEvaluatedTargeting()); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id1") - .status("active") - .source("rubicon") - .accountId("accountId") - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id2") - .status("active") - .source("appnexus") - .accountId("accountId") - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).isEmpty(); - - assertThat(auctionContext.getDeepDebugLog().entries()).containsOnly( - ExtTraceDeal.of("id1", ZonedDateTime.now(clock), Category.targeting, - "Line Item id1 targeting did not match imp with id imp1")); - } - - @Test - public void findMatchingLineItemsShouldReturnLineItemsThatMatchedTargeting() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()); - - given(targetingService.parseTargetingDefinition(any(), eq("id1"))) - .willReturn(TargetingDefinition.of(context -> false)); - given(targetingService.parseTargetingDefinition(any(), eq("id2"))) - .willReturn(TargetingDefinition.of(context -> true)); - given(targetingService.matchesTargeting(any(), any(), any(), any())) - .willAnswer(withEvaluatedTargeting()); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id1") - .status("active") - .source("rubicon") - .accountId("accountId") - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id2") - .status("active") - .source("appnexus") - .accountId("accountId") - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "appnexus", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).containsOnly("id2"); - - assertThat(auctionContext.getDeepDebugLog().entries()).containsOnly( - ExtTraceDeal.of("id2", ZonedDateTime.now(clock), Category.targeting, - "Line Item id2 targeting matched imp with id imp1"), - ExtTraceDeal.of("id2", ZonedDateTime.now(clock), Category.pacing, - "Matched Line Item id2 for bidder appnexus ready to serve. relPriority null")); - } - - @Test - public void findMatchingLineItemsShouldFilterNullTargeting() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()); - - given(targetingService.parseTargetingDefinition(any(), eq("id1"))) - .willReturn(null); - given(targetingService.parseTargetingDefinition(any(), eq("id2"))) - .willReturn(TargetingDefinition.of(context -> true)); - given(targetingService.matchesTargeting(any(), any(), any(), any())) - .willAnswer(withEvaluatedTargeting()); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id1") - .status("active") - .source("rubicon") - .accountId("accountId") - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id2") - .status("active") - .source("appnexus") - .accountId("accountId") - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).isEmpty(); - - assertThat(auctionContext.getDeepDebugLog().entries()).containsOnly( - ExtTraceDeal.of("id1", ZonedDateTime.now(clock), Category.targeting, - "Line Item id1 targeting was not defined or has incorrect format")); - } - - @Test - public void findMatchingLineItemsShouldFilterNotReadyLineItems() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id1") - .status("active") - .source("rubicon") - .accountId("accountId") - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusMinutes(1), - now.plusDays(1), singleton(Token.of(1, 1))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id2") - .status("active") - .source("appnexus") - .accountId("accountId") - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - lineItemService.getLineItemById("id1").incSpentToken(now.plusSeconds(1)); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).isEmpty(); - } - - @Test - public void findMatchingLineItemsShouldFilterLineItemsWithFcapIdsWhenUserDetailsFcapIsNull() { - // given - final AuctionContext auctionContext = givenAuctionContext(null); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id1") - .status("active") - .source("rubicon") - .accountId("accountId") - .frequencyCaps(singletonList(FrequencyCap.builder().fcapId("123").build())) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id2") - .status("active") - .source("appnexus") - .accountId("accountId") - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).isEmpty(); - } - - @Test - public void findMatchingLineItemsShouldFilterFcappedLineItems() { - // given - final AuctionContext auctionContext = givenAuctionContext(asList("fcap2", "fcap3")); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id1") - .status("active") - .source("rubicon") - .accountId("accountId") - .frequencyCaps(singletonList(FrequencyCap.builder().fcapId("fcap2").build())) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id2") - .status("active") - .source("appnexus") - .accountId("accountId") - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).isEmpty(); - assertThat(auctionContext.getTxnLog().lineItemsMatchedTargetingFcapped()).containsOnly("id1"); - assertThat(auctionContext.getDeepDebugLog().entries()).contains( - ExtTraceDeal.of("id1", ZonedDateTime.now(clock), Category.pacing, - "Matched Line Item id1 for bidder rubicon is frequency capped by fcap id fcap2.")); - } - - @Test - public void findMatchingLineItemsShouldFilterSameSentToBidderAsTopMatchLineItemsPerBidder() { - // given - final TxnLog txnLog = TxnLog.create(); - txnLog.lineItemsSentToBidderAsTopMatch().put("rubicon", new HashSet<>(singleton("id1"))); - final AuctionContext auctionContext = givenAuctionContext(emptyList()).toBuilder().txnLog(txnLog).build(); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id1") - .status("active") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id2") - .status("active") - .source("rubicon") - .accountId("accountId") - .relativePriority(2) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).containsOnly("id2"); - } - - @Test - public void findMatchingLineItemsShouldFilterSameSentToBidderAsTopMatchLineItemsPerAllBidders() { - // given - final TxnLog txnLog = TxnLog.create(); - txnLog.lineItemsSentToBidderAsTopMatch().put("appnexus", new HashSet<>(singleton("id1"))); - final AuctionContext auctionContext = givenAuctionContext(emptyList()).toBuilder().txnLog(txnLog).build(); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id1") - .status("active") - .source("appnexus") - .accountId("accountId") - .relativePriority(1) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id2") - .status("active") - .source("rubicon") - .accountId("accountId") - .relativePriority(2) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).containsOnly("id2"); - } - - @Test - public void findMatchingLineItemsShouldFilterLineItemsWithSameDealAndLowestPriorityTokenClassWithinBidder() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id1") - .status("active") - .dealId("dealId1") - .source("rubicon") - .accountId("accountId") - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(3, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id2") - .status("active") - .dealId("dealId1") - .source("rubicon") - .accountId("accountId") - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).containsOnly("id2"); - } - - @Test - public void findMatchingLineItemsShouldFilterLineItemsWithSameDealIdAndLowestLineItemPriority() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id1") - .status("active") - .dealId("dealId1") - .source("rubicon") - .accountId("accountId") - .relativePriority(3) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id2") - .status("active") - .dealId("dealId1") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).containsOnly("id2"); - } - - @Test - public void findMatchingLineItemsShouldFilterLineItemsWithSameDealIdAndLowestCpm() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id1") - .status("active") - .dealId("dealId1") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.ONE, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id2") - .status("active") - .dealId("dealId1") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.TEN, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).containsOnly("id2"); - } - - @Test - public void findMatchingLineItemsShouldFilterLineItemsWithoutUnspentTokensAndIncrementDeferred() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id1") - .status("active") - .dealId("dealId1") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.ONE, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 0))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id2") - .status("active") - .dealId("dealId2") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.TEN, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(auctionContext.getTxnLog().lineItemsPacingDeferred()).contains("id1"); - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).containsOnly("id2"); - assertThat(auctionContext.getDeepDebugLog().entries()).contains( - ExtTraceDeal.of("id1", ZonedDateTime.now(clock), Category.pacing, - "Matched Line Item id1 for bidder rubicon does not have unspent tokens to be served")); - } - - @Test - public void findMatchingLineItemsShouldLimitLineItemsPerBidder() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id1") - .status("active") - .dealId("1") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.ONE, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id2") - .status("active") - .dealId("2") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.TEN, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id3") - .status("active") - .dealId("3") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.TEN, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).containsOnly("id2", "id3"); - } - - @Test - public void findMatchingLineItemsShouldReturnLineItemWithReadyToServeEqualToNow() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()); - - givenTargetingService(); - givenClock(now, now.plusSeconds((now.plusMinutes(5).toEpochSecond() - now.toEpochSecond()) / 100)); - - final List planResponse = singletonList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id1") - .status("active") - .dealId("1") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.ONE, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("futurePlanId", now.minusMinutes(1), - now.plusMinutes(5), singleton(Token.of(1, 100))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).containsOnly("id1"); - } - - @Test - public void findMatchingLineItemsShouldRecordLineItemsInTxnLog() { - // given - final AuctionContext auctionContext = givenAuctionContext(asList("fcap2", "fcap3")); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id1") - .status("active") - .dealId("1") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.ONE, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id2") - .status("active") - .dealId("2") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.TEN, "USD")) - .frequencyCaps(singletonList(FrequencyCap.builder().fcapId("fcap3").build())) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id3") - .status("active") - .dealId("3") - .source("appnexus") - .accountId("accountId") - .relativePriority(2) - .price(Price.of(BigDecimal.ONE, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id4") - .status("active") - .dealId("4") - .source("appnexus") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.TEN, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "appnexus", bidderAliases, auctionContext); - - // then - final TxnLog expectedTxnLog = TxnLog.create(); - expectedTxnLog.lineItemsMatchedWholeTargeting().addAll(asList("id1", "id2", "id3", "id4")); - expectedTxnLog.lineItemsMatchedTargetingFcapped().add("id2"); - expectedTxnLog.lineItemsReadyToServe().addAll(asList("id1", "id3", "id4")); - expectedTxnLog.lineItemsSentToBidderAsTopMatch().put("rubicon", singleton("id1")); - expectedTxnLog.lineItemsSentToBidderAsTopMatch().put("appnexus", singleton("id4")); - expectedTxnLog.lineItemsSentToBidder().get("rubicon").add("id1"); - expectedTxnLog.lineItemsSentToBidder().get("appnexus").addAll(asList("id3", "id4")); - expectedTxnLog.lostMatchingToLineItems().put("id3", singleton("id4")); - assertThat(auctionContext.getTxnLog()).isEqualTo(expectedTxnLog); - } - - @Test - public void findMatchingLineItemsShouldRecordLineItemsInTxnLogWhenPacingDeferred() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()); - givenTargetingService(); - - final List planResponse = singletonList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id5") - .status("active") - .dealId("5") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.TEN, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(2), singleton(Token.of(1, 2))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - lineItemService.getLineItemById("id5").incSpentToken(now.plusSeconds(1)); - lineItemService.getLineItemById("id5").incSpentToken(now.plusSeconds(1)); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - final TxnLog expectedTxnLog = TxnLog.create(); - expectedTxnLog.lineItemsMatchedWholeTargeting().add("id5"); - expectedTxnLog.lineItemsPacingDeferred().add("id5"); - assertThat(auctionContext.getTxnLog()).isEqualTo(expectedTxnLog); - } - - @Test - public void findMatchingLineItemsShouldRecordLineItemsInTxnLogWhenFcapLookupFailed() { - // given - final AuctionContext auctionContext = givenAuctionContext(null); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id1") - .status("active") - .dealId("1") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.ONE, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id2") - .status("active") - .dealId("2") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.TEN, "USD")) - .frequencyCaps(singletonList(FrequencyCap.builder().fcapId("fcap3").build())) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(auctionContext.getTxnLog().lineItemsMatchedTargetingFcapLookupFailed()).containsOnly("id2"); - assertThat(auctionContext.getDeepDebugLog().entries()).contains( - ExtTraceDeal.of("id2", ZonedDateTime.now(clock), Category.pacing, - "Failed to match fcap for Line Item id2 bidder rubicon in a reason of bad response" - + " from user data service")); - } - - @Test - public void findMatchingLineItemsShouldHasCorrectRandomDistribution() { - // given - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - lineItemService = new LineItemService( - 3, - targetingService, - conversionService, - applicationEventService, - "USD", - clock, - criteriaLogManager); - - final List planResponse = asList( - givenLineItemMetaData("id1", now, "1", - singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), now, singleton(Token.of(1, 100)))), Function.identity()), - givenLineItemMetaData("id2", now, "2", - singletonList(givenDeliverySchedule("planId2", now.minusHours(1), - now.plusMinutes(1), now, singleton(Token.of(1, 100)))), Function.identity()), - givenLineItemMetaData("id3", now, "3", - singletonList(givenDeliverySchedule("planId3", now.minusHours(1), - now.plusMinutes(1), now, singleton(Token.of(1, 100)))), Function.identity())); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final Map count = new HashMap<>(); - for (int i = 0; i < 1000; i++) { - final AuctionContext auctionContext = givenAuctionContext(emptyList()); - final MatchLineItemsResult matchLineItemsResult = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - count.compute(matchLineItemsResult.getLineItems().get(0).getLineItemId(), - (s, integer) -> integer != null ? ++integer : 1); - } - - // then - assertThat(count.get("id1")).isBetween(290, 390); - assertThat(count.get("id2")).isBetween(290, 390); - assertThat(count.get("id3")).isBetween(290, 390); - } - - @Test - public void findMatchingLineItemsShouldAddDebugMessages() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id1") - .status("active") - .source("rubicon") - .accountId("accountId") - .relativePriority(2) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(1), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId("id2") - .status("active") - .source("appnexus") - .accountId("accountId") - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusMinutes(1), - now.plusDays(1), singleton(Token.of(1, 2))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - lineItemService.getLineItemById("id2").incSpentToken(now.plusSeconds(1)); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "appnexus", bidderAliases, auctionContext); - - // then - assertThat(auctionContext.getDeepDebugLog().entries()).containsOnly( - ExtTraceDeal.of("id1", ZonedDateTime.now(clock), Category.targeting, - "Line Item id1 targeting matched imp with id imp1"), - ExtTraceDeal.of("id2", ZonedDateTime.now(clock), Category.targeting, - "Line Item id2 targeting matched imp with id imp1"), - ExtTraceDeal.of("id1", ZonedDateTime.now(clock), Category.pacing, - "Matched Line Item id1 for bidder rubicon ready to serve. relPriority 2"), - ExtTraceDeal.of("id2", ZonedDateTime.now(clock), Category.pacing, - "Matched Line Item id2 for bidder appnexus not ready to serve. Will be ready" - + " at 2019-07-26T21:59:30.000Z, current time is 2019-07-26T10:01:00.000Z")); - } - - @Test - public void findMatchingLineItemsShouldReturnWithoutUnspentTokensOrOnCoolDownIfIgnorePacingHeaderProvided() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()) - .toBuilder() - .httpRequest(HttpRequestContext.builder() - .headers(CaseInsensitiveMultiMap.builder().add(HttpUtil.PG_IGNORE_PACING, "1").build()) - .build()) - .build(); - - givenTargetingService(); - - givenClock(now.plusMinutes(5), now); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(10)) - .lineItemId("id1") - .status("active") - .dealId("dealId1") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.ONE, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(10), singleton(Token.of(1, 0))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(10)) - .lineItemId("id2") - .status("active") - .dealId("dealId2") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.TEN, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(10), singleton(Token.of(1, 100))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).containsExactly("id2", "id1"); - } - - @Test - public void findMatchingLineItemsShouldLowerPriorityIfDeliveryPlanIsNullAndPgIgnorePacing() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()) - .toBuilder() - .httpRequest(HttpRequestContext.builder() - .headers(CaseInsensitiveMultiMap.builder().add(HttpUtil.PG_IGNORE_PACING, "1").build()) - .build()) - .build(); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(10)) - .lineItemId("id1") - .status("active") - .dealId("dealId1") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.ONE, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(10), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(10)) - .lineItemId("id2") - .status("active") - .dealId("dealId2") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.TEN, "USD")) - .deliverySchedules(null) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).containsExactly("id1", "id2"); - } - - @Test - public void findMatchingLineItemsShouldLowerPriorityIfNoTokensUnspentAndPgIgnorePacing() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()) - .toBuilder() - .httpRequest(HttpRequestContext.builder() - .headers(CaseInsensitiveMultiMap.builder().add(HttpUtil.PG_IGNORE_PACING, "1").build()) - .build()) - .build(); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(10)) - .lineItemId("id1") - .status("active") - .dealId("dealId1") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.ONE, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(10), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(10)) - .lineItemId("id2") - .status("active") - .dealId("dealId2") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.TEN, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(10), singleton(Token.of(1, 0))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).containsExactly("id1", "id2"); - } - - @Test - public void findMatchingLineItemsShouldLowerPriorityIfRelativePriorityIsNullAndPgIgnorePacing() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()) - .toBuilder() - .httpRequest(HttpRequestContext.builder() - .headers(CaseInsensitiveMultiMap.builder().add(HttpUtil.PG_IGNORE_PACING, "1").build()) - .build()) - .build(); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(10)) - .lineItemId("id1") - .status("active") - .dealId("dealId1") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.ONE, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(10), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(10)) - .lineItemId("id2") - .status("active") - .dealId("dealId2") - .source("rubicon") - .accountId("accountId") - .relativePriority(null) - .price(Price.of(BigDecimal.TEN, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(10), singleton(Token.of(1, 100))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).containsExactly("id1", "id2"); - } - - @Test - public void findMatchingLineItemsShouldLowerPriorityIfCpmIsNullAndPgIgnorePacing() { - // given - final AuctionContext auctionContext = givenAuctionContext(emptyList()) - .toBuilder() - .httpRequest(HttpRequestContext.builder() - .headers(CaseInsensitiveMultiMap.builder().add(HttpUtil.PG_IGNORE_PACING, "1").build()) - .build()) - .build(); - - givenTargetingService(); - - givenClock(now, now.plusMinutes(1)); - - final List planResponse = asList( - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(10)) - .lineItemId("id1") - .status("active") - .dealId("dealId1") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(BigDecimal.ZERO, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(10), singleton(Token.of(1, 100))))) - .build(), - LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(10)) - .lineItemId("id2") - .status("active") - .dealId("dealId2") - .source("rubicon") - .accountId("accountId") - .relativePriority(1) - .price(Price.of(null, "USD")) - .deliverySchedules(singletonList(givenDeliverySchedule("planId1", now.minusHours(1), - now.plusMinutes(10), singleton(Token.of(1, 100))))) - .build()); - - lineItemService.updateLineItems(planResponse, true); - - final Imp imp = Imp.builder().id("imp1").build(); - - // when - final MatchLineItemsResult result = lineItemService.findMatchingLineItems( - auctionContext.getBidRequest(), imp, "rubicon", bidderAliases, auctionContext); - - // then - assertThat(result.getLineItems()).extracting(LineItem::getLineItemId).containsExactly("id1", "id2"); - } - - private static LineItemMetaData givenLineItemMetaData( - String lineItemId, - ZonedDateTime now, - String dealId, - List deliverySchedules, - Function lineItemMetaDataCustomizer) { - return lineItemMetaDataCustomizer.apply(LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId(lineItemId) - .dealId(dealId) - .status("active") - .accountId("accountId") - .source("rubicon") - .price(Price.of(BigDecimal.ONE, "USD")) - .relativePriority(5) - .updatedTimeStamp(now) - .deliverySchedules(deliverySchedules)) - .build(); - } - - private static LineItemMetaData givenLineItemMetaData( - String lineItemId, String account, String bidderCode, List deliverySchedules, - ZonedDateTime now) { - - return LineItemMetaData.builder() - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .lineItemId(lineItemId) - .dealId("dealId") - .status("active") - .accountId(account) - .source(bidderCode) - .price(Price.of(BigDecimal.ONE, "USD")) - .relativePriority(5) - .startTimeStamp(now.minusHours(1)) - .endTimeStamp(now.plusHours(1)) - .updatedTimeStamp(now) - .deliverySchedules(deliverySchedules) - .build(); - } - - private static DeliverySchedule givenDeliverySchedule(String planId, ZonedDateTime start, ZonedDateTime end, - ZonedDateTime updated, Set tokens) { - return DeliverySchedule.builder() - .planId(planId) - .startTimeStamp(start) - .endTimeStamp(end) - .updatedTimeStamp(updated) - .tokens(tokens) - .build(); - } - - private static DeliverySchedule givenDeliverySchedule(String planId, ZonedDateTime start, ZonedDateTime end, - Set tokens) { - return givenDeliverySchedule(planId, start, end, start, tokens); - } - - private void incSpentTokens(int times, String... lineItemIds) { - for (final String lineItemId : lineItemIds) { - final LineItem lineItem = lineItemService.getLineItemById(lineItemId); - IntStream.range(0, times).forEach(i -> lineItem.incSpentToken(now)); - } - } - - private AuctionContext givenAuctionContext(List fcaps) { - return AuctionContext.builder() - .httpRequest(HttpRequestContext.builder().headers(CaseInsensitiveMultiMap.empty()).build()) - .account(Account.builder().id("accountId").build()) - .deepDebugLog(DeepDebugLog.create(true, clock)) - .txnLog(TxnLog.create()) - .bidRequest(BidRequest.builder() - .user(User.builder().ext( - ExtUser.builder().fcapIds(fcaps).build()).build()) - .ext(ExtRequest.of(ExtRequestPrebid.builder() - .aliases(singletonMap("rubiAlias", "rubicon")) - .build())) - .build()) - .build(); - } - - private void givenTargetingService() { - given(targetingService.parseTargetingDefinition(any(), any())) - .willReturn(TargetingDefinition.of(context -> true)); - given(targetingService.matchesTargeting(any(), any(), any(), any())) - .willAnswer(withEvaluatedTargeting()); - } - - private Answer withEvaluatedTargeting() { - return invocation -> ((TargetingDefinition) invocation.getArgument(2)).getRootExpression().matches(null); - } - - private void givenClock(ZonedDateTime... dateTimes) { - given(clock.instant()).willReturn( - dateTimes[0].toInstant(), - Arrays.stream(dateTimes).skip(1).map(ZonedDateTime::toInstant).toArray(Instant[]::new)); - given(clock.getZone()).willReturn(dateTimes[0].getZone()); - } -} diff --git a/src/test/java/org/prebid/server/deals/PlannerServiceTest.java b/src/test/java/org/prebid/server/deals/PlannerServiceTest.java deleted file mode 100644 index 940f6c3628c..00000000000 --- a/src/test/java/org/prebid/server/deals/PlannerServiceTest.java +++ /dev/null @@ -1,351 +0,0 @@ -package org.prebid.server.deals; - -import com.fasterxml.jackson.core.JsonProcessingException; -import io.vertx.core.Future; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.BDDMockito; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.VertxTest; -import org.prebid.server.deals.model.AlertPriority; -import org.prebid.server.deals.model.DeploymentProperties; -import org.prebid.server.deals.model.PlannerProperties; -import org.prebid.server.deals.proto.DeliverySchedule; -import org.prebid.server.deals.proto.FrequencyCap; -import org.prebid.server.deals.proto.LineItemMetaData; -import org.prebid.server.deals.proto.Price; -import org.prebid.server.deals.proto.Token; -import org.prebid.server.metric.MetricName; -import org.prebid.server.metric.Metrics; -import org.prebid.server.vertx.http.HttpClient; -import org.prebid.server.vertx.http.model.HttpClientResponse; - -import java.math.BigDecimal; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.util.List; -import java.util.concurrent.TimeoutException; - -import static java.util.Arrays.asList; -import static java.util.Collections.emptyList; -import static java.util.Collections.singleton; -import static java.util.Collections.singletonList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.startsWith; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.anyBoolean; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class PlannerServiceTest extends VertxTest { - - private static final String PLAN_ENDPOINT = "plan-endpoint"; - private static final String REGISTER_ENDPOINT = "register-endpoint"; - private static final String USERNAME = "username"; - private static final String PASSWORD = "password"; - private static final String PBS_HOST = "pbs-host"; - private static final String PBS_REGION = "pbs-region"; - private static final String PBS_VENDOR = "pbs-vendor"; - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private HttpClient httpClient; - @Mock - private LineItemService lineItemService; - @Mock - private DeliveryProgressService deliveryProgressService; - @Mock - private AlertHttpService alertHttpService; - @Mock - private Metrics metrics; - @Mock - private Clock clock; - - private PlannerService plannerService; - - private ZonedDateTime now; - - @Before - public void setUp() throws JsonProcessingException { - clock = Clock.fixed(Instant.parse("2019-07-26T10:00:00Z"), ZoneOffset.UTC); - now = ZonedDateTime.now(clock); - - plannerService = new PlannerService( - PlannerProperties.builder() - .planEndpoint(PLAN_ENDPOINT) - .registerEndpoint(REGISTER_ENDPOINT) - .timeoutMs(100L) - .registerPeriodSeconds(60L) - .username(USERNAME) - .password(PASSWORD) - .build(), - DeploymentProperties.builder().pbsHostId(PBS_HOST).pbsRegion(PBS_REGION).pbsVendor(PBS_VENDOR).build(), - lineItemService, - deliveryProgressService, - alertHttpService, - httpClient, - metrics, - clock, - jacksonMapper); - - givenPlanHttpResponse(200, mapper.writeValueAsString( - asList(givenLineItemMetaData("lineItem1", "1001", "rubicon", now), - givenLineItemMetaData("lineItem2", "1002", "appnexus", now)))); - } - - @Test - public void updateLineItemMetaDataShouldRetryOnceWhenResponseCantBeParsed() { - // given - givenPlanHttpResponse(200, "{"); - - // when - plannerService.updateLineItemMetaData(); - - // then - verify(lineItemService, never()).updateLineItems(any(), anyBoolean()); - verify(alertHttpService).alertWithPeriod(eq("planner"), - eq("pbs-planner-client-error"), - eq(AlertPriority.MEDIUM), - eq("Failed to retrieve line items from GP. Reason: Cannot parse response: {")); - verify(metrics, times(2)).updatePlannerRequestMetric(eq(false)); - verify(httpClient, times(2)).get(anyString(), any(), anyLong()); - } - - @Test - public void updateLineItemMetaDataShouldRetryWhenHttpClientReturnsFailedFuture() { - // given - given(httpClient.get(anyString(), any(), anyLong())) - .willReturn(Future.failedFuture(new TimeoutException("Timeout has been exceeded"))); - - // when - plannerService.updateLineItemMetaData(); - - // then - verify(alertHttpService).alertWithPeriod(eq("planner"), eq("pbs-planner-client-error"), - eq(AlertPriority.MEDIUM), - eq("Failed to retrieve line items from GP. Reason: Timeout has been exceeded")); - verify(httpClient, times(2)).get(anyString(), any(), anyLong()); - } - - @Test - public void updateLineItemMetaDataShouldAlertWithoutRetryWhenPlannerReturnsEmptyLineItemList() - throws JsonProcessingException { - // given - givenPlanHttpResponse(200, mapper.writeValueAsString(emptyList())); - - // when - plannerService.updateLineItemMetaData(); - - // then - verify(alertHttpService).alertWithPeriod(eq("planner"), eq("pbs-planner-empty-response-error"), - eq(AlertPriority.LOW), eq("Response without line items was received from planner")); - verify(httpClient).get(anyString(), any(), anyLong()); - verify(lineItemService).updateLineItems(eq(emptyList()), anyBoolean()); - } - - @SuppressWarnings("unchecked") - @Test - public void getIdToLineItemsShouldReturnLineItemsSuccessfulInitialization() { - // when - plannerService.updateLineItemMetaData(); - - // then - final ArgumentCaptor> planResponseCaptor = ArgumentCaptor.forClass(List.class); - verify(lineItemService).updateLineItems(planResponseCaptor.capture(), anyBoolean()); - assertThat(planResponseCaptor.getValue()).isEqualTo(asList( - givenLineItemMetaData("lineItem1", "1001", "rubicon", now), - givenLineItemMetaData("lineItem2", "1002", "appnexus", now))); - verify(alertHttpService).resetAlertCount(eq("pbs-planner-empty-response-error")); - verify(metrics).updatePlannerRequestMetric(eq(true)); - verify(metrics).updateLineItemsNumberMetric(eq(2L)); - verify(metrics).updateRequestTimeMetric(eq(MetricName.planner_request_time), anyLong()); - } - - @SuppressWarnings("unchecked") - @Test - public void getIdToLineItemsShouldReturnOverwrittenMetaDataAfterSchedulerCallsRefresh() - throws JsonProcessingException { - // given - givenHttpClientReturnsResponses( - Future.succeededFuture(HttpClientResponse.of(200, null, - mapper.writeValueAsString(singletonList(LineItemMetaData.builder().lineItemId("id1") - .deliverySchedules(singletonList(DeliverySchedule.builder() - .planId("id1") - .startTimeStamp(now.minusHours(1)) - .endTimeStamp(now.plusHours(1)) - .updatedTimeStamp(now) - .tokens(singleton(Token.of(1, 300))).build())) - .accountId("1").build())))), - Future.succeededFuture(HttpClientResponse.of(200, null, - mapper.writeValueAsString(singletonList(LineItemMetaData.builder().lineItemId("id2") - .deliverySchedules(singletonList(DeliverySchedule.builder() - .planId("id2") - .startTimeStamp(now.minusHours(1)) - .endTimeStamp(now.plusHours(1)) - .updatedTimeStamp(now) - .tokens(singleton(Token.of(1, 300))).build())) - .accountId("2").build()))))); - - // when and then - plannerService.updateLineItemMetaData(); - - // fire request seconds time - plannerService.updateLineItemMetaData(); - - verify(httpClient, times(2)).get(anyString(), any(), anyLong()); - verify(lineItemService, times(2)).updateLineItems(any(), anyBoolean()); - - final ArgumentCaptor> planResponseCaptor = ArgumentCaptor.forClass(List.class); - verify(lineItemService, times(2)).updateLineItems(planResponseCaptor.capture(), anyBoolean()); - - assertThat(planResponseCaptor.getAllValues().get(1)) - .isEqualTo(singletonList(LineItemMetaData.builder().lineItemId("id2") - .deliverySchedules(singletonList(DeliverySchedule.builder() - .planId("id2") - .startTimeStamp(now.minusHours(1)) - .endTimeStamp(now.plusHours(1)) - .updatedTimeStamp(now) - .tokens(singleton(Token.of(1, 300))).build())) - .accountId("2").build())); - } - - @SuppressWarnings("unchecked") - @Test - public void getIdToLineItemMetaDataShouldReturnExpectedResult() { - // when - plannerService.updateLineItemMetaData(); - - // then - final ArgumentCaptor> planResponseCaptor = ArgumentCaptor.forClass(List.class); - verify(lineItemService).updateLineItems(planResponseCaptor.capture(), anyBoolean()); - - assertThat(planResponseCaptor.getValue()) - .containsOnly( - givenLineItemMetaData("lineItem1", "1001", "rubicon", now), - givenLineItemMetaData("lineItem2", "1002", "appnexus", now)); - } - - @SuppressWarnings("unchecked") - @Test - public void getIdToLineItemMetaDataShouldNotCallUpdateLineItemAfterFailedRequest() { - // given - givenPlanHttpResponse(404, null); - - // when - plannerService.updateLineItemMetaData(); - - // then - final ArgumentCaptor> planResponseCaptor = ArgumentCaptor.forClass(List.class); - verify(lineItemService, never()).updateLineItems(planResponseCaptor.capture(), anyBoolean()); - } - - @SuppressWarnings("unchecked") - @Test - public void getIdToLineItemMetaDataShouldNotCallUpdateLineItemsWhenBodyIsNull() { - // given - givenPlanHttpResponse(200, null); - - // when - plannerService.updateLineItemMetaData(); - - // then - final ArgumentCaptor> planResponseCaptor = ArgumentCaptor.forClass(List.class); - verify(lineItemService, never()).updateLineItems(planResponseCaptor.capture(), anyBoolean()); - } - - @SuppressWarnings("unchecked") - @Test - public void getIdToLineItemMetaDataShouldNotCallUpdateLineItemWhenBodyCantBeParsed() { - // given - givenPlanHttpResponse(200, "{"); - - // when - plannerService.updateLineItemMetaData(); - - // then - final ArgumentCaptor> planResponseCaptor = ArgumentCaptor.forClass(List.class); - verify(lineItemService, never()).updateLineItems(planResponseCaptor.capture(), anyBoolean()); - } - - @SuppressWarnings("unchecked") - @Test - public void getIdToLineItemsShouldNotCallLineItemsUpdateAfter404Response() { - // given - givenPlanHttpResponse(404, null); - - // when - plannerService.updateLineItemMetaData(); - - // then - final ArgumentCaptor> planResponseCaptor = ArgumentCaptor.forClass(List.class); - verify(lineItemService, never()).updateLineItems(planResponseCaptor.capture(), anyBoolean()); - } - - @SuppressWarnings("unchecked") - @Test - public void getIdToLineItemsShouldNotCallLineItemsUpdateWhenBodyIsNull() { - // given - givenPlanHttpResponse(200, null); - - // when - plannerService.updateLineItemMetaData(); - - // then - final ArgumentCaptor> planResponseCaptor = ArgumentCaptor.forClass(List.class); - verify(lineItemService, never()).updateLineItems(planResponseCaptor.capture(), anyBoolean()); - } - - private void givenPlanHttpResponse(int statusCode, String response) { - final HttpClientResponse httpClientResponse = HttpClientResponse.of(statusCode, null, response); - given(httpClient.get(startsWith(PLAN_ENDPOINT), any(), anyLong())) - .willReturn(Future.succeededFuture(httpClientResponse)); - } - - private static LineItemMetaData givenLineItemMetaData(String lineItemId, String account, String bidderCode, - ZonedDateTime now) { - return LineItemMetaData.builder() - .lineItemId(lineItemId) - .dealId("dealId") - .accountId(account) - .source(bidderCode) - .price(Price.of(BigDecimal.ONE, "USD")) - .relativePriority(5) - .startTimeStamp(now) - .endTimeStamp(now) - .updatedTimeStamp(now) - .frequencyCaps(singletonList(FrequencyCap.builder() - .fcapId("fcap").count(6L).periods(7).periodType("day").build())) - .deliverySchedules(singletonList(DeliverySchedule.builder() - .planId("plan") - .startTimeStamp(now.minusHours(1)) - .endTimeStamp(now.plusHours(1)) - .updatedTimeStamp(now) - .tokens(singleton(Token.of(1, 300))).build())) - .targeting(mapper.createObjectNode()) - .build(); - } - - @SafeVarargs - private void givenHttpClientReturnsResponses(Future... futureHttpClientResponses) { - BDDMockito.BDDMyOngoingStubbing> stubbing = - given(httpClient.get(anyString(), any(), anyLong())); - - // setup multiple answers - for (Future futureHttpClientResponse : futureHttpClientResponses) { - stubbing = stubbing.willReturn(futureHttpClientResponse); - } - } -} diff --git a/src/test/java/org/prebid/server/deals/RegisterServiceTest.java b/src/test/java/org/prebid/server/deals/RegisterServiceTest.java deleted file mode 100644 index 1f65a78fd79..00000000000 --- a/src/test/java/org/prebid/server/deals/RegisterServiceTest.java +++ /dev/null @@ -1,269 +0,0 @@ -package org.prebid.server.deals; - -import com.fasterxml.jackson.core.JsonProcessingException; -import io.vertx.core.Future; -import io.vertx.core.MultiMap; -import io.vertx.core.Vertx; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.VertxTest; -import org.prebid.server.currency.CurrencyConversionService; -import org.prebid.server.deals.events.AdminEventService; -import org.prebid.server.deals.model.AdminCentralResponse; -import org.prebid.server.deals.model.AlertPriority; -import org.prebid.server.deals.model.DeploymentProperties; -import org.prebid.server.deals.model.PlannerProperties; -import org.prebid.server.deals.model.ServicesCommand; -import org.prebid.server.deals.proto.CurrencyServiceState; -import org.prebid.server.deals.proto.RegisterRequest; -import org.prebid.server.deals.proto.Status; -import org.prebid.server.deals.proto.report.DeliveryProgressReport; -import org.prebid.server.exception.PreBidException; -import org.prebid.server.health.HealthMonitor; -import org.prebid.server.vertx.http.HttpClient; -import org.prebid.server.vertx.http.model.HttpClientResponse; - -import java.math.BigDecimal; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.startsWith; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; - -public class RegisterServiceTest extends VertxTest { - - private static final String PLAN_ENDPOINT = "plan-endpoint"; - private static final String REGISTER_ENDPOINT = "register-endpoint"; - private static final String USERNAME = "username"; - private static final String PASSWORD = "password"; - private static final String PBS_HOST = "pbs-host"; - private static final String PBS_REGION = "pbs-region"; - private static final String PBS_VENDOR = "pbs-vendor"; - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - private RegisterService registerService; - @Mock - private HealthMonitor healthMonitor; - @Mock - private CurrencyConversionService currencyConversionService; - @Mock - private AdminEventService adminEventService; - @Mock - private DeliveryProgressService deliveryProgressService; - @Mock - private HttpClient httpClient; - @Mock - private AlertHttpService alertHttpService; - @Mock - private Vertx vertx; - - private ZonedDateTime fixedDate; - - @Before - public void setUp() { - fixedDate = ZonedDateTime.now(Clock.fixed(Instant.parse("2019-07-26T10:00:00Z"), ZoneOffset.UTC)); - registerService = new RegisterService( - PlannerProperties.builder() - .planEndpoint(PLAN_ENDPOINT) - .registerEndpoint(REGISTER_ENDPOINT) - .timeoutMs(100L) - .registerPeriodSeconds(60L) - .username(USERNAME) - .password(PASSWORD) - .build(), - DeploymentProperties.builder().pbsHostId(PBS_HOST).pbsRegion(PBS_REGION).pbsVendor(PBS_VENDOR).build(), - adminEventService, - deliveryProgressService, - alertHttpService, - healthMonitor, - currencyConversionService, - httpClient, - vertx, - jacksonMapper); - - givenRegisterHttpResponse(200); - } - - @Test - public void initializeShouldSetRegisterTimer() throws JsonProcessingException { - // given - given(vertx.setPeriodic(anyLong(), any())).willReturn(1L); - given(healthMonitor.calculateHealthIndex()).willReturn(BigDecimal.ONE); - given(currencyConversionService.getLastUpdated()).willReturn(fixedDate); - - // when - registerService.initialize(); - - // then - verify(vertx).setPeriodic(eq(60000L), any()); - verify(vertx, never()).cancelTimer(anyLong()); - - final ArgumentCaptor registerBodyCaptor = ArgumentCaptor.forClass(String.class); - verify(httpClient).post(startsWith(REGISTER_ENDPOINT), any(), registerBodyCaptor.capture(), anyLong()); - assertThat(registerBodyCaptor.getValue()).isEqualTo(mapper.writeValueAsString( - RegisterRequest.of(BigDecimal.ONE, Status.of(CurrencyServiceState.of("2019-07-26T10:00:00.000Z"), null), - PBS_HOST, PBS_REGION, PBS_VENDOR))); - } - - @Test - public void initializeShouldSetDeliveryReportToRegisterRequest() throws JsonProcessingException { - // given - given(vertx.setPeriodic(anyLong(), any())).willReturn(1L); - given(healthMonitor.calculateHealthIndex()).willReturn(BigDecimal.ONE); - given(deliveryProgressService.getOverallDeliveryProgressReport()).willReturn(DeliveryProgressReport.builder() - .reportId("reportId").build()); - - // when - registerService.initialize(); - - // then - final ArgumentCaptor registerBodyCaptor = ArgumentCaptor.forClass(String.class); - verify(httpClient).post(startsWith(REGISTER_ENDPOINT), any(), registerBodyCaptor.capture(), anyLong()); - assertThat(registerBodyCaptor.getValue()).isEqualTo(mapper.writeValueAsString( - RegisterRequest.of(BigDecimal.ONE, - Status.of(null, DeliveryProgressReport.builder().reportId("reportId").build()), - PBS_HOST, PBS_REGION, PBS_VENDOR))); - } - - @Test - public void registerShouldNotCallAdminCentralWhenResponseIsEmpty() { - // given - given(healthMonitor.calculateHealthIndex()).willReturn(BigDecimal.ONE); - given(httpClient.post(anyString(), any(), anyString(), anyLong())) - .willReturn(Future.succeededFuture(HttpClientResponse.of(200, MultiMap.caseInsensitiveMultiMap(), ""))); - - // when - registerService.register(MultiMap.caseInsensitiveMultiMap()); - - // then - verifyNoInteractions(adminEventService); - } - - @Test - public void registerShouldCallAdminCentralWhenResponseIsNotEmpty() throws JsonProcessingException { - // given - given(healthMonitor.calculateHealthIndex()).willReturn(BigDecimal.ONE); - given(httpClient.post(anyString(), any(), anyString(), anyLong())) - .willReturn(Future.succeededFuture(HttpClientResponse.of(200, MultiMap.caseInsensitiveMultiMap(), - mapper.writeValueAsString(AdminCentralResponse.of(null, null, null, null, null, - ServicesCommand.of("stop")))))); - - // when - registerService.register(MultiMap.caseInsensitiveMultiMap()); - - // then - verify(adminEventService).publishAdminCentralEvent(any()); - } - - @Test - public void registerShouldNotCallAdminCentralWhenFutureFailed() { - // given - given(healthMonitor.calculateHealthIndex()).willReturn(BigDecimal.ONE); - given(httpClient.post(anyString(), any(), anyString(), anyLong())) - .willReturn(Future.failedFuture("failed")); - - // when - registerService.register(MultiMap.caseInsensitiveMultiMap()); - - // then - verifyNoInteractions(adminEventService); - } - - @Test - public void registerShouldCallAlertServiceWhenFutureFailed() { - // given - given(healthMonitor.calculateHealthIndex()).willReturn(BigDecimal.ONE); - given(httpClient.post(anyString(), any(), anyString(), anyLong())) - .willReturn(Future.failedFuture("failed")); - - // when - registerService.register(MultiMap.caseInsensitiveMultiMap()); - - // then - verify(alertHttpService).alertWithPeriod(eq("register"), eq("pbs-register-client-error"), - eq(AlertPriority.MEDIUM), - eq("Error occurred while registering with the Planner:" - + " io.vertx.core.impl.NoStackTraceThrowable: failed")); - } - - @Test - public void registerShouldCallAlertServiceResetWhenRequestWasSuccessful() { - // given - given(healthMonitor.calculateHealthIndex()).willReturn(BigDecimal.ONE); - given(httpClient.post(anyString(), any(), anyString(), anyLong())) - .willReturn(Future.succeededFuture(HttpClientResponse.of(200, MultiMap.caseInsensitiveMultiMap(), ""))); - - // when - registerService.register(MultiMap.caseInsensitiveMultiMap()); - - // then - verify(alertHttpService).resetAlertCount(eq("pbs-register-client-error")); - } - - @Test - public void registerShouldNotSendAdminEventWhenResponseStatusIsBadRequest() { - // given - given(httpClient.post(anyString(), any(), anyString(), anyLong())) - .willReturn(Future.succeededFuture(HttpClientResponse.of(400, null, null))); - - // when - registerService.register(MultiMap.caseInsensitiveMultiMap()); - - // then - verifyNoInteractions(adminEventService); - } - - @Test - public void registerShouldThrowPrebidExceptionWhenResponseIsInvalidJson() { - // given - given(httpClient.post(anyString(), any(), anyString(), anyLong())) - .willReturn(Future.succeededFuture(HttpClientResponse.of(200, null, "{"))); - - // when and then - assertThatThrownBy(() -> registerService.register(MultiMap.caseInsensitiveMultiMap())) - .isInstanceOf(PreBidException.class) - .hasMessage("Cannot parse register response: {"); - } - - @Test - public void suspendShouldStopRegisterTimer() { - // when - registerService.suspend(); - - // then - verify(vertx).cancelTimer(anyLong()); - } - - @Test - public void initializeShouldCallHealthMonitor() { - // when - registerService.initialize(); - - // then - verify(healthMonitor).calculateHealthIndex(); - } - - private void givenRegisterHttpResponse(int statusCode) { - final HttpClientResponse httpClientResponse = HttpClientResponse.of(statusCode, null, null); - given(httpClient.post(startsWith(REGISTER_ENDPOINT), any(), anyString(), anyLong())) - .willReturn(Future.succeededFuture(httpClientResponse)); - } -} diff --git a/src/test/java/org/prebid/server/deals/TargetingServiceTest.java b/src/test/java/org/prebid/server/deals/TargetingServiceTest.java deleted file mode 100644 index 30274979ef8..00000000000 --- a/src/test/java/org/prebid/server/deals/TargetingServiceTest.java +++ /dev/null @@ -1,919 +0,0 @@ -package org.prebid.server.deals; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.IntNode; -import com.fasterxml.jackson.databind.node.TextNode; -import com.iab.openrtb.request.Banner; -import com.iab.openrtb.request.BidRequest; -import com.iab.openrtb.request.Data; -import com.iab.openrtb.request.Device; -import com.iab.openrtb.request.Format; -import com.iab.openrtb.request.Geo; -import com.iab.openrtb.request.Imp; -import com.iab.openrtb.request.Publisher; -import com.iab.openrtb.request.Segment; -import com.iab.openrtb.request.Site; -import com.iab.openrtb.request.User; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.VertxTest; -import org.prebid.server.auction.model.AuctionContext; -import org.prebid.server.deals.model.TxnLog; -import org.prebid.server.deals.targeting.TargetingDefinition; -import org.prebid.server.deals.targeting.interpret.And; -import org.prebid.server.deals.targeting.interpret.DomainMetricAwareExpression; -import org.prebid.server.deals.targeting.interpret.InIntegers; -import org.prebid.server.deals.targeting.interpret.InStrings; -import org.prebid.server.deals.targeting.interpret.IntersectsIntegers; -import org.prebid.server.deals.targeting.interpret.IntersectsSizes; -import org.prebid.server.deals.targeting.interpret.IntersectsStrings; -import org.prebid.server.deals.targeting.interpret.Matches; -import org.prebid.server.deals.targeting.interpret.Not; -import org.prebid.server.deals.targeting.interpret.Or; -import org.prebid.server.deals.targeting.interpret.Within; -import org.prebid.server.deals.targeting.model.GeoRegion; -import org.prebid.server.deals.targeting.model.Size; -import org.prebid.server.deals.targeting.syntax.TargetingCategory; -import org.prebid.server.deals.targeting.syntax.TargetingCategory.Type; -import org.prebid.server.exception.TargetingSyntaxException; -import org.prebid.server.proto.openrtb.ext.request.ExtDevice; -import org.prebid.server.proto.openrtb.ext.request.ExtGeo; -import org.prebid.server.proto.openrtb.ext.request.ExtUser; - -import java.io.IOException; - -import static java.util.Arrays.asList; -import static java.util.Collections.singletonMap; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class TargetingServiceTest extends VertxTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - private TargetingService targetingService; - - @Before - public void setUp() { - targetingService = new TargetingService(jacksonMapper); - } - - @Test - public void parseTargetingDefinitionShouldReturnValidExpression() throws IOException { - // when - final TargetingDefinition definition = targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-valid-targeting-definition.json"), "lineItemId"); - - // then - assertThat(definition).isNotNull().isEqualTo(TargetingDefinition.of( - new And(asList( - new IntersectsSizes(category(Type.size), asList(Size.of(300, 250), Size.of(400, 200))), - new IntersectsStrings(category(Type.mediaType), asList("banner", "video")), - new Or(asList( - new Or(asList( - new DomainMetricAwareExpression(new Matches(category(Type.domain), - "*nba.com*"), "lineItemId"), - new DomainMetricAwareExpression(new Matches(category(Type.publisherDomain), - "*nba.com*"), "lineItemId"))), - new Or(asList( - new DomainMetricAwareExpression(new Matches(category(Type.domain), - "nba.com*"), "lineItemId"), - new DomainMetricAwareExpression(new Matches(category(Type.publisherDomain), - "nba.com*"), "lineItemId"))), - new Or(asList( - new DomainMetricAwareExpression(new InStrings(category(Type.domain), - asList("nba.com", "cnn.com")), "lineItemId"), - new DomainMetricAwareExpression(new InStrings(category(Type.publisherDomain), - asList("nba.com", "cnn.com")), "lineItemId"))) - )), - new Or(asList( - new Matches(category(Type.referrer), "*sports*"), - new Matches(category(Type.referrer), "http://nba.com/lalakers*"), - new InStrings(category(Type.referrer), - asList("http://cnn.com/culture", "http://cnn.com/weather")) - )), - new Or(asList( - new Matches(category(Type.appBundle), "*com.google.calendar*"), - new Matches(category(Type.appBundle), "com.google.calendar*"), - new InStrings(category(Type.appBundle), - asList("com.google.calendar", "com.tmz")) - )), - new Or(asList( - new Matches(category(Type.adslot), "*/home/top*"), - new Matches(category(Type.adslot), "/home/top*"), - new InStrings(category(Type.adslot), asList("/home/top", "/home/bottom")) - )), - new InStrings(category(Type.deviceGeoExt, "vendor.attribute"), - asList("device_geo_ext_value1", "device_geo_ext_value2")), - new InStrings(category(Type.deviceGeoExt, "vendor.nested.attribute"), - asList("device_geo_ext_nested_value1", "device_geo_ext_nested_value2")), - new InStrings(category(Type.deviceExt, "vendor.attribute"), - asList("device_ext_value1", "device_ext_value2")), - new InStrings(category(Type.deviceExt, "vendor.nested.attribute"), - asList("device_ext_nested_value1", "device_ext_nested_value2")), - new InIntegers(category(Type.pagePosition), asList(1, 3)), - new Within(category(Type.location), GeoRegion.of(123.456f, 789.123f, 10.0f)), - new Or(asList( - new InIntegers(category(Type.bidderParam, "siteId"), asList(123, 321)), - new IntersectsIntegers(category(Type.bidderParam, "siteId"), asList(123, 321)) - )), - new Or(asList( - new Matches(category(Type.bidderParam, "placementName"), "*somePlacement*"), - new Matches(category(Type.bidderParam, "placementName"), "somePlacement*"), - new InStrings(category(Type.bidderParam, "placementName"), - asList("somePlacement1", "somePlacement2")), - new IntersectsStrings(category(Type.bidderParam, "placementName"), - asList("somePlacement1", "somePlacement2")) - )), - new Or(asList( - new IntersectsStrings( - category(Type.userSegment, "rubicon"), asList("123", "234", "345")), - new IntersectsStrings( - category(Type.userSegment, "bluekai"), asList("123", "234", "345")) - )), - new Or(asList( - new InIntegers(category(Type.userFirstPartyData, "someId"), asList(123, 321)), - new IntersectsIntegers(category(Type.userFirstPartyData, "someId"), asList(123, 321)) - )), - new Or(asList( - new Matches(category(Type.userFirstPartyData, "sport"), "*hockey*"), - new Matches(category(Type.userFirstPartyData, "sport"), "hockey*"), - new InStrings(category(Type.userFirstPartyData, "sport"), asList("hockey", "soccer")), - new IntersectsStrings( - category(Type.userFirstPartyData, "sport"), asList("hockey", "soccer")) - )), - new Or(asList( - new InIntegers(category(Type.siteFirstPartyData, "someId"), asList(123, 321)), - new IntersectsIntegers(category(Type.siteFirstPartyData, "someId"), asList(123, 321)) - )), - new Or(asList( - new Matches(category(Type.siteFirstPartyData, "sport"), "*hockey*"), - new Matches(category(Type.siteFirstPartyData, "sport"), "hockey*"), - new InStrings(category(Type.siteFirstPartyData, "sport"), asList("hockey", "soccer")), - new IntersectsStrings( - category(Type.siteFirstPartyData, "sport"), asList("hockey", "soccer")) - )), - new InIntegers(category(Type.dow), asList(5, 6)), - new InIntegers(category(Type.hour), asList(10, 11, 12, 13, 14)) - )))); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenTopLevelFieldIsNonObject() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-non-object.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected array, got NUMBER"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenTopLevelObjectHasMultipleFields() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-multiple-fields.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected only one element in the object, got 2"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenBooleanOperatorArgumentHasMultipleFields() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-multiple-fields-boolean-args.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected only one element in the object, got 2"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenFieldIsUnknown() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-unknown-field.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected either boolean operator or targeting category, got aaa"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenAndWithNonArray() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-and-with-non-array.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected array, got OBJECT"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenNotWithNonObject() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-not-with-non-object.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected object, got ARRAY"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenCategoryWithNonObject() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-category-non-object.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected object, got NUMBER"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenFunctionHasMultipleFields() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-multiple-fields-function.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected only one element in the object, got 2"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenUnknownFunction() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-unknown-function.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected matching function, got $abc"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenCategoryWithIncompatibleFunction() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-category-incompatible-function.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected $intersects matching function, got $in"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenIntersectsNonArray() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-intersects-non-array.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected array, got OBJECT"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenIntersectsSizesWithNonObjects() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-intersects-sizes-non-objects.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected object, got NUMBER"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenIntersectsSizesWithNonReadableSize() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-intersects-sizes-non-readable-size.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessageStartingWith("Exception occurred while parsing size: " - + "Cannot deserialize value of type `java.lang.Integer`"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenIntersectsSizesWithEmptySize() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-intersects-sizes-empty-size.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Height and width in size definition could not be null or missing"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenIntersectsStringsWithNonString() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-intersects-strings-non-string.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected string, got NUMBER"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenIntersectsStringsWithEmptyString() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-intersects-strings-empty.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("String value could not be empty"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenUnknownStringFunction() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-unknown-string-function.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected matching function, got $abc"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenCategoryWithIncompatibleStringFunction() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-category-incompatible-string-function.json"), - null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected one of $matches, $in matching functions, got $intersects"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenMatchesWithNonString() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-matches-non-string.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected string, got NUMBER"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenMatchesWithEmptyString() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-matches-empty.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("String value could not be empty"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenInIntegersWithNonInteger() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-in-integers-non-integer.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected integer, got STRING"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenCategoryWithIncompatibleGeoFunction() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-category-incompatible-geo-function.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected $within matching function, got $intersects"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenWithinWithNonObject() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-within-non-object.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected object, got ARRAY"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenWithinWithNonReadableGeoRegion() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-within-non-readable-georegion.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessageStartingWith("Exception occurred while parsing geo region: " - + "Cannot deserialize value of type `java.lang.Float`"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenWithinWithEmptyGeoRegion() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-within-empty-georegion.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Lat, lon and radiusMiles in geo region definition could not be null or missing"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenCategoryWithIncompatibleSegmentFunction() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom( - "targeting/test-invalid-targeting-definition-category-incompatible-segment-function.json"), - null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected $intersects matching function, got $in"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenUnknownTypedFunction() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-unknown-typed-function.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected matching function, got $abc"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenCategoryWithIncompatibleTypedFunction() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-category-incompatible-typed-function.json"), - null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected one of $matches, $in, $intersects matching functions, got $within"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenTypedFunctionWithIncompatibleType() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-typed-function-incompatible-type.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected integer or string, got BOOLEAN"); - } - - @Test - public void parseTargetingDefinitionShouldFailWhenTypedFunctionWithMixedTypes() { - assertThatThrownBy(() -> targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-invalid-targeting-definition-typed-function-mixed-types.json"), null)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Expected integer, got STRING"); - } - - @Test - public void matchesTargetingShouldReturnTrue() { - // given - final TargetingDefinition targetingDefinition = TargetingDefinition.of( - new And(asList( - new IntersectsSizes(category(Type.size), asList(Size.of(300, 250), Size.of(400, 200))), - new IntersectsStrings(category(Type.mediaType), asList("banner", "video")), - new DomainMetricAwareExpression( - new Matches(category(Type.domain), "*nba.com*"), "lineItemId"), - new DomainMetricAwareExpression( - new Matches(category(Type.domain), "lakers.nba.com"), "lineItemId"), - new DomainMetricAwareExpression( - new Matches(category(Type.publisherDomain), "nba.com"), "lineItemId"), - new InIntegers(category(Type.pagePosition), asList(1, 3)), - new Within(category(Type.location), GeoRegion.of(50.424744f, 30.506435f, 10.0f)), - new InIntegers(category(Type.bidderParam, "siteId"), asList(123, 321)), - new IntersectsStrings(category(Type.userSegment, "rubicon"), asList("123", "234", "345")), - new IntersectsIntegers(category(Type.userFirstPartyData, "someId"), asList(123, 321))))); - - final BidRequest bidRequest = BidRequest.builder() - .site(Site.builder() - .domain("lakers.nba.com") - .publisher(Publisher.builder().domain("nba.com").build()) - .build()) - .device(Device.builder() - .geo(Geo.builder() - .lat(50.432069f) - .lon(30.516455f) - .build()) - .build()) - .user(User.builder() - .data(asList( - Data.builder() - .id("rubicon") - .segment(asList( - Segment.builder().id("234").build(), - Segment.builder().id("567").build())) - .build(), - Data.builder() - .id("bluekai") - .segment(asList( - Segment.builder().id("789").build(), - Segment.builder().id("890").build())) - .build())) - .ext(ExtUser.builder().data(mapper.valueToTree(singletonMap("someId", asList(123, 456)))) - .build()) - .build()) - .build(); - - final TxnLog txnLog = TxnLog.create(); - final AuctionContext auctionContext = AuctionContext.builder().txnLog(txnLog).build(); - - final Imp imp = Imp.builder() - .banner(Banner.builder() - .format(asList( - Format.builder().w(300).h(500).build(), - Format.builder().w(300).h(250).build(), - Format.builder().w(400).h(500).build())) - .pos(3) - .build()) - .ext(mapper.createObjectNode().set("bidder", mapper.valueToTree(singletonMap("siteId", 123)))) - .build(); - - // when and then - assertThat(targetingService.matchesTargeting(bidRequest, imp, targetingDefinition, auctionContext)).isTrue(); - assertThat(txnLog.lineItemsMatchedDomainTargeting()).containsOnly("lineItemId"); - } - - @Test - public void matchesTargetingShouldReturnTrueForIntersectsStringsOnSingleString() { - // given - final TargetingDefinition targetingDefinition = TargetingDefinition.of( - new IntersectsStrings(category(Type.userFirstPartyData, "segment"), asList("test", "111"))); - - final BidRequest bidRequest = BidRequest.builder() - .user(User.builder() - .ext(ExtUser.builder() - .data(mapper.createObjectNode().set("segment", TextNode.valueOf("test"))) - .build()) - .build()) - .build(); - - final TxnLog txnLog = TxnLog.create(); - final AuctionContext auctionContext = AuctionContext.builder().txnLog(txnLog).build(); - - final Imp imp = Imp.builder().build(); - - // when and then - assertThat(targetingService.matchesTargeting(bidRequest, imp, targetingDefinition, auctionContext)).isTrue(); - } - - @Test - public void matchesTargetingShouldReturnTrueForIntersectsIntegersOnSingleInteger() { - // given - final TargetingDefinition targetingDefinition = TargetingDefinition.of( - new IntersectsIntegers(category(Type.userFirstPartyData, "segment"), asList(123, 456))); - - final BidRequest bidRequest = BidRequest.builder() - .user(User.builder() - .ext(ExtUser.builder() - .data(mapper.createObjectNode().set("segment", IntNode.valueOf(123))) - .build()) - .build()) - .build(); - - final TxnLog txnLog = TxnLog.create(); - final AuctionContext auctionContext = AuctionContext.builder().txnLog(txnLog).build(); - - final Imp imp = Imp.builder().build(); - - // when and then - assertThat(targetingService.matchesTargeting(bidRequest, imp, targetingDefinition, auctionContext)).isTrue(); - } - - @Test - public void matchesTargetingShouldReturnTrueForNotInIntegers() throws IOException { - // given - final TargetingDefinition targetingDefinition = targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-not-in-integers-definition.json"), "lineItemId"); - - final BidRequest bidRequest = BidRequest.builder() - .build(); - - final TxnLog txnLog = TxnLog.create(); - final AuctionContext auctionContext = AuctionContext.builder().txnLog(txnLog).build(); - - final Imp imp = Imp.builder() - .ext(mapper.createObjectNode() - .set("prebid", mapper.createObjectNode() - .set("bidder", mapper.valueToTree( - singletonMap("rubicon", singletonMap("siteId", 123)))))) - .build(); - - // when and then - assertThat(targetingService.matchesTargeting(bidRequest, imp, targetingDefinition, auctionContext)).isTrue(); - } - - @Test - public void matchesTargetingShouldReturnTrueForNotInStrings() throws IOException { - // given - final TargetingDefinition targetingDefinition = targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-not-in-strings-definition.json"), "lineItemId"); - - final BidRequest bidRequest = BidRequest.builder() - .site(Site.builder() - .domain("lakers.nba.com") - .build()) - .build(); - - final TxnLog txnLog = TxnLog.create(); - final AuctionContext auctionContext = AuctionContext.builder().txnLog(txnLog).build(); - - final Imp imp = Imp.builder() - .build(); - - // when and then - assertThat(targetingService.matchesTargeting(bidRequest, imp, targetingDefinition, auctionContext)).isTrue(); - } - - @Test - public void matchesTargetingShouldReturnTrueForNotIntersectsInteger() throws IOException { - final TargetingDefinition targetingDefinition = targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-not-intersects-integer-definition.json"), "lineItemId"); - - final BidRequest bidRequest = BidRequest.builder() - .user(User.builder() - .ext(ExtUser.builder().data(mapper.valueToTree(singletonMap("someId", asList(123, 456)))) - .build()) - .build()) - .build(); - - final TxnLog txnLog = TxnLog.create(); - final AuctionContext auctionContext = AuctionContext.builder().txnLog(txnLog).build(); - - final Imp imp = Imp.builder().build(); - - // when and then - assertThat(targetingService.matchesTargeting(bidRequest, imp, targetingDefinition, auctionContext)).isTrue(); - } - - @Test - public void matchesTargetingShouldReturnTrueForNotIntersectsSizes() throws IOException { - // given - final TargetingDefinition targetingDefinition = targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-not-intersects-sizes-definition.json"), "lineItemId"); - - final BidRequest bidRequest = BidRequest.builder().build(); - - final TxnLog txnLog = TxnLog.create(); - final AuctionContext auctionContext = AuctionContext.builder().txnLog(txnLog).build(); - - final Imp imp = Imp.builder() - .banner(Banner.builder() - .format(asList( - Format.builder().w(300).h(500).build(), - Format.builder().w(300).h(250).build(), - Format.builder().w(400).h(500).build())) - .build()) - .build(); - - // when and then - assertThat(targetingService.matchesTargeting(bidRequest, imp, targetingDefinition, auctionContext)).isTrue(); - } - - @Test - public void matchesTargetingShouldReturnTrueForNotWithin() throws IOException { - // given - final TargetingDefinition targetingDefinition = targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-not-within-definition.json"), "lineItemId"); - - final BidRequest bidRequest = BidRequest.builder() - .device(Device.builder() - .geo(Geo.builder() - .lat(50.432069f) - .lon(30.516455f) - .build()) - .build()) - .build(); - - final TxnLog txnLog = TxnLog.create(); - final AuctionContext auctionContext = AuctionContext.builder().txnLog(txnLog).build(); - - final Imp imp = Imp.builder() - .build(); - - // when and then - assertThat(targetingService.matchesTargeting(bidRequest, imp, targetingDefinition, auctionContext)).isTrue(); - } - - @Test - public void matchesTargetingShouldReturnTrueForNotFalseAnd() throws IOException { - // given - final TargetingDefinition targetingDefinition = targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-not-and-definition.json"), "lineItemId"); - - final BidRequest bidRequest = BidRequest.builder().build(); - - final TxnLog txnLog = TxnLog.create(); - final AuctionContext auctionContext = AuctionContext.builder().txnLog(txnLog).build(); - - final Imp imp = Imp.builder() - .banner(Banner.builder() - .format(asList( - Format.builder().w(300).h(500).build(), - Format.builder().w(300).h(250).build(), - Format.builder().w(400).h(500).build())) - .build()) - .build(); - - // when and then - assertThat(targetingService.matchesTargeting(bidRequest, imp, targetingDefinition, auctionContext)).isTrue(); - } - - @Test - public void matchesTargetingShouldReturnTrueForNotMatches() throws IOException { - // given - final TargetingDefinition targetingDefinition = targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-not-matches-definition.json"), "lineItemId"); - - final BidRequest bidRequest = BidRequest.builder() - .site(Site.builder() - .domain("lakers.uefa.com") - .build()) - .build(); - - final TxnLog txnLog = TxnLog.create(); - final AuctionContext auctionContext = AuctionContext.builder().txnLog(txnLog).build(); - - final Imp imp = Imp.builder() - - .build(); - - // when and then - assertThat(targetingService.matchesTargeting(bidRequest, imp, targetingDefinition, auctionContext)).isTrue(); - } - - @Test - public void matchesTargetingShouldReturnFalseForNotTrueOr() throws IOException { - // given - final TargetingDefinition targetingDefinition = targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-not-or-definition.json"), "lineItemId"); - - final BidRequest bidRequest = BidRequest.builder().build(); - - final TxnLog txnLog = TxnLog.create(); - final AuctionContext auctionContext = AuctionContext.builder().txnLog(txnLog).build(); - - final Imp imp = Imp.builder() - .banner(Banner.builder() - .format(asList( - Format.builder().w(300).h(500).build(), - Format.builder().w(300).h(250).build(), - Format.builder().w(400).h(500).build())) - .build()) - .build(); - - // when and then - assertThat(targetingService.matchesTargeting(bidRequest, imp, targetingDefinition, auctionContext)) - .isFalse(); - } - - @Test - public void matchesTargetingShouldReturnTrueForDeviceExt() throws IOException { - // given - final TargetingDefinition targetingDefinition = targetingService.parseTargetingDefinition( - jsonFrom("targeting/test-device-targeting.json"), "lineItemId"); - - final ExtGeo extGeo = ExtGeo.of(); - extGeo.addProperty("geoprovider", mapper.createObjectNode().set("country", new TextNode("us"))); - final ExtDevice extDevice = ExtDevice.empty(); - extDevice.addProperty("deviceinfoprovider", mapper.createObjectNode().set("browser", new TextNode("Chrome"))); - final BidRequest bidRequest = BidRequest.builder() - .device(Device - .builder() - .geo(Geo.builder().ext(extGeo) - .build()) - .ext(extDevice) - .build()).build(); - - final TxnLog txnLog = TxnLog.create(); - - final AuctionContext auctionContext = AuctionContext.builder().txnLog(txnLog).build(); - - final Imp imp = Imp.builder().build(); - - // when and then - assertThat(targetingService.matchesTargeting(bidRequest, imp, targetingDefinition, auctionContext)).isTrue(); - } - - @Test - public void matchesTargetingShouldReturnFalseForNotInIntegers() { - // given - final TargetingDefinition targetingDefinition = TargetingDefinition.of( - new Not(new InIntegers(category(Type.bidderParam, "siteId"), asList(123, 778)))); - - final BidRequest bidRequest = BidRequest.builder() - .build(); - - final TxnLog txnLog = TxnLog.create(); - final AuctionContext auctionContext = AuctionContext.builder().txnLog(txnLog).build(); - - final Imp imp = Imp.builder() - .ext(mapper.createObjectNode().set("bidder", mapper.valueToTree(singletonMap("siteId", 123)))) - .build(); - - // when and then - assertThat(targetingService.matchesTargeting(bidRequest, imp, targetingDefinition, auctionContext)) - .isFalse(); - } - - @Test - public void matchesTargetingShouldReturnFalseForNotInStrings() { - // given - final TargetingDefinition targetingDefinition = TargetingDefinition.of( - new Not(new InStrings(category(Type.domain), asList("nba.com", "cnn.com")))); - - final BidRequest bidRequest = BidRequest.builder() - .site(Site.builder() - .domain("nba.com") - .build()) - .build(); - - final TxnLog txnLog = TxnLog.create(); - final AuctionContext auctionContext = AuctionContext.builder().txnLog(txnLog).build(); - - final Imp imp = Imp.builder() - .build(); - - // when and then - assertThat(targetingService.matchesTargeting(bidRequest, imp, targetingDefinition, auctionContext)) - .isFalse(); - } - - @Test - public void matchesTargetingShouldReturnFalseForNotIntersectsInteger() { - final TargetingDefinition targetingDefinition = TargetingDefinition.of( - new Not(new IntersectsIntegers(category(Type.userFirstPartyData, "someId"), asList(123, 321)))); - - final BidRequest bidRequest = BidRequest.builder() - .user(User.builder() - .ext(ExtUser.builder().data(mapper.valueToTree(singletonMap("someId", asList(123, 456)))) - .build()) - .build()) - .build(); - - final TxnLog txnLog = TxnLog.create(); - final AuctionContext auctionContext = AuctionContext.builder().txnLog(txnLog).build(); - - final Imp imp = Imp.builder().build(); - - // when and then - assertThat(targetingService.matchesTargeting(bidRequest, imp, targetingDefinition, auctionContext)) - .isFalse(); - } - - @Test - public void matchesTargetingShouldReturnFalseForNotIntersectsSizes() { - // given - final TargetingDefinition targetingDefinition = TargetingDefinition.of( - new Not(new IntersectsSizes(category(Type.size), asList(Size.of(300, 250), Size.of(400, 200))))); - - final BidRequest bidRequest = BidRequest.builder().build(); - - final TxnLog txnLog = TxnLog.create(); - final AuctionContext auctionContext = AuctionContext.builder().txnLog(txnLog).build(); - - final Imp imp = Imp.builder() - .banner(Banner.builder() - .format(asList( - Format.builder().w(300).h(500).build(), - Format.builder().w(300).h(250).build(), - Format.builder().w(400).h(500).build())) - .build()) - .build(); - - // when and then - assertThat(targetingService.matchesTargeting(bidRequest, imp, targetingDefinition, auctionContext)) - .isFalse(); - } - - @Test - public void matchesTargetingShouldReturnFalseForNotWithin() { - // given - final TargetingDefinition targetingDefinition = TargetingDefinition.of( - new Not(new Within(category(Type.location), GeoRegion.of(50.424744f, 30.506435f, 10.0f)))); - - final BidRequest bidRequest = BidRequest.builder() - .device(Device.builder() - .geo(Geo.builder() - .lat(50.432069f) - .lon(30.516455f) - .build()) - .build()) - .build(); - - final TxnLog txnLog = TxnLog.create(); - final AuctionContext auctionContext = AuctionContext.builder().txnLog(txnLog).build(); - - final Imp imp = Imp.builder() - .build(); - - // when and then - assertThat(targetingService.matchesTargeting(bidRequest, imp, targetingDefinition, auctionContext)) - .isFalse(); - } - - @Test - public void matchesTargetingShouldReturnFalseForNotTrueAnd() { - // given - final TargetingDefinition targetingDefinition = TargetingDefinition.of( - new Not(new And(asList( - new IntersectsSizes(category(Type.size), asList(Size.of(300, 250), Size.of(400, 200))), - new IntersectsStrings(category(Type.mediaType), asList("banner", "video")))))); - - final BidRequest bidRequest = BidRequest.builder().build(); - - final TxnLog txnLog = TxnLog.create(); - final AuctionContext auctionContext = AuctionContext.builder().txnLog(txnLog).build(); - - final Imp imp = Imp.builder() - .banner(Banner.builder() - .format(asList( - Format.builder().w(300).h(500).build(), - Format.builder().w(300).h(250).build(), - Format.builder().w(400).h(500).build())) - .build()) - .build(); - - // when and then - assertThat(targetingService.matchesTargeting(bidRequest, imp, targetingDefinition, auctionContext)) - .isFalse(); - } - - @Test - public void matchesTargetingShouldReturnFalseForNotMatches() { - // given - final TargetingDefinition targetingDefinition = TargetingDefinition.of( - new Not(new Matches(category(Type.domain), "*nba.com*"))); - - final BidRequest bidRequest = BidRequest.builder() - .site(Site.builder() - .domain("lakers.nba.com") - .build()) - .build(); - - final TxnLog txnLog = TxnLog.create(); - final AuctionContext auctionContext = AuctionContext.builder().txnLog(txnLog).build(); - - final Imp imp = Imp.builder() - - .build(); - - // when and then - assertThat(targetingService.matchesTargeting(bidRequest, imp, targetingDefinition, auctionContext)) - .isFalse(); - } - - private static JsonNode jsonFrom(String file) throws IOException { - return mapper.readTree(TargetingServiceTest.class.getResourceAsStream(file)); - } - - private static TargetingCategory category(Type type) { - return new TargetingCategory(type); - } - - private static TargetingCategory category(Type type, String path) { - return new TargetingCategory(type, path); - } -} diff --git a/src/test/java/org/prebid/server/deals/UserAdditionalInfoServiceTest.java b/src/test/java/org/prebid/server/deals/UserAdditionalInfoServiceTest.java deleted file mode 100644 index c11d278412f..00000000000 --- a/src/test/java/org/prebid/server/deals/UserAdditionalInfoServiceTest.java +++ /dev/null @@ -1,507 +0,0 @@ -package org.prebid.server.deals; - -import com.iab.openrtb.request.BidRequest; -import com.iab.openrtb.request.Data; -import com.iab.openrtb.request.Device; -import com.iab.openrtb.request.Geo; -import com.iab.openrtb.request.Imp; -import com.iab.openrtb.request.Segment; -import com.iab.openrtb.request.User; -import io.vertx.core.Future; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.VertxTest; -import org.prebid.server.auction.model.AuctionContext; -import org.prebid.server.auction.model.TimeoutContext; -import org.prebid.server.deals.deviceinfo.DeviceInfoService; -import org.prebid.server.deals.model.DeviceInfo; -import org.prebid.server.deals.model.UserData; -import org.prebid.server.deals.model.UserDetails; -import org.prebid.server.geolocation.GeoLocationService; -import org.prebid.server.geolocation.model.GeoInfo; -import org.prebid.server.log.CriteriaLogManager; -import org.prebid.server.proto.openrtb.ext.request.ExtDevice; -import org.prebid.server.proto.openrtb.ext.request.ExtDeviceInt; -import org.prebid.server.proto.openrtb.ext.request.ExtDevicePrebid; -import org.prebid.server.proto.openrtb.ext.request.ExtDeviceVendor; -import org.prebid.server.proto.openrtb.ext.request.ExtGeo; -import org.prebid.server.proto.openrtb.ext.request.ExtGeoVendor; -import org.prebid.server.proto.openrtb.ext.request.ExtUser; -import org.prebid.server.proto.openrtb.ext.request.ExtUserTime; -import org.prebid.server.settings.model.Account; - -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.function.Function; -import java.util.function.UnaryOperator; - -import static java.util.Collections.emptyList; -import static java.util.Collections.singletonList; -import static java.util.function.UnaryOperator.identity; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; - -public class UserAdditionalInfoServiceTest extends VertxTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private LineItemService lineItemService; - - @Mock - private DeviceInfoService deviceInfoService; - - @Mock - private GeoLocationService geoLocationService; - - @Mock - private UserService userService; - - @Mock - private CriteriaLogManager criteriaLogManager; - - private UserAdditionalInfoService userAdditionalInfoService; - - private static final Clock CLOCK = Clock.fixed(Instant.parse("2019-10-10T00:01:00Z"), ZoneOffset.UTC); - - @Before - public void setUp() { - given(lineItemService.accountHasDeals(any())).willReturn(true); - - given(deviceInfoService.getDeviceInfo(any())) - .willReturn(Future.failedFuture("deviceInfoService error")); - given(geoLocationService.lookup(any(), any())) - .willReturn(Future.failedFuture("geoLocationService error")); - given(userService.getUserDetails(any(), any())) - .willReturn(Future.failedFuture("userService error")); - - userAdditionalInfoService = new UserAdditionalInfoService( - lineItemService, - deviceInfoService, - geoLocationService, - userService, - CLOCK, - jacksonMapper, - criteriaLogManager); - } - - @Test - public void populateShouldReturnOriginalContextIfAccountHasNoDeals() { - // given - given(lineItemService.accountHasDeals(any())).willReturn(false); - - final AuctionContext auctionContext = AuctionContext.builder() - .account(givenAccount(identity())) - .bidRequest(givenBidRequest(identity())) - .build(); - - // when - final AuctionContext result = userAdditionalInfoService.populate(auctionContext).result(); - - // then - assertThat(result).isSameAs(auctionContext); - } - - @Test - public void populateShouldPopulateDevice() { - // given - given(deviceInfoService.getDeviceInfo(any())) - .willReturn(Future.succeededFuture(DeviceInfo.builder() - .vendor("vendor") - .deviceTypeRaw("mobile") - .os("os") - .osVersion("osVersion") - .browser("browser") - .browserVersion("browserVersion") - .language("ENG") - .carrier("AT&T") - .manufacturer("Apple") - .model("iPhone 8") - .build())); - - final BidRequest bidRequest = givenBidRequest(builder -> builder - .imp(singletonList(Imp.builder().ext(mapper.createObjectNode()).build())) - .device(Device.builder() - .ip("ip") - .ua("ua") - .ext(ExtDevice.of(null, ExtDevicePrebid.of(ExtDeviceInt.of(640, 480)))) - .build())); - final AuctionContext auctionContext = givenAuctionContext(bidRequest, givenAccount(identity())); - - // when - final AuctionContext result = userAdditionalInfoService.populate(auctionContext).result(); - - // then - final ExtDevice expectedExtDevice = ExtDevice.of(null, ExtDevicePrebid.of(ExtDeviceInt.of(640, 480))); - expectedExtDevice.addProperty("vendor", mapper.valueToTree(ExtDeviceVendor.builder() - .type("mobile") - .os("os") - .osver("osVersion") - .browser("browser") - .browserver("browserVersion") - .make("Apple") - .model("iPhone 8") - .language("ENG") - .carrier("AT&T") - .build())); - assertThat(result.getBidRequest().getDevice()).isEqualTo(Device.builder() - .ip("ip") - .ua("ua") - .ext(expectedExtDevice) - .build()); - } - - @Test - public void populateShouldPopulateDeviceGeo() { - // given - given(geoLocationService.lookup(any(), any())) - .willReturn(Future.succeededFuture(GeoInfo.builder() - .vendor("vendor") - .continent("continent") - .country("country") - .region("region") - .regionCode(1) - .city("city") - .metroGoogle("metroGoogle") - .metroNielsen(516) - .zip("12345") - .connectionSpeed("broadband") - .lat(11.11F) - .lon(22.22F) - .build())); - - final BidRequest bidRequest = givenBidRequest(builder -> builder - .imp(singletonList(Imp.builder().ext(mapper.createObjectNode()).build())) - .device(Device.builder() - .geo(Geo.builder().zip("zip").build()) - .build())); - final AuctionContext auctionContext = givenAuctionContext(bidRequest, givenAccount(identity())); - - // when - final AuctionContext result = userAdditionalInfoService.populate(auctionContext).result(); - - // then - final ExtGeo expectedExtGeo = ExtGeo.of(); - expectedExtGeo.addProperty("vendor", mapper.valueToTree(ExtGeoVendor.builder() - .continent("continent") - .country("country") - .region(1) - .metro(516) - .city("city") - .zip("12345") - .build())); - final ExtDevice expectedDevice = ExtDevice.of(null, null); - expectedDevice.addProperty("vendor", mapper.valueToTree(ExtDeviceVendor.builder() - .connspeed("broadband") - .build())); - assertThat(result.getBidRequest().getDevice()).isEqualTo(Device.builder() - .geo(Geo.builder() - .zip("zip") - .country("country") - .region("region") - .metro("metroGoogle") - .lat(11.11F) - .lon(22.22F) - .ext(expectedExtGeo) - .build()) - .ext(expectedDevice) - .build()); - } - - @Test - public void populateShouldPopulateUserWithUserDetails() { - // given - given(userService.getUserDetails(any(), any())) - .willReturn(Future.succeededFuture(UserDetails.of( - singletonList(UserData.of( - null, - "rubicon", - singletonList(org.prebid.server.deals.model.Segment.of("segmentId")))), - singletonList("fcapId")))); - - final BidRequest bidRequest = givenBidRequest(builder -> builder - .imp(singletonList(Imp.builder().ext(mapper.createObjectNode()).build())) - .device(Device.builder().ip("ip").ua("ua").build()) - .user(User.builder() - .consent("consent") - .build())); - final AuctionContext auctionContext = givenAuctionContext(bidRequest, givenAccount(identity())); - - // when - final AuctionContext result = userAdditionalInfoService.populate(auctionContext).result(); - - // then - assertThat(result.getBidRequest().getUser()).isEqualTo(User.builder() - .data(singletonList(Data.builder() - .id("rubicon") - .segment(singletonList(Segment.builder().id("segmentId").build())) - .build())) - .consent("consent") - .ext(ExtUser.builder() - .fcapIds(singletonList("fcapId")) - .time(ExtUserTime.of(5, 0)) - .build()) - .build()); - } - - @Test - public void populateShouldUseForGeoLocationIpV6IfIpV4IsNotDefined() { - // given - final BidRequest bidRequest = givenBidRequest(builder -> builder - .imp(singletonList(Imp.builder().ext(mapper.createObjectNode()).build())) - .device(Device.builder().ipv6("ipv6").build())); - final AuctionContext auctionContext = givenAuctionContext(bidRequest, givenAccount(identity())); - - // when - userAdditionalInfoService.populate(auctionContext).result(); - - // then - verify(geoLocationService).lookup(eq("ipv6"), any()); - } - - @Test - public void populateShouldPopulateUserExtWithGeoInfo() { - // given - given(geoLocationService.lookup(any(), any())) - .willReturn(Future.succeededFuture(GeoInfo.builder() - .vendor("vendor") - .timeZone(ZoneId.of("America/Los_Angeles")) - .build())); - - final BidRequest bidRequest = givenBidRequest(builder -> builder - .imp(singletonList(Imp.builder().ext(mapper.createObjectNode()).build())) - .device(Device.builder().ip("ip").ua("ua").build()) - .user(User.builder().consent("consent").build())); - final AuctionContext auctionContext = givenAuctionContext(bidRequest, givenAccount(identity())); - - // when - final AuctionContext result = userAdditionalInfoService.populate(auctionContext).result(); - - // then - assertThat(result.getBidRequest().getUser()).isEqualTo(User.builder() - .consent("consent") - .ext(ExtUser.builder().time(ExtUserTime.of(4, 17)).build()) - .build()); - } - - @Test - public void populateShouldPopulateUserExtWithGeoInfoIfTimeZoneIsMissing() { - // given - given(geoLocationService.lookup(any(), any())) - .willReturn(Future.succeededFuture(GeoInfo.builder().vendor("vendor").build())); - - final BidRequest bidRequest = givenBidRequest(builder -> builder - .imp(singletonList(Imp.builder().ext(mapper.createObjectNode()).build())) - .device(Device.builder().ip("ip").ua("ua").build())); - final AuctionContext auctionContext = givenAuctionContext(bidRequest, givenAccount(identity())); - - // when - final AuctionContext result = userAdditionalInfoService.populate(auctionContext).result(); - - // then - assertThat(result.getBidRequest().getUser()).isEqualTo(User.builder() - .ext(ExtUser.builder().time(ExtUserTime.of(5, 0)).build()) - .build()); - } - - @Test - public void populateShouldPopulateUserWithEmptyCappedIds() { - // given - given(userService.getUserDetails(any(), any())) - .willReturn(Future.succeededFuture(UserDetails.of(null, null))); - - final BidRequest bidRequest = givenBidRequest(builder -> builder - .imp(singletonList(Imp.builder().ext(mapper.createObjectNode()).build())) - .device(Device.builder().ip("ip").ua("ua").build())); - final AuctionContext auctionContext = givenAuctionContext(bidRequest, givenAccount(identity())); - - // when - final AuctionContext result = userAdditionalInfoService.populate(auctionContext).result(); - - // then - assertThat(result.getBidRequest().getUser()).isEqualTo(User.builder() - .ext(ExtUser.builder() - .fcapIds(emptyList()) - .time(ExtUserTime.of(5, 0)) - .build()) - .build()); - } - - @Test - public void populateShouldPopulateUserWithNullCappedIds() { - // given - final BidRequest bidRequest = givenBidRequest(builder -> builder - .imp(singletonList(Imp.builder().ext(mapper.createObjectNode()).build())) - .device(Device.builder().ip("ip").ua("ua").build()) - .user(User.builder().consent("consent").build())); - final AuctionContext auctionContext = givenAuctionContext(bidRequest, givenAccount(identity())); - - // when - final AuctionContext result = userAdditionalInfoService.populate(auctionContext).result(); - - // then - assertThat(result.getBidRequest().getUser()).isEqualTo(User.builder() - .consent("consent") - .ext(ExtUser.builder().time(ExtUserTime.of(5, 0)).build()) - .build()); - } - - @Test - public void populateShouldNotPopulateDeviceGeoIfGeolocationServiceIsNotDefined() { - // given - userAdditionalInfoService = new UserAdditionalInfoService( - lineItemService, - deviceInfoService, - null, - userService, - CLOCK, - jacksonMapper, - criteriaLogManager); - - final BidRequest bidRequest = givenBidRequest(builder -> builder - .imp(singletonList(Imp.builder().ext(mapper.createObjectNode()).build())) - .device(Device.builder().build())); - - final AuctionContext auctionContext = givenAuctionContext(bidRequest, givenAccount(identity())); - - // when - final AuctionContext result = userAdditionalInfoService.populate(auctionContext).result(); - - // then - assertThat(result.getBidRequest().getDevice().getGeo()).isNull(); - } - - @Test - public void populateShouldCreateExtDeviceIfDeviceInfoIsNotEmptyAndExtDidNotExistBefore() { - // given - given(geoLocationService.lookup(any(), any())) - .willReturn(Future.succeededFuture(GeoInfo.builder().vendor("geoVendor").build())); - - given(deviceInfoService.getDeviceInfo(any())) - .willReturn(Future.succeededFuture(DeviceInfo.builder() - .vendor("deviceVendor") - .browser("browser") - .build())); - - final BidRequest bidRequest = givenBidRequest(builder -> builder - .imp(singletonList(Imp.builder().ext(mapper.createObjectNode()).build())) - .device(Device.builder().build())); - - final AuctionContext auctionContext = givenAuctionContext(bidRequest, givenAccount(identity())); - - // when - final AuctionContext result = userAdditionalInfoService.populate(auctionContext).result(); - - // then - final ExtDevice expectedExtDevice = ExtDevice.of(null, null); - expectedExtDevice.addProperty( - "deviceVendor", mapper.valueToTree(ExtDeviceVendor.builder().browser("browser").build())); - assertThat(result.getBidRequest().getDevice().getExt()).isEqualTo(expectedExtDevice); - } - - @Test - public void populateShouldCreateExtDeviceIfGeoInfoIsNotEmptyAndExtDidNotExistBefore() { - // given - given(geoLocationService.lookup(any(), any())) - .willReturn(Future.succeededFuture(GeoInfo.builder() - .vendor("geoVendor") - .connectionSpeed("100") - .continent("continent") - .build())); - - given(deviceInfoService.getDeviceInfo(any())) - .willReturn(Future.succeededFuture(DeviceInfo.builder().vendor("deviceVendor").build())); - - final BidRequest bidRequest = givenBidRequest(builder -> builder - .imp(singletonList(Imp.builder().ext(mapper.createObjectNode()).build())) - .device(Device.builder().build())); - - final AuctionContext auctionContext = givenAuctionContext(bidRequest, givenAccount(identity())); - - // when - final AuctionContext result = userAdditionalInfoService.populate(auctionContext).result(); - - // then - final ExtDevice expectedExtDevice = ExtDevice.of(null, null); - expectedExtDevice.addProperty( - "geoVendor", mapper.valueToTree(ExtDeviceVendor.builder().connspeed("100").build())); - assertThat(result.getBidRequest().getDevice().getExt()).isEqualTo(expectedExtDevice); - } - - @Test - public void populateShouldUseGeoInfoFromContext() { - // given - final BidRequest bidRequest = givenBidRequest(builder -> builder - .imp(singletonList(Imp.builder().ext(mapper.createObjectNode()).build())) - .device(Device.builder().build())); - final GeoInfo geoInfo = GeoInfo.builder() - .vendor("vendor") - .city("city") - .build(); - final AuctionContext auctionContext = givenAuctionContext(bidRequest, givenAccount(identity())).toBuilder() - .geoInfo(geoInfo) - .build(); - - // when - final AuctionContext result = userAdditionalInfoService.populate(auctionContext).result(); - - // then - final ExtGeo expectedExtGeo = ExtGeo.of(); - expectedExtGeo.addProperty("vendor", mapper.valueToTree(ExtGeoVendor.builder().city("city").build())); - assertThat(result.getBidRequest().getDevice()).isEqualTo(Device.builder() - .geo(Geo.builder().ext(expectedExtGeo).build()) - .build()); - verifyNoInteractions(geoLocationService); - assertThat(result.getGeoInfo()).isSameAs(geoInfo); - } - - @Test - public void populateShouldStoreGeoInfoInContext() { - // given - final GeoInfo geoInfo = GeoInfo.builder() - .vendor("vendor") - .city("city") - .build(); - given(geoLocationService.lookup(any(), any())).willReturn(Future.succeededFuture(geoInfo)); - - final BidRequest bidRequest = givenBidRequest(builder -> builder - .imp(singletonList(Imp.builder().ext(mapper.createObjectNode()).build())) - .device(Device.builder().build())); - final AuctionContext auctionContext = givenAuctionContext(bidRequest, givenAccount(identity())); - - // when - final AuctionContext result = userAdditionalInfoService.populate(auctionContext).result(); - - // then - assertThat(result.getGeoInfo()).isSameAs(geoInfo); - } - - private static BidRequest givenBidRequest(UnaryOperator customizer) { - return customizer.apply(BidRequest.builder()).build(); - } - - private static Account givenAccount(Function customizer) { - return customizer.apply(Account.builder().id("accountId")).build(); - } - - private static AuctionContext givenAuctionContext(BidRequest bidRequest, Account account) { - return AuctionContext.builder() - .bidRequest(bidRequest) - .account(account) - .timeoutContext(TimeoutContext.of(0, null, 0)) - .debugWarnings(new ArrayList<>()) - .build(); - } -} diff --git a/src/test/java/org/prebid/server/deals/UserServiceTest.java b/src/test/java/org/prebid/server/deals/UserServiceTest.java deleted file mode 100644 index 241e00d99d4..00000000000 --- a/src/test/java/org/prebid/server/deals/UserServiceTest.java +++ /dev/null @@ -1,596 +0,0 @@ -package org.prebid.server.deals; - -import com.fasterxml.jackson.core.JsonProcessingException; -import io.vertx.core.Future; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.VertxTest; -import org.prebid.server.auction.model.AuctionContext; -import org.prebid.server.cache.model.CacheHttpRequest; -import org.prebid.server.cache.model.DebugHttpCall; -import org.prebid.server.cookie.UidsCookie; -import org.prebid.server.cookie.model.UidWithExpiry; -import org.prebid.server.cookie.proto.Uids; -import org.prebid.server.deals.lineitem.LineItem; -import org.prebid.server.deals.model.ExtUser; -import org.prebid.server.deals.model.Segment; -import org.prebid.server.deals.model.User; -import org.prebid.server.deals.model.UserData; -import org.prebid.server.deals.model.UserDetails; -import org.prebid.server.deals.model.UserDetailsProperties; -import org.prebid.server.deals.model.UserDetailsRequest; -import org.prebid.server.deals.model.UserDetailsResponse; -import org.prebid.server.deals.model.UserId; -import org.prebid.server.deals.model.UserIdRule; -import org.prebid.server.deals.model.WinEventNotification; -import org.prebid.server.deals.proto.FrequencyCap; -import org.prebid.server.deals.proto.LineItemMetaData; -import org.prebid.server.exception.PreBidException; -import org.prebid.server.execution.Timeout; -import org.prebid.server.execution.TimeoutFactory; -import org.prebid.server.metric.MetricName; -import org.prebid.server.metric.Metrics; -import org.prebid.server.vertx.http.HttpClient; -import org.prebid.server.vertx.http.model.HttpClientResponse; - -import java.io.IOException; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeFormatterBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.TimeoutException; - -import static java.util.Arrays.asList; -import static java.util.Collections.emptyMap; -import static java.util.Collections.singletonList; -import static java.util.Collections.singletonMap; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; - -public class UserServiceTest extends VertxTest { - - private static final DateTimeFormatter UTC_MILLIS_FORMATTER = new DateTimeFormatterBuilder() - .appendPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - .toFormatter(); - - private static final String USER_DETAILS_ENDPOINT = "http://user-data.com"; - private static final String WIN_EVENT_ENDPOINT = "http://win-event.com"; - private static final String DATA_CENTER_REGION = "region"; - private static final long CONFIG_TIMEOUT = 300L; - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private LineItemService lineItemService; - @Mock - private HttpClient httpClient; - @Mock - private Metrics metrics; - - private List userIdRules; - private Clock clock; - - private UserService userService; - - private UidsCookie uidsCookie; - private AuctionContext auctionContext; - private Timeout timeout; - private ZonedDateTime now; - - @Before - public void setUp() { - clock = Clock.fixed(Instant.parse("2019-07-26T10:00:00Z"), ZoneOffset.UTC); - now = ZonedDateTime.now(clock); - userIdRules = singletonList(UserIdRule.of("khaos", "uid", "rubicon")); - - userService = new UserService( - UserDetailsProperties.of(USER_DETAILS_ENDPOINT, WIN_EVENT_ENDPOINT, CONFIG_TIMEOUT, userIdRules), - DATA_CENTER_REGION, - lineItemService, - httpClient, - clock, - metrics, - jacksonMapper); - - uidsCookie = new UidsCookie(Uids.builder() - .uids(singletonMap("rubicon", new UidWithExpiry("uid", null))) - .build(), jacksonMapper); - auctionContext = AuctionContext.builder().uidsCookie(uidsCookie).debugHttpCalls(new HashMap<>()).build(); - - timeout = new TimeoutFactory(Clock.fixed(Instant.now(), ZoneId.systemDefault())).create(500L); - } - - @Test - public void getUserDetailsShouldReturnEmptyUserDetailsWhenUidsAreEmpty() { - // given - final UidsCookie uidsCookie = new UidsCookie(Uids.builder().uids(emptyMap()).build(), jacksonMapper); - final AuctionContext context = AuctionContext.builder().uidsCookie(uidsCookie) - .debugHttpCalls(new HashMap<>()).build(); - - // when - final UserDetails result = userService.getUserDetails(context, timeout).result(); - - // then - verify(metrics).updateUserDetailsRequestPreparationFailed(); - verifyNoInteractions(httpClient); - - assertEquals(UserDetails.empty(), result); - } - - @Test - public void getUserDetailsShouldReturnReturnEmptyUserDetailsWhenUidsDoesNotContainRuleLocation() { - // given - final List ruleWithMissingLocation = singletonList( - UserIdRule.of("khaos", "uid", "bad_location")); - - userService = new UserService( - UserDetailsProperties.of( - USER_DETAILS_ENDPOINT, WIN_EVENT_ENDPOINT, CONFIG_TIMEOUT, ruleWithMissingLocation), - DATA_CENTER_REGION, - lineItemService, - httpClient, - clock, - metrics, - jacksonMapper); - - // when - final UserDetails result = userService.getUserDetails(auctionContext, timeout).result(); - - // then - verify(metrics).updateUserDetailsRequestPreparationFailed(); - verifyNoInteractions(httpClient); - - assertEquals(UserDetails.empty(), result); - } - - @Test - public void getUserDetailsShouldSendPostRequestWithExpectedParameters() throws IOException { - // given - given(httpClient.post(anyString(), anyString(), anyLong())).willReturn(Future.failedFuture("something")); - - // when - userService.getUserDetails(auctionContext, timeout); - - // then - final ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); - verify(httpClient).post(eq(USER_DETAILS_ENDPOINT), captor.capture(), eq(CONFIG_TIMEOUT)); - - final UserDetailsRequest capturedRequest = mapper.readValue(captor.getValue(), UserDetailsRequest.class); - - assertThat(ZonedDateTime.parse(capturedRequest.getTime())).isEqualTo(UTC_MILLIS_FORMATTER.format(now)); - assertThat(capturedRequest.getIds()).hasSize(1) - .containsOnly(UserId.of("khaos", "uid")); - verify(metrics).updateUserDetailsRequestMetric(eq(false)); - verify(metrics).updateRequestTimeMetric(eq(MetricName.user_details_request_time), anyLong()); - } - - @Test - public void getUserDetailsShouldUseRemainingGlobalTimeoutIfTimeoutFromConfigurationIsGreaterThanRemaining() { - // given - given(httpClient.post(anyString(), anyString(), anyLong())).willReturn(Future.failedFuture("something")); - - userService = new UserService( - UserDetailsProperties.of(USER_DETAILS_ENDPOINT, WIN_EVENT_ENDPOINT, 600L, userIdRules), - DATA_CENTER_REGION, - lineItemService, - httpClient, - clock, - metrics, - jacksonMapper); - - // when - userService.getUserDetails(auctionContext, timeout); - - // then - verify(metrics).updateUserDetailsRequestMetric(eq(false)); - verify(metrics).updateRequestTimeMetric(eq(MetricName.user_details_request_time), anyLong()); - verify(httpClient).post(anyString(), anyString(), eq(500L)); - } - - @Test - public void getUserDetailsShouldReturnFailedFutureWhenResponseStatusIsNotOk() { - // given - given(httpClient.post(anyString(), anyString(), anyLong())) - .willReturn(Future.succeededFuture(HttpClientResponse.of(400, null, null))); - - // when - final Future result = userService.getUserDetails(auctionContext, timeout); - - // then - verify(metrics).updateRequestTimeMetric(eq(MetricName.user_details_request_time), anyLong()); - verify(metrics).updateUserDetailsRequestMetric(eq(false)); - verify(httpClient).post(eq(USER_DETAILS_ENDPOINT), anyString(), eq(CONFIG_TIMEOUT)); - - assertTrue(result.failed()); - assertThat(result.cause()) - .isInstanceOf(PreBidException.class) - .hasMessage("Bad response status code: 400"); - } - - @Test - public void getUserDetailsShouldReturnFailedFutureWhenErrorOccurs() { - // given - given(httpClient.post(anyString(), anyString(), anyLong())) - .willReturn(Future.failedFuture(new TimeoutException("Timeout has been exceeded"))); - - // when - final Future result = userService.getUserDetails(auctionContext, timeout); - - // then - verify(metrics).updateUserDetailsRequestMetric(eq(false)); - verify(metrics).updateRequestTimeMetric(eq(MetricName.user_details_request_time), anyLong()); - verify(httpClient).post(eq(USER_DETAILS_ENDPOINT), anyString(), eq(CONFIG_TIMEOUT)); - - assertTrue(result.failed()); - assertThat(result.cause()) - .isInstanceOf(TimeoutException.class) - .hasMessage("Timeout has been exceeded"); - } - - @Test - public void getUserDetailsShouldReturnFailedFutureWhenResponseBodyDecodingFails() { - // given - given(httpClient.post(anyString(), anyString(), anyLong())) - .willReturn(Future.succeededFuture(HttpClientResponse.of(200, null, "invalid_body"))); - - // when - final Future result = userService.getUserDetails(auctionContext, timeout); - - // then - verify(metrics).updateUserDetailsRequestMetric(eq(false)); - verify(metrics).updateRequestTimeMetric(eq(MetricName.user_details_request_time), anyLong()); - verify(httpClient).post(eq(USER_DETAILS_ENDPOINT), anyString(), eq(CONFIG_TIMEOUT)); - - assertTrue(result.failed()); - assertThat(result.cause()) - .isInstanceOf(PreBidException.class) - .hasMessage("Cannot parse response: invalid_body"); - } - - @Test - public void getUserDetailsShouldReturnExpectedResult() { - // given - final UserDetailsResponse response = UserDetailsResponse.of(User.of( - asList( - UserData.of("1", "rubicon", asList(Segment.of("2222"), Segment.of("3333"))), - UserData.of("2", "bluekai", asList(Segment.of("5555"), Segment.of("6666")))), - ExtUser.of(asList("L-1111", "O-2222")))); - - given(httpClient.post(anyString(), anyString(), anyLong())).willReturn( - Future.succeededFuture(HttpClientResponse.of(200, null, jacksonMapper.encodeToString(response)))); - - // when - final UserDetails result = userService.getUserDetails(auctionContext, timeout).result(); - - // then - verify(metrics).updateUserDetailsRequestMetric(eq(true)); - verify(metrics).updateRequestTimeMetric(eq(MetricName.user_details_request_time), anyLong()); - verify(httpClient).post(eq(USER_DETAILS_ENDPOINT), anyString(), eq(CONFIG_TIMEOUT)); - - final UserDetails expectedDetails = UserDetails.of( - asList(UserData.of("1", "rubicon", asList(Segment.of("2222"), Segment.of("3333"))), - UserData.of("2", "bluekai", asList(Segment.of("5555"), Segment.of("6666")))), - asList("L-1111", "O-2222")); - - assertEquals(expectedDetails, result); - } - - @Test - public void getUserDetailsShouldReturnFailedFutureWhenUserInResponseIsNull() { - // given - final UserDetailsResponse response = UserDetailsResponse.of(null); - - given(httpClient.post(anyString(), anyString(), anyLong())).willReturn( - Future.succeededFuture(HttpClientResponse.of(200, null, jacksonMapper.encodeToString(response)))); - - // when - final Future result = userService.getUserDetails(auctionContext, timeout); - - // then - verify(metrics).updateUserDetailsRequestMetric(eq(false)); - assertThat(result.failed()).isTrue(); - assertThat(result.cause()).isInstanceOf(PreBidException.class) - .hasMessage("Field 'user' is missing in response: {}"); - } - - @Test - public void getUserDetailsShouldReturnFailedFutureWhenUserDataInResponseIsNull() { - // given - final UserDetailsResponse response = UserDetailsResponse.of(User.of( - null, ExtUser.of(asList("L-1111", "O-2222")))); - - given(httpClient.post(anyString(), anyString(), anyLong())).willReturn( - Future.succeededFuture(HttpClientResponse.of(200, null, jacksonMapper.encodeToString(response)))); - - // when - final Future result = userService.getUserDetails(auctionContext, timeout); - - // then - verify(metrics).updateUserDetailsRequestMetric(eq(false)); - assertThat(result.failed()).isTrue(); - assertThat(result.cause()).isInstanceOf(PreBidException.class) - .hasMessage("Field 'user.data' is missing in response: {\"user\":{\"ext\":{\"fcapIds\":[\"L-1111\"," - + "\"O-2222\"]}}}"); - } - - @Test - public void getUserDetailsShouldReturnFailedFutureWhenExtUserInResponseIsNull() { - // given - final UserDetailsResponse response = UserDetailsResponse.of(User.of( - singletonList(UserData.of("2", "bluekai", singletonList(Segment.of("6666")))), null)); - - given(httpClient.post(anyString(), anyString(), anyLong())).willReturn( - Future.succeededFuture(HttpClientResponse.of(200, null, jacksonMapper.encodeToString(response)))); - - // when - final Future result = userService.getUserDetails(auctionContext, timeout); - - // then - verify(metrics).updateUserDetailsRequestMetric(eq(false)); - assertThat(result.failed()).isTrue(); - assertThat(result.cause()).isInstanceOf(PreBidException.class) - .hasMessage("Field 'user.ext' is missing in response: {\"user\":{\"data\":[{\"id\":\"2\",\"name\":" - + "\"bluekai\",\"segment\":[{\"id\":\"6666\"}]}]}}"); - } - - @Test - public void getUserDetailsShouldAddEmptyCachedHttpCallWhenUidsAreNotDefined() { - // given - final UidsCookie uidsCookie = new UidsCookie(Uids.builder().uids(emptyMap()).build(), jacksonMapper); - final AuctionContext context = AuctionContext.builder().uidsCookie(uidsCookie) - .debugHttpCalls(new HashMap<>()).build(); - - // when - userService.getUserDetails(context, timeout).result(); - - // then - assertThat(context.getDebugHttpCalls()).hasSize(1) - .containsEntry("userservice", singletonList(DebugHttpCall.empty())); - } - - @Test - public void getUserDetailsShouldAddEmptyCachedHttpCallWhenUserIdsAreNotDefined() { - // given - final List ruleWithMissingLocation = singletonList( - UserIdRule.of("khaos", "uid", "bad_location")); - - userService = new UserService( - UserDetailsProperties.of( - USER_DETAILS_ENDPOINT, WIN_EVENT_ENDPOINT, CONFIG_TIMEOUT, ruleWithMissingLocation), - DATA_CENTER_REGION, - lineItemService, - httpClient, - clock, - metrics, - jacksonMapper); - - // when - userService.getUserDetails(auctionContext, timeout).result(); - - // then - assertThat(auctionContext.getDebugHttpCalls()).hasSize(1) - .containsEntry("userservice", singletonList(DebugHttpCall.empty())); - } - - @Test - public void getUserDetailsShouldAddCachedHttpCallWhenThrowsPrebidException() throws JsonProcessingException { - // given - given(httpClient.post(anyString(), anyString(), anyLong())) - .willReturn(Future.succeededFuture(HttpClientResponse.of(200, null, "invalid_body"))); - - // when - userService.getUserDetails(auctionContext, timeout); - - // then - assertThat(auctionContext.getDebugHttpCalls()).hasSize(1) - .containsEntry("userservice", singletonList(DebugHttpCall.builder() - .requestUri("http://user-data.com") - .requestBody(mapper.writeValueAsString(UserDetailsRequest.of(UTC_MILLIS_FORMATTER.format(now), - singletonList(UserId.of("khaos", "uid"))))) - .responseStatus(200) - .responseBody("invalid_body") - .responseTimeMillis(0) - .build())); - } - - @Test - public void getUserDetailsShouldAddCachedHttpCallWhenCallCompletesSuccessful() throws JsonProcessingException { - // given - final UserDetailsResponse response = UserDetailsResponse.of(User.of( - singletonList( - UserData.of("1", "rubicon", asList(Segment.of("2222"), Segment.of("3333")))), - ExtUser.of(asList("L-1111", "O-2222")))); - - given(httpClient.post(anyString(), anyString(), anyLong())).willReturn( - Future.succeededFuture(HttpClientResponse.of(200, null, jacksonMapper.encodeToString(response)))); - - // when - userService.getUserDetails(auctionContext, timeout).result(); - - CacheHttpRequest.of("http://user-data.com", - mapper.writeValueAsString(UserDetailsRequest.of(UTC_MILLIS_FORMATTER.format(now), - singletonList(UserId.of("khaos", "uid"))))); - - // then - assertThat(auctionContext.getDebugHttpCalls()).hasSize(1) - .containsEntry("userservice", singletonList(DebugHttpCall.builder() - .requestUri("http://user-data.com") - .requestBody(mapper.writeValueAsString(UserDetailsRequest.of(UTC_MILLIS_FORMATTER.format(now), - singletonList(UserId.of("khaos", "uid"))))) - .responseStatus(200) - .responseBody(mapper.writeValueAsString( - UserDetailsResponse.of(User.of(singletonList(UserData.of("1", "rubicon", - asList(Segment.of("2222"), Segment.of("3333")))), - ExtUser.of(asList("L-1111", "O-2222")))))) - .responseTimeMillis(0) - .build())); - } - - @Test - public void getUserDetailsShouldAddCachedHttpCallWhenCallFailed() throws JsonProcessingException { - // given - given(httpClient.post(anyString(), anyString(), anyLong())) - .willReturn(Future.succeededFuture(HttpClientResponse.of(400, null, null))); - - // when - userService.getUserDetails(auctionContext, timeout); - - // then - assertThat(auctionContext.getDebugHttpCalls()).hasSize(1) - .containsEntry("userservice", singletonList(DebugHttpCall.builder() - .requestUri("http://user-data.com") - .requestBody(mapper.writeValueAsString(UserDetailsRequest.of(UTC_MILLIS_FORMATTER.format(now), - singletonList(UserId.of("khaos", "uid"))))) - .responseTimeMillis(0) - .build())); - } - - @Test - public void processWinEventShouldCallMetricsPreparationFailedMetricWhenHttpClientWhenMetaDataIsMissing() { - // given - given(lineItemService.getLineItemById(any())).willReturn( - null, - LineItem.of(LineItemMetaData.builder().build(), null, null, ZonedDateTime.now(clock))); - - // when - userService.processWinEvent("lineItem1", "bidId", uidsCookie); - - // then - verify(metrics).updateWinRequestPreparationFailed(); - verifyNoInteractions(httpClient); - } - - @Test - public void processWinEventShouldCallMetricsPreparationFailedMetricWhenHttpClientWhenUserIdsAreMissing() { - // given - final List frequencyCaps = singletonList(FrequencyCap.builder().fcapId("213").build()); - final UidsCookie emptyCookie = new UidsCookie(Uids.builder().uids(emptyMap()).build(), jacksonMapper); - - given(lineItemService.getLineItemById(any())).willReturn(LineItem.of( - LineItemMetaData.builder() - .source("rubicon") - .updatedTimeStamp(now) - .frequencyCaps(frequencyCaps) - .build(), - null, null, ZonedDateTime.now(clock))); - - // when - userService.processWinEvent("lineItem1", "bidId", emptyCookie); - - // then - verify(metrics).updateWinRequestPreparationFailed(); - verifyNoInteractions(httpClient); - } - - @Test - public void processWinEventShouldCallMetricsWinRequestWithFalseWhenStatusIsNot200() { - // given - final List frequencyCaps = singletonList(FrequencyCap.builder().fcapId("213").build()); - - given(lineItemService.getLineItemById(any())).willReturn(LineItem.of( - LineItemMetaData.builder() - .source("rubicon") - .updatedTimeStamp(now) - .frequencyCaps(frequencyCaps) - .build(), - null, null, ZonedDateTime.now(clock))); - - given(httpClient.post(anyString(), anyString(), anyLong())) - .willReturn(Future.succeededFuture(HttpClientResponse.of(400, null, null))); - - // when - userService.processWinEvent("lineItem1", "bidId", uidsCookie); - - // then - verify(metrics).updateWinEventRequestMetric(eq(false)); - verify(metrics).updateWinRequestTime(anyLong()); - } - - @Test - public void processWinEventShouldCallMetricsWinRequestWithFalseWhenFailedFuture() { - // given - final List frequencyCaps = singletonList(FrequencyCap.builder().fcapId("213").build()); - - given(lineItemService.getLineItemById(any())).willReturn(LineItem.of( - LineItemMetaData.builder() - .source("rubicon") - .updatedTimeStamp(now) - .frequencyCaps(frequencyCaps) - .build(), - null, null, ZonedDateTime.now(clock))); - - given(httpClient.post(anyString(), anyString(), anyLong())) - .willReturn(Future.failedFuture(new TimeoutException("timeout"))); - - // when - userService.processWinEvent("lineItem1", "bidId", uidsCookie); - - // then - verify(metrics).updateWinEventRequestMetric(eq(false)); - verify(metrics).updateWinRequestTime(anyLong()); - } - - @Test - public void processWinEventShouldCallExpectedServicesWithExpectedParameters() throws IOException { - // given - final List frequencyCaps = singletonList(FrequencyCap.builder().fcapId("213").build()); - - given(lineItemService.getLineItemById(any())).willReturn(LineItem.of( - LineItemMetaData.builder() - .source("rubicon") - .updatedTimeStamp(now) - .frequencyCaps(frequencyCaps) - .build(), - null, null, ZonedDateTime.now(clock))); - - given(httpClient.post(anyString(), anyString(), anyLong())) - .willReturn(Future.succeededFuture(HttpClientResponse.of(200, null, null))); - - // when - userService.processWinEvent("lineItem1", "bidId", uidsCookie); - - // then - verify(lineItemService).getLineItemById(eq("lineItem1")); - verify(metrics).updateWinNotificationMetric(); - verify(metrics).updateWinEventRequestMetric(eq(true)); - verify(metrics).updateWinRequestTime(anyLong()); - final ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); - verify(httpClient).post(eq(WIN_EVENT_ENDPOINT), captor.capture(), eq(CONFIG_TIMEOUT)); - - final WinEventNotification capturedRequest = mapper.readValue(captor.getValue(), WinEventNotification.class); - assertThat(capturedRequest.getWinEventDateTime()).isEqualTo(UTC_MILLIS_FORMATTER.format(now)); - - final WinEventNotification expectedRequestWithoutWinTime = WinEventNotification.builder() - .bidderCode("rubicon") - .bidId("bidId") - .lineItemId("lineItem1") - .region(DATA_CENTER_REGION) - .userIds(singletonList(UserId.of("khaos", "uid"))) - .lineUpdatedDateTime(now) - .frequencyCaps(frequencyCaps) - .build(); - - assertThat(capturedRequest) - .usingRecursiveComparison() - .ignoringFields("winEventDateTime") - .isEqualTo(expectedRequestWithoutWinTime); - } -} diff --git a/src/test/java/org/prebid/server/deals/events/AdminEventServiceTest.java b/src/test/java/org/prebid/server/deals/events/AdminEventServiceTest.java deleted file mode 100644 index 98ef9e34f94..00000000000 --- a/src/test/java/org/prebid/server/deals/events/AdminEventServiceTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.prebid.server.deals.events; - -import io.vertx.core.Context; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.core.eventbus.EventBus; -import io.vertx.ext.unit.Async; -import io.vertx.ext.unit.TestContext; -import io.vertx.ext.unit.junit.VertxUnitRunner; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.prebid.server.deals.model.AdminCentralResponse; -import org.prebid.server.vertx.LocalMessageCodec; - -import static java.util.Collections.emptyList; -import static java.util.Collections.singletonList; -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(VertxUnitRunner.class) -public class AdminEventServiceTest { - - private Vertx vertx; - private EventBus eventBus; - - @Before - public void setUp(TestContext context) { - vertx = Vertx.vertx(); - vertx.exceptionHandler(context.exceptionHandler()); - - eventBus = vertx.eventBus(); - eventBus.registerCodec(LocalMessageCodec.create()); - } - - @After - public void tearDown(TestContext context) { - vertx.close(context.asyncAssertSuccess()); - } - - @Test - public void publishAuctionEventShouldPassEventToAllRecorders(TestContext testContext) { - // given - final Context initContext = vertx.getOrCreateContext(); - final Context publishContext = vertx.getOrCreateContext(); - - final AdminCentralResponse adminCentralResponse = AdminCentralResponse.of(null, null, null, null, null, null); - - final Handler consumeHandler = event -> { - // then - assertThat(event).isSameAs(adminCentralResponse); - assertThat(Vertx.currentContext()).isSameAs(initContext); - }; - - final AdminEventService adminEventService = new AdminEventService(eventBus); - final EventServiceInitializer eventServiceInitializer = new EventServiceInitializer( - emptyList(), singletonList(new ProcessorStub(consumeHandler)), eventBus); - - // when - final Async initAsync = testContext.async(); - initContext.runOnContext(ignored -> { - eventServiceInitializer.initialize(); - initAsync.complete(); - }); - initAsync.await(); - - publishContext.runOnContext(ignored -> adminEventService.publishAdminCentralEvent(adminCentralResponse)); - } - - private static class ProcessorStub implements AdminEventProcessor { - - private final Handler handler; - - ProcessorStub(Handler handler) { - this.handler = handler; - } - - @Override - public void processAdminCentralEvent(AdminCentralResponse adminCentralResponse) { - handler.handle(adminCentralResponse); - } - } -} diff --git a/src/test/java/org/prebid/server/deals/events/ApplicationEventServiceTest.java b/src/test/java/org/prebid/server/deals/events/ApplicationEventServiceTest.java deleted file mode 100644 index 4aeae4e52d8..00000000000 --- a/src/test/java/org/prebid/server/deals/events/ApplicationEventServiceTest.java +++ /dev/null @@ -1,156 +0,0 @@ -package org.prebid.server.deals.events; - -import io.vertx.core.Context; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.core.eventbus.EventBus; -import io.vertx.ext.unit.Async; -import io.vertx.ext.unit.TestContext; -import io.vertx.ext.unit.junit.VertxUnitRunner; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.prebid.server.auction.model.AuctionContext; -import org.prebid.server.deals.model.TxnLog; -import org.prebid.server.vertx.LocalMessageCodec; - -import static java.util.Arrays.asList; -import static java.util.Collections.emptyList; -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(VertxUnitRunner.class) -public class ApplicationEventServiceTest { - - private Vertx vertx; - private EventBus eventBus; - - @Before - public void setUp(TestContext context) { - vertx = Vertx.vertx(); - vertx.exceptionHandler(context.exceptionHandler()); - - eventBus = vertx.eventBus(); - eventBus.registerCodec(LocalMessageCodec.create()); - } - - @After - public void tearDown(TestContext context) { - vertx.close(context.asyncAssertSuccess()); - } - - @Test - public void publishAuctionEventShouldPassEventToAllRecorders(TestContext testContext) { - // given - final Context initContext = vertx.getOrCreateContext(); - final Context publishContext = vertx.getOrCreateContext(); - - final AuctionContext auctionContext = AuctionContext.builder().txnLog(TxnLog.create()).build(); - - final Async async = testContext.async(2); - final Handler consumeHandler = event -> { - // then - assertThat(event).isSameAs(auctionContext); - assertThat(Vertx.currentContext()).isSameAs(initContext); - async.countDown(); - }; - - final ApplicationEventService applicationEventService = new ApplicationEventService(eventBus); - final EventServiceInitializer eventServiceInitializer = new EventServiceInitializer( - asList(new ProcessorStub(consumeHandler), new ProcessorStub(consumeHandler)), emptyList(), eventBus); - - // when - final Async initAsync = testContext.async(); - initContext.runOnContext(ignored -> { - eventServiceInitializer.initialize(); - initAsync.complete(); - }); - initAsync.await(); - - publishContext.runOnContext(ignored -> applicationEventService.publishAuctionEvent(auctionContext)); - } - - @Test - public void publishLineItemWinEventShouldPassEventToAllRecorders(TestContext testContext) { - // given - final Context initContext = vertx.getOrCreateContext(); - final Context publishContext = vertx.getOrCreateContext(); - - final String lineItemId = "lineItemId1"; - - final Async async = testContext.async(2); - final Handler consumeHandler = event -> { - // then - assertThat(event).isSameAs(lineItemId); - assertThat(Vertx.currentContext()).isSameAs(initContext); - async.countDown(); - }; - - final ApplicationEventService applicationEventService = new ApplicationEventService(eventBus); - final EventServiceInitializer eventServiceInitializer = new EventServiceInitializer( - asList(new ProcessorStub(consumeHandler), new ProcessorStub(consumeHandler)), emptyList(), eventBus); - - // when - final Async initAsync = testContext.async(); - initContext.runOnContext(ignored -> { - eventServiceInitializer.initialize(); - initAsync.complete(); - }); - initAsync.await(); - - publishContext.runOnContext(ignored -> applicationEventService.publishLineItemWinEvent(lineItemId)); - } - - @Test - public void publishDeliveryProgressUpdateEventShouldPassEventToAllRecorders(TestContext testContext) { - // given - final Context initContext = vertx.getOrCreateContext(); - final Context publishContext = vertx.getOrCreateContext(); - - final Async async = testContext.async(2); - final Handler consumeHandler = event -> { - // then - assertThat(event).isSameAs(null); - assertThat(Vertx.currentContext()).isSameAs(initContext); - async.countDown(); - }; - - final ApplicationEventService applicationEventService = new ApplicationEventService(eventBus); - final EventServiceInitializer eventServiceInitializer = new EventServiceInitializer( - asList(new ProcessorStub(consumeHandler), new ProcessorStub(consumeHandler)), emptyList(), eventBus); - - // when - final Async initAsync = testContext.async(); - initContext.runOnContext(ignored -> { - eventServiceInitializer.initialize(); - initAsync.complete(); - }); - initAsync.await(); - - publishContext.runOnContext(ignored -> applicationEventService.publishDeliveryUpdateEvent()); - } - - private static class ProcessorStub implements ApplicationEventProcessor { - - private final Handler handler; - - ProcessorStub(Handler handler) { - this.handler = handler; - } - - @Override - public void processAuctionEvent(AuctionContext auctionContext) { - handler.handle(auctionContext); - } - - @Override - public void processLineItemWinEvent(String lineItemId) { - handler.handle(lineItemId); - } - - @Override - public void processDeliveryProgressUpdateEvent() { - handler.handle(null); - } - } -} diff --git a/src/test/java/org/prebid/server/deals/lineitem/DeliveryPlanTest.java b/src/test/java/org/prebid/server/deals/lineitem/DeliveryPlanTest.java deleted file mode 100644 index 1e104f2f8f2..00000000000 --- a/src/test/java/org/prebid/server/deals/lineitem/DeliveryPlanTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.prebid.server.deals.lineitem; - -import org.junit.Test; -import org.prebid.server.deals.proto.DeliverySchedule; -import org.prebid.server.deals.proto.Token; - -import java.util.HashSet; -import java.util.Set; -import java.util.stream.IntStream; - -import static org.assertj.core.api.Assertions.assertThat; - -public class DeliveryPlanTest { - - @Test - public void getHighestUnspentTokensClassShouldReturnHighestUnspentToken() { - // given - final Set tokens = new HashSet<>(); - tokens.add(Token.of(1, 100)); - tokens.add(Token.of(2, 100)); - tokens.add(Token.of(3, 100)); - - final DeliveryPlan plan = DeliveryPlan.of(DeliverySchedule.builder().tokens(tokens).build()); - - IntStream.range(0, 150).forEach(i -> plan.incSpentToken()); - - // when and then - assertThat(plan.getHighestUnspentTokensClass()).isEqualTo(2); - } -} diff --git a/src/test/java/org/prebid/server/deals/lineitem/DeliveryProgressTest.java b/src/test/java/org/prebid/server/deals/lineitem/DeliveryProgressTest.java deleted file mode 100644 index bc03de3aa36..00000000000 --- a/src/test/java/org/prebid/server/deals/lineitem/DeliveryProgressTest.java +++ /dev/null @@ -1,365 +0,0 @@ -package org.prebid.server.deals.lineitem; - -import org.assertj.core.groups.Tuple; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.VertxTest; -import org.prebid.server.deals.LineItemService; -import org.prebid.server.deals.model.TxnLog; -import org.prebid.server.deals.proto.DeliverySchedule; -import org.prebid.server.deals.proto.Token; -import org.prebid.server.deals.proto.report.Event; - -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import static java.util.Collections.singleton; -import static java.util.Collections.singletonMap; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - -public class DeliveryProgressTest extends VertxTest { - - @Rule - public MockitoRule rule = MockitoJUnit.rule(); - - @Mock - private Clock clock; - - @Mock - private LineItemService lineItemService; - - private ZonedDateTime now; - - private DeliveryProgress deliveryProgress; - - @Before - public void setUp() { - now = ZonedDateTime.now(Clock.fixed(Instant.parse("2019-07-26T10:00:00Z"), ZoneOffset.UTC)); - - given(clock.instant()).willReturn(now.toInstant()); - given(clock.getZone()).willReturn(ZoneOffset.UTC); - deliveryProgress = DeliveryProgress.of(now, lineItemService); - } - - @Test - public void cleanLineItemStatusesShouldRemoveOldestCachedPlans() { - // given - final TxnLog txnLog1 = TxnLog.create(); - txnLog1.lineItemSentToClientAsTopMatch().add("lineItemId1"); - - final TxnLog txnLog2 = TxnLog.create(); - txnLog2.lineItemSentToClientAsTopMatch().add("lineItemId1"); - - final TxnLog txnLog3 = TxnLog.create(); - txnLog3.lineItemSentToClientAsTopMatch().add("lineItemId1"); - - final LineItem lineItem1 = Mockito.mock(LineItem.class); - final DeliveryPlan deliveryPlan1 = Mockito.mock(DeliveryPlan.class); - final DeliveryPlan deliveryPlan2 = Mockito.mock(DeliveryPlan.class); - final DeliveryPlan deliveryPlan3 = Mockito.mock(DeliveryPlan.class); - - given(deliveryPlan1.getPlanId()).willReturn("lineItemId1Plan"); - given(deliveryPlan2.getPlanId()).willReturn("lineItemId2Plan"); - given(deliveryPlan3.getPlanId()).willReturn("lineItemId3Plan"); - - given(deliveryPlan1.withoutSpentTokens()).willReturn(deliveryPlan1); - given(deliveryPlan2.withoutSpentTokens()).willReturn(deliveryPlan2); - given(deliveryPlan3.withoutSpentTokens()).willReturn(deliveryPlan3); - - given(deliveryPlan1.getEndTimeStamp()).willReturn(now.minusMinutes(1)); - given(deliveryPlan2.getEndTimeStamp()).willReturn(now.minusMinutes(2)); - given(deliveryPlan3.getEndTimeStamp()).willReturn(now.minusMinutes(3)); - - given(lineItem1.getEndTimeStamp()).willReturn(now.minusMinutes(1)); - given(lineItem1.getActiveDeliveryPlan()).willReturn(deliveryPlan1, deliveryPlan2, deliveryPlan3); - - given(lineItemService.getLineItemById(eq("lineItemId1"))).willReturn(lineItem1); - - // when and then - deliveryProgress.recordTransactionLog(txnLog1, singletonMap("lineItemId1Plan", 1), "1001"); - deliveryProgress.recordTransactionLog(txnLog2, singletonMap("lineItemId2Plan", 1), "1001"); - deliveryProgress.recordTransactionLog(txnLog3, singletonMap("lineItemId3Plan", 1), "1001"); - - // check that 3 lineItemStatuses - assertThat(deliveryProgress.getLineItemStatuses().get("lineItemId1").getDeliveryPlans()) - .hasSize(3) - .extracting(DeliveryPlan::getPlanId) - .containsOnly("lineItemId1Plan", "lineItemId2Plan", "lineItemId3Plan"); - - deliveryProgress.cleanLineItemStatuses(now, 10000000L, 1); - - assertThat(deliveryProgress.getLineItemStatuses().get("lineItemId1").getDeliveryPlans()) - .hasSize(1) - .extracting(DeliveryPlan::getPlanId) - .containsOnly("lineItemId1Plan"); - } - - @Test - public void cleanLineItemStatusesShouldRemoveExpiredLineItemStatuses() { - // given - final TxnLog txnLog = TxnLog.create(); - txnLog.lineItemsSentToClient().add("lineItemId1"); - txnLog.lineItemsSentToClient().add("lineItemId2"); - final Map planIdToTokenPriority = new HashMap<>(); - planIdToTokenPriority.put("lineItemId1Plan", 1); - planIdToTokenPriority.put("lineItemId2Plan", 1); - - final LineItem lineItem1 = Mockito.mock(LineItem.class); - final LineItem lineItem2 = Mockito.mock(LineItem.class); - - given(lineItem1.getEndTimeStamp()).willReturn(now.minusHours(1)); - given(lineItem2.getEndTimeStamp()).willReturn(now.minusHours(2)); - - given(lineItemService.getLineItemById(eq("lineItemId1"))).willReturn(lineItem1); - given(lineItemService.getLineItemById(eq("lineItemId2"))).willReturn(lineItem2); - - // when and then - deliveryProgress.recordTransactionLog(txnLog, planIdToTokenPriority, "1001"); - - // check that 2 lineItemStatuses - assertThat(deliveryProgress.getLineItemStatuses().keySet()).hasSize(2) - .containsOnly("lineItemId1", "lineItemId2"); - - deliveryProgress.cleanLineItemStatuses(now, 6000000, 5); - - assertThat(deliveryProgress.getLineItemStatuses().keySet()).hasSize(1) - .containsOnly("lineItemId1"); - } - - @Test - public void fromAnotherCopyingPlansShouldReturnDeliveryProgressWithPlansAndStatistics() { - // given - final DeliveryProgress deliveryProgress = DeliveryProgress.of(now, lineItemService); - final TxnLog txnLog = TxnLog.create(); - txnLog.lineItemsMatchedWholeTargeting().add("lineItemId1"); - txnLog.lineItemsMatchedDomainTargeting().add("lineItemId1"); - txnLog.lineItemsReadyToServe().add("lineItemId1"); - txnLog.lineItemsMatchedTargetingFcapped().add("lineItemId1"); - txnLog.lineItemsMatchedTargetingFcapLookupFailed().add("lineItemId1"); - txnLog.lineItemsPacingDeferred().add("lineItemId1"); - txnLog.lineItemsSentToBidder().get("bidder1").add("lineItemId1"); - txnLog.lineItemsSentToBidderAsTopMatch().put("bidder1", singleton("lineItemId1")); - txnLog.lineItemsReceivedFromBidder().get("bidder1").add("lineItemId1"); - txnLog.lineItemsSentToClient().add("lineItemId1"); - txnLog.lineItemSentToClientAsTopMatch().add("lineItemId1"); - txnLog.lostAuctionToLineItems().put("lineItemId1", singleton("lineItemId2")); - txnLog.lostMatchingToLineItems().put("lineItemId1", singleton("lineItemId3")); - - final LineItem lineItem = mock(LineItem.class); - given(lineItemService.getLineItemById("lineItemId1")).willReturn(lineItem); - given(lineItem.getLineItemId()).willReturn("lineItemId1"); - given(lineItem.getActiveDeliveryPlan()).willReturn(DeliveryPlan.of(givenDeliverySchedule(now, "planId1"))); - - deliveryProgress.recordTransactionLog(txnLog, singletonMap("planId1", 1), "1001"); - - // when - final DeliveryProgress copiedDeliveryProgress = deliveryProgress.copyWithOriginalPlans(); - - // then - final LineItemStatus lineItemStatusCopied = copiedDeliveryProgress.getLineItemStatuses().get("lineItemId1"); - final LineItemStatus lineItemStatusOriginal = deliveryProgress.getLineItemStatuses().get("lineItemId1"); - - assertThat(lineItemStatusCopied).isNotSameAs(lineItemStatusOriginal); - - assertThat(lineItemStatusCopied.getDomainMatched().sum()) - .isEqualTo(lineItemStatusOriginal.getDomainMatched().sum()); - - assertThat(lineItemStatusCopied.getTargetMatched().sum()) - .isEqualTo(lineItemStatusOriginal.getTargetMatched().sum()); - - assertThat(lineItemStatusCopied.getTargetMatchedButFcapped().sum()) - .isEqualTo(lineItemStatusOriginal.getTargetMatchedButFcapped().sum()); - - assertThat(lineItemStatusCopied.getTargetMatchedButFcapLookupFailed().sum()) - .isEqualTo(lineItemStatusOriginal.getTargetMatchedButFcapLookupFailed().sum()); - - assertThat(lineItemStatusCopied.getPacingDeferred().sum()) - .isEqualTo(lineItemStatusOriginal.getPacingDeferred().sum()); - - assertThat(lineItemStatusCopied.getSentToBidder().sum()) - .isEqualTo(lineItemStatusOriginal.getSentToBidder().sum()); - - assertThat(lineItemStatusCopied.getSentToBidderAsTopMatch().sum()) - .isEqualTo(lineItemStatusOriginal.getSentToBidderAsTopMatch().sum()); - - assertThat(lineItemStatusCopied.getReceivedFromBidder().sum()) - .isEqualTo(lineItemStatusOriginal.getReceivedFromBidder().sum()); - - assertThat(lineItemStatusCopied.getReceivedFromBidderInvalidated().sum()) - .isEqualTo(lineItemStatusOriginal.getReceivedFromBidderInvalidated().sum()); - - assertThat(lineItemStatusCopied.getSentToClient().sum()) - .isEqualTo(lineItemStatusOriginal.getSentToClient().sum()); - - assertThat(lineItemStatusCopied.getSentToClientAsTopMatch().sum()) - .isEqualTo(lineItemStatusOriginal.getSentToClientAsTopMatch().sum()); - - assertThat(lineItemStatusCopied.getSentToClientAsTopMatch().sum()) - .isEqualTo(lineItemStatusOriginal.getSentToClientAsTopMatch().sum()); - - assertThat(copiedDeliveryProgress.getLineItemIdToLost().get("lineItemId1").entrySet()) - .extracting(Map.Entry::getKey, entry -> entry.getValue().getCount().sum()) - .containsOnly(Tuple.tuple("lineItemId2", 1L), Tuple.tuple("lineItemId3", 1L)); - - final DeliveryPlan originDeliveryPlan = lineItemStatusOriginal.getDeliveryPlans().stream().findFirst().get(); - final DeliveryPlan copiedDeliveryPlan = lineItemStatusCopied.getDeliveryPlans().stream().findFirst().get(); - assertThat(originDeliveryPlan).isSameAs(copiedDeliveryPlan); - } - - @Test - public void recordWinEventShouldRecordEventForAbsentInReportLineItemStatus() { - // given - final DeliveryProgress deliveryProgress = DeliveryProgress.of(now, lineItemService); - - // when - deliveryProgress.recordWinEvent("lineItemId1"); - - // then - final LineItemStatus lineItemStatus = deliveryProgress.getLineItemStatuses().get("lineItemId1"); - assertThat(lineItemStatus.getEvents()) - .extracting(Event::getType, event -> event.getCount().sum()) - .containsOnly(Tuple.tuple("win", 1L)); - } - - @Test - public void upsertPlanReferenceFromLineItemShouldInsertReferenceToNotExistingLineItemStatus() { - // given - final DeliveryProgress deliveryProgress = DeliveryProgress.of(now, lineItemService); - final LineItem lineItem = mock(LineItem.class); - given(lineItem.getActiveDeliveryPlan()).willReturn(DeliveryPlan.of(givenDeliverySchedule(now, "planId1"))); - given(lineItem.getLineItemId()).willReturn("lineItemId1"); - - // when - deliveryProgress.upsertPlanReferenceFromLineItem(lineItem); - - // then - assertThat(deliveryProgress.getLineItemStatuses()).hasSize(1); - final Set deliveryPlans = deliveryProgress.getLineItemStatuses().get("lineItemId1") - .getDeliveryPlans(); - assertThat(deliveryPlans).hasSize(1).extracting(DeliveryPlan::getDeliverySchedule) - .containsOnly(givenDeliverySchedule(now, "planId1")); - } - - @Test - public void upsertPlanReferenceFromLineItemShouldInsertToExistingWhenNotContainsPlanWithSameId() { - final DeliveryProgress deliveryProgress = DeliveryProgress.of(now, lineItemService); - deliveryProgress.getLineItemStatuses().put("lineItemId1", LineItemStatus.of("lineItemId1")); - final LineItem lineItem = mock(LineItem.class); - given(lineItem.getActiveDeliveryPlan()).willReturn(DeliveryPlan.of(givenDeliverySchedule(now, "planId1"))); - given(lineItem.getLineItemId()).willReturn("lineItemId1"); - - // when - deliveryProgress.upsertPlanReferenceFromLineItem(lineItem); - - // then - assertThat(deliveryProgress.getLineItemStatuses()).hasSize(1); - final Set deliveryPlans = deliveryProgress.getLineItemStatuses().get("lineItemId1") - .getDeliveryPlans(); - assertThat(deliveryPlans).hasSize(1).extracting(DeliveryPlan::getDeliverySchedule) - .containsOnly(givenDeliverySchedule(now, "planId1")); - } - - @Test - public void upsertPlanReferenceFromLineItemShouldReplacePlanWhenContainsPlanWithSameId() { - // given - final DeliveryProgress deliveryProgress = DeliveryProgress.of(now, lineItemService); - final LineItemStatus lineItemStatus = LineItemStatus.of("lineItemId1"); - lineItemStatus.getDeliveryPlans().add(DeliveryPlan.of(givenDeliverySchedule(now.minusMinutes(1), "planId1"))); - deliveryProgress.getLineItemStatuses().put("lineItemId1", lineItemStatus); - final LineItem lineItem = mock(LineItem.class); - given(lineItem.getActiveDeliveryPlan()).willReturn(DeliveryPlan.of(givenDeliverySchedule(now, "planId1"))); - given(lineItem.getLineItemId()).willReturn("lineItemId1"); - - // when - deliveryProgress.upsertPlanReferenceFromLineItem(lineItem); - - // then - assertThat(deliveryProgress.getLineItemStatuses()).hasSize(1); - final Set deliveryPlans = deliveryProgress.getLineItemStatuses().get("lineItemId1") - .getDeliveryPlans(); - assertThat(deliveryPlans).hasSize(1).extracting(DeliveryPlan::getDeliverySchedule) - .containsOnly(givenDeliverySchedule(now, "planId1")); - } - - @Test - public void mergePlanFromLineItemShouldMergeCurrentPlanWithNewActiveOne() { - // given - final DeliveryProgress deliveryProgress = DeliveryProgress.of(now, lineItemService); - final LineItemStatus lineItemStatus = LineItemStatus.of("lineItemId1"); - lineItemStatus.getDeliveryPlans().add(DeliveryPlan.of(DeliverySchedule.builder().planId("planId1") - .startTimeStamp(now.minusMinutes(1)).endTimeStamp(now.plusMinutes(1)) - .updatedTimeStamp(now.minusMinutes(2)) - .tokens(singleton(Token.of(2, 50))).build())); - deliveryProgress.getLineItemStatuses().put("lineItemId1", lineItemStatus); - final LineItem lineItem = mock(LineItem.class); - given(lineItem.getActiveDeliveryPlan()).willReturn(DeliveryPlan.of(givenDeliverySchedule(now, "planId1"))); - given(lineItem.getLineItemId()).willReturn("lineItemId1"); - - // when - deliveryProgress.mergePlanFromLineItem(lineItem); - - // then - assertThat(deliveryProgress.getLineItemStatuses()).hasSize(1); - final Set deliveryPlans = deliveryProgress.getLineItemStatuses().get("lineItemId1") - .getDeliveryPlans(); - assertThat(deliveryPlans).hasSize(1) - .flatExtracting(DeliveryPlan::getDeliveryTokens) - .extracting(DeliveryToken::getPriorityClass, DeliveryToken::getTotal, - deliveryToken -> deliveryToken.getSpent().sum()) - .containsOnly(Tuple.tuple(1, 100, 0L), Tuple.tuple(2, 50, 0L)); - - assertThat(deliveryPlans).hasSize(1) - .extracting(DeliveryPlan::getPlanId, DeliveryPlan::getUpdatedTimeStamp) - .containsOnly(Tuple.tuple("planId1", now.minusMinutes(1))); - } - - @Test - public void mergePlanFromLineItemShouldReplaceCurrentPlanWithNewActiveOneWithoutSpentTokens() { - // given - final DeliveryProgress deliveryProgress = DeliveryProgress.of(now, lineItemService); - deliveryProgress.getLineItemStatuses().put("lineItemId1", LineItemStatus.of("lineItemId1")); - final LineItem lineItem = mock(LineItem.class); - given(lineItem.getActiveDeliveryPlan()).willReturn(DeliveryPlan.of(givenDeliverySchedule(now, "planId1"))); - given(lineItem.getLineItemId()).willReturn("lineItemId1"); - - // when - deliveryProgress.mergePlanFromLineItem(lineItem); - - // then - assertThat(deliveryProgress.getLineItemStatuses()).hasSize(1); - final Set deliveryPlans = deliveryProgress.getLineItemStatuses().get("lineItemId1") - .getDeliveryPlans(); - assertThat(deliveryPlans).hasSize(1) - .flatExtracting(DeliveryPlan::getDeliveryTokens) - .extracting(DeliveryToken::getPriorityClass, DeliveryToken::getTotal, - deliveryToken -> deliveryToken.getSpent().sum()) - .containsOnly(Tuple.tuple(1, 100, 0L)); - - assertThat(deliveryPlans).hasSize(1) - .extracting(DeliveryPlan::getPlanId, DeliveryPlan::getUpdatedTimeStamp) - .containsOnly(Tuple.tuple("planId1", now.minusMinutes(1))); - } - - private static DeliverySchedule givenDeliverySchedule(ZonedDateTime now, String planId) { - return DeliverySchedule.builder() - .planId(planId) - .startTimeStamp(now.minusMinutes(1)) - .endTimeStamp(now.plusMinutes(1)) - .updatedTimeStamp(now.minusMinutes(1)) - .tokens(singleton(Token.of(1, 100))) - .build(); - } -} diff --git a/src/test/java/org/prebid/server/deals/model/DeepDebugLogTest.java b/src/test/java/org/prebid/server/deals/model/DeepDebugLogTest.java deleted file mode 100644 index 0e70f86ca56..00000000000 --- a/src/test/java/org/prebid/server/deals/model/DeepDebugLogTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.prebid.server.deals.model; - -import org.junit.Test; -import org.prebid.server.proto.openrtb.ext.response.ExtTraceDeal; -import org.prebid.server.proto.openrtb.ext.response.ExtTraceDeal.Category; - -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.util.function.Supplier; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - -public class DeepDebugLogTest { - - private final Clock clock = Clock.fixed(Instant.now(), ZoneId.systemDefault()); - - @SuppressWarnings("unchecked") - @Test - public void addShouldNotRecordMessageWhenDeepDebugIsDisabled() { - // given - final DeepDebugLog deepDebugLog = DeepDebugLog.create(false, clock); - - final Supplier messageSupplier = (Supplier) mock(Supplier.class); - - // when - deepDebugLog.add(null, Category.pacing, messageSupplier); - - // then - verify(messageSupplier, never()).get(); - - assertThat(deepDebugLog.entries()).isEmpty(); - } - - @Test - public void addShouldRecordMessageWhenDeepDebugIsEnabled() { - // given - final DeepDebugLog deepDebugLog = DeepDebugLog.create(true, clock); - - // when - deepDebugLog.add(null, Category.pacing, () -> "debug message 1"); - - // then - assertThat(deepDebugLog.entries()).containsOnly( - ExtTraceDeal.of(null, ZonedDateTime.now(clock), Category.pacing, "debug message 1")); - } -} diff --git a/src/test/java/org/prebid/server/deals/simulation/DealsSimulationAdminHandlerTest.java b/src/test/java/org/prebid/server/deals/simulation/DealsSimulationAdminHandlerTest.java deleted file mode 100644 index 72069ad5f88..00000000000 --- a/src/test/java/org/prebid/server/deals/simulation/DealsSimulationAdminHandlerTest.java +++ /dev/null @@ -1,227 +0,0 @@ -package org.prebid.server.deals.simulation; - -import com.fasterxml.jackson.core.JsonProcessingException; -import io.vertx.core.MultiMap; -import io.vertx.core.buffer.Buffer; -import io.vertx.core.http.HttpServerRequest; -import io.vertx.core.http.HttpServerResponse; -import io.vertx.ext.web.RoutingContext; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.VertxTest; -import org.prebid.server.exception.PreBidException; - -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.util.Collections; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.startsWith; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.verify; - -public class DealsSimulationAdminHandlerTest extends VertxTest { - - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private SimulationAwareRegisterService registerService; - - @Mock - private SimulationAwarePlannerService plannerService; - - @Mock - private SimulationAwareDeliveryProgressService deliveryProgressService; - - @Mock - private SimulationAwareDeliveryStatsService deliveryStatsService; - - @Mock - private SimulationAwareHttpBidderRequester httpBidderRequester; - - @Mock - private RoutingContext routingContext; - - @Mock - private HttpServerRequest request; - - @Mock - private HttpServerResponse response; - - private ZonedDateTime now; - - private DealsSimulationAdminHandler dealsSimulationAdminHandler; - - @Before - public void setUp() { - now = ZonedDateTime.now(Clock.fixed(Instant.parse("2019-10-10T00:00:00Z"), ZoneOffset.UTC)); - dealsSimulationAdminHandler = new DealsSimulationAdminHandler(registerService, - plannerService, deliveryProgressService, deliveryStatsService, httpBidderRequester, jacksonMapper, - "endpoint"); - given(routingContext.request()).willReturn(request); - given(routingContext.response()).willReturn(response); - given(request.headers()).willReturn(MultiMap.caseInsensitiveMultiMap() - .add("pg-sim-timestamp", now.toString())); - given(response.setStatusCode(anyInt())).willReturn(response); - } - - @Test - public void handleShouldCallPerformRegistrationHandler() { - // given - given(request.uri()).willReturn("/pbs-admin/e2eAdmin/planner/register"); - - // when - dealsSimulationAdminHandler.handle(routingContext); - - // then - verify(registerService).performRegistration(eq(now)); - } - - @Test - public void handleShouldCallFetchLineItemHandler() { - // given - given(request.uri()).willReturn("/pbs-admin/e2eAdmin/planner/fetchLineItems"); - - // when - dealsSimulationAdminHandler.handle(routingContext); - - // then - verify(plannerService).initiateLineItemsFetching(eq(now)); - } - - @Test - public void handleShouldCallAdvancePlanHandler() { - // given - given(request.uri()).willReturn("/pbs-admin/e2eAdmin/advancePlans"); - - // when - dealsSimulationAdminHandler.handle(routingContext); - - // then - verify(plannerService).advancePlans(eq(now)); - } - - @Test - public void handleShouldCallReportHandler() { - // given - given(request.uri()).willReturn("/pbs-admin/e2eAdmin/dealstats/report"); - - // when - dealsSimulationAdminHandler.handle(routingContext); - - // then - verify(deliveryProgressService).createDeliveryProgressReport(eq(now)); - verify(deliveryStatsService).sendDeliveryProgressReports(eq(now)); - } - - @Test - public void handleShouldCallSetBidRateHandler() throws JsonProcessingException { - // given - given(request.uri()).willReturn("/pbs-admin/e2eAdmin/bidRate"); - given(routingContext.getBody()).willReturn(Buffer.buffer( - mapper.writeValueAsString(Collections.singletonMap("lineItemId", 1.00)))); - - // when - dealsSimulationAdminHandler.handle(routingContext); - - // then - verify(httpBidderRequester).setBidRates(any()); - } - - @Test - public void handleShouldRespondWithErrorWhenBidderRequesterIsNotSet() { - // given - dealsSimulationAdminHandler = new DealsSimulationAdminHandler( - registerService, plannerService, deliveryProgressService, deliveryStatsService, null, jacksonMapper, - "endpoint"); - given(request.uri()).willReturn("/pbs-admin/e2eAdmin/bidRate"); - - // when - dealsSimulationAdminHandler.handle(routingContext); - - // then - verify(response).setStatusCode(400); - verify(response).end(eq("Calling /bidRate is not make sense since " - + "Prebid Server configured to use real bidder exchanges in simulation mode")); - } - - @Test - public void handleShouldRespondWithNotFoundWhenHandlerNotFound() { - // given - given(request.uri()).willReturn("/pbs-admin/e2eAdmin/invalid"); - - // when - dealsSimulationAdminHandler.handle(routingContext); - - // then - verify(response).setStatusCode(404); - verify(response).end(eq("Requested url /invalid was not found")); - } - - @Test - public void handleShouldRespondWithBadRequestWhenRequiredDateHeaderNotFound() { - // given - given(request.uri()).willReturn("/pbs-admin/e2eAdmin/dealstats/startreport"); - given(request.headers()).willReturn(MultiMap.caseInsensitiveMultiMap()); - - // when - dealsSimulationAdminHandler.handle(routingContext); - - // then - verify(response).setStatusCode(400); - verify(response).end(eq("pg-sim-timestamp with simulated current date is required for endpoints:" - + " /planner/register, /planner/fetchLineItems, /advancePlans, /dealstats/report")); - } - - @Test - public void handleShouldRespondWithBadRequestWhenBodyNotFoundForSetBidRatesHandler() { - // given - given(request.uri()).willReturn("/pbs-admin/e2eAdmin/bidRate"); - given(routingContext.getBody()).willReturn(null); - - // when - dealsSimulationAdminHandler.handle(routingContext); - - // then - verify(response).setStatusCode(400); - verify(response).end(eq("Body is required for /bidRate endpoint")); - } - - @Test - public void handleShouldRespondWithBadRequestWhenBodyHasIncorrectFormatForSetBidRatesHandler() { - // given - given(request.uri()).willReturn("/pbs-admin/e2eAdmin/bidRate"); - given(routingContext.getBody()).willReturn(Buffer.buffer("{")); - - // when - dealsSimulationAdminHandler.handle(routingContext); - - // then - verify(response).setStatusCode(400); - verify(response).end(startsWith("Failed to parse bid rates body")); - } - - @Test - public void handleShouldRespondWithInternalServerErrorStatus() { - // given - given(request.uri()).willReturn("/pbs-admin/e2eAdmin/advancePlans"); - doThrow(new PreBidException("Error")).when(plannerService).advancePlans(any()); - - // when - dealsSimulationAdminHandler.handle(routingContext); - - // then - verify(response).setStatusCode(eq(500)); - verify(response).end(eq("Error")); - } -} diff --git a/src/test/java/org/prebid/server/deals/simulation/SimulationAwareHttpBidderRequesterTest.java b/src/test/java/org/prebid/server/deals/simulation/SimulationAwareHttpBidderRequesterTest.java deleted file mode 100644 index 3287ca2e1a1..00000000000 --- a/src/test/java/org/prebid/server/deals/simulation/SimulationAwareHttpBidderRequesterTest.java +++ /dev/null @@ -1,324 +0,0 @@ -package org.prebid.server.deals.simulation; - -import com.fasterxml.jackson.databind.node.IntNode; -import com.iab.openrtb.request.BidRequest; -import com.iab.openrtb.request.Deal; -import com.iab.openrtb.request.Format; -import com.iab.openrtb.request.Imp; -import com.iab.openrtb.request.Pmp; -import com.iab.openrtb.response.Bid; -import io.vertx.core.Future; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.VertxTest; -import org.prebid.server.auction.BidderAliases; -import org.prebid.server.auction.model.BidRejectionTracker; -import org.prebid.server.auction.model.BidderRequest; -import org.prebid.server.bidder.BidderErrorNotifier; -import org.prebid.server.bidder.BidderRequestCompletionTrackerFactory; -import org.prebid.server.bidder.HttpBidderRequestEnricher; -import org.prebid.server.bidder.model.BidderBid; -import org.prebid.server.bidder.model.BidderError; -import org.prebid.server.bidder.model.BidderSeatBid; -import org.prebid.server.deals.LineItemService; -import org.prebid.server.deals.lineitem.LineItem; -import org.prebid.server.deals.proto.LineItemMetaData; -import org.prebid.server.deals.proto.Price; -import org.prebid.server.exception.PreBidException; -import org.prebid.server.model.CaseInsensitiveMultiMap; -import org.prebid.server.proto.openrtb.ext.request.ExtDeal; -import org.prebid.server.proto.openrtb.ext.request.ExtDealLine; -import org.prebid.server.proto.openrtb.ext.response.BidType; -import org.prebid.server.vertx.http.HttpClient; -import org.springframework.test.util.ReflectionTestUtils; - -import java.math.BigDecimal; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import static java.util.Arrays.asList; -import static java.util.Collections.singletonList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.tuple; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; - -public class SimulationAwareHttpBidderRequesterTest extends VertxTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - private SimulationAwareHttpBidderRequester bidderRequester; - - @Mock - private HttpClient httpClient; - @Mock - private BidderAliases bidderAliases; - @Mock - private BidRejectionTracker bidRejectionTracker; - @Mock - private BidderRequestCompletionTrackerFactory bidderRequestCompletionTrackerFactory; - @Mock - private BidderErrorNotifier bidderErrorNotifier; - @Mock - private HttpBidderRequestEnricher requestEnricher; - @Mock - private CaseInsensitiveMultiMap requestHeaders; - @Mock - private LineItemService lineItemService; - - @Before - public void setUp() { - bidderRequester = new SimulationAwareHttpBidderRequester( - httpClient, bidderRequestCompletionTrackerFactory, bidderErrorNotifier, requestEnricher, - lineItemService, jacksonMapper); - } - - @Test - public void requestBidsShouldReturnBidderSeatBidWithOneBidAndFilterOutOne() { - // given - final Map rates = new HashMap<>(); - rates.put("lineItemId1", 1.00); - rates.put("lineItemId2", 0.00); - bidderRequester.setBidRates(rates); - given(lineItemService.getLineItemById(eq("lineItemId1"))).willReturn(LineItem.of( - LineItemMetaData.builder().price(Price.of(BigDecimal.ONE, "USD")).build(), Price.of(BigDecimal.ONE, - "USD"), null, null)); - given(lineItemService.getLineItemById(eq("lineItemId2"))).willReturn(LineItem.of( - LineItemMetaData.builder().price(Price.of(BigDecimal.TEN, "USD")).build(), Price.of(BigDecimal.ONE, - "USD"), null, null)); - - final BidRequest bidRequest = BidRequest.builder().imp(asList( - Imp.builder().id("impId1").pmp(Pmp.builder().deals(singletonList(Deal.builder() - .id("dealId1") - .ext(mapper.valueToTree(ExtDeal.of(ExtDealLine.of("lineItemId1", null, - singletonList(Format.builder().w(100).h(100).build()), null)))) - .build())).build()).build(), - Imp.builder().id("impId2").pmp(Pmp.builder().deals(singletonList(Deal.builder() - .id("dealId2") - .ext(mapper.valueToTree(ExtDeal.of(ExtDealLine.of("lineItemId2", null, - singletonList(Format.builder().w(100).h(100).build()), null)))) - .build())).build()).build())) - .build(); - final BidderRequest bidderRequest = BidderRequest.builder().bidder("bidder").bidRequest(bidRequest).build(); - - // when - final Future result = bidderRequester - .requestBids( - null, - bidderRequest, - bidRejectionTracker, - null, - requestHeaders, - bidderAliases, - false); - - // then - assertThat(result.succeeded()).isTrue(); - assertThat(result.result()).isEqualTo(BidderSeatBid.of(singletonList( - BidderBid.of( - Bid.builder().id("impId1-lineItemId1").impid("impId1").dealid("dealId1").price(BigDecimal.ONE) - .adm("").crid("crid").w(100).h(100) - .build(), - BidType.banner, - "USD")))); - } - - @Test - public void requestBidsShouldFilterBidderSeatBidForWhichImpPmpIsNull() { - // given - bidderRequester.setBidRates(Collections.singletonMap("lineItemId1", 1.00)); - given(lineItemService.getLineItemById(eq("lineItemId1"))).willReturn(LineItem.of( - LineItemMetaData.builder().price(Price.of(BigDecimal.ONE, "USD")).build(), - Price.of(BigDecimal.ONE, "USD"), null, null)); - - final BidRequest bidRequest = BidRequest.builder().imp(asList( - Imp.builder().id("impId1").pmp(Pmp.builder().deals(singletonList(Deal.builder() - .id("dealId1") - .ext(mapper.valueToTree(ExtDeal.of(ExtDealLine.of("lineItemId1", null, - singletonList(Format.builder().w(100).h(100).build()), null)))) - .build())).build()).build(), - Imp.builder().id("impId2").build())) - .build(); - final BidderRequest bidderRequest = BidderRequest.builder().bidder("bidder").bidRequest(bidRequest).build(); - - // when - final Future result = bidderRequester.requestBids( - null, - bidderRequest, - bidRejectionTracker, - null, - requestHeaders, - bidderAliases, - false); - - // then - assertThat(result.succeeded()).isTrue(); - assertThat(result.result()).isEqualTo(BidderSeatBid.of(singletonList( - BidderBid.of( - Bid.builder().id("impId1-lineItemId1").impid("impId1").dealid("dealId1").price(BigDecimal.ONE) - .adm("").crid("crid").w(100).h(100) - .build(), - BidType.banner, - "USD")))); - } - - @Test - public void requestBidsShouldSetSizesAsZeroIfExtDealsLinesDoesNotHaveSizes() { - // given - final Map rates = new HashMap<>(); - rates.put("lineItemId1", 1.00); - bidderRequester.setBidRates(rates); - given(lineItemService.getLineItemById(eq("lineItemId1"))).willReturn(LineItem.of( - LineItemMetaData.builder().price(Price.of(BigDecimal.ONE, "USD")).build(), - Price.of(BigDecimal.ONE, "USD"), null, null)); - - final BidRequest bidRequest = BidRequest.builder().imp(singletonList( - Imp.builder().id("impId1").pmp(Pmp.builder().deals(singletonList(Deal.builder() - .id("dealId1") - .ext(mapper.valueToTree(ExtDeal.of(ExtDealLine.of("lineItemId1", null, null, null)))) - .build())).build()).build())) - .build(); - final BidderRequest bidderRequest = BidderRequest.builder().bidder("bidder").bidRequest(bidRequest).build(); - - // when - final Future result = bidderRequester.requestBids( - null, - bidderRequest, - bidRejectionTracker, - null, - requestHeaders, - bidderAliases, - false); - - // then - assertThat(result.succeeded()).isTrue(); - assertThat(result.result()).isEqualTo(BidderSeatBid.of(singletonList( - BidderBid.of( - Bid.builder().id("impId1-lineItemId1").impid("impId1").dealid("dealId1").price(BigDecimal.ONE) - .adm("").crid("crid").w(0).h(0) - .build(), - BidType.banner, - "USD")))); - } - - @Test - public void requestBidsShouldThrowPrebidExceptionWhenExtDealsInvalidFormat() { - // given - final Map rates = new HashMap<>(); - rates.put("lineItemId1", 1.00); - bidderRequester.setBidRates(rates); - given(lineItemService.getLineItemById(eq("lineItemId1"))).willReturn(LineItem.of( - LineItemMetaData.builder().price(Price.of(BigDecimal.ONE, "USD")).build(), - Price.of(BigDecimal.ONE, "USD"), null, null)); - - final BidRequest bidRequest = BidRequest.builder().imp(singletonList( - Imp.builder().id("impId1").pmp(Pmp.builder().deals(singletonList(Deal.builder() - .id("dealId1") - .ext(mapper.createObjectNode().set("line", new IntNode(5))) - .build())).build()).build())) - .build(); - final BidderRequest bidderRequest = BidderRequest.builder().bidder("bidder").bidRequest(bidRequest).build(); - - // when and then - assertThatThrownBy(() -> bidderRequester - .requestBids( - null, - bidderRequest, - bidRejectionTracker, - null, - requestHeaders, - bidderAliases, - false)) - .isInstanceOf(PreBidException.class) - .hasMessageStartingWith("Error decoding bidRequest.imp.pmp.deal.ext:"); - } - - @Test - public void requestBidsShouldReturnBidderSeatBidWithoutBidderBidsAndWithError() { - // given - bidderRequester.setBidRates(Collections.singletonMap("lineItemId1", 1.00)); - - final BidRequest bidRequest = BidRequest.builder().imp(singletonList( - Imp.builder().id("impId1").pmp(Pmp.builder().deals(singletonList(Deal.builder() - .id("dealId1").build())).build()).build())) - .build(); - final BidderRequest bidderRequest = BidderRequest.builder().bidder("bidder").bidRequest(bidRequest).build(); - - // when - final Future result = bidderRequester - .requestBids( - null, - bidderRequest, - bidRejectionTracker, - null, - requestHeaders, - bidderAliases, - false); - - // then - assertThat(result.succeeded()).isTrue(); - assertThat(result.result()).isEqualTo(BidderSeatBid.builder() - .errors(singletonList(BidderError.failedToRequestBids( - "Matched or ready to serve line items were not found, but required in simulation mode"))) - .build()); - } - - @Test - public void requestBidsShouldThrowPrebidExceptionWhenBidRatesForLineItemWereNotFound() { - // given - bidderRequester.setBidRates(Collections.singletonMap("lineItemId1", 1.00)); - - final BidRequest bidRequest = BidRequest.builder().imp(singletonList( - Imp.builder().id("impId1").pmp(Pmp.builder().deals(singletonList(Deal.builder() - .id("dealId1") - .ext(mapper.valueToTree(ExtDeal.of(ExtDealLine.of("lineItemId2", null, null, null)))) - .build())).build()).build())) - .build(); - final BidderRequest bidderRequest = BidderRequest.builder().bidder("bidder").bidRequest(bidRequest).build(); - - // when - assertThatThrownBy(() -> bidderRequester - .requestBids( - null, - bidderRequest, - bidRejectionTracker, - null, - requestHeaders, - bidderAliases, - false)) - .isInstanceOf(PreBidException.class) - .hasMessage("Bid rate for line item with id lineItemId2 was not found"); - } - - @Test - public void setBidRatesShouldMergeRates() { - // given - final Map initialBidRates = new HashMap<>(); - initialBidRates.put("lineItemId1", 1.00); - initialBidRates.put("lineItemId2", 0.5); - bidderRequester.setBidRates(initialBidRates); - - final Map updateBidRates = new HashMap<>(); - updateBidRates.put("lineItemId1", 0.00); - updateBidRates.put("lineItemId3", 0.75); - - // when - bidderRequester.setBidRates(updateBidRates); - - // then - @SuppressWarnings("unchecked") final Map resultBidRates = - (Map) ReflectionTestUtils.getField(bidderRequester, "bidRates"); - - assertThat(resultBidRates).isNotNull(); - assertThat(resultBidRates.entrySet()).hasSize(3) - .extracting(Map.Entry::getKey, Map.Entry::getValue) - .containsOnly(tuple("lineItemId1", 0.00), tuple("lineItemId2", 0.5), tuple("lineItemId3", 0.75)); - } -} diff --git a/src/test/java/org/prebid/server/deals/simulation/SimulationAwarePlannerServiceTest.java b/src/test/java/org/prebid/server/deals/simulation/SimulationAwarePlannerServiceTest.java deleted file mode 100644 index 0774f31314d..00000000000 --- a/src/test/java/org/prebid/server/deals/simulation/SimulationAwarePlannerServiceTest.java +++ /dev/null @@ -1,164 +0,0 @@ -package org.prebid.server.deals.simulation; - -import com.fasterxml.jackson.core.JsonProcessingException; -import io.vertx.core.Future; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.VertxTest; -import org.prebid.server.deals.AlertHttpService; -import org.prebid.server.deals.DeliveryProgressService; -import org.prebid.server.deals.model.DeploymentProperties; -import org.prebid.server.deals.model.PlannerProperties; -import org.prebid.server.deals.proto.LineItemMetaData; -import org.prebid.server.metric.Metrics; -import org.prebid.server.vertx.http.HttpClient; -import org.prebid.server.vertx.http.model.HttpClientResponse; -import org.springframework.test.util.ReflectionTestUtils; - -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeoutException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyList; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - -public class SimulationAwarePlannerServiceTest extends VertxTest { - - private static final String PLAN_ENDPOINT = "plan-endpoint"; - private static final String REGISTER_ENDPOINT = "register-endpoint"; - private static final String USERNAME = "username"; - private static final String PASSWORD = "password"; - private static final String PBS_HOST = "pbs-host"; - private static final String PBS_REGION = "pbs-region"; - private static final String PBS_VENDOR = "pbs-vendor"; - - @Rule - public final MockitoRule rule = MockitoJUnit.rule(); - - @Mock - private HttpClient httpClient; - @Mock - private SimulationAwareLineItemService lineItemService; - @Mock - private DeliveryProgressService deliveryProgressService; - @Mock - private AlertHttpService alertHttpService; - @Mock - private Metrics metrics; - - private SimulationAwarePlannerService simulationAwarePlannerService; - - private ZonedDateTime now; - - @Before - public void setUp() { - final Clock clock = Clock.fixed(Instant.parse("2019-07-26T10:00:00Z"), ZoneOffset.UTC); - now = ZonedDateTime.now(clock); - - simulationAwarePlannerService = new SimulationAwarePlannerService( - PlannerProperties.builder() - .planEndpoint(PLAN_ENDPOINT) - .registerEndpoint(REGISTER_ENDPOINT) - .timeoutMs(100L) - .registerPeriodSeconds(60L) - .username(USERNAME) - .password(PASSWORD) - .build(), - DeploymentProperties.builder().pbsHostId(PBS_HOST).pbsRegion(PBS_REGION).pbsVendor(PBS_VENDOR).build(), - lineItemService, - deliveryProgressService, - alertHttpService, - httpClient, - metrics, - clock, - jacksonMapper); - } - - @Test - public void initiateLineItemFetchingShouldNotCallLineItemServiceUpdateMethod() throws JsonProcessingException { - // given - given(httpClient.get(anyString(), any(), anyLong())) - .willReturn(Future.succeededFuture(HttpClientResponse.of(200, null, mapper.writeValueAsString( - Collections.singletonList(LineItemMetaData.builder().lineItemId("id").build()))))); - - // when - simulationAwarePlannerService.initiateLineItemsFetching(now); - - // then - verify(lineItemService, never()).updateLineItems(any(), anyBoolean()); - } - - @Test - public void initiateLineItemFetchingShouldNotRetryWhenCallToPlannerFailed() { - // given - given(httpClient.get(anyString(), any(), anyLong())) - .willReturn(Future.failedFuture(new TimeoutException("time out"))); - - // when - simulationAwarePlannerService.initiateLineItemsFetching(now); - - // then - verify(httpClient).get(anyString(), any(), anyLong()); - } - - @Test - public void initiateLineItemFetchingShouldUpdateMetricsAndLineItemServiceWithResponsiveFlagWhenCallSuccessful() - throws JsonProcessingException { - // given - given(httpClient.get(anyString(), any(), anyLong())) - .willReturn(Future.succeededFuture(HttpClientResponse.of(200, null, mapper.writeValueAsString( - Collections.singletonList(LineItemMetaData.builder().lineItemId("id").build()))))); - - // when - simulationAwarePlannerService.initiateLineItemsFetching(now); - - // then - @SuppressWarnings("unchecked") - final List lineItemMetaData = (List) ReflectionTestUtils - .getField(simulationAwarePlannerService, "lineItemMetaData"); - assertThat(lineItemMetaData).hasSize(1) - .containsOnly(LineItemMetaData.builder().lineItemId("id").build()); - verify(metrics).updatePlannerRequestMetric(eq(true)); - verify(lineItemService).updateIsPlannerResponsive(eq(true)); - } - - @Test - public void initiateLineItemFetchingShouldUpdateMetricsAndLineItemServiceWithResponsiveFlagWhenCallFailed() { - // given - given(httpClient.get(anyString(), any(), anyLong())) - .willReturn(Future.failedFuture(new TimeoutException("time out"))); - - // when - simulationAwarePlannerService.initiateLineItemsFetching(now); - - // then - verify(metrics).updatePlannerRequestMetric(eq(false)); - verify(lineItemService).updateIsPlannerResponsive(eq(false)); - } - - @Test - public void advancePlansShouldCallUpdateLineItemsAndUpdateProgress() { - // given and when - simulationAwarePlannerService.advancePlans(now); - - // then - verify(lineItemService).updateLineItems(anyList(), anyBoolean(), eq(now)); - verify(lineItemService).advanceToNextPlan(now); - } -} diff --git a/src/test/java/org/prebid/server/deals/targeting/RequestContextTest.java b/src/test/java/org/prebid/server/deals/targeting/RequestContextTest.java deleted file mode 100644 index 7d80fd036bb..00000000000 --- a/src/test/java/org/prebid/server/deals/targeting/RequestContextTest.java +++ /dev/null @@ -1,1262 +0,0 @@ -package org.prebid.server.deals.targeting; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.fasterxml.jackson.databind.node.TextNode; -import com.iab.openrtb.request.App; -import com.iab.openrtb.request.Banner; -import com.iab.openrtb.request.BidRequest; -import com.iab.openrtb.request.Data; -import com.iab.openrtb.request.Device; -import com.iab.openrtb.request.Format; -import com.iab.openrtb.request.Geo; -import com.iab.openrtb.request.Imp; -import com.iab.openrtb.request.Native; -import com.iab.openrtb.request.Publisher; -import com.iab.openrtb.request.Segment; -import com.iab.openrtb.request.Site; -import com.iab.openrtb.request.User; -import com.iab.openrtb.request.Video; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.VertxTest; -import org.prebid.server.deals.model.TxnLog; -import org.prebid.server.deals.targeting.model.GeoLocation; -import org.prebid.server.deals.targeting.model.LookupResult; -import org.prebid.server.deals.targeting.model.Size; -import org.prebid.server.deals.targeting.syntax.TargetingCategory; -import org.prebid.server.exception.TargetingSyntaxException; -import org.prebid.server.proto.openrtb.ext.request.ExtApp; -import org.prebid.server.proto.openrtb.ext.request.ExtDevice; -import org.prebid.server.proto.openrtb.ext.request.ExtGeo; -import org.prebid.server.proto.openrtb.ext.request.ExtSite; -import org.prebid.server.proto.openrtb.ext.request.ExtUser; -import org.prebid.server.proto.openrtb.ext.request.ExtUserTime; - -import java.util.function.Function; - -import static java.util.Arrays.asList; -import static java.util.Collections.singletonList; -import static java.util.function.Function.identity; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class RequestContextTest extends VertxTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - private TxnLog txnLog; - - @Before - public void setUp() { - txnLog = TxnLog.create(); - } - - @Test - public void lookupStringShouldReturnDomainFromSite() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.domain); - final RequestContext context = new RequestContext( - request(r -> r.site(site(s -> s.domain("domain.com")))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("domain.com"); - } - - @Test - public void lookupStringShouldReturnDomainFromSitePublisher() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.domain); - final RequestContext context = new RequestContext( - request(r -> r.site(site(s -> s - .publisher(Publisher.builder().domain("domain.com").build())))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("domain.com"); - } - - @Test - public void lookupStringShouldReturnEmptyResultWhenDomainIsMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.domain); - final RequestContext context = new RequestContext( - request(r -> r.site(site(identity()))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupStringShouldReturnEmptyResultForDomainWhenSiteIsMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.domain); - final RequestContext context = new RequestContext( - request(identity()), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupStringShouldReturnPublisherDomainFromSitePublisher() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.publisherDomain); - final RequestContext context = - new RequestContext( - request(r -> r.site(site(s -> s - .publisher(Publisher.builder().domain("domain.com").build())))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("domain.com"); - } - - @Test - public void lookupStringShouldReturnEmptyResultForPublisherDomainWhenSiteIsMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.publisherDomain); - final RequestContext context = new RequestContext(request(identity()), imp(identity()), txnLog, jacksonMapper); - - // when and then - assertThat(context.lookupString(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupStringShouldReturnReferrer() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.referrer); - final RequestContext context = new RequestContext( - request(r -> r.site(site(s -> s.page("https://domain.com/index")))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("https://domain.com/index"); - } - - @Test - public void lookupStringShouldReturnAppBundle() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.appBundle); - final RequestContext context = new RequestContext( - request(r -> r.app(app(a -> a.bundle("com.google.calendar")))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("com.google.calendar"); - } - - @Test - public void lookupStringShouldReturnEmptyResultWhenBundleIsMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.appBundle); - final RequestContext context = new RequestContext( - request(r -> r.app(app(identity()))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupStringShouldReturnEmptyResultWhenAppIsMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.appBundle); - final RequestContext context = new RequestContext( - request(identity()), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupStringShouldReturnAdslotFromTagId() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.adslot); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.tagid("/123/456")), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("/123/456"); - } - - @Test - public void lookupStringShouldReturnAdslotFromGpid() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.adslot); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(mapper.createObjectNode().set("gpid", TextNode.valueOf("/234/567")))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("/234/567"); - } - - @Test - public void lookupStringShouldReturnAdslotFromDataPbadslot() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.adslot); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(mapper.createObjectNode() - .set("data", mapper.createObjectNode().put("pbadslot", "/345/678")))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("/345/678"); - } - - @Test - public void lookupStringShouldReturnAdslotFromDataAdserverAdslot() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.adslot); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(mapper.createObjectNode() - .set("data", mapper.createObjectNode() - .set("adserver", obj("adslot", "/456/789"))))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("/456/789"); - } - - @Test - public void lookupStringShouldReturnEmptyResultWhenAdslotIsMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.adslot); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(obj("context", obj("data", mapper.createObjectNode())))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupStringShouldReturnCountryFromDeviceGeoExtValue() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.deviceGeoExt, - "vendor.attribute"); - final ExtGeo extGeo = ExtGeo.of(); - extGeo.addProperty("vendor", obj("attribute", "value")); - final RequestContext context = new RequestContext( - request(r -> r.device(device(d -> d.geo(geo(g -> g.ext(extGeo)))))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("value"); - } - - @Test - public void lookupStringShouldReturnRegionFromDeviceGeoExtValue() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.deviceGeoExt, - "vendor.nested.attribute"); - final ExtGeo extGeo = ExtGeo.of(); - extGeo.addProperty("vendor", obj("nested", obj("attribute", "value"))); - final RequestContext context = new RequestContext( - request(r -> r.device(device(d -> d.geo(geo(g -> g.ext(extGeo)))))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("value"); - } - - @Test - public void lookupStringShouldReturnMetroFromDeviceExtValue() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.deviceExt, - "vendor.attribute"); - final ExtDevice extDevice = ExtDevice.of(null, null); - extDevice.addProperty("vendor", obj("attribute", "value")); - - final RequestContext context = new RequestContext( - request(r -> r.device(device(d -> d.ext(extDevice)))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("value"); - } - - @Test - public void lookupStringShouldReturnMetroFromDeviceExtNestedValue() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.deviceExt, - "vendor.nested.attribute"); - final ExtDevice extDevice = ExtDevice.of(null, null); - extDevice.addProperty("vendor", obj("nested", obj("attribute", "value"))); - final RequestContext context = new RequestContext( - request(r -> r.device(device(d -> d.ext(extDevice)))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("value"); - } - - @Test - public void lookupStringShouldReturnSimpleBidderParam() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.bidderParam, "siteId"); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(obj("bidder", obj("siteId", "123")))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("123"); - } - - @Test - public void lookupStringShouldReturnNestedBidderParam() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.bidderParam, "inv.code"); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(obj("bidder", obj("inv", obj("code", "123"))))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("123"); - } - - @Test - public void lookupStringShouldReturnEmptyResultWhenBidderParamIsNotString() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.bidderParam, "rubicon.siteId"); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(obj("rubicon", obj("siteId", mapper.valueToTree(123))))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupStringShouldReturnEmptyResultWhenBidderParamIsMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.bidderParam, "rubicon.siteId"); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(obj("rubicon", "phony"))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupStringShouldReturnEmptyResultWhenImpExtIsMissingForBidderParam() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.bidderParam, "rubicon.siteId"); - final RequestContext context = new RequestContext( - request(identity()), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupStringShouldReturnSimpleUserFirstPartyDataFromObject() { - // given - final TargetingCategory category = new TargetingCategory( - TargetingCategory.Type.userFirstPartyData, "buyeruid"); - final RequestContext context = new RequestContext( - request(r -> r.user(user(u -> u.buyeruid("123")))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("123"); - } - - @Test - public void lookupStringShouldReturnSimpleUserFirstPartyDataFromExt() { - // given - final TargetingCategory category = new TargetingCategory( - TargetingCategory.Type.userFirstPartyData, "sport"); - final ExtUser extUser = ExtUser.builder().data(obj("sport", "hockey")).build(); - final RequestContext context = new RequestContext( - request(r -> r.user(user(u -> u.ext(extUser)))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("hockey"); - } - - @Test - public void lookupStringShouldReturnUserFirstPartyDataFromExtWhenObjectAttributeTypeIsNotString() { - // given - final TargetingCategory category = new TargetingCategory( - TargetingCategory.Type.userFirstPartyData, "yob"); - final ExtUser extUser = ExtUser.builder().data(obj("yob", "1900")).build(); - final RequestContext context = new RequestContext( - request(r -> r.user(user(u -> u.yob(1800).ext(extUser)))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("1900"); - } - - @Test - public void lookupStringShouldReturnNestedUserFirstPartyData() { - // given - final TargetingCategory category = new TargetingCategory( - TargetingCategory.Type.userFirstPartyData, "section.sport"); - final ExtUser extUser = ExtUser.builder().data(obj("section", obj("sport", "hockey"))).build(); - final RequestContext context = new RequestContext( - request(r -> r.user(user(u -> u.ext(extUser)))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("hockey"); - } - - @Test - public void lookupStringShouldReturnEmptyResultWhenUserFirstPartyDataIsNotString() { - // given - final TargetingCategory category = new TargetingCategory( - TargetingCategory.Type.userFirstPartyData, "sport"); - final ExtUser extUser = ExtUser.builder().data(obj("sport", mapper.valueToTree(123))).build(); - final RequestContext context = new RequestContext( - request(r -> r.user(user(u -> u.ext(extUser)))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupStringShouldReturnEmptyResultWhenUserExtIsMissingForUserFirstPartyData() { - // given - final TargetingCategory category = new TargetingCategory( - TargetingCategory.Type.userFirstPartyData, "sport"); - final RequestContext context = new RequestContext( - request(r -> r.user(user(identity()))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupStringShouldReturnEmptyResultWhenUserIsMissingForUserFirstPartyData() { - // given - final TargetingCategory category = new TargetingCategory( - TargetingCategory.Type.userFirstPartyData, "sport"); - final RequestContext context = new RequestContext( - request(identity()), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupStringShouldReturnSiteFirstPartyDataFromImpExt() { - // given - final TargetingCategory category = new TargetingCategory( - TargetingCategory.Type.siteFirstPartyData, "section.sport"); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(obj("context", obj("data", obj("section", obj("sport", "hockey")))))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("hockey"); - } - - @Test - public void lookupStringShouldReturnSiteFirstPartyDataFromSiteExt() { - // given - final TargetingCategory category = new TargetingCategory( - TargetingCategory.Type.siteFirstPartyData, "section.sport"); - final ExtSite extSite = ExtSite.of(null, obj("section", obj("sport", "hockey"))); - final RequestContext context = new RequestContext( - request(r -> r.site(site(s -> s.ext(extSite)))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("hockey"); - } - - @Test - public void lookupStringShouldReturnSiteFirstPartyDataFromAppExt() { - // given - final TargetingCategory category = new TargetingCategory( - TargetingCategory.Type.siteFirstPartyData, "section.sport"); - final ExtApp extApp = ExtApp.of(null, obj("section", obj("sport", "hockey"))); - final RequestContext context = new RequestContext( - request(r -> r.app(app(a -> a.ext(extApp)))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("hockey"); - } - - @Test - public void lookupStringShouldReturnSiteFirstPartyDataFromImpExtData() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.siteFirstPartyData, "sport"); - final RequestContext context = new RequestContext( - request(identity()), - imp(imp -> imp.ext(obj("data", obj("sport", "hockey")))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupString(category).getValues()).containsExactly("hockey"); - } - - @Test - public void lookupIntegerShouldReturnDowFromUserExt() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.dow); - final ExtUser extUser = ExtUser.builder().time(ExtUserTime.of(5, 15)).build(); - final RequestContext context = new RequestContext( - request(r -> r.user(user(u -> u.ext(extUser)))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupInteger(category).getValues()).containsExactly(5); - } - - @Test - public void lookupIntegerShouldReturnHourFromExt() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.hour); - final ExtUser extUser = ExtUser.builder().time(ExtUserTime.of(5, 15)).build(); - final RequestContext context = new RequestContext( - request(r -> r.user(user(u -> u.ext(extUser)))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupInteger(category).getValues()).containsExactly(15); - } - - @Test - public void lookupIntegerShouldReturnBidderParam() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.bidderParam, "siteId"); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(obj("bidder", obj("siteId", mapper.valueToTree(123))))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupInteger(category).getValues()).containsExactly(123); - } - - @Test - public void lookupIntegerShouldReturnEmptyResultWhenBidderParamIsNotInteger() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.bidderParam, "rubicon.siteId"); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(obj("rubicon", obj("siteId", mapper.valueToTree(123.456d))))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupInteger(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupIntegerShouldReturnEmptyResultWhenBidderParamIsMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.bidderParam, "rubicon.siteId"); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(obj("rubicon", "phony"))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupInteger(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupIntegerShouldReturnUserFirstPartyData() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.userFirstPartyData, "sport"); - final ExtUser extUser = ExtUser.builder().data(obj("sport", mapper.valueToTree(123))).build(); - final RequestContext context = new RequestContext( - request(r -> r.user(user(u -> u.ext(extUser)))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupInteger(category).getValues()).containsExactly(123); - } - - @Test - public void lookupIntegerShouldReturnSiteFirstPartyData() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.siteFirstPartyData, "sport"); - final ExtSite extSite = ExtSite.of(null, obj("sport", mapper.valueToTree(123))); - final RequestContext context = new RequestContext( - request(r -> r.site(site(s -> s.ext(extSite)))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupInteger(category).getValues()).containsExactly(123); - } - - @Test - public void lookupIntegerShouldReturnSiteFirstPartyDataFromImpExtData() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.siteFirstPartyData, "sport"); - final RequestContext context = new RequestContext( - request(identity()), - imp(imp -> imp.ext(obj("data", obj("sport", 1)))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupInteger(category).getValues()).containsExactly(1); - } - - @Test - public void lookupStringsShouldReturnMediaTypeBannerAndVideo() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.mediaType); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.banner(banner(identity())).video(Video.builder().build())), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupStrings(category).getValues()).containsExactly(asList("banner", "video")); - } - - @Test - public void lookupStringsShouldReturnMediaTypeVideoAndNative() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.mediaType); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.video(Video.builder().build()).xNative(Native.builder().build())), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupStrings(category).getValues()).containsExactly(asList("video", "native")); - } - - @Test - public void lookupStringsShouldReturnBidderParam() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.bidderParam, "siteId"); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(obj("bidder", obj("siteId", mapper.valueToTree(asList("123", "456")))))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupStrings(category).getValues()).containsExactly(asList("123", "456")); - } - - @Test - public void lookupStringsShouldReturnEmptyResultWhenBidderParamIsNotArray() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.bidderParam, "rubicon.siteId"); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(obj("bidder", obj("siteId", mapper.createObjectNode())))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupStrings(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupStringsShouldReturnListOfSingleStringWhenBidderParamIsString() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.bidderParam, "siteId"); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(obj("bidder", obj("siteId", "value")))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupStrings(category).getValues()).containsExactly(singletonList("value")); - } - - @Test - public void lookupStringsShouldReturnOnlyStringsWhenNonStringBidderParamPresent() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.bidderParam, "siteId"); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(obj("bidder", obj("siteId", mapper.valueToTree(asList("123", 456)))))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupStrings(category).getValues()).containsExactly(singletonList("123")); - } - - @Test - public void lookupStringsShouldReturnEmptyResultWhenBidderParamIsMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.bidderParam, "rubicon.siteId"); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(obj("bidder", obj("bidder", obj("rubicon", "phony"))))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupStrings(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupStringsShouldReturnUserFirstPartyData() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.userFirstPartyData, "buyeruid"); - final ExtUser extUser = ExtUser.builder() - .data(obj("buyeruid", mapper.valueToTree(asList("buyeruid1", "buyeruid2")))) - .build(); - final RequestContext context = new RequestContext( - request(r -> r.user(user(u -> u.buyeruid("buyeruid3").ext(extUser)))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupStrings(category).getValues()) - .containsExactly(singletonList("buyeruid3"), asList("buyeruid1", "buyeruid2")); - } - - @Test - public void lookupStringsShouldReturnSiteFirstPartyData() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.siteFirstPartyData, "sport"); - final ExtSite extSite = ExtSite.of(null, obj("sport", mapper.valueToTree(asList("123", "456")))); - final RequestContext context = new RequestContext( - request(r -> r.site(site(s -> s.ext(extSite)))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupStrings(category).getValues()).containsExactly(asList("123", "456")); - } - - @Test - public void lookupStringsShouldReturnSiteFirstPartyDataFromImpExtData() { - // given - final TargetingCategory category = new TargetingCategory( - TargetingCategory.Type.siteFirstPartyData, "sport"); - final RequestContext context = new RequestContext( - request(identity()), - imp(imp -> imp.ext(obj("data", obj("sport", mapper.valueToTree(asList("hockey", "football")))))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupStrings(category).getValues()).containsExactly(asList("hockey", "football")); - } - - @Test - public void lookupStringsShouldReturnSegmentsWithDesiredSource() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.userSegment, "rubicon"); - final RequestContext context = new RequestContext( - request(r -> r.user(user(u -> u.data(asList( - data(d -> d.id("rubicon").segment(asList(segment(s -> s.id("1")), segment(s -> s.id("2"))))), - data(d -> d.id("bluekai").segment( - asList(segment(s -> s.id("3")), segment(s -> s.id("4")))))))))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupStrings(category).getValues()).containsExactly(asList("1", "2")); - } - - @Test - public void lookupStringsShouldReturnEmptyResultWhenDesiredSourceIsMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.userSegment, "rubicon"); - final RequestContext context = new RequestContext( - request(r -> r.user(user(u -> u.data(singletonList( - data(d -> d.id("bluekai").segment( - asList(segment(s -> s.id("3")), segment(s -> s.id("4")))))))))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupStrings(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupStringsShouldSkipSegmentsWithoutIds() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.userSegment, "rubicon"); - final RequestContext context = new RequestContext( - request(r -> r.user(user(u -> u.data(singletonList( - data(d -> d.id("rubicon").segment(asList(segment(s -> s.id("1")), segment(identity()))))))))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupStrings(category).getValues()).containsExactly(singletonList("1")); - } - - @Test - public void lookupStringsShouldReturnEmptyResultWhenSegmentsAreMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.userSegment, "rubicon"); - final RequestContext context = new RequestContext( - request(r -> r.user(user(u -> u.data(singletonList(data(d -> d.id("rubicon"))))))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupStrings(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupStringsShouldTolerateMissingSource() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.userSegment, "rubicon"); - final RequestContext context = new RequestContext( - request(r -> r.user(user(u -> u.data(singletonList(data(identity())))))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupStrings(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupStringsShouldReturnEmptyResultWhenDataIsMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.userSegment, "rubicon"); - final RequestContext context = new RequestContext( - request(r -> r.user(user(identity()))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupStrings(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupStringsShouldReturnEmptyResultWhenUserIsMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.userSegment, "rubicon"); - final RequestContext context = new RequestContext( - request(identity()), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupStrings(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupIntegersShouldReturnBidderParam() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.bidderParam, "siteId"); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(obj("bidder", obj("siteId", mapper.valueToTree(asList(123, 456)))))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupIntegers(category).getValues()).containsExactly(asList(123, 456)); - } - - @Test - public void lookupIntegersShouldReturnEmptyResultWhenBidderParamIsNotArray() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.bidderParam, "rubicon.siteId"); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(obj("bidder", obj("siteId", mapper.createObjectNode())))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupIntegers(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupIntegersShouldReturnListOfSingleIntegerWhenBidderParamIsInteger() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.bidderParam, "siteId"); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(obj("bidder", obj("siteId", 123)))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupIntegers(category).getValues()).containsExactly(singletonList(123)); - } - - @Test - public void lookupIntegersShouldReturnOnlyIntegersWhenNonIntegerBidderParamPresent() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.bidderParam, "siteId"); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(obj("bidder", obj("siteId", mapper.valueToTree(asList(123, "456")))))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupIntegers(category).getValues()).containsExactly(singletonList(123)); - } - - @Test - public void lookupIntegersShouldReturnEmptyResultWhenBidderParamIsMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.bidderParam, "rubicon.siteId"); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.ext(obj("bidder", "phony"))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupIntegers(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupIntegersShouldReturnUserFirstPartyData() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.userFirstPartyData, "yob"); - final ExtUser extUser = ExtUser.builder().data(obj("yob", mapper.valueToTree(asList(123, 456)))).build(); - final RequestContext context = new RequestContext( - request(r -> r.user(user(u -> u.yob(789).ext(extUser)))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupIntegers(category).getValues()).containsExactly(singletonList(789), asList(123, 456)); - } - - @Test - public void lookupIntegersShouldReturnSiteFirstPartyData() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.siteFirstPartyData, "sport"); - final ExtSite extSite = ExtSite.of(null, obj("sport", mapper.valueToTree(asList(123, 456)))); - final RequestContext context = new RequestContext( - request(r -> r.site(site(s -> s.ext(extSite)))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupIntegers(category).getValues()).containsExactly(asList(123, 456)); - } - - @Test - public void lookupIntegersShouldReturnSiteFirstPartyDataFromImpExtData() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.siteFirstPartyData, "sport"); - final RequestContext context = new RequestContext( - request(identity()), - imp(imp -> imp.ext(obj("data", obj("sport", mapper.valueToTree(asList(1, 2)))))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupIntegers(category).getValues()).containsExactly(asList(1, 2)); - } - - @Test - public void lookupSizesShouldReturnSizes() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.size); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i - .banner(banner(b -> b.format(asList(format(300, 250), format(400, 300))))) - .video(Video.builder().w(350).h(350).build())), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupSizes(category).getValues()) - .containsExactly(asList(Size.of(300, 250), Size.of(400, 300), Size.of(350, 350))); - } - - @Test - public void lookupSizesShouldReturnEmptyResultWhenFormatIsMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.size); - final RequestContext context = new RequestContext( - request(identity()), - imp(i -> i.banner(banner(identity()))), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupSizes(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupSizesShouldReturnEmptyResultWhenBannerIsMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.size); - final RequestContext context = new RequestContext( - request(identity()), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupSizes(category)).isEqualTo(LookupResult.empty()); - } - - @Test - public void lookupSizesShouldThrowExceptionWhenUnexpectedCategory() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.domain); - final RequestContext context = new RequestContext( - request(identity()), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThatThrownBy(() -> context.lookupSizes(category)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Unexpected category for fetching sizes for: domain"); - } - - @Test - public void lookupGeoLocationShouldReturnLocation() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.location); - final RequestContext context = new RequestContext( - request(r -> r.device(device(d -> d.geo(geo(g -> g.lat(50f).lon(60f)))))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupGeoLocation(category)).isEqualTo(GeoLocation.of(50f, 60f)); - } - - @Test - public void lookupGeoLocationShouldReturnNullWhenLonIsMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.location); - final RequestContext context = new RequestContext( - request(r -> r.device(device(d -> d.geo(geo(g -> g.lat(50f)))))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupGeoLocation(category)).isNull(); - } - - @Test - public void lookupGeoLocationShouldReturnNullWhenLatIsMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.location); - final RequestContext context = new RequestContext( - request(r -> r.device(device(d -> d.geo(geo(g -> g.lon(60f)))))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupGeoLocation(category)).isNull(); - } - - @Test - public void lookupGeoLocationShouldReturnNullWhenGeoIsMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.location); - final RequestContext context = new RequestContext( - request(r -> r.device(device(identity()))), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupGeoLocation(category)).isNull(); - } - - @Test - public void lookupGeoLocationShouldReturnNullWhenDeviceIsMissing() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.location); - final RequestContext context = new RequestContext( - request(identity()), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThat(context.lookupGeoLocation(category)).isNull(); - } - - @Test - public void lookupGeoLocationShouldThrowExceptionWhenUnexpectedCategory() { - // given - final TargetingCategory category = new TargetingCategory(TargetingCategory.Type.domain); - final RequestContext context = new RequestContext( - request(identity()), - imp(identity()), - txnLog, - jacksonMapper); - - // when and then - assertThatThrownBy(() -> context.lookupGeoLocation(category)) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("Unexpected category for fetching geo location for: domain"); - } - - private static BidRequest request(Function customizer) { - return customizer.apply(BidRequest.builder()).build(); - } - - private static Site site(Function customizer) { - return customizer.apply(Site.builder()).build(); - } - - private static App app(Function customizer) { - return customizer.apply(App.builder()).build(); - } - - private static Device device(Function customizer) { - return customizer.apply(Device.builder()).build(); - } - - private static Geo geo(Function customizer) { - return customizer.apply(Geo.builder()).build(); - } - - private static User user(Function customizer) { - return customizer.apply(User.builder()).build(); - } - - private static Data data(Function customizer) { - return customizer.apply(Data.builder()).build(); - } - - private static Segment segment(Function customizer) { - return customizer.apply(Segment.builder()).build(); - } - - private static Imp imp(Function customizer) { - return customizer.apply(Imp.builder()).build(); - } - - private static Banner banner(Function customizer) { - return customizer.apply(Banner.builder()).build(); - } - - private static Format format(int w, int h) { - return Format.builder().w(w).h(h).build(); - } - - private static ObjectNode obj(String field, String value) { - return mapper.createObjectNode().put(field, value); - } - - private static ObjectNode obj(String field, Integer value) { - return mapper.createObjectNode().put(field, value); - } - - private static ObjectNode obj(String field, JsonNode value) { - return mapper.createObjectNode().set(field, value); - } -} diff --git a/src/test/java/org/prebid/server/deals/targeting/interpret/AndTest.java b/src/test/java/org/prebid/server/deals/targeting/interpret/AndTest.java deleted file mode 100644 index 0cb4b0d02cd..00000000000 --- a/src/test/java/org/prebid/server/deals/targeting/interpret/AndTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.prebid.server.deals.targeting.interpret; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.deals.targeting.RequestContext; - -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.verify; - -public class AndTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private TerminalExpression trueExpression; - @Mock - private TerminalExpression falseExpression; - @Mock - private RequestContext context; - - @Before - public void setUp() { - given(trueExpression.matches(any())).willReturn(true); - given(falseExpression.matches(any())).willReturn(false); - } - - @Test - public void matchesShouldReturnTrue() { - assertThat(new And(asList(trueExpression, trueExpression, trueExpression)).matches(context)).isTrue(); - } - - @Test - public void matchesShouldReturnFalse() { - assertThat(new And(asList(falseExpression, falseExpression, falseExpression)).matches(context)).isFalse(); - } - - @Test - public void matchesShouldReturnFalseAndNotEvaluateRemainingExpressions() { - assertThat(new And(asList(trueExpression, falseExpression, trueExpression)).matches(context)).isFalse(); - - verify(trueExpression).matches(context); - verify(falseExpression).matches(context); - } -} diff --git a/src/test/java/org/prebid/server/deals/targeting/interpret/InIntegersTest.java b/src/test/java/org/prebid/server/deals/targeting/interpret/InIntegersTest.java deleted file mode 100644 index 805060bd30d..00000000000 --- a/src/test/java/org/prebid/server/deals/targeting/interpret/InIntegersTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.prebid.server.deals.targeting.interpret; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.deals.targeting.RequestContext; -import org.prebid.server.deals.targeting.model.LookupResult; -import org.prebid.server.deals.targeting.syntax.TargetingCategory; - -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.willReturn; -import static org.mockito.Mockito.verify; - -public class InIntegersTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private RequestContext context; - - private Expression expression; - private TargetingCategory category; - - @Before - public void setUp() { - // given - category = new TargetingCategory(TargetingCategory.Type.pagePosition); - expression = new InIntegers(category, asList(1, 2, 3)); - } - - @Test - public void matchesShouldReturnTrueWhenThereIsMatch() { - // given - willReturn(LookupResult.ofValue(2)).given(context).lookupInteger(any()); - - // when and then - assertThat(expression.matches(context)).isTrue(); - verify(context).lookupInteger(eq(category)); - } - - @Test - public void matchesShouldReturnFalseWhenThereIsNoMatch() { - // given - willReturn(LookupResult.ofValue(4)).given(context).lookupInteger(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } - - @Test - public void matchesShouldReturnFalseWhenActualValueIsMissing() { - // given - willReturn(LookupResult.empty()).given(context).lookupInteger(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } -} diff --git a/src/test/java/org/prebid/server/deals/targeting/interpret/InStringsTest.java b/src/test/java/org/prebid/server/deals/targeting/interpret/InStringsTest.java deleted file mode 100644 index abad9a83326..00000000000 --- a/src/test/java/org/prebid/server/deals/targeting/interpret/InStringsTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.prebid.server.deals.targeting.interpret; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.deals.targeting.RequestContext; -import org.prebid.server.deals.targeting.model.LookupResult; -import org.prebid.server.deals.targeting.syntax.TargetingCategory; - -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.willReturn; -import static org.mockito.Mockito.verify; - -public class InStringsTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private RequestContext context; - - private Expression expression; - private TargetingCategory category; - - @Before - public void setUp() { - // given - category = new TargetingCategory(TargetingCategory.Type.referrer); - expression = new InStrings(category, asList("Munich", "Berlin", "Stuttgart", "123")); - } - - @Test - public void matchesShouldReturnTrueWhenThereIsMatch() { - // given - willReturn(LookupResult.ofValue("Berlin")).given(context).lookupString(any()); - - // when and then - assertThat(expression.matches(context)).isTrue(); - verify(context).lookupString(eq(category)); - } - - @Test - public void matchesShouldReturnFalseWhenThereIsNoMatch() { - // given - willReturn(LookupResult.ofValue("Ingolstadt")).given(context).lookupString(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } - - @Test - public void matchesShouldPerformCaseInsensitiveComparison() { - // given - willReturn(LookupResult.ofValue("BERLIN")).given(context).lookupString(any()); - - // when and then - assertThat(expression.matches(context)).isTrue(); - } - - @Test - public void matchesShouldReturnFalseWhenActualValueIsMissing() { - // given - willReturn(LookupResult.empty()).given(context).lookupString(any()); - willReturn(LookupResult.empty()).given(context).lookupInteger(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } - - @Test - public void matchesShouldReturnTrueWhenActualValueIsInteger() { - // given - willReturn(LookupResult.empty()).given(context).lookupString(any()); - willReturn(LookupResult.ofValue(123)).given(context).lookupInteger(any()); - - // when and then - assertThat(expression.matches(context)).isTrue(); - } -} diff --git a/src/test/java/org/prebid/server/deals/targeting/interpret/IntersectsIntegersTest.java b/src/test/java/org/prebid/server/deals/targeting/interpret/IntersectsIntegersTest.java deleted file mode 100644 index 56ec56d1de2..00000000000 --- a/src/test/java/org/prebid/server/deals/targeting/interpret/IntersectsIntegersTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.prebid.server.deals.targeting.interpret; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.deals.targeting.RequestContext; -import org.prebid.server.deals.targeting.model.LookupResult; -import org.prebid.server.deals.targeting.syntax.TargetingCategory; - -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.willReturn; -import static org.mockito.Mockito.verify; - -public class IntersectsIntegersTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private RequestContext context; - - private Expression expression; - private TargetingCategory category; - - @Before - public void setUp() { - // given - category = TargetingCategory.fromString("bidp.rubicon.invCodes"); - expression = new IntersectsIntegers(category, asList(1, 2, 3)); - } - - @Test - public void matchesShouldReturnTrueWhenThereIsMatch() { - // given - willReturn(LookupResult.ofValue(asList(2, 3, 4))).given(context).lookupIntegers(any()); - - // when and then - assertThat(expression.matches(context)).isTrue(); - verify(context).lookupIntegers(eq(category)); - } - - @Test - public void matchesShouldReturnFalseWhenThereIsNoMatch() { - // given - willReturn(LookupResult.ofValue(asList(4, 5))).given(context).lookupIntegers(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } - - @Test - public void matchesShouldReturnFalseWhenActualValueIsMissing() { - // given - willReturn(LookupResult.empty()).given(context).lookupIntegers(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } - - @Test - public void matchesShouldReturnFalseWhenActualValueIsNotDefined() { - // given - willReturn(LookupResult.empty()).given(context).lookupIntegers(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } -} diff --git a/src/test/java/org/prebid/server/deals/targeting/interpret/IntersectsSizesTest.java b/src/test/java/org/prebid/server/deals/targeting/interpret/IntersectsSizesTest.java deleted file mode 100644 index 236c8a9f3eb..00000000000 --- a/src/test/java/org/prebid/server/deals/targeting/interpret/IntersectsSizesTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.prebid.server.deals.targeting.interpret; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.deals.targeting.RequestContext; -import org.prebid.server.deals.targeting.model.LookupResult; -import org.prebid.server.deals.targeting.model.Size; -import org.prebid.server.deals.targeting.syntax.TargetingCategory; - -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.willReturn; -import static org.mockito.Mockito.verify; - -public class IntersectsSizesTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private RequestContext context; - - private Expression expression; - private TargetingCategory category; - - @Before - public void setUp() { - // given - category = TargetingCategory.fromString("adunit.size"); - expression = new IntersectsSizes(category, asList(Size.of(250, 300), Size.of(300, 350), Size.of(350, 400))); - } - - @Test - public void matchesShouldReturnTrueWhenThereIsMatch() { - // given - willReturn(LookupResult.ofValue(asList(Size.of(300, 350), Size.of(350, 400), Size.of(450, 500)))) - .given(context).lookupSizes(any()); - - // when and then - assertThat(expression.matches(context)).isTrue(); - verify(context).lookupSizes(eq(category)); - } - - @Test - public void matchesShouldReturnFalseWhenThereIsNoMatch() { - // given - willReturn(LookupResult.ofValue(asList(Size.of(450, 500), Size.of(500, 550)))) - .given(context).lookupSizes(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } - - @Test - public void matchesShouldReturnFalseWhenActualValueIsMissing() { - // given - willReturn(LookupResult.empty()).given(context).lookupSizes(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } - - @Test - public void matchesShouldReturnFalseWhenActualValueIsNotDefined() { - // given - willReturn(LookupResult.empty()).given(context).lookupSizes(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } -} diff --git a/src/test/java/org/prebid/server/deals/targeting/interpret/IntersectsStringsTest.java b/src/test/java/org/prebid/server/deals/targeting/interpret/IntersectsStringsTest.java deleted file mode 100644 index d41ddd4db9d..00000000000 --- a/src/test/java/org/prebid/server/deals/targeting/interpret/IntersectsStringsTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.prebid.server.deals.targeting.interpret; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.deals.targeting.RequestContext; -import org.prebid.server.deals.targeting.model.LookupResult; -import org.prebid.server.deals.targeting.syntax.TargetingCategory; - -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.willReturn; -import static org.mockito.Mockito.verify; - -public class IntersectsStringsTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private RequestContext context; - - private Expression expression; - private TargetingCategory category; - - @Before - public void setUp() { - // given - category = TargetingCategory.fromString("adunit.mediatype"); - expression = new IntersectsStrings(category, asList("Pop", "Rock", "Alternative")); - } - - @Test - public void matchesShouldReturnTrueWhenThereIsMatch() { - // given - willReturn(LookupResult.ofValue(asList("Rock", "Alternative", "Folk"))).given(context).lookupStrings(any()); - - // when and then - assertThat(expression.matches(context)).isTrue(); - verify(context).lookupStrings(eq(category)); - } - - @Test - public void matchesShouldReturnFalseWhenThereIsNoMatch() { - // given - willReturn(LookupResult.ofValue(asList("Folk", "Trance"))).given(context).lookupStrings(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } - - @Test - public void matchesShouldPerformCaseInsensitiveComparison() { - // given - willReturn(LookupResult.ofValue(asList("ROCK", "ALTERNATIVE", "FOLK"))).given(context).lookupStrings(any()); - - // when and then - assertThat(expression.matches(context)).isTrue(); - } - - @Test - public void matchesShouldReturnFalseWhenActualValueIsMissing() { - // given - willReturn(LookupResult.empty()).given(context).lookupStrings(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } - - @Test - public void matchesShouldReturnFalseWhenActualValueIsNotDefined() { - // given - willReturn(LookupResult.empty()).given(context).lookupStrings(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } -} diff --git a/src/test/java/org/prebid/server/deals/targeting/interpret/MatchesTest.java b/src/test/java/org/prebid/server/deals/targeting/interpret/MatchesTest.java deleted file mode 100644 index c4fbab9a98b..00000000000 --- a/src/test/java/org/prebid/server/deals/targeting/interpret/MatchesTest.java +++ /dev/null @@ -1,168 +0,0 @@ -package org.prebid.server.deals.targeting.interpret; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.deals.targeting.RequestContext; -import org.prebid.server.deals.targeting.model.LookupResult; -import org.prebid.server.deals.targeting.syntax.TargetingCategory; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.willReturn; -import static org.mockito.Mockito.verify; - -public class MatchesTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private RequestContext context; - - private Expression expression; - private TargetingCategory category; - - @Before - public void setUp() { - // given - category = TargetingCategory.fromString("adunit.adslot"); - } - - @Test - public void matchesShouldReturnTrueWhenThereIsMatchForEquals() { - // given - expression = new Matches(category, "adunit"); - - willReturn(LookupResult.ofValue("adunit")).given(context).lookupString(any()); - - // when and then - assertThat(expression.matches(context)).isTrue(); - verify(context).lookupString(eq(category)); - } - - @Test - public void matchesShouldReturnFalseWhenThereIsNoMatchForEquals() { - // given - expression = new Matches(category, "adunit"); - - willReturn(LookupResult.ofValue("notadunit")).given(context).lookupString(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } - - @Test - public void matchesShouldReturnTrueWhenThereIsMatchForStartsWith() { - // given - expression = new Matches(category, "adunit*"); - - willReturn(LookupResult.ofValue("adunitOne")).given(context).lookupString(any()); - - // when and then - assertThat(expression.matches(context)).isTrue(); - } - - @Test - public void matchesShouldReturnFalseWhenThereIsNoMatchForStartsWith() { - // given - expression = new Matches(category, "adunit"); - - willReturn(LookupResult.ofValue("somedunit")).given(context).lookupString(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } - - @Test - public void matchesShouldReturnTrueWhenThereIsMatchForEndsWith() { - // given - expression = new Matches(category, "*adunit"); - - willReturn(LookupResult.ofValue("someadunit")).given(context).lookupString(any()); - - // when and then - assertThat(expression.matches(context)).isTrue(); - } - - @Test - public void matchesShouldReturnFalseWhenThereIsNoMatchForEndsWith() { - // given - expression = new Matches(category, "*adunit"); - - willReturn(LookupResult.ofValue("adunitOne")).given(context).lookupString(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } - - @Test - public void matchesShouldReturnTrueWhenThereIsMatchForContainsInTheMiddle() { - // given - expression = new Matches(category, "*adunit*"); - - willReturn(LookupResult.ofValue("someadunitOne")).given(context).lookupString(any()); - - // when and then - assertThat(expression.matches(context)).isTrue(); - } - - @Test - public void matchesShouldReturnTrueWhenThereIsMatchForContainsInTheBeginning() { - // given - expression = new Matches(category, "*adunit*"); - - willReturn(LookupResult.ofValue("adunitOne")).given(context).lookupString(any()); - - // when and then - assertThat(expression.matches(context)).isTrue(); - } - - @Test - public void matchesShouldReturnTrueWhenThereIsMatchForContainsInTheEnd() { - // given - expression = new Matches(category, "*adunit*"); - - willReturn(LookupResult.ofValue("someadunit")).given(context).lookupString(any()); - - // when and then - assertThat(expression.matches(context)).isTrue(); - } - - @Test - public void matchesShouldReturnFalseWhenThereIsNoMatchForContains() { - // given - expression = new Matches(category, "*adunit*"); - - willReturn(LookupResult.ofValue("One")).given(context).lookupString(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } - - @Test - public void matchesShouldPerformCaseInsensitiveComparison() { - // given - expression = new Matches(category, "AdUnIt"); - - willReturn(LookupResult.ofValue("aDuNiT")).given(context).lookupString(any()); - - // when and then - assertThat(expression.matches(context)).isTrue(); - } - - @Test - public void matchesShouldReturnFalseWhenActualValueIsMissing() { - // given - expression = new Matches(category, "adunit"); - - willReturn(LookupResult.empty()).given(context).lookupString(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } -} diff --git a/src/test/java/org/prebid/server/deals/targeting/interpret/NotTest.java b/src/test/java/org/prebid/server/deals/targeting/interpret/NotTest.java deleted file mode 100644 index ef1fec7e66f..00000000000 --- a/src/test/java/org/prebid/server/deals/targeting/interpret/NotTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.prebid.server.deals.targeting.interpret; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.deals.targeting.RequestContext; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.BDDMockito.given; - -public class NotTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private TerminalExpression trueExpression; - @Mock - private TerminalExpression falseExpression; - @Mock - private RequestContext context; - - @Before - public void setUp() { - given(trueExpression.matches(any())).willReturn(true); - given(falseExpression.matches(any())).willReturn(false); - } - - @Test - public void matchesShouldReturnTrue() { - assertThat(new Not(trueExpression).matches(context)).isFalse(); - } - - @Test - public void matchesShouldReturnFalse() { - assertThat(new Not(falseExpression).matches(context)).isTrue(); - } -} diff --git a/src/test/java/org/prebid/server/deals/targeting/interpret/OrTest.java b/src/test/java/org/prebid/server/deals/targeting/interpret/OrTest.java deleted file mode 100644 index f677fd09da4..00000000000 --- a/src/test/java/org/prebid/server/deals/targeting/interpret/OrTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.prebid.server.deals.targeting.interpret; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.deals.targeting.RequestContext; - -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.verify; - -public class OrTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private TerminalExpression trueExpression; - @Mock - private TerminalExpression falseExpression; - @Mock - private RequestContext context; - - @Before - public void setUp() { - given(trueExpression.matches(any())).willReturn(true); - given(falseExpression.matches(any())).willReturn(false); - } - - @Test - public void matchesShouldReturnTrue() { - assertThat(new Or(asList(trueExpression, trueExpression, trueExpression)).matches(context)).isTrue(); - } - - @Test - public void matchesShouldReturnFalse() { - assertThat(new Or(asList(falseExpression, falseExpression, falseExpression)).matches(context)).isFalse(); - } - - @Test - public void matchesShouldReturnTrueAndNotEvaluateRemainingExpressions() { - assertThat(new Or(asList(falseExpression, trueExpression, falseExpression)).matches(context)).isTrue(); - - verify(falseExpression).matches(context); - verify(trueExpression).matches(context); - } -} diff --git a/src/test/java/org/prebid/server/deals/targeting/interpret/WithinTest.java b/src/test/java/org/prebid/server/deals/targeting/interpret/WithinTest.java deleted file mode 100644 index c6dccf1e537..00000000000 --- a/src/test/java/org/prebid/server/deals/targeting/interpret/WithinTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.prebid.server.deals.targeting.interpret; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.deals.targeting.RequestContext; -import org.prebid.server.deals.targeting.model.GeoLocation; -import org.prebid.server.deals.targeting.model.GeoRegion; -import org.prebid.server.deals.targeting.syntax.TargetingCategory; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.willReturn; -import static org.mockito.Mockito.verify; - -public class WithinTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private RequestContext context; - - private Expression expression; - private TargetingCategory category; - - @Before - public void setUp() { - // given - category = new TargetingCategory(TargetingCategory.Type.location); - expression = new Within(category, GeoRegion.of(50.424782f, 30.506423f, 10f)); - } - - @Test - public void matchesShouldReturnTrueWhenThereIsMatch() { - // given - willReturn(GeoLocation.of(50.442406f, 30.521439f)).given(context).lookupGeoLocation(any()); - - // when and then - assertThat(expression.matches(context)).isTrue(); - verify(context).lookupGeoLocation(eq(category)); - } - - @Test - public void matchesShouldReturnFalseWhenThereIsNoMatch() { - // given - willReturn(GeoLocation.of(50.588196f, 30.512357f)).given(context).lookupGeoLocation(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } - - @Test - public void matchesShouldReturnFalseWhenActualValueIsMissing() { - // given - willReturn(null).given(context).lookupGeoLocation(any()); - - // when and then - assertThat(expression.matches(context)).isFalse(); - } -} diff --git a/src/test/java/org/prebid/server/deals/targeting/syntax/BooleanOperatorTest.java b/src/test/java/org/prebid/server/deals/targeting/syntax/BooleanOperatorTest.java deleted file mode 100644 index bfc03545845..00000000000 --- a/src/test/java/org/prebid/server/deals/targeting/syntax/BooleanOperatorTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.prebid.server.deals.targeting.syntax; - -import org.assertj.core.api.SoftAssertions; -import org.junit.Test; - -import java.util.EnumMap; -import java.util.Map; - -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class BooleanOperatorTest { - - @Test - public void isBooleanOperatorShouldReturnTrueForKnownFunctions() { - SoftAssertions.assertSoftly(softly -> { - for (final String functionString : asList("$and", "$or", "$not")) { - softly.assertThat(BooleanOperator.isBooleanOperator(functionString)).isTrue(); - } - }); - } - - @Test - public void isBooleanOperatorShouldReturnFalseForUnknownFunctions() { - assertThat(BooleanOperator.isBooleanOperator("unknown")).isFalse(); - } - - @Test - public void fromStringShouldReturnEnumValue() { - // given - final EnumMap enumToString = new EnumMap<>(BooleanOperator.class); - enumToString.put(BooleanOperator.AND, "$and"); - enumToString.put(BooleanOperator.OR, "$or"); - enumToString.put(BooleanOperator.NOT, "$not"); - - // when and then - SoftAssertions.assertSoftly(softly -> { - for (final Map.Entry entry : enumToString.entrySet()) { - softly.assertThat(BooleanOperator.fromString(entry.getValue())).isEqualTo(entry.getKey()); - } - }); - } - - @Test - public void fromStringShouldThrowExceptionWhenUnkownFunction() { - assertThatThrownBy(() -> BooleanOperator.fromString("unknown")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Unrecognized boolean operator: unknown"); - } -} diff --git a/src/test/java/org/prebid/server/deals/targeting/syntax/MatchingFunctionTest.java b/src/test/java/org/prebid/server/deals/targeting/syntax/MatchingFunctionTest.java deleted file mode 100644 index 748ffd3289c..00000000000 --- a/src/test/java/org/prebid/server/deals/targeting/syntax/MatchingFunctionTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.prebid.server.deals.targeting.syntax; - -import org.assertj.core.api.SoftAssertions; -import org.junit.Test; - -import java.util.EnumMap; -import java.util.Map; - -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class MatchingFunctionTest { - - @Test - public void isMatchingFunctionShouldReturnTrueForKnownFunctions() { - SoftAssertions.assertSoftly(softly -> { - for (final String functionString : asList("$matches", "$in", "$intersects", "$within")) { - softly.assertThat(MatchingFunction.isMatchingFunction(functionString)).isTrue(); - } - }); - } - - @Test - public void isMatchingFunctionShouldReturnFalseForUnknownFunctions() { - assertThat(MatchingFunction.isMatchingFunction("unknown")).isFalse(); - } - - @Test - public void fromStringShouldReturnEnumValue() { - // given - final EnumMap enumToString = new EnumMap<>(MatchingFunction.class); - enumToString.put(MatchingFunction.MATCHES, "$matches"); - enumToString.put(MatchingFunction.IN, "$in"); - enumToString.put(MatchingFunction.INTERSECTS, "$intersects"); - enumToString.put(MatchingFunction.WITHIN, "$within"); - - // when and then - SoftAssertions.assertSoftly(softly -> { - for (final Map.Entry entry : enumToString.entrySet()) { - softly.assertThat(MatchingFunction.fromString(entry.getValue())).isEqualTo(entry.getKey()); - } - }); - } - - @Test - public void fromStringShouldThrowExceptionWhenUnkownFunction() { - assertThatThrownBy(() -> MatchingFunction.fromString("unknown")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Unrecognized matching function: unknown"); - } -} diff --git a/src/test/java/org/prebid/server/deals/targeting/syntax/TargetingCategoryTest.java b/src/test/java/org/prebid/server/deals/targeting/syntax/TargetingCategoryTest.java deleted file mode 100644 index 8b75e609ed5..00000000000 --- a/src/test/java/org/prebid/server/deals/targeting/syntax/TargetingCategoryTest.java +++ /dev/null @@ -1,121 +0,0 @@ -package org.prebid.server.deals.targeting.syntax; - -import org.assertj.core.api.AutoCloseableSoftAssertions; -import org.junit.Test; -import org.prebid.server.exception.TargetingSyntaxException; - -import java.util.List; - -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class TargetingCategoryTest { - - @Test - public void isTargetingCategoryShouldReturnTrueForKnownCategories() { - final List categories = asList( - "adunit.size", - "adunit.mediatype", - "adunit.adslot", - "site.domain", - "site.publisher.domain", - "site.referrer", - "app.bundle", - "device.geo.ext.vendor.attribute", - "device.geo.ext.vendor.nested.attribute", - "device.ext.vendor.attribute", - "device.ext.vendor.nested.attribute", - "pos", - "geo.distance", - "segment.bluekai", - "user.ext.time.userdow", - "user.ext.time.userhour", - "bidp.rubicon.siteId", - "ufpd.sport", - "sfpd.sport"); - - try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) { - categories.forEach(categoryString -> - softly.assertThat(TargetingCategory.isTargetingCategory(categoryString)).isTrue()); - } - } - - @Test - public void isTargetingCategoryShouldReturnFalseForUnknownCategory() { - assertThat(TargetingCategory.isTargetingCategory("phony")).isFalse(); - } - - @Test - public void fromStringShouldReturnCategoryWithoutPathForStaticTypes() { - final List categories = asList( - "adunit.size", - "adunit.mediatype", - "adunit.adslot", - "site.domain", - "site.publisher.domain", - "site.referrer", - "app.bundle", - "pos", - "geo.distance", - "user.ext.time.userdow", - "user.ext.time.userhour"); - - try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) { - for (final String categoryString : categories) { - final TargetingCategory category = TargetingCategory.fromString(categoryString); - softly.assertThat(category.type()).isEqualTo(TargetingCategory.Type.fromString(categoryString)); - softly.assertThat(category.path()).isNull(); - } - } - } - - @Test - public void fromStringShouldReturnCategoryWithPathForDynamicTypes() { - // when - final TargetingCategory bidderParamCategory = TargetingCategory.fromString("bidp.rubicon.siteId"); - // then - assertThat(bidderParamCategory.type()).isEqualTo(TargetingCategory.Type.bidderParam); - assertThat(bidderParamCategory.path()).isEqualTo("siteId"); - - // when - final TargetingCategory userSegmentCategory = TargetingCategory.fromString("segment.bluekai"); - // then - assertThat(userSegmentCategory.type()).isEqualTo(TargetingCategory.Type.userSegment); - assertThat(userSegmentCategory.path()).isEqualTo("bluekai"); - - // when - final TargetingCategory userFirstPartyDataCategory = TargetingCategory.fromString("ufpd.sport"); - // then - assertThat(userFirstPartyDataCategory.type()).isEqualTo(TargetingCategory.Type.userFirstPartyData); - assertThat(userFirstPartyDataCategory.path()).isEqualTo("sport"); - - // when - final TargetingCategory siteFirstPartyDataCategory = TargetingCategory.fromString("sfpd.sport"); - // then - assertThat(siteFirstPartyDataCategory.type()).isEqualTo(TargetingCategory.Type.siteFirstPartyData); - assertThat(siteFirstPartyDataCategory.path()).isEqualTo("sport"); - } - - @Test - public void fromStringShouldThrowExceptionWhenCategoryIsUnknown() { - assertThatThrownBy(() -> TargetingCategory.fromString("unknown")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Unrecognized targeting category: unknown"); - } - - @Test - public void fromStringShouldThrowExceptionWhenBidderParamIsIncorrect() { - assertThatThrownBy(() -> TargetingCategory.fromString("bidp.rubicon")) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("BidderParam path is incorrect: rubicon"); - - assertThatThrownBy(() -> TargetingCategory.fromString("bidp.rubicon.")) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("BidderParam path is incorrect: rubicon."); - - assertThatThrownBy(() -> TargetingCategory.fromString("bidp.rubicon.siteId.")) - .isInstanceOf(TargetingSyntaxException.class) - .hasMessage("BidderParam path is incorrect: rubicon.siteId."); - } -} diff --git a/src/test/java/org/prebid/server/events/EventUtilTest.java b/src/test/java/org/prebid/server/events/EventUtilTest.java index 59a8b1044aa..12fe4381fe0 100644 --- a/src/test/java/org/prebid/server/events/EventUtilTest.java +++ b/src/test/java/org/prebid/server/events/EventUtilTest.java @@ -216,8 +216,7 @@ public void fromShouldReturnExpectedEventRequest() { .add("b", "bidId") .add("ts", "1000") .add("f", "i") - .add("x", "0") - .add("l", "lineItemId")); + .add("x", "0")); // when final EventRequest result = EventUtil.from(routingContext); @@ -231,7 +230,6 @@ public void fromShouldReturnExpectedEventRequest() { .timestamp(1000L) .format(EventRequest.Format.image) .analytics(EventRequest.Analytics.disabled) - .lineItemId("lineItemId") .build()); } @@ -273,7 +271,6 @@ public void toUrlShouldReturnExpectedUrl() { .integration("pbjs") .analytics(EventRequest.Analytics.enabled) .timestamp(1000L) - .lineItemId("lineItemId") .build(); // when @@ -282,12 +279,11 @@ public void toUrlShouldReturnExpectedUrl() { // then assertThat(result).isEqualTo( "http://external-url/event?t=win&b=bidId&a=accountId" - + "&aid=auctionId&ts=1000&bidder=bidder&f=b&int=pbjs&x=1" - + "&l=lineItemId"); + + "&aid=auctionId&ts=1000&bidder=bidder&f=b&int=pbjs&x=1"); } @Test - public void toUrlShouldReturnExpectedUrlWithoutFormatAndAnalyticsAndLineItemId() { + public void toUrlShouldReturnExpectedUrlWithoutFormatAndAnalytics() { // given final EventRequest eventRequest = EventRequest.builder() .type(EventRequest.Type.win) diff --git a/src/test/java/org/prebid/server/events/EventsServiceTest.java b/src/test/java/org/prebid/server/events/EventsServiceTest.java index 6ebab3978e6..d423044670a 100644 --- a/src/test/java/org/prebid/server/events/EventsServiceTest.java +++ b/src/test/java/org/prebid/server/events/EventsServiceTest.java @@ -30,30 +30,12 @@ public void createEventsShouldReturnExpectedEvent() { .build(); // when - final Events events = eventsService.createEvent("bidId", "bidder", "accountId", "lineItemId", true, - eventsContext); + final Events events = eventsService.createEvent("bidId", "bidder", "accountId", true, eventsContext); // then assertThat(events).isEqualTo(Events.of( - "http://external-url/event?t=win&b=bidId&a=accountId&aid=auctionId&ts=1000&bidder=bidder&f=i&int=pbjs&l=lineItemId", - "http://external-url/event?t=imp&b=bidId&a=accountId&aid=auctionId&ts=1000&bidder=bidder&f=i&int=pbjs&l=lineItemId")); - } - - @Test - public void createEventsShouldSkipLineItemIdIfMissing() { - // given - final EventsContext eventsContext = EventsContext.builder().auctionId("auctionId").integration( - "pbjs").auctionTimestamp(1000L).build(); - - // when - final Events events = eventsService.createEvent("bidId", "bidder", "accountId", null, true, eventsContext); - - // then - assertThat(events).isEqualTo(Events.of( - "http://external-url/event?t=win&b=bidId&a=accountId" - + "&aid=auctionId&ts=1000&bidder=bidder&f=i&int=pbjs", - "http://external-url/event?t=imp&b=bidId&a=accountId" - + "&aid=auctionId&ts=1000&bidder=bidder&f=i&int=pbjs")); + "http://external-url/event?t=win&b=bidId&a=accountId&aid=auctionId&ts=1000&bidder=bidder&f=i&int=pbjs", + "http://external-url/event?t=imp&b=bidId&a=accountId&aid=auctionId&ts=1000&bidder=bidder&f=i&int=pbjs")); } @Test @@ -62,15 +44,12 @@ public void createEventsShouldSetAnalyticsDisabled() { final EventsContext eventsContext = EventsContext.builder().integration("pbjs").auctionTimestamp(1000L).build(); // when - final Events events = eventsService.createEvent("bidId", "bidder", "accountId", "lineItemId", false, - eventsContext); + final Events events = eventsService.createEvent("bidId", "bidder", "accountId", false, eventsContext); // then assertThat(events).isEqualTo(Events.of( - "http://external-url/event?t=win&b=bidId&a=accountId&ts=1000&bidder=bidder&f=i&int=pbjs&x=0" - + "&l=lineItemId", - "http://external-url/event?t=imp&b=bidId&a=accountId&ts=1000&bidder=bidder&f=i&int=pbjs&x=0" - + "&l=lineItemId")); + "http://external-url/event?t=win&b=bidId&a=accountId&ts=1000&bidder=bidder&f=i&int=pbjs&x=0", + "http://external-url/event?t=imp&b=bidId&a=accountId&ts=1000&bidder=bidder&f=i&int=pbjs&x=0")); } @Test @@ -79,11 +58,11 @@ public void winUrlShouldReturnExpectedUrl() { final EventsContext eventsContext = EventsContext.builder().integration("pbjs").auctionTimestamp(1000L).build(); // when - final String winUrl = eventsService.winUrl("bidId", "bidder", "accountId", "lineItemId", true, eventsContext); + final String winUrl = eventsService.winUrl("bidId", "bidder", "accountId", true, eventsContext); // then assertThat(winUrl).isEqualTo( - "http://external-url/event?t=win&b=bidId&a=accountId&ts=1000&bidder=bidder&f=i&int=pbjs&l=lineItemId"); + "http://external-url/event?t=win&b=bidId&a=accountId&ts=1000&bidder=bidder&f=i&int=pbjs"); } @Test @@ -92,12 +71,11 @@ public void winUrlShouldSEtAnalyticsDisabled() { final EventsContext eventsContext = EventsContext.builder().integration("pbjs").auctionTimestamp(1000L).build(); // when - final String winUrl = eventsService.winUrl("bidId", "bidder", "accountId", "lineItemId", false, eventsContext); + final String winUrl = eventsService.winUrl("bidId", "bidder", "accountId", false, eventsContext); // then assertThat(winUrl).isEqualTo( - "http://external-url/event?t=win&b=bidId&a=accountId&ts=1000&bidder=bidder&f=i&int=pbjs&x=0" - + "&l=lineItemId"); + "http://external-url/event?t=win&b=bidId&a=accountId&ts=1000&bidder=bidder&f=i&int=pbjs&x=0"); } @Test @@ -109,11 +87,10 @@ public void vastUrlShouldReturnExpectedUrl() { .build(); // when - final String vastUrl = eventsService.vastUrlTracking("bidId", "bidder", "accountId", "lineItemId", - eventsContext); + final String vastUrl = eventsService.vastUrlTracking("bidId", "bidder", "accountId", eventsContext); // then assertThat(vastUrl).isEqualTo( - "http://external-url/event?t=imp&b=bidId&a=accountId&aid=auctionId&ts=1000&bidder=bidder&f=b&int=pbjs&l=lineItemId"); + "http://external-url/event?t=imp&b=bidId&a=accountId&aid=auctionId&ts=1000&bidder=bidder&f=b&int=pbjs"); } } diff --git a/src/test/java/org/prebid/server/execution/TimeoutTest.java b/src/test/java/org/prebid/server/execution/TimeoutTest.java index 69aa867d1cc..1f1f3048752 100644 --- a/src/test/java/org/prebid/server/execution/TimeoutTest.java +++ b/src/test/java/org/prebid/server/execution/TimeoutTest.java @@ -10,17 +10,6 @@ public class TimeoutTest { - @Test - public void minusShouldReturnTimeoutReducedBySpecifiedAmount() { - // given - final Instant now = Instant.now(); - final Timeout timeout = - new Timeout(Clock.fixed(now, ZoneId.systemDefault()), now.plusMillis(1000L).toEpochMilli()); - - // when and then - assertThat(timeout.minus(500L).remaining()).isEqualTo(500L); - } - @Test public void remainingShouldReturnZeroIfTimeoutAlreadyExpired() { // given diff --git a/src/test/java/org/prebid/server/handler/DealsStatusHandlerTest.java b/src/test/java/org/prebid/server/handler/DealsStatusHandlerTest.java deleted file mode 100644 index 68e4a2fed66..00000000000 --- a/src/test/java/org/prebid/server/handler/DealsStatusHandlerTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package org.prebid.server.handler; - -import io.netty.handler.codec.http.HttpHeaderValues; -import io.vertx.core.http.HttpServerResponse; -import io.vertx.ext.web.RoutingContext; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.VertxTest; -import org.prebid.server.deals.DeliveryProgressService; -import org.prebid.server.deals.proto.report.DeliveryProgressReport; -import org.prebid.server.util.HttpUtil; - -import java.io.IOException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - -public class DealsStatusHandlerTest extends VertxTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - private DealsStatusHandler dealsStatusHandler; - - @Mock - private DeliveryProgressService deliveryProgressService; - - @Mock - private RoutingContext routingContext; - - @Mock - private HttpServerResponse httpServerResponse; - - @Before - public void setUp() { - dealsStatusHandler = new DealsStatusHandler(deliveryProgressService, jacksonMapper); - given(routingContext.response()).willReturn(httpServerResponse); - given(httpServerResponse.putHeader(any(CharSequence.class), any(CharSequence.class))) - .willReturn(httpServerResponse); - given(httpServerResponse.closed()).willReturn(false); - given(httpServerResponse.exceptionHandler(any())).willReturn(httpServerResponse); - } - - @Test - public void handleShouldNotSendDeliveryProgressReportWhenClientHasGone() { - // given - given(httpServerResponse.closed()).willReturn(true); - - // when - dealsStatusHandler.handle(routingContext); - - // then - verify(httpServerResponse, never()).end(); - } - - @Test - public void handleShouldReturnDeliveryProgressReport() throws IOException { - // given - given(deliveryProgressService.getOverallDeliveryProgressReport()) - .willReturn(DeliveryProgressReport.builder().reportId("reportId").build()); - - // when - dealsStatusHandler.handle(routingContext); - - // then - final String responseBody = getResponseBody(); - verify(httpServerResponse).putHeader(eq(HttpUtil.CONTENT_TYPE_HEADER), eq(HttpHeaderValues.APPLICATION_JSON)); - assertThat(mapper.readValue(responseBody, DeliveryProgressReport.class)) - .isEqualTo(DeliveryProgressReport.builder().reportId("reportId").build()); - } - - private String getResponseBody() { - final ArgumentCaptor bodyCaptor = ArgumentCaptor.forClass(String.class); - verify(httpServerResponse).end(bodyCaptor.capture()); - return bodyCaptor.getValue(); - } -} diff --git a/src/test/java/org/prebid/server/handler/ForceDealsUpdateHandlerTest.java b/src/test/java/org/prebid/server/handler/ForceDealsUpdateHandlerTest.java deleted file mode 100644 index 3a414d3eb36..00000000000 --- a/src/test/java/org/prebid/server/handler/ForceDealsUpdateHandlerTest.java +++ /dev/null @@ -1,240 +0,0 @@ -package org.prebid.server.handler; - -import io.vertx.core.http.HttpServerRequest; -import io.vertx.core.http.HttpServerResponse; -import io.vertx.ext.web.RoutingContext; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.deals.AlertHttpService; -import org.prebid.server.deals.DeliveryProgressService; -import org.prebid.server.deals.DeliveryStatsService; -import org.prebid.server.deals.LineItemService; -import org.prebid.server.deals.PlannerService; -import org.prebid.server.deals.RegisterService; -import org.prebid.server.exception.PreBidException; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; - -public class ForceDealsUpdateHandlerTest { - - private static final String ACTION_NAME_PARAM = "action_name"; - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private DeliveryStatsService deliveryStatsService; - @Mock - private PlannerService plannerService; - @Mock - private RegisterService registerService; - @Mock - private AlertHttpService alertHttpService; - @Mock - private DeliveryProgressService deliveryProgressService; - @Mock - private LineItemService lineItemService; - - private ForceDealsUpdateHandler handler; - @Mock - private RoutingContext routingContext; - @Mock - private HttpServerRequest httpRequest; - @Mock - private HttpServerResponse httpResponse; - - @Before - public void setUp() { - handler = new ForceDealsUpdateHandler( - deliveryStatsService, - plannerService, - registerService, - alertHttpService, - deliveryProgressService, - lineItemService, - "/endpoint"); - - given(routingContext.request()).willReturn(httpRequest); - given(routingContext.response()).willReturn(httpResponse); - - given(httpResponse.setStatusCode(anyInt())).willReturn(httpResponse); - given(httpResponse.closed()).willReturn(false); - } - - @Test - public void shouldReturnBadRequestWhenActionParamIsMissing() { - // given - given(httpRequest.getParam(any())).willReturn(null); - - // when - handler.handle(routingContext); - - // then - verify(httpRequest).getParam(eq(ACTION_NAME_PARAM)); - - verify(httpResponse).setStatusCode(400); - verify(httpResponse).end("Parameter '%s' is required and can't be empty".formatted(ACTION_NAME_PARAM)); - } - - @Test - public void shouldReturnBadRequestWhenBadActionParamIsGiven() { - // given - final String badParamName = "bad_param_name"; - given(httpRequest.getParam(any())).willReturn(badParamName); - - // when - handler.handle(routingContext); - - // then - verify(httpRequest).getParam(eq(ACTION_NAME_PARAM)); - - verify(httpResponse).setStatusCode(400); - verify(httpResponse).end("Given '%s' parameter value '%s' is not among possible actions" - .formatted(ACTION_NAME_PARAM, badParamName)); - } - - @Test - public void shouldCallLineItemsUpdateMethodWhenUpdateLineItemsParamIsGiven() { - // given - given(httpRequest.getParam(any())).willReturn(ForceDealsUpdateHandler.DealsAction.UPDATE_LINE_ITEMS.name()); - - // when - handler.handle(routingContext); - - // then - verify(plannerService).updateLineItemMetaData(); - verifyNoInteractions(deliveryStatsService, registerService, alertHttpService, deliveryProgressService, - lineItemService); - - verify(httpResponse).setStatusCode(204); - verify(httpResponse).end(); - } - - @Test - public void shouldCallReportSendingMethodWhenSendReportParamIsGiven() { - // given - given(httpRequest.getParam(any())).willReturn(ForceDealsUpdateHandler.DealsAction.SEND_REPORT.name()); - - // when - handler.handle(routingContext); - - // then - verify(deliveryStatsService).sendDeliveryProgressReports(); - verifyNoInteractions(plannerService, registerService, alertHttpService, deliveryProgressService, - lineItemService); - - verify(httpResponse).setStatusCode(204); - verify(httpResponse).end(); - } - - @Test - public void shouldCallRegisterInstanceMethodWhenRegisterInstanceParamIsGiven() { - // given - given(httpRequest.getParam(any())).willReturn(ForceDealsUpdateHandler.DealsAction.REGISTER_INSTANCE.name()); - - // when - handler.handle(routingContext); - - // then - verify(registerService).performRegistration(); - verifyNoInteractions(plannerService, deliveryStatsService, alertHttpService, deliveryProgressService, - lineItemService); - - verify(httpResponse).setStatusCode(204); - verify(httpResponse).end(); - } - - @Test - public void shouldCallResetAlertCountMethodWhenResetAlertCounterParamIsGiven() { - // given - given(httpRequest.getParam(any())).willReturn(ForceDealsUpdateHandler.DealsAction.RESET_ALERT_COUNT.name()); - - // when - handler.handle(routingContext); - - // then - verify(alertHttpService).resetAlertCount("pbs-register-client-error"); - verify(alertHttpService).resetAlertCount("pbs-planner-client-error"); - verify(alertHttpService).resetAlertCount("pbs-planner-empty-response-error"); - verify(alertHttpService).resetAlertCount("pbs-delivery-stats-client-error"); - verifyNoInteractions(plannerService, deliveryStatsService, registerService, deliveryProgressService, - lineItemService); - - verify(httpResponse).setStatusCode(204); - verify(httpResponse).end(); - } - - @Test - public void shouldCallCreateReportMethodWhenCreateReportParamIsGiven() { - // given - given(httpRequest.getParam(any())).willReturn(ForceDealsUpdateHandler.DealsAction.CREATE_REPORT.name()); - - // when - handler.handle(routingContext); - - // then - verify(deliveryProgressService).createDeliveryProgressReports(any()); - verifyNoInteractions(registerService, plannerService, deliveryStatsService, alertHttpService, - lineItemService); - - verify(httpResponse).setStatusCode(204); - verify(httpResponse).end(); - } - - @Test - public void shouldCallInvalidateLineItemsMethodWhenInvalidateLineItemsParamIsGiven() { - // given - given(httpRequest.getParam(any())).willReturn(ForceDealsUpdateHandler.DealsAction.INVALIDATE_LINE_ITEMS.name()); - - // when - handler.handle(routingContext); - - // then - verify(lineItemService).invalidateLineItems(); - verifyNoInteractions(registerService, plannerService, deliveryStatsService, alertHttpService, - deliveryProgressService); - - verify(httpResponse).setStatusCode(204); - verify(httpResponse).end(); - } - - @Test - public void shouldReturnInternalServerExceptionWhenUpdatingLineItemActionFailed() { - // given - given(httpRequest.getParam(any())).willReturn(ForceDealsUpdateHandler.DealsAction.UPDATE_LINE_ITEMS.name()); - final String exceptionMessage = "Failed to fetch data from Planner"; - doThrow(new PreBidException(exceptionMessage)).when(plannerService).updateLineItemMetaData(); - - // when - handler.handle(routingContext); - - // then - verify(httpResponse).setStatusCode(500); - verify(httpResponse).end(exceptionMessage); - } - - @Test - public void shouldReturnInternalServerExceptionWhenSendingReportActionFailed() { - // given - given(httpRequest.getParam(any())).willReturn(ForceDealsUpdateHandler.DealsAction.SEND_REPORT.name()); - final String exceptionMessage = "Sending report failed"; - doThrow(new PreBidException(exceptionMessage)).when(deliveryStatsService).sendDeliveryProgressReports(); - - // when - handler.handle(routingContext); - - // then - verify(httpResponse).setStatusCode(500); - verify(httpResponse).end(exceptionMessage); - } -} diff --git a/src/test/java/org/prebid/server/handler/LineItemStatusHandlerTest.java b/src/test/java/org/prebid/server/handler/LineItemStatusHandlerTest.java deleted file mode 100644 index d05dbe49b76..00000000000 --- a/src/test/java/org/prebid/server/handler/LineItemStatusHandlerTest.java +++ /dev/null @@ -1,104 +0,0 @@ -package org.prebid.server.handler; - -import io.vertx.core.MultiMap; -import io.vertx.core.http.HttpServerRequest; -import io.vertx.core.http.HttpServerResponse; -import io.vertx.ext.web.RoutingContext; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.prebid.server.VertxTest; -import org.prebid.server.deals.DeliveryProgressService; -import org.prebid.server.deals.proto.report.LineItemStatusReport; -import org.prebid.server.exception.PreBidException; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.verify; - -public class LineItemStatusHandlerTest extends VertxTest { - - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private DeliveryProgressService deliveryProgressService; - - private LineItemStatusHandler handler; - @Mock - private RoutingContext routingContext; - @Mock - private HttpServerRequest httpRequest; - @Mock - private HttpServerResponse httpResponse; - - @Before - public void setUp() { - given(routingContext.request()).willReturn(httpRequest); - given(routingContext.response()).willReturn(httpResponse); - - given(httpRequest.headers()).willReturn(MultiMap.caseInsensitiveMultiMap()); - given(httpResponse.setStatusCode(anyInt())).willReturn(httpResponse); - - given(routingContext.request().getParam(any())).willReturn("lineItemId"); - - handler = new LineItemStatusHandler(deliveryProgressService, jacksonMapper, "endpoint"); - } - - @Test - public void handleShouldRespondWithErrorIfNoLineItemIdSpecified() { - // given - given(routingContext.request().getParam(any())).willReturn(null); - - // when - handler.handle(routingContext); - - // then - verify(httpResponse).setStatusCode(400); - verify(httpResponse).end("id parameter is required"); - } - - @Test - public void handleShouldRespondWithErrorIfProcessingFailed() { - // given - given(deliveryProgressService.getLineItemStatusReport(any())).willThrow(new PreBidException("error")); - - // when - handler.handle(routingContext); - - // then - verify(httpResponse).setStatusCode(400); - verify(httpResponse).end("error"); - } - - @Test - public void handleShouldRespondWithErrorIfUnexpectedExceptionOccurred() { - // given - given(deliveryProgressService.getLineItemStatusReport(any())).willThrow(new RuntimeException("error")); - - // when - handler.handle(routingContext); - - // then - verify(httpResponse).setStatusCode(500); - verify(httpResponse).end("error"); - } - - @Test - public void handleShouldRespondWithExpectedResult() { - // given - given(deliveryProgressService.getLineItemStatusReport(any())) - .willReturn(LineItemStatusReport.builder().lineItemId("lineItemId").build()); - - // when - handler.handle(routingContext); - - // then - verify(httpResponse).setStatusCode(200); - verify(httpResponse).end("{\"lineItemId\":\"lineItemId\"}"); - } -} diff --git a/src/test/java/org/prebid/server/handler/NotificationEventHandlerTest.java b/src/test/java/org/prebid/server/handler/NotificationEventHandlerTest.java index 42a5a78bad7..3262830eba7 100644 --- a/src/test/java/org/prebid/server/handler/NotificationEventHandlerTest.java +++ b/src/test/java/org/prebid/server/handler/NotificationEventHandlerTest.java @@ -19,9 +19,6 @@ import org.prebid.server.analytics.model.NotificationEvent; import org.prebid.server.analytics.reporter.AnalyticsReporterDelegator; import org.prebid.server.auction.model.Tuple2; -import org.prebid.server.cookie.UidsCookieService; -import org.prebid.server.deals.UserService; -import org.prebid.server.deals.events.ApplicationEventService; import org.prebid.server.exception.PreBidException; import org.prebid.server.execution.TimeoutFactory; import org.prebid.server.model.CaseInsensitiveMultiMap; @@ -38,8 +35,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -49,12 +44,6 @@ public class NotificationEventHandlerTest extends VertxTest { @Rule public final MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private UidsCookieService uidsCookieService; - @Mock - private ApplicationEventService applicationEventService; - @Mock - private UserService userService; @Mock private ActivityInfrastructureCreator activityInfrastructureCreator; @Mock @@ -85,15 +74,11 @@ public void setUp() { given(httpResponse.setStatusCode(anyInt())).willReturn(httpResponse); notificationHandler = new NotificationEventHandler( - uidsCookieService, - applicationEventService, - userService, activityInfrastructureCreator, analyticsReporterDelegator, timeoutFactory, applicationSettings, - 1000, - true); + 1000); } @Test @@ -315,117 +300,6 @@ public void shouldPassEventToAnalyticsReporterWhenAccountEventEnabled() { }); } - @Test - public void shouldUpdateEventForLineItemForEventTypeWinAndAccountEventsEnabled() { - // given - given(httpRequest.params()).willReturn(MultiMap.caseInsensitiveMultiMap() - .add("t", "win") - .add("b", "bidId") - .add("l", "lineItemId") - .add("a", "accountId")); - - final Account account = Account.builder() - .auction(AccountAuctionConfig.builder() - .events(AccountEventsConfig.of(true)) - .build()) - .build(); - given(applicationSettings.getAccountById(anyString(), any())) - .willReturn(Future.succeededFuture(account)); - - // when - notificationHandler.handle(routingContext); - - // then - verify(applicationEventService).publishLineItemWinEvent(eq("lineItemId")); - } - - @Test - public void shouldProcessLineItemEventWhenRequestAnalyticsFlagDisabled() { - // given - given(httpRequest.params()).willReturn(MultiMap.caseInsensitiveMultiMap() - .add("t", "win") - .add("b", "bidId") - .add("l", "lineItemId") - .add("a", "accountId") - .add("x", "0")); - - final Account account = Account.builder() - .auction(AccountAuctionConfig.builder() - .events(AccountEventsConfig.of(true)) - .build()) - .build(); - given(applicationSettings.getAccountById(anyString(), any())) - .willReturn(Future.succeededFuture(account)); - - // when - notificationHandler.handle(routingContext); - - // then - verify(applicationEventService).publishLineItemWinEvent(eq("lineItemId")); - verify(userService).processWinEvent(eq("lineItemId"), eq("bidId"), any()); - } - - @Test - public void shouldProcessLineItemEventWhenAccountEventsDisabled() { - // given - given(httpRequest.params()).willReturn(MultiMap.caseInsensitiveMultiMap() - .add("t", "win") - .add("b", "bidId") - .add("l", "lineItemId") - .add("a", "accountId")); - - final Account account = Account.builder() - .auction(AccountAuctionConfig.builder() - .events(AccountEventsConfig.of(false)) - .build()) - .build(); - given(applicationSettings.getAccountById(anyString(), any())) - .willReturn(Future.succeededFuture(account)); - - // when - notificationHandler.handle(routingContext); - - // then - verify(applicationEventService).publishLineItemWinEvent(eq("lineItemId")); - verify(userService).processWinEvent(eq("lineItemId"), eq("bidId"), any()); - } - - @Test - public void shouldNotProcessLineItemEventWhenDealsDisabled() { - // given - notificationHandler = new NotificationEventHandler( - uidsCookieService, - applicationEventService, - userService, - activityInfrastructureCreator, - analyticsReporterDelegator, - timeoutFactory, - applicationSettings, - 1000, - false); - - given(httpRequest.params()).willReturn(MultiMap.caseInsensitiveMultiMap() - .add("t", "win") - .add("b", "bidId") - .add("l", "lineItemId") - .add("a", "accountId")); - - final Account account = Account.builder() - .auction(AccountAuctionConfig.builder() - .events(AccountEventsConfig.of(true)) - .build()) - .build(); - given(applicationSettings.getAccountById(anyString(), any())) - .willReturn(Future.succeededFuture(account)); - - // when - notificationHandler.handle(routingContext); - - // then - verifyNoInteractions(applicationEventService); - verifyNoInteractions(userService); - } - @Test public void shouldNotPassEventToAnalyticsReporterWhenAnalyticsValueIsZero() { // given @@ -567,56 +441,6 @@ public void shouldPassExpectedEventToAnalyticsReporter() { }); } - @Test - public void shouldPassEventObjectToUserServiceWhenLineItemIdParameterIsPresent() { - // given - given(httpRequest.params()) - .willReturn(MultiMap.caseInsensitiveMultiMap() - .add("t", "win") - .add("b", "bidId") - .add("a", "accountId") - .add("l", "lineItemId")); - - given(applicationSettings.getAccountById(anyString(), any())) - .willReturn(Future.succeededFuture(Account.builder() - .id("accountId") - .auction(AccountAuctionConfig.builder() - .events(AccountEventsConfig.of(true)) - .build()) - .build())); - - // when - notificationHandler.handle(routingContext); - - // then - verify(uidsCookieService).parseFromRequest(eq(routingContext)); - - final CaseInsensitiveMultiMap.Builder queryParams = CaseInsensitiveMultiMap.builder() - .add("t", "win") - .add("b", "bidId") - .add("a", "accountId") - .add("l", "lineItemId"); - - final HttpRequestContext expectedHttpContext = HttpRequestContext.builder() - .queryParams(queryParams.build()) - .headers(CaseInsensitiveMultiMap.empty()) - .build(); - - verify(userService).processWinEvent(eq("lineItemId"), eq("bidId"), isNull()); - assertThat(captureAnalyticEvent()).satisfies(event -> { - assertThat(event.getType()).isEqualTo(NotificationEvent.Type.win); - assertThat(event.getBidId()).isEqualTo("bidId"); - assertThat(event.getAccount()).isEqualTo(Account.builder() - .id("accountId") - .auction(AccountAuctionConfig.builder() - .events(AccountEventsConfig.of(true)) - .build()) - .build()); - assertThat(event.getHttpContext()).isEqualTo(expectedHttpContext); - assertThat(event.getLineItemId()).isEqualTo("lineItemId"); - }); - } - private Integer captureResponseStatusCode() { final ArgumentCaptor captor = ArgumentCaptor.forClass(Integer.class); verify(httpResponse).setStatusCode(captor.capture()); diff --git a/src/test/java/org/prebid/server/handler/TracerLogHandlerTest.java b/src/test/java/org/prebid/server/handler/TracerLogHandlerTest.java index fe86539c68c..0d94217fea3 100644 --- a/src/test/java/org/prebid/server/handler/TracerLogHandlerTest.java +++ b/src/test/java/org/prebid/server/handler/TracerLogHandlerTest.java @@ -54,7 +54,7 @@ public void handleShouldReturnBadRequestWhenNoParametersInRequest() { // then verify(httpResponse).setStatusCode(eq(400)); - verify(httpResponse).end(eq("At least one parameter should ne defined: account, bidderCode, lineItemId")); + verify(httpResponse).end(eq("At least one parameter should be defined: account, bidderCode")); } @Test @@ -90,7 +90,7 @@ public void handleShouldReturnBadRequestWhenLogLevelHasIncorrectValue() { given(httpRequest.params()).willReturn(MultiMap.caseInsensitiveMultiMap().add("account", "1001") .add("duration", "200").add("level", "invalid")); doThrow(new IllegalArgumentException("Invalid LoggingLevel: invalid")) - .when(criteriaManager).addCriteria(any(), any(), any(), any(), any()); + .when(criteriaManager).addCriteria(any(), any(), any(), any()); // when tracerLogHandler.handle(routingContext); diff --git a/src/test/java/org/prebid/server/handler/openrtb2/AmpHandlerTest.java b/src/test/java/org/prebid/server/handler/openrtb2/AmpHandlerTest.java index 33b071d9a95..502f13fccc6 100644 --- a/src/test/java/org/prebid/server/handler/openrtb2/AmpHandlerTest.java +++ b/src/test/java/org/prebid/server/handler/openrtb2/AmpHandlerTest.java @@ -566,7 +566,7 @@ public void shouldRespondWithDebugInfoIncludedIfTestFlagIsTrue() { givenHoldAuction(givenBidResponseWithExt( ExtBidResponse.builder() - .debug(ExtResponseDebug.of(null, auctionContext.getBidRequest(), null, null)) + .debug(ExtResponseDebug.of(null, auctionContext.getBidRequest(), null)) .prebid(ExtBidResponsePrebid.builder().auctiontimestamp(1000L).targeting(emptyMap()).build()) .build())); diff --git a/src/test/java/org/prebid/server/handler/openrtb2/AuctionHandlerTest.java b/src/test/java/org/prebid/server/handler/openrtb2/AuctionHandlerTest.java index 17ef6934398..14f83a310f9 100644 --- a/src/test/java/org/prebid/server/handler/openrtb2/AuctionHandlerTest.java +++ b/src/test/java/org/prebid/server/handler/openrtb2/AuctionHandlerTest.java @@ -395,8 +395,7 @@ public void shouldRespondWithCorrectResolvedRequestMediaTypePriceGranularity() { final BidResponse bidResponse = BidResponse.builder() .ext(ExtBidResponse.builder() - .debug(ExtResponseDebug.of(null, resolvedRequest, - null, null)) + .debug(ExtResponseDebug.of(null, resolvedRequest, null)) .build()) .build(); final AuctionContext auctionContext = AuctionContext.builder() diff --git a/src/test/java/org/prebid/server/hooks/execution/HookStageExecutorTest.java b/src/test/java/org/prebid/server/hooks/execution/HookStageExecutorTest.java index a2972ac36c9..5159ee38e2c 100644 --- a/src/test/java/org/prebid/server/hooks/execution/HookStageExecutorTest.java +++ b/src/test/java/org/prebid/server/hooks/execution/HookStageExecutorTest.java @@ -56,6 +56,7 @@ import org.prebid.server.hooks.v1.InvocationResult; import org.prebid.server.hooks.v1.InvocationResultImpl; import org.prebid.server.hooks.v1.InvocationStatus; +import org.prebid.server.hooks.v1.PayloadUpdate; import org.prebid.server.hooks.v1.analytics.ActivityImpl; import org.prebid.server.hooks.v1.analytics.AppliedToImpl; import org.prebid.server.hooks.v1.analytics.ResultImpl; @@ -107,7 +108,6 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.prebid.server.assertion.FutureAssertion.assertThat; -import static org.prebid.server.hooks.v1.PayloadUpdate.identity; @RunWith(VertxUnitRunner.class) public class HookStageExecutorTest extends VertxTest { @@ -2886,6 +2886,10 @@ private HookStageExecutor createExecutor(String hostExecutionPlan, String defaul jacksonMapper); } + private static PayloadUpdate identity() { + return payload -> payload; + } + @Value(staticConstructor = "of") @NonFinal private static class EntrypointHookImpl implements EntrypointHook { diff --git a/src/test/java/org/prebid/server/it/ApplicationTest.java b/src/test/java/org/prebid/server/it/ApplicationTest.java index 4184a06f04c..ac40c02648c 100644 --- a/src/test/java/org/prebid/server/it/ApplicationTest.java +++ b/src/test/java/org/prebid/server/it/ApplicationTest.java @@ -649,7 +649,6 @@ public void traceHandlerShouldReturn200Ok() { .param("duration", "1000") .param("account", "1001") .param("bidderCode", "rubicon") - .param("lineitemId", "1001") .post("/pbs-admin/tracelog") .then() .assertThat() diff --git a/src/test/java/org/prebid/server/it/DealsSimulationTest.java b/src/test/java/org/prebid/server/it/DealsSimulationTest.java deleted file mode 100644 index ffed682509e..00000000000 --- a/src/test/java/org/prebid/server/it/DealsSimulationTest.java +++ /dev/null @@ -1,269 +0,0 @@ -package org.prebid.server.it; - -import com.github.tomakehurst.wiremock.client.VerificationException; -import com.github.tomakehurst.wiremock.junit.WireMockClassRule; -import com.github.tomakehurst.wiremock.matching.AnythingPattern; -import com.github.tomakehurst.wiremock.verification.LoggedRequest; -import io.restassured.response.Response; -import io.restassured.specification.RequestSpecification; -import org.json.JSONException; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.prebid.server.VertxTest; -import org.prebid.server.deals.LineItemService; -import org.skyscreamer.jsonassert.ArrayValueMatcher; -import org.skyscreamer.jsonassert.Customization; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; -import org.skyscreamer.jsonassert.ValueMatcher; -import org.skyscreamer.jsonassert.comparator.CustomComparator; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; - -import java.io.IOException; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeFormatterBuilder; -import java.time.temporal.WeekFields; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; -import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; -import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; -import static io.restassured.RestAssured.given; -import static java.util.Collections.singletonList; -import static org.awaitility.Awaitility.await; - -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) -@RunWith(SpringRunner.class) -@TestPropertySource(locations = { - "test-application.properties", - "deals/test-deals-application.properties", - "deals/test-deals-simulation-application.properties"}) -@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) -public class DealsSimulationTest extends VertxTest { - - private static final int APP_PORT = 10080; - private static final int WIREMOCK_PORT = 8090; - - private static final RequestSpecification SPEC = IntegrationTest.spec(APP_PORT); - - @ClassRule - public static final WireMockClassRule WIRE_MOCK_RULE = new WireMockClassRule(options().port(WIREMOCK_PORT)); - - private static final ZonedDateTime NOW = ZonedDateTime.now( - Clock.fixed(Instant.parse("2019-10-10T00:00:00Z"), ZoneOffset.UTC)); - - private static final DateTimeFormatter UTC_MILLIS_FORMATTER = new DateTimeFormatterBuilder() - .appendPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - .toFormatter(); - - private static final String RUBICON = "rubicon"; - - @Autowired - private LineItemService lineItemService; - - @Autowired - private Clock clock; - - @BeforeClass - public static void setUpInner() throws IOException { - // given - WIRE_MOCK_RULE.stubFor(get(urlPathEqualTo("/planner-plan")) - .withQueryParam("instanceId", equalTo("localhost")) - .withQueryParam("region", equalTo("local")) - .withQueryParam("vendor", equalTo("local")) - .withBasicAuth("username", "password") - .withHeader("pg-trx-id", new AnythingPattern()) - .withHeader("pg-sim-timestamp", equalTo(UTC_MILLIS_FORMATTER.format(NOW))) - .willReturn(aResponse() - .withBody(IntegrationTest.jsonFrom("deals/simulation/test-planner-plan-response-1.json")))); - - WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/planner-register")) - .withBasicAuth("username", "password") - .withHeader("pg-trx-id", new AnythingPattern()) - .withHeader("pg-sim-timestamp", equalTo(NOW.toString())) - .withRequestBody(equalToJson(IntegrationTest.jsonFrom( - "deals/simulation/test-planner-register-request-1.json"))) - .willReturn(aResponse())); - } - - @Test - public void openrtb2AuctionShouldRespondWithDealBids() throws IOException, JSONException, InterruptedException { - // given - given(SPEC) - .header("pg-sim-timestamp", NOW.plusSeconds(0).toString()) - .when() - .post("/pbs-admin/e2eAdmin/planner/fetchLineItems"); - - TimeUnit.SECONDS.sleep(1); // no way to check that planner response handling is complete - - given(SPEC) - .when() - .header("pg-sim-timestamp", NOW.plusSeconds(1).toString()) - .post("/pbs-admin/e2eAdmin/advancePlans"); - - awaitForLineItemMetadata(NOW.plusSeconds(1)); - - given(SPEC) - .when() - .body(IntegrationTest.jsonFrom("deals/simulation/test-bid-rates.json")) - .post("/pbs-admin/e2eAdmin/bidRate"); - - final Response beforePlansUpdateResponse = given(SPEC) - .header("Referer", "http://www.example.com") - .header("User-Agent", "userAgent") - .header("X-Forwarded-For", "185.199.110.153") - .header("pg-sim-timestamp", NOW.plusSeconds(2).toString()) - // this uids cookie value stands for {"uids":{"rubicon":"J5VLCWQP-26-CWFT"}} - .cookie("uids", "eyJ1aWRzIjp7InJ1Ymljb24iOiJKNVZMQ1dRUC0yNi1DV0ZUIn19") - .body(IntegrationTest.jsonFrom("deals/simulation/test-auction-request.json")) - .post("/openrtb2/auction"); - - assertResponse("deals/simulation/test-auction-response-1.json", beforePlansUpdateResponse, - singletonList(RUBICON)); - - WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/delivery-stats-progress")) - .withBasicAuth("username", "password") - .withHeader("pg-sim-timestamp", equalTo(UTC_MILLIS_FORMATTER.format(NOW.plusSeconds(3)))) - .withHeader("pg-trx-id", new AnythingPattern()) - .willReturn(aResponse())); - - given(SPEC) - .when() - .header("pg-sim-timestamp", NOW.plusSeconds(3).toString()) - .post("/pbs-admin/e2eAdmin/dealstats/report"); - - // update plans for now date = 2019-10-10T00:15:00Z - making lineItem1 inactive due to absence of active plan - given(SPEC) - .when() - .header("pg-sim-timestamp", NOW.plusMinutes(15).toString()) - .post("/pbs-admin/e2eAdmin/advancePlans"); - - final Response afterPlansUpdateResponse = given(SPEC) - .header("Referer", "http://www.example.com") - .header("User-Agent", "userAgent") - .header("X-Forwarded-For", "185.199.110.153") - .header("pg-sim-timestamp", NOW.plusMinutes(16).toString()) - // this uids cookie value stands for {"uids":{"rubicon":"J5VLCWQP-26-CWFT"}} - .cookie("uids", "eyJ1aWRzIjp7InJ1Ymljb24iOiJKNVZMQ1dRUC0yNi1DV0ZUIn19") - .body(IntegrationTest.jsonFrom("deals/simulation/test-auction-request.json")) - .post("/openrtb2/auction"); - - assertResponse("deals/simulation/test-auction-response-2.json", afterPlansUpdateResponse, - singletonList(RUBICON)); - - WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/delivery-stats-progress")) - .withBasicAuth("username", "password") - .withHeader("pg-sim-timestamp", equalTo(UTC_MILLIS_FORMATTER.format(NOW.plusMinutes(17)))) - .withHeader("pg-trx-id", new AnythingPattern()) - .willReturn(aResponse())); - - given(SPEC) - .when() - .header("pg-sim-timestamp", NOW.plusMinutes(17).toString()) - .post("/pbs-admin/e2eAdmin/dealstats/report"); - - assertDeliveryStatsProgressRequests( - "deals/simulation/test-delivery-stats-progress-request-1.json", - "deals/simulation/test-delivery-stats-progress-request-2.json"); - - given(SPEC) - .header("pg-sim-timestamp", NOW.toString()) - .when() - .post("/pbs-admin/e2eAdmin/planner/register"); - } - - private void awaitForLineItemMetadata(ZonedDateTime now) { - await().atMost(20, TimeUnit.SECONDS).pollInterval(100, TimeUnit.MILLISECONDS) - .until(() -> lineItemService.accountHasDeals("2001", now)); - } - - /** - * Timestamps in response are always generated anew. - * This comparator allows to just verify they are present and parsable. - */ - private static CustomComparator openrtbDeepDebugTimeComparator() { - final ValueMatcher timeValueMatcher = (actual, expected) -> { - try { - return mapper.readValue("\"" + actual.toString() + "\"", ZonedDateTime.class) != null; - } catch (IOException e) { - return false; - } - }; - - final ArrayValueMatcher arrayValueMatcher = new ArrayValueMatcher<>(new CustomComparator( - JSONCompareMode.NON_EXTENSIBLE, - new Customization("ext.debug.trace.deals[*].time", timeValueMatcher))); - - final List arrayValueMatchers = IntStream.range(1, 5) - .mapToObj(i -> new Customization("ext.debug.trace.lineitems.lineItem" + i, - new ArrayValueMatcher<>(new CustomComparator( - JSONCompareMode.NON_EXTENSIBLE, - new Customization("ext.debug.trace.lineitems.lineItem" + i + "[*].time", - timeValueMatcher))))) - .collect(Collectors.toCollection(ArrayList::new)); - - arrayValueMatchers.add(new Customization("ext.debug.trace.deals", arrayValueMatcher)); - - return new CustomComparator(JSONCompareMode.NON_EXTENSIBLE, - arrayValueMatchers.toArray(Customization[]::new)); - } - - private void assertResponse(String expectedResponsePath, Response response, List bidders) - throws IOException, JSONException { - final String expectedAuctionResponse = withTemporalFields(IntegrationTest.openrtbAuctionResponseFrom( - expectedResponsePath, response, bidders)); - JSONAssert.assertEquals(expectedAuctionResponse, response.asString(), openrtbDeepDebugTimeComparator()); - } - - public static void assertDeliveryStatsProgressRequests(String path1, String path2) - throws IOException, JSONException { - final String firstReportRequest = IntegrationTest.jsonFrom(path1); - final String secondReportRequest = IntegrationTest.jsonFrom(path2); - - await().atMost(20, TimeUnit.SECONDS).pollInterval(1, TimeUnit.SECONDS).until(() -> - verify(() -> WIRE_MOCK_RULE.verify(2, postRequestedFor(urlPathEqualTo("/delivery-stats-progress"))))); - - final List loggedRequests = - WIRE_MOCK_RULE.findAll(postRequestedFor(urlPathEqualTo("/delivery-stats-progress"))); - - JSONAssert.assertEquals(firstReportRequest, loggedRequests.get(0).getBodyAsString(), JSONCompareMode.LENIENT); - JSONAssert.assertEquals(secondReportRequest, loggedRequests.get(1).getBodyAsString(), JSONCompareMode.LENIENT); - } - - private String withTemporalFields(String auctionResponse) { - final ZonedDateTime dateTime = ZonedDateTime.now(clock); - - return auctionResponse - .replaceAll("\"?\\{\\{ userdow }}\"?", Integer.toString( - dateTime.getDayOfWeek().get(WeekFields.SUNDAY_START.dayOfWeek()))) - .replaceAll("\"?\\{\\{ userhour }}\"?", Integer.toString(dateTime.getHour())); - } - - private static boolean verify(Runnable verify) { - try { - verify.run(); - return true; - } catch (VerificationException e) { - return false; - } - } -} diff --git a/src/test/java/org/prebid/server/it/DealsTest.java b/src/test/java/org/prebid/server/it/DealsTest.java deleted file mode 100644 index 78f775288d8..00000000000 --- a/src/test/java/org/prebid/server/it/DealsTest.java +++ /dev/null @@ -1,333 +0,0 @@ -package org.prebid.server.it; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.github.tomakehurst.wiremock.client.CountMatchingStrategy; -import com.github.tomakehurst.wiremock.client.VerificationException; -import com.github.tomakehurst.wiremock.junit.WireMockClassRule; -import com.github.tomakehurst.wiremock.matching.AnythingPattern; -import com.github.tomakehurst.wiremock.verification.LoggedRequest; -import io.restassured.response.Response; -import io.restassured.specification.RequestSpecification; -import org.apache.commons.collections4.CollectionUtils; -import org.json.JSONException; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.prebid.server.VertxTest; -import org.prebid.server.deals.LineItemService; -import org.prebid.server.deals.proto.report.DeliveryProgressReport; -import org.prebid.server.deals.proto.report.Event; -import org.prebid.server.deals.proto.report.LineItemStatus; -import org.skyscreamer.jsonassert.ArrayValueMatcher; -import org.skyscreamer.jsonassert.Customization; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; -import org.skyscreamer.jsonassert.ValueMatcher; -import org.skyscreamer.jsonassert.comparator.CustomComparator; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; - -import java.io.IOException; -import java.time.Clock; -import java.time.ZonedDateTime; -import java.time.temporal.WeekFields; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; -import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; -import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; -import static io.restassured.RestAssured.given; -import static java.util.Collections.emptyMap; -import static java.util.Collections.singletonList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.awaitility.Awaitility.await; -import static org.prebid.server.it.IntegrationTest.equalToBidCacheRequest; -import static org.prebid.server.it.IntegrationTest.openrtbAuctionResponseFrom; -import static org.prebid.server.util.IntegrationTestsUtil.jsonFrom; -import static org.skyscreamer.jsonassert.JSONCompare.compareJSON; - -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) -@RunWith(SpringRunner.class) -@TestPropertySource(locations = {"test-application.properties", "deals/test-deals-application.properties"}) -@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) -public class DealsTest extends VertxTest { - - private static final int APP_PORT = 8070; - private static final int WIREMOCK_PORT = 8090; - - private static final RequestSpecification SPEC = IntegrationTest.spec(APP_PORT); - - @SuppressWarnings("unchecked") - @ClassRule - public static final WireMockClassRule WIRE_MOCK_RULE = new WireMockClassRule(options() - .port(WIREMOCK_PORT) - .extensions( - IntegrationTest.CacheResponseTransformer.class, - IntegrationTest.ResponseOrderTransformer.class)); - - private static final String GENERIC = "generic"; - - @Autowired - private LineItemService lineItemService; - - @Autowired - private Clock clock; - - @BeforeClass - public static void setUpInner() throws IOException { - // given - WIRE_MOCK_RULE.stubFor(get(urlPathEqualTo("/periodic-update")) - .willReturn(aResponse() - .withJsonBody(mapper.createObjectNode() - .putPOJO("requests", emptyMap()) - .putPOJO("imps", emptyMap())))); - - WIRE_MOCK_RULE.stubFor(get(urlPathEqualTo("/currency-rates")) - .willReturn(aResponse().withJsonBody(mapper.createObjectNode()))); - - WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/delivery-stats-progress")) - .withBasicAuth("username", "password") - .withHeader("pg-trx-id", new AnythingPattern()) - .willReturn(aResponse())); - - WIRE_MOCK_RULE.stubFor(get(urlPathEqualTo("/planner-plan")) - .withQueryParam("instanceId", equalTo("localhost")) - .withQueryParam("region", equalTo("local")) - .withQueryParam("vendor", equalTo("local")) - .withBasicAuth("username", "password") - .withHeader("pg-trx-id", new AnythingPattern()) - .willReturn(aResponse().withBody(plannerResponseFrom("deals/test-planner-plan-response.json")))); - - WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/planner-register")) - .withBasicAuth("username", "password") - .withHeader("pg-trx-id", new AnythingPattern()) - .withRequestBody(equalToJson(jsonFrom("deals/test-planner-register-request.json"), false, true)) - .willReturn(aResponse().withBody(jsonFrom("deals/test-planner-register-response.json")))); - - // pre-bid cache - WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/cache")) - .withRequestBody(equalToBidCacheRequest(jsonFrom("deals/test-cache-deals-request.json"))) - .willReturn(aResponse() - .withTransformers("cache-response-transformer") - .withTransformerParameter("matcherName", "deals/test-cache-matcher.json"))); - } - - @Before - public void setUp() throws IOException { - // given - WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/user-data-win-event")) - .withRequestBody(equalToJson(jsonFrom("deals/test-user-data-win-event-request.json"), false, true)) - .willReturn(aResponse())); - - WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/user-data-details")) - .withRequestBody(equalToJson(jsonFrom("deals/test-user-data-details-request.json"), false, true)) - .willReturn(aResponse().withBody(jsonFrom("deals/test-user-data-details-generic-response.json")))); - - WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/generic-exchange")) - .withRequestBody(equalToJson(jsonFrom("deals/test-generic-bid-request.json"), false, true)) - .willReturn(aResponse() - .withFixedDelay(600) - .withBody(jsonFrom("deals/test-generic-bid-response.json")))); - } - - @Test - public void openrtb2AuctionShouldRespondWithDealBids() throws IOException, JSONException { - // given - awaitForLineItemMetadata(); - - // when - final Response response = given(SPEC) - .header("Referer", "http://www.example.com") - .header("User-Agent", "userAgent") - .header("X-Forwarded-For", "185.199.110.153") - // this uids cookie value stands for { "tempUIDs":{ "rubicon":{ "uid":"J5VLCWQP-26-CWFT", - // "expires":"2023-12-05T19:00:05.103329-03:00" } } } - .cookie("uids", "eyAidGVtcFVJRHMiOnsgInJ1Ymljb24iOnsgInVpZCI6Iko1VkxDV1FQ" - + "LTI2LUNXRlQiLCAiZXhwaXJlcyI6IjIwMjMtMTItMDVUMTk6MDA6MDUuMTAzMzI5LTAzOjAwIiB9IH0gfQ==") - .body(jsonFrom("deals/test-auction-request.json")) - .post("/openrtb2/auction"); - - // then - JSONAssert.assertEquals( - withTemporalFields(openrtbAuctionResponseFrom( - "deals/test-auction-response.json", response, singletonList(GENERIC))), - response.asString(), - openrtbDeepDebugTimeComparator()); - - // when - final Response eventResponse = given(SPEC) - .queryParam("t", "win") - .queryParam("b", "bidId") - .queryParam("a", "14062") - .queryParam("l", "lineItem1") - .queryParam("f", "i") - // this uids cookie value stands for { "tempUIDs":{ "rubicon":{ "uid":"J5VLCWQP-26-CWFT", - // "expires":"2023-12-05T19:00:05.103329-03:00" } } } - .cookie("uids", "eyAidGVtcFVJRHMiOnsgInJ1Ymljb24iOnsgInVpZCI6Iko1VkxDV1FQ" - + "LTI2LUNXRlQiLCAiZXhwaXJlcyI6IjIwMjMtMTItMDVUMTk6MDA6MDUuMTAzMzI5LTAzOjAwIiB9IH0gfQ==") - .get("/event"); - - // then - assertThat(eventResponse.getStatusCode()).isEqualTo(200); - await().atMost(5, TimeUnit.SECONDS).pollInterval(1, TimeUnit.SECONDS).until(() -> - verify(() -> WIRE_MOCK_RULE.verify(postRequestedFor(urlPathEqualTo("/user-data-win-event"))))); - - // verify delivery stats report - await().atMost(10, TimeUnit.SECONDS).pollInterval(1, TimeUnit.SECONDS).until(() -> - verify(() -> WIRE_MOCK_RULE.verify( - new CountMatchingStrategy(CountMatchingStrategy.GREATER_THAN_OR_EQUAL, 2), - postRequestedFor(urlPathEqualTo("/delivery-stats-progress"))))); - - final List requestList = WIRE_MOCK_RULE.findAll( - postRequestedFor(urlPathEqualTo("/delivery-stats-progress"))); - final DeliveryProgressReport report = chooseReportToCompare(requestList); - - JSONAssert.assertEquals( - jsonFrom("deals/test-delivery-stats-progress-request.json"), - mapper.writeValueAsString(report), - JSONCompareMode.LENIENT); - } - - private static String plannerResponseFrom(String templatePath) throws IOException { - final ZonedDateTime now = ZonedDateTime.now().withFixedOffsetZone(); - - return jsonFrom(templatePath) - .replaceAll("\\{\\{ now }}", now.toString()) - .replaceAll("\\{\\{ lineItem.startTime }}", now.minusDays(5).toString()) - .replaceAll("\\{\\{ lineItem.endTime }}", now.plusDays(5).toString()) - .replaceAll("\\{\\{ plan.startTime }}", now.minusHours(1).toString()) - .replaceAll("\\{\\{ plan.endTime }}", now.plusHours(1).toString()); - } - - private String withTemporalFields(String auctionResponse) { - final ZonedDateTime dateTime = ZonedDateTime.now(clock); - final int dayOfWeek = dateTime.getDayOfWeek().get(WeekFields.SUNDAY_START.dayOfWeek()); - - return auctionResponse - .replaceAll("\"?\\{\\{ userdow }}\"?", Integer.toString(dayOfWeek)) - .replaceAll("\"?\\{\\{ userhour }}\"?", Integer.toString(dateTime.getHour())); - } - - private void awaitForLineItemMetadata() { - await().atMost(5, TimeUnit.SECONDS).pollInterval(1, TimeUnit.SECONDS) - .until(() -> lineItemService.accountHasDeals("2001", ZonedDateTime.now(clock))); - } - - /** - * Timestamps in response are always generated anew. - * This comparator allows to just verify they are present and parsable. - */ - private static CustomComparator openrtbDeepDebugTimeComparator() { - final ValueMatcher timeValueMatcher = (actual, expected) -> { - try { - return mapper.readValue("\"" + actual.toString() + "\"", ZonedDateTime.class) != null; - } catch (IOException e) { - return false; - } - }; - - final ArrayValueMatcher arrayValueMatcher = new ArrayValueMatcher<>(new CustomComparator( - JSONCompareMode.NON_EXTENSIBLE, - new Customization("ext.debug.trace.deals[*].time", timeValueMatcher))); - - final ValueMatcher jsonStringValueMatcher = (actual, expected) -> { - try { - return compareJSON(actual.toString(), expected.toString(), JSONCompareMode.NON_EXTENSIBLE).passed(); - } catch (JSONException e) { - throw new RuntimeException("Unexpected json exception", e); - } - }; - - final ArrayValueMatcher cacheArrayValueMatcher = new ArrayValueMatcher<>(new CustomComparator( - JSONCompareMode.NON_EXTENSIBLE, - new Customization("ext.debug.httpcalls.cache[*].requestbody", jsonStringValueMatcher), - new Customization("ext.debug.httpcalls.cache[*].responsebody", jsonStringValueMatcher))); - - final List arrayValueMatchers = IntStream.range(1, 5) - .mapToObj(i -> new Customization( - "ext.debug.trace.lineitems.lineItem" + i, - new ArrayValueMatcher<>( - new CustomComparator( - JSONCompareMode.NON_EXTENSIBLE, - new Customization( - "ext.debug.trace.lineitems.lineItem" + i + "[*].time", - timeValueMatcher))))) - .collect(Collectors.toCollection(ArrayList::new)); - - arrayValueMatchers.add(new Customization("ext.debug.trace.deals", arrayValueMatcher)); - arrayValueMatchers.add(new Customization("ext.debug.httpcalls.cache", cacheArrayValueMatcher)); - arrayValueMatchers.add(new Customization("ext.debug.httpcalls.generic", new ArrayValueMatcher<>( - new CustomComparator( - JSONCompareMode.NON_EXTENSIBLE, - new Customization("**.requestheaders", (o1, o2) -> true), - new Customization("**.requestbody", (o1, o2) -> true), - new Customization("**.responsebody", (o1, o2) -> true))))); - - return new CustomComparator(JSONCompareMode.NON_EXTENSIBLE, arrayValueMatchers.toArray(Customization[]::new)); - } - - private static boolean verify(Runnable verify) { - try { - verify.run(); - return true; - } catch (VerificationException e) { - return false; - } - } - - private static DeliveryProgressReport chooseReportToCompare(List requestList) - throws JsonProcessingException { - - final int size = requestList.size(); - final DeliveryProgressReport firstReport = readDeliveryProgressReport(requestList.get(size - 2)); - final DeliveryProgressReport secondReport = readDeliveryProgressReport(requestList.get(size - 1)); - - // in a reason cron high dependent on time value, report with statistic should be chosen - final DeliveryProgressReport report = firstReport.getClientAuctions() != 0 ? firstReport : secondReport; - final LineItemStatus lineItem1 = firstReport.getLineItemStatus().stream() - .filter(lineItemStatus -> lineItemStatus.getLineItemId().equals("lineItem1")) - .findFirst().orElse(null); - - // if report does not contain win event for lineItem1 it is possible that it got by the second report - if (lineItem1 != null && CollectionUtils.isEmpty(lineItem1.getEvents())) { - final Set mergedEvents = lineItem1.getEvents(); - - firstReport.getLineItemStatus().stream() - .filter(lineItemStatus -> lineItemStatus.getLineItemId().equals("lineItem1")) - .map(LineItemStatus::getEvents) - .filter(CollectionUtils::isNotEmpty) - .findFirst() - .ifPresent(mergedEvents::addAll); - - secondReport.getLineItemStatus().stream() - .filter(lineItemStatus -> lineItemStatus.getLineItemId().equals("lineItem1")) - .map(LineItemStatus::getEvents) - .filter(CollectionUtils::isNotEmpty) - .findFirst() - .ifPresent(mergedEvents::addAll); - } - - return report; - } - - private static DeliveryProgressReport readDeliveryProgressReport(LoggedRequest loggedRequest) - throws JsonProcessingException { - - return mapper.readValue(loggedRequest.getBodyAsString(), DeliveryProgressReport.class); - } -} diff --git a/src/test/java/org/prebid/server/it/IntegrationTest.java b/src/test/java/org/prebid/server/it/IntegrationTest.java index ab1af668b7c..5892f823654 100644 --- a/src/test/java/org/prebid/server/it/IntegrationTest.java +++ b/src/test/java/org/prebid/server/it/IntegrationTest.java @@ -42,13 +42,6 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Queue; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -303,77 +296,6 @@ public boolean applyGlobally() { } } - static final String LINE_ITEM_RESPONSE_ORDER = "lineItemResponseOrder"; - static final String ID_TO_EXECUTION_PARAMETERS = "idToExecutionParameters"; - - public static class ResponseOrderTransformer extends ResponseTransformer { - - private static final String LINE_ITEM_PATH = "/imp/0/ext/rp/target/line_item"; - - private final Lock lock = new ReentrantLock(); - private final Condition lockCondition = lock.newCondition(); - - @Override - @SuppressWarnings("unchecked") - public com.github.tomakehurst.wiremock.http.Response transform( - Request request, - com.github.tomakehurst.wiremock.http.Response response, - FileSource files, - Parameters parameters) { - - final Queue lineItemResponseOrder = - (Queue) parameters.get(LINE_ITEM_RESPONSE_ORDER); - final Map idToParameters = - (Map) parameters.get(ID_TO_EXECUTION_PARAMETERS); - - final String requestDealId; - try { - requestDealId = readStringValue(mapper.readTree(request.getBodyAsString()), LINE_ITEM_PATH); - } catch (IOException e) { - throw new RuntimeException("Request should contain imp/ext/rp/target/line_item for deals request"); - } - - final BidRequestExecutionParameters requestParameters = idToParameters.get(requestDealId); - - waitForTurn(lineItemResponseOrder, requestParameters.getDealId(), requestParameters.getDelay()); - - return com.github.tomakehurst.wiremock.http.Response.response() - .body(requestParameters.getBody()) - .status(requestParameters.getStatus()) - .build(); - } - - private void waitForTurn(Queue dealsResponseOrder, String id, Long delay) { - lock.lock(); - try { - while (!Objects.equals(dealsResponseOrder.peek(), id)) { - lockCondition.await(); - } - TimeUnit.MILLISECONDS.sleep(delay); - dealsResponseOrder.poll(); - lockCondition.signalAll(); - } catch (InterruptedException e) { - throw new RuntimeException("Failed on waiting to return bid request for lineItem id = " + id); - } finally { - lock.unlock(); - } - } - - private String readStringValue(JsonNode jsonNode, String path) { - return jsonNode.at(path).asText(); - } - - @Override - public String getName() { - return "response-order-transformer"; - } - - @Override - public boolean applyGlobally() { - return false; - } - } - @Value @AllArgsConstructor(staticName = "of") static class BidRequestExecutionParameters { diff --git a/src/test/java/org/prebid/server/it/PrematureReturnTest.java b/src/test/java/org/prebid/server/it/PrematureReturnTest.java deleted file mode 100644 index dec6e307a14..00000000000 --- a/src/test/java/org/prebid/server/it/PrematureReturnTest.java +++ /dev/null @@ -1,451 +0,0 @@ -package org.prebid.server.it; - -import com.github.tomakehurst.wiremock.junit.WireMockClassRule; -import com.github.tomakehurst.wiremock.matching.AnythingPattern; -import io.restassured.response.Response; -import io.restassured.specification.RequestSpecification; -import org.json.JSONException; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.prebid.server.VertxTest; -import org.prebid.server.deals.LineItemService; -import org.skyscreamer.jsonassert.ArrayValueMatcher; -import org.skyscreamer.jsonassert.Customization; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; -import org.skyscreamer.jsonassert.ValueMatcher; -import org.skyscreamer.jsonassert.comparator.CustomComparator; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; - -import java.io.IOException; -import java.time.Clock; -import java.time.ZonedDateTime; -import java.time.temporal.WeekFields; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; -import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; -import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; -import static io.restassured.RestAssured.given; -import static java.util.Collections.singletonList; -import static org.awaitility.Awaitility.await; - -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) -@RunWith(SpringRunner.class) -@TestPropertySource(locations = {"test-application.properties", "deals/test-deals-application.properties"}) -@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) -public class PrematureReturnTest extends VertxTest { - - private static final int APP_PORT = 8070; - private static final int WIREMOCK_PORT = 8090; - - private static final RequestSpecification SPEC = IntegrationTest.spec(APP_PORT); - - @SuppressWarnings("unchecked") - @ClassRule - public static final WireMockClassRule WIRE_MOCK_RULE = new WireMockClassRule(options() - .port(WIREMOCK_PORT) - .extensions(IntegrationTest.ResponseOrderTransformer.class)); - - private static final String RUBICON = "rubicon"; - - @Autowired - private LineItemService lineItemService; - - @Autowired - private Clock clock; - - @BeforeClass - public static void setUpInner() throws IOException { - // given - WIRE_MOCK_RULE.stubFor(get(urlPathEqualTo("/planner-plan")) - .withQueryParam("instanceId", equalTo("localhost")) - .withQueryParam("region", equalTo("local")) - .withQueryParam("vendor", equalTo("local")) - .withBasicAuth("username", "password") - .withHeader("pg-trx-id", new AnythingPattern()) - .willReturn(aResponse() - .withBody(plannerResponseFrom("deals/premature/test-planner-plan-response.json")))); - - WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/planner-register")) - .withBasicAuth("username", "password") - .withHeader("pg-trx-id", new AnythingPattern()) - .withRequestBody(equalToJson(IntegrationTest.jsonFrom("deals/test-planner-register-request.json"), - false, true)) - .willReturn(aResponse())); - - WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/user-data-details")) - .withRequestBody(equalToJson(IntegrationTest - .jsonFrom("deals/test-user-data-details-request.json"), false, true)) - .willReturn(aResponse().withBody(IntegrationTest - .jsonFrom("deals/test-user-data-details-rubicon-response.json")))); - } - - @Test - public void openrtb2AuctionWhenAllThreeBidsReturnsInOrderWithMinimalDelay() throws IOException, JSONException { - // given - awaitForLineItemMetadata(); - - final Queue lineItemResponseOrder = new LinkedList<>(); - lineItemResponseOrder.add("extLineItem1"); - lineItemResponseOrder.add("extLineItem2"); - lineItemResponseOrder.add("extLineItem3"); - - final Map idToExecutionParameters = new HashMap<>(); - idToExecutionParameters.put("extLineItem1", IntegrationTest.BidRequestExecutionParameters.of("extLineItem1", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-bid-response-1.json"), 200, 0L)); - idToExecutionParameters.put("extLineItem2", IntegrationTest.BidRequestExecutionParameters.of("extLineItem2", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-bid-response-2.json"), 200, 20L)); - idToExecutionParameters.put("extLineItem3", IntegrationTest.BidRequestExecutionParameters.of("extLineItem3", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-bid-response-3.json"), 200, 20L)); - - stubExchange(lineItemResponseOrder, idToExecutionParameters); - - // when - final Response response = givenResponse(); - - final String expectedAuctionResponse = withTemporalFields(IntegrationTest.openrtbAuctionResponseFrom( - "deals/premature/responses/test-auction-in-order-response.json", response, singletonList(RUBICON))); - - JSONAssert.assertEquals(expectedAuctionResponse, response.asString(), openrtbDeepDebugTimeComparator()); - } - - @Test - public void openrtb2AuctionWhenAllThreeBidsReturnsInReverseOrderWithMinimalDelay() throws IOException, - JSONException { - // given - awaitForLineItemMetadata(); - - final Queue lineItemResponseOrder = new LinkedList<>(); - lineItemResponseOrder.add("extLineItem3"); - lineItemResponseOrder.add("extLineItem2"); - lineItemResponseOrder.add("extLineItem1"); - - final Map idToExecutionParameters = new HashMap<>(); - idToExecutionParameters.put("extLineItem1", IntegrationTest.BidRequestExecutionParameters.of("extLineItem1", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-bid-response-1.json"), 200, 20L)); - idToExecutionParameters.put("extLineItem2", IntegrationTest.BidRequestExecutionParameters.of("extLineItem2", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-bid-response-2.json"), 200, 20L)); - idToExecutionParameters.put("extLineItem3", IntegrationTest.BidRequestExecutionParameters.of("extLineItem3", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-bid-response-3.json"), 200, 0L)); - - stubExchange(lineItemResponseOrder, idToExecutionParameters); - - // when - final Response response = givenResponse(); - - final String expectedAuctionResponse = withTemporalFields(IntegrationTest.openrtbAuctionResponseFrom( - "deals/premature/responses/test-auction-in-reverse-order-response.json", response, - singletonList(RUBICON))); - - JSONAssert.assertEquals(expectedAuctionResponse, response.asString(), openrtbDeepDebugTimeComparator()); - } - - @Test - public void openrtb2AuctionWhenAllThreeBidsReturnsInOrderWithHighDelay() throws IOException, JSONException { - // given - awaitForLineItemMetadata(); - - final Queue lineItemResponseOrder = new LinkedList<>(); - lineItemResponseOrder.add("extLineItem1"); - lineItemResponseOrder.add("extLineItem2"); - lineItemResponseOrder.add("extLineItem3"); - - final Map idToExecutionParameters = new HashMap<>(); - idToExecutionParameters.put("extLineItem1", IntegrationTest.BidRequestExecutionParameters.of("extLineItem1", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-bid-response-1.json"), 200, 0L)); - idToExecutionParameters.put("extLineItem2", IntegrationTest.BidRequestExecutionParameters.of("extLineItem2", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-bid-response-2.json"), 200, 200L)); - idToExecutionParameters.put("extLineItem3", IntegrationTest.BidRequestExecutionParameters.of("extLineItem3", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-bid-response-3.json"), 200, 200L)); - - stubExchange(lineItemResponseOrder, idToExecutionParameters); - - // when - final Response response = givenResponse(); - - final String expectedAuctionResponse = withTemporalFields(IntegrationTest.openrtbAuctionResponseFrom( - "deals/premature/responses/test-auction-in-order-response.json", response, singletonList(RUBICON))); - - JSONAssert.assertEquals(expectedAuctionResponse, response.asString(), openrtbDeepDebugTimeComparator()); - } - - @Test - public void openrtb2AuctionWhenAllThreeBidsReturnsInReverseOrderWithHighDelay() throws IOException, JSONException { - // given - awaitForLineItemMetadata(); - - final Queue lineItemResponseOrder = new LinkedList<>(); - lineItemResponseOrder.add("extLineItem3"); - lineItemResponseOrder.add("extLineItem2"); - lineItemResponseOrder.add("extLineItem1"); - - final Map idToExecutionParameters = new HashMap<>(); - idToExecutionParameters.put("extLineItem1", IntegrationTest.BidRequestExecutionParameters.of("extLineItem1", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-bid-response-1.json"), 200, 200L)); - idToExecutionParameters.put("extLineItem2", IntegrationTest.BidRequestExecutionParameters.of("extLineItem2", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-bid-response-2.json"), 200, 200L)); - idToExecutionParameters.put("extLineItem3", IntegrationTest.BidRequestExecutionParameters.of("extLineItem3", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-bid-response-3.json"), 200, 0L)); - - stubExchange(lineItemResponseOrder, idToExecutionParameters); - - // when - final Response response = givenResponse(); - - final String expectedAuctionResponse = withTemporalFields(IntegrationTest.openrtbAuctionResponseFrom( - "deals/premature/responses/test-auction-in-reverse-order-response.json", response, - singletonList(RUBICON))); - - JSONAssert.assertEquals(expectedAuctionResponse, response.asString(), openrtbDeepDebugTimeComparator()); - } - - @Test - public void openrtb2AuctionWhenOnlyFirstBidComesBack() throws IOException, JSONException { - // given - awaitForLineItemMetadata(); - - final Queue lineItemResponseOrder = new LinkedList<>(); - lineItemResponseOrder.add("extLineItem1"); - lineItemResponseOrder.add("extLineItem2"); - lineItemResponseOrder.add("extLineItem3"); - - final Map idToExecutionParameters = new HashMap<>(); - idToExecutionParameters.put("extLineItem1", IntegrationTest.BidRequestExecutionParameters.of("extLineItem1", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-bid-response-1.json"), 200, 0L)); - idToExecutionParameters.put("extLineItem2", IntegrationTest.BidRequestExecutionParameters.of("extLineItem2", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-no-bid-response-2.json"), 200, 20L)); - idToExecutionParameters.put("extLineItem3", IntegrationTest.BidRequestExecutionParameters.of("extLineItem3", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-no-bid-response-3.json"), 200, 20L)); - - stubExchange(lineItemResponseOrder, idToExecutionParameters); - - // when - final Response response = givenResponse(); - - final String expectedAuctionResponse = withTemporalFields(IntegrationTest.openrtbAuctionResponseFrom( - "deals/premature/responses/test-auction-first-bid-only-response.json", response, - singletonList(RUBICON))); - - JSONAssert.assertEquals(expectedAuctionResponse, response.asString(), openrtbDeepDebugTimeComparator()); - } - - @Test - public void openrtb2AuctionWhenOnlySecondBidComesBack() throws IOException, JSONException { - // given - awaitForLineItemMetadata(); - - final Queue lineItemResponseOrder = new LinkedList<>(); - lineItemResponseOrder.add("extLineItem1"); - lineItemResponseOrder.add("extLineItem2"); - lineItemResponseOrder.add("extLineItem3"); - - final Map idToExecutionParameters = new HashMap<>(); - idToExecutionParameters.put("extLineItem1", IntegrationTest.BidRequestExecutionParameters.of("extLineItem1", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-no-bid-response-1.json"), 200, 0L)); - idToExecutionParameters.put("extLineItem2", IntegrationTest.BidRequestExecutionParameters.of("extLineItem2", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-bid-response-2.json"), 200, 20L)); - idToExecutionParameters.put("extLineItem3", IntegrationTest.BidRequestExecutionParameters.of("extLineItem3", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-no-bid-response-3.json"), 200, 20L)); - - stubExchange(lineItemResponseOrder, idToExecutionParameters); - - // when - final Response response = givenResponse(); - - final String expectedAuctionResponse = withTemporalFields(IntegrationTest.openrtbAuctionResponseFrom( - "deals/premature/responses/test-auction-second-bid-only-response.json", response, - singletonList(RUBICON))); - - JSONAssert.assertEquals(expectedAuctionResponse, response.asString(), openrtbDeepDebugTimeComparator()); - } - - @Test - public void openrtb2AuctionWhenOnlyThirdBidComesBack() throws IOException, JSONException { - // given - awaitForLineItemMetadata(); - - final Queue lineItemResponseOrder = new LinkedList<>(); - lineItemResponseOrder.add("extLineItem1"); - lineItemResponseOrder.add("extLineItem2"); - lineItemResponseOrder.add("extLineItem3"); - - final Map idToExecutionParameters = new HashMap<>(); - idToExecutionParameters.put("extLineItem1", IntegrationTest.BidRequestExecutionParameters.of("extLineItem1", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-no-bid-response-1.json"), 200, 0L)); - idToExecutionParameters.put("extLineItem2", IntegrationTest.BidRequestExecutionParameters.of("extLineItem2", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-no-bid-response-2.json"), 200, 20L)); - idToExecutionParameters.put("extLineItem3", IntegrationTest.BidRequestExecutionParameters.of("extLineItem3", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-bid-response-3.json"), 200, 20L)); - - stubExchange(lineItemResponseOrder, idToExecutionParameters); - - // when - final Response response = givenResponse(); - final String expectedAuctionResponse = withTemporalFields(IntegrationTest.openrtbAuctionResponseFrom( - "deals/premature/responses/test-auction-third-bid-only-response.json", response, - singletonList(RUBICON))); - - JSONAssert.assertEquals(expectedAuctionResponse, response.asString(), openrtbDeepDebugTimeComparator()); - } - - @Test - public void openrtb2AuctionWhenFirstAndSecondBidsComesBackReverseWithHighDelay() throws IOException, JSONException { - // given - awaitForLineItemMetadata(); - - final Queue lineItemResponseOrder = new LinkedList<>(); - lineItemResponseOrder.add("extLineItem2"); - lineItemResponseOrder.add("extLineItem1"); - lineItemResponseOrder.add("extLineItem3"); - - final Map idToExecutionParameters = new HashMap<>(); - idToExecutionParameters.put("extLineItem1", IntegrationTest.BidRequestExecutionParameters.of("extLineItem1", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-bid-response-1.json"), 200, 200L)); - idToExecutionParameters.put("extLineItem2", IntegrationTest.BidRequestExecutionParameters.of("extLineItem2", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-bid-response-2.json"), 200, 0L)); - idToExecutionParameters.put("extLineItem3", IntegrationTest.BidRequestExecutionParameters.of("extLineItem3", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-no-bid-response-3.json"), 200, 200L)); - - stubExchange(lineItemResponseOrder, idToExecutionParameters); - - // when - final Response response = givenResponse(); - - final String expectedAuctionResponse = withTemporalFields(IntegrationTest.openrtbAuctionResponseFrom( - "deals/premature/responses/test-auction-first-and-second-response.json", response, - singletonList(RUBICON))); - - JSONAssert.assertEquals(expectedAuctionResponse, response.asString(), openrtbDeepDebugTimeComparator()); - } - - @Test - public void openrtb2AuctionWhenSecondAndThirdBidsComesBackReverseWithHighDelay() throws IOException, JSONException { - // given - awaitForLineItemMetadata(); - - final Queue lineItemResponseOrder = new LinkedList<>(); - lineItemResponseOrder.add("extLineItem3"); - lineItemResponseOrder.add("extLineItem2"); - lineItemResponseOrder.add("extLineItem1"); - - final Map idToExecutionParameters = new HashMap<>(); - idToExecutionParameters.put("extLineItem1", IntegrationTest.BidRequestExecutionParameters.of("extLineItem1", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-no-bid-response-1.json"), 200, 200L)); - idToExecutionParameters.put("extLineItem2", IntegrationTest.BidRequestExecutionParameters.of("extLineItem2", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-bid-response-2.json"), 200, 200L)); - idToExecutionParameters.put("extLineItem3", IntegrationTest.BidRequestExecutionParameters.of("extLineItem3", - IntegrationTest.jsonFrom("deals/premature/test-rubicon-bid-response-3.json"), 200, 0L)); - - stubExchange(lineItemResponseOrder, idToExecutionParameters); - - // when - final Response response = givenResponse(); - - final String expectedAuctionResponse = withTemporalFields(IntegrationTest.openrtbAuctionResponseFrom( - "deals/premature/responses/test-auction-third-and-second-response.json", response, - singletonList(RUBICON))); - - JSONAssert.assertEquals(expectedAuctionResponse, response.asString(), openrtbDeepDebugTimeComparator()); - } - - private Response givenResponse() throws IOException { - return given(SPEC) - .header("Referer", "http://www.example.com") - .header("User-Agent", "userAgent") - .header("X-Forwarded-For", "185.199.110.153") - // this uids cookie value stands for { "tempUIDs":{ "rubicon":{ "uid":"J5VLCWQP-26-CWFT", - // "expires":"2023-12-05T19:00:05.103329-03:00" } } } - .cookie("uids", "eyAidGVtcFVJRHMiOnsgInJ1Ymljb24iOnsgInVpZCI6Iko1VkxDV1FQ" - + "LTI2LUNXRlQiLCAiZXhwaXJlcyI6IjIwMjMtMTItMDVUMTk6MDA6MDUuMTAzMzI5LTAzOjAwIiB9IH0gfQ==") - .body(IntegrationTest.jsonFrom("deals/premature/test-auction-request.json")) - .post("/openrtb2/auction"); - } - - private void stubExchange(Queue lineItemResponseOrder, - Map idToExecutionParameters) { - WIRE_MOCK_RULE.stubFor(post(urlMatching("/rubicon-exchange.*")) - .willReturn(aResponse() - .withTransformers("response-order-transformer") - .withTransformerParameter(IntegrationTest.LINE_ITEM_RESPONSE_ORDER, lineItemResponseOrder) - .withTransformerParameter(IntegrationTest.ID_TO_EXECUTION_PARAMETERS, - idToExecutionParameters))); - } - - private void awaitForLineItemMetadata() { - await().atMost(20, TimeUnit.SECONDS).pollInterval(100, TimeUnit.MILLISECONDS) - .until(() -> lineItemService.accountHasDeals("2001", ZonedDateTime.now(clock))); - } - - private static String plannerResponseFrom(String templatePath) throws IOException { - final ZonedDateTime now = ZonedDateTime.now().withFixedOffsetZone(); - - return IntegrationTest.jsonFrom(templatePath) - .replaceAll("\\{\\{ now }}", now.toString()) - .replaceAll("\\{\\{ lineItem.startTime }}", now.minusDays(5).toString()) - .replaceAll("\\{\\{ lineItem.endTime }}", now.plusDays(5).toString()) - .replaceAll("\\{\\{ plan.startTime }}", now.minusHours(1).toString()) - .replaceAll("\\{\\{ plan.endTime }}", now.plusHours(1).toString()); - } - - private static CustomComparator openrtbDeepDebugTimeComparator() { - final ValueMatcher timeValueMatcher = (actual, expected) -> { - try { - return mapper.readValue("\"" + actual.toString() + "\"", ZonedDateTime.class) != null; - } catch (IOException e) { - return false; - } - }; - - final ArrayValueMatcher arrayValueMatcher = new ArrayValueMatcher<>(new CustomComparator( - JSONCompareMode.NON_EXTENSIBLE, - new Customization("ext.debug.trace.deals[*].time", timeValueMatcher))); - - final List arrayValueMatchers = IntStream.range(1, 5) - .mapToObj(i -> new Customization("ext.debug.trace.lineitems.lineItem" + i, - new ArrayValueMatcher<>(new CustomComparator( - JSONCompareMode.NON_EXTENSIBLE, - new Customization("ext.debug.trace.lineitems.lineItem" + i + "[*].time", - timeValueMatcher))))) - .collect(Collectors.toCollection(ArrayList::new)); - - arrayValueMatchers.add(new Customization("ext.debug.trace.deals", arrayValueMatcher)); - arrayValueMatchers.add(new Customization("ext.debug.httpcalls.rubicon", new ArrayValueMatcher<>( - new CustomComparator( - JSONCompareMode.NON_EXTENSIBLE, - new Customization("**.requestheaders", (o1, o2) -> true), - new Customization("**.requestbody", (o1, o2) -> true), - new Customization("**.responsebody", (o1, o2) -> true))))); - - return new CustomComparator(JSONCompareMode.NON_EXTENSIBLE, - arrayValueMatchers.toArray(new Customization[0])); - } - - private String withTemporalFields(String auctionResponse) { - final ZonedDateTime dateTime = ZonedDateTime.now(clock); - - return auctionResponse - .replaceAll("\"?\\{\\{ userdow }}\"?", Integer.toString( - dateTime.getDayOfWeek().get(WeekFields.SUNDAY_START.dayOfWeek()))) - .replaceAll("\"?\\{\\{ userhour }}\"?", Integer.toString(dateTime.getHour())); - } -} diff --git a/src/test/java/org/prebid/server/log/CriteriaManagerTest.java b/src/test/java/org/prebid/server/log/CriteriaManagerTest.java index 7be8a0c8af7..b8dd599c790 100644 --- a/src/test/java/org/prebid/server/log/CriteriaManagerTest.java +++ b/src/test/java/org/prebid/server/log/CriteriaManagerTest.java @@ -8,7 +8,6 @@ import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.prebid.server.VertxTest; -import org.prebid.server.deals.model.LogCriteriaFilter; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; @@ -35,14 +34,14 @@ public void setUp() { @Test public void addCriteriaShouldThrowIllegalArgumentExceptionWhenLoggerLevelHasInvalidValue() { assertThatIllegalArgumentException() - .isThrownBy(() -> criteriaManager.addCriteria("1001", "rubicon", "lineItemId1", "invalid", 800)) + .isThrownBy(() -> criteriaManager.addCriteria("1001", "rubicon", "invalid", 800)) .withMessage("Invalid LoggingLevel: invalid"); } @Test public void addCriteriaShouldAddVertxTimerWithLimitedDurationInMillis() { // given and when - criteriaManager.addCriteria("1001", "rubicon", "lineItemId1", "error", 800000); + criteriaManager.addCriteria("1001", "rubicon", "error", 800000); // then verify(vertx).setTimer(eq(300000L), any()); @@ -51,25 +50,7 @@ public void addCriteriaShouldAddVertxTimerWithLimitedDurationInMillis() { @Test public void addCriteriaShouldAddVertxTimerWithDefaultDurationInMillis() { // given and when - criteriaManager.addCriteria("1001", "rubicon", "lineItemId1", "error", 200000); - - // then - verify(vertx).setTimer(eq(200000L), any()); - } - - @Test - public void addCriteriaByFilterShouldAddVertxTimeWithLimitedDurationInMillis() { - // given and when - criteriaManager.addCriteria(LogCriteriaFilter.of("1001", "rubicon", "lineItemId1"), 800L); - - // then - verify(vertx).setTimer(eq(300000L), any()); - } - - @Test - public void addCriteriaByFilterShouldAddVertxTimeWithNotLimitedDurationInMillis() { - // given and when - criteriaManager.addCriteria(LogCriteriaFilter.of("1001", "rubicon", "lineItemId1"), 200L); + criteriaManager.addCriteria("1001", "rubicon", "error", 200000); // then verify(vertx).setTimer(eq(200000L), any()); diff --git a/src/test/java/org/prebid/server/log/CriteriaTest.java b/src/test/java/org/prebid/server/log/CriteriaTest.java index 4e5fcad3839..dd24d167fa0 100644 --- a/src/test/java/org/prebid/server/log/CriteriaTest.java +++ b/src/test/java/org/prebid/server/log/CriteriaTest.java @@ -20,73 +20,22 @@ public class CriteriaTest { @Mock private Logger logger; - @Test - public void logShouldChooseCriteriaLoggerLevelWhenAccountsMatchedAndElseFieldsAreNull() { - // given - final Criteria criteria = Criteria.create("account", null, null, Logger::error); - - // when - criteria.log(Criteria.builder().account("account").bidder("rubicon").build(), logger, "message", logger::info); - - // then - verify(logger).error(anyString()); - } - - @Test - public void logShouldChooseDefaultLogLevelWhenAccountsMatchedAndElseFieldsAreNotNullAndNotMatched() { - // given - final Criteria criteria = Criteria.create("account", "appnexus", null, Logger::error); - - // when - criteria.log(Criteria.builder().account("account").bidder("rubicon").build(), - logger, "message", logger::info); - - // then - verify(logger).info(anyString()); - } - - @Test - public void logShouldChooseCriteriaLogLevelAccountAndBidderMatchedLineItemIsNull() { - // given - final Criteria criteria = Criteria.create("account", "rubicon", null, Logger::error); - - // when - criteria.log(Criteria.builder().account("account").bidder("rubicon") - .lineItemId("lineItemId").build(), logger, "message", logger::info); - - // then - verify(logger).error(anyString()); - } - - @Test - public void logShouldChooseCriteriaLogLevelWhenAllMatched() { - // given - final Criteria criteria = Criteria.create("account", "rubicon", "lineItemId", Logger::error); - - // when - criteria.log(Criteria.builder().account("account").bidder("rubicon") - .lineItemId("lineItemId").build(), logger, "message", logger::info); - - // then - verify(logger).error(anyString()); - } - @Test public void logResponseShouldLogResponseWhenAllNotNullCriteriasPresent() { // given - final Criteria criteria = Criteria.create("account", null, "lineItemId", Logger::error); + final Criteria criteria = Criteria.create("account", null, Logger::error); // when - criteria.logResponse("Response has account and lineItemId", logger); + criteria.logResponse("Response has account", logger); // then verify(logger).error(anyString()); } @Test - public void logResponseShouldNotLogResponseWhenOneOfNutNullCriteriaMissing() { + public void logResponseShouldNotLogResponseWhenOneOfNotNullCriteriaMissing() { // given - final Criteria criteria = Criteria.create("account", null, "lineItemId", Logger::error); + final Criteria criteria = Criteria.create("account", "bidder", Logger::error); // when criteria.logResponse("Response has account", logger); @@ -98,19 +47,19 @@ public void logResponseShouldNotLogResponseWhenOneOfNutNullCriteriaMissing() { @Test public void logResponseAndRequestShouldLogResponseWhenAllNotNullCriteriasPresent() { // given - final Criteria criteria = Criteria.create("account", null, "lineItemId", Logger::error); + final Criteria criteria = Criteria.create("account", null, Logger::error); // when - criteria.logResponseAndRequest("Response has account", "Request has lineItemId", logger); + criteria.logResponseAndRequest("Response has account", "Request", logger); // then verify(logger, times(2)).error(anyString()); } @Test - public void logResponseAndRequestShouldNotLogResponseWhenOneOfNutNullCriteriaMissing() { + public void logResponseAndRequestShouldNotLogResponseWhenOneOfNotNullCriteriaMissing() { // given - final Criteria criteria = Criteria.create("account", null, "lineItemId", Logger::error); + final Criteria criteria = Criteria.create("account", "bidder", Logger::error); // when criteria.logResponseAndRequest("Response has account", "Request", logger); diff --git a/src/test/java/org/prebid/server/metric/MetricsTest.java b/src/test/java/org/prebid/server/metric/MetricsTest.java index 8a6518666d5..cf1d8d56225 100644 --- a/src/test/java/org/prebid/server/metric/MetricsTest.java +++ b/src/test/java/org/prebid/server/metric/MetricsTest.java @@ -672,140 +672,6 @@ public void updateCookieSyncFilteredMetricShouldIncrementMetric() { assertThat(metricRegistry.counter("cookie_sync.conversant.filtered").getCount()).isEqualTo(2); } - @Test - public void updateGpRequestMetricShouldIncrementPlannerRequestAndPlannerSuccessfulRequest() { - // when - metrics.updatePlannerRequestMetric(true); - - // then - assertThat(metricRegistry.counter("pg.planner_requests").getCount()).isEqualTo(1); - assertThat(metricRegistry.counter("pg.planner_request_successful").getCount()).isEqualTo(1); - } - - @Test - public void updateGpRequestMetricShouldIncrementPlannerRequestAndPlannerFailedRequest() { - // when - metrics.updatePlannerRequestMetric(false); - - // then - assertThat(metricRegistry.counter("pg.planner_requests").getCount()).isEqualTo(1); - assertThat(metricRegistry.counter("pg.planner_request_failed").getCount()).isEqualTo(1); - } - - @Test - public void updateGpRequestMetricShouldIncrementUserDetailsSuccessfulRequest() { - // when - metrics.updateUserDetailsRequestMetric(true); - - // then - assertThat(metricRegistry.counter("user_details_requests").getCount()).isEqualTo(1); - assertThat(metricRegistry.counter("user_details_request_successful").getCount()).isEqualTo(1); - } - - @Test - public void updateGpRequestMetricShouldIncrementUserDetailsFailedRequest() { - // when - metrics.updateUserDetailsRequestMetric(false); - - // then - assertThat(metricRegistry.counter("user_details_requests").getCount()).isEqualTo(1); - assertThat(metricRegistry.counter("user_details_request_failed").getCount()).isEqualTo(1); - } - - @Test - public void updateGpRequestMetricShouldIncrementWinSuccessfulRequest() { - // when - metrics.updateWinEventRequestMetric(true); - - // then - assertThat(metricRegistry.counter("win_requests").getCount()).isEqualTo(1); - assertThat(metricRegistry.counter("win_request_successful").getCount()).isEqualTo(1); - } - - @Test - public void updateGpRequestMetricShouldIncrementWinFailedRequest() { - // when - metrics.updateWinEventRequestMetric(false); - - // then - assertThat(metricRegistry.counter("win_requests").getCount()).isEqualTo(1); - assertThat(metricRegistry.counter("win_request_failed").getCount()).isEqualTo(1); - } - - @Test - public void updateWinRequestTimeShouldLogTime() { - // when - metrics.updateWinRequestTime(20L); - - // then - assertThat(metricRegistry.timer("win_request_time").getCount()).isEqualTo(1); - } - - @Test - public void updateWinRequestPreparationFailedShouldIncrementMetric() { - // when - metrics.updateWinRequestPreparationFailed(); - - // then - assertThat(metricRegistry.counter("win_request_preparation_failed").getCount()).isEqualTo(1); - } - - @Test - public void updateUserDetailsRequestPreparationFailedShouldIncrementMetric() { - // when - metrics.updateUserDetailsRequestPreparationFailed(); - - // then - assertThat(metricRegistry.counter("user_details_request_preparation_failed").getCount()).isEqualTo(1); - } - - @Test - public void updateDeliveryRequestMetricShouldIncrementDeliveryRequestAndSuccessfulDeliveryRequest() { - // when - metrics.updateDeliveryRequestMetric(true); - - // then - assertThat(metricRegistry.counter("pg.delivery_requests").getCount()).isEqualTo(1); - assertThat(metricRegistry.counter("pg.delivery_request_successful").getCount()).isEqualTo(1); - } - - @Test - public void updateDeliveryRequestMetricShouldIncrementDeliveryRequestAndFailedDeliveryRequest() { - // when - metrics.updateDeliveryRequestMetric(false); - - // then - assertThat(metricRegistry.counter("pg.delivery_requests").getCount()).isEqualTo(1); - assertThat(metricRegistry.counter("pg.delivery_request_failed").getCount()).isEqualTo(1); - } - - @Test - public void updateLineItemsNumberMetricShouldIncrementLineItemsNumberForAAcountValue() { - // when - metrics.updateLineItemsNumberMetric(20L); - - // then - assertThat(metricRegistry.counter("pg.planner_lineitems_received").getCount()).isEqualTo(20); - } - - @Test - public void updatePlannerRequestTimeShouldLogTime() { - // when - metrics.updatePlannerRequestTime(20L); - - // then - assertThat(metricRegistry.timer("pg.planner_request_time").getCount()).isEqualTo(1); - } - - @Test - public void updateDeliveryRequestTimeShouldLogTime() { - // when - metrics.updateDeliveryRequestTime(20L); - - // then - assertThat(metricRegistry.timer("pg.delivery_request_time").getCount()).isEqualTo(1); - } - @Test public void updateAuctionTcfMetricsShouldIncrementMetrics() { // when @@ -1353,15 +1219,6 @@ public void updateAccountModuleDurationMetricShouldNotIncrementMetricsIfVerbosit .isZero(); } - @Test - public void shouldIncrementWinNotificationMetric() { - // when - metrics.updateWinNotificationMetric(); - - // then - assertThat(metricRegistry.counter("win_notifications").getCount()).isEqualTo(1); - } - @Test public void shouldIncrementRequestsActivityDisallowedCount() { // when diff --git a/src/test/java/org/prebid/server/util/HttpUtilTest.java b/src/test/java/org/prebid/server/util/HttpUtilTest.java index 7abfcc6532f..d516ad2c6d8 100644 --- a/src/test/java/org/prebid/server/util/HttpUtilTest.java +++ b/src/test/java/org/prebid/server/util/HttpUtilTest.java @@ -11,18 +11,15 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; -import org.prebid.server.exception.PreBidException; import org.prebid.server.model.CaseInsensitiveMultiMap; import org.prebid.server.model.HttpRequestContext; -import java.time.ZonedDateTime; import java.util.Map; import java.util.function.Consumer; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; @@ -204,53 +201,4 @@ public void executeSafelyShouldReturnFalseIfResponseFailed() { // then assertThat(result).isFalse(); } - - @Test - public void getDateFromHeaderShouldReturnDate() { - // given - final MultiMap headers = MultiMap.caseInsensitiveMultiMap().add("date-header", - "2019-11-04T13:31:24.365+02:00[Europe/Kiev]"); - - // when - final ZonedDateTime result = HttpUtil.getDateFromHeader(headers, "date-header"); - - // then - assertThat(result).isEqualTo(ZonedDateTime.parse("2019-11-04T13:31:24.365+02:00[Europe/Kiev]")); - } - - @Test - public void getDateFromHeaderShouldReturnNullWhenHeaderWasNotFound() { - // given - final MultiMap headers = MultiMap.caseInsensitiveMultiMap(); - - // when - final ZonedDateTime result = HttpUtil.getDateFromHeader(headers, "not-exist"); - - // then - assertThat(result).isNull(); - } - - @Test - public void getDateFromHeaderShouldThrowExceptionWhenHeaderHasIncorrectFormat() { - // given - final MultiMap headers = MultiMap.caseInsensitiveMultiMap().add("date-header", "invalid"); - - // when and then - assertThatThrownBy(() -> HttpUtil.getDateFromHeader(headers, "date-header")) - .isInstanceOf(PreBidException.class) - .hasMessage("date-header header is not compatible to ISO-8601 format: invalid"); - } - - @Test - public void getDateFromHeaderShouldReturnDateFromHeaders() { - // given - final MultiMap headers = MultiMap.caseInsensitiveMultiMap().add("date-header", - "2019-11-04T13:31:24.365+02:00[Europe/Kiev]"); - - // when - final ZonedDateTime result = HttpUtil.getDateFromHeader(headers, "date-header"); - - // then - assertThat(result).isEqualTo(ZonedDateTime.parse("2019-11-04T13:31:24.365+02:00[Europe/Kiev]")); - } } diff --git a/src/test/java/org/prebid/server/validation/ResponseBidValidatorTest.java b/src/test/java/org/prebid/server/validation/ResponseBidValidatorTest.java index 2b87c30ae63..42ea4cb3f4a 100644 --- a/src/test/java/org/prebid/server/validation/ResponseBidValidatorTest.java +++ b/src/test/java/org/prebid/server/validation/ResponseBidValidatorTest.java @@ -20,8 +20,6 @@ import org.prebid.server.bidder.model.BidderBid; import org.prebid.server.metric.MetricName; import org.prebid.server.metric.Metrics; -import org.prebid.server.proto.openrtb.ext.request.ExtDeal; -import org.prebid.server.proto.openrtb.ext.request.ExtDealLine; import org.prebid.server.proto.openrtb.ext.response.BidType; import org.prebid.server.settings.model.Account; import org.prebid.server.settings.model.AccountAuctionConfig; @@ -37,7 +35,6 @@ import static java.util.function.UnaryOperator.identity; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; import static org.prebid.server.settings.model.BidValidationEnforcement.enforce; @@ -62,7 +59,7 @@ public class ResponseBidValidatorTest extends VertxTest { @Before public void setUp() { - target = new ResponseBidValidator(enforce, enforce, metrics, jacksonMapper, true, 0.01); + target = new ResponseBidValidator(enforce, enforce, metrics, 0.01); given(bidderAliases.resolveBidder(anyString())).willReturn(BIDDER_NAME); } @@ -359,7 +356,7 @@ public void validateShouldReturnSuccessfulResultForValidBid() { @Test public void validateShouldReturnSuccessIfBannerSizeValidationNotEnabled() { // given - target = new ResponseBidValidator(skip, enforce, metrics, jacksonMapper, true, 0.01); + target = new ResponseBidValidator(skip, enforce, metrics, 0.01); // when final ValidationResult result = target.validate( @@ -375,7 +372,7 @@ public void validateShouldReturnSuccessIfBannerSizeValidationNotEnabled() { @Test public void validateShouldReturnSuccessWithWarningIfBannerSizeEnforcementIsWarn() { // given - target = new ResponseBidValidator(warn, enforce, metrics, jacksonMapper, true, 0.01); + target = new ResponseBidValidator(warn, enforce, metrics, 0.01); // when final ValidationResult result = target.validate( @@ -396,7 +393,7 @@ public void validateShouldReturnSuccessWithWarningIfBannerSizeEnforcementIsWarn( @Test public void validateShouldReturnSuccessIfSecureMarkupValidationNotEnabled() { // given - target = new ResponseBidValidator(enforce, skip, metrics, jacksonMapper, true, 0.01); + target = new ResponseBidValidator(enforce, skip, metrics, 0.01); // when final ValidationResult result = target.validate( @@ -412,7 +409,7 @@ public void validateShouldReturnSuccessIfSecureMarkupValidationNotEnabled() { @Test public void validateShouldReturnSuccessWithWarningIfSecureMarkupEnforcementIsWarn() { // given - target = new ResponseBidValidator(enforce, warn, metrics, jacksonMapper, true, 0.01); + target = new ResponseBidValidator(enforce, warn, metrics, 0.01); // when final ValidationResult result = target.validate( @@ -446,7 +443,7 @@ public void validateShouldIncrementSizeValidationErrMetrics() { @Test public void validateShouldIncrementSizeValidationWarnMetrics() { // given - target = new ResponseBidValidator(warn, warn, metrics, jacksonMapper, true, 0.01); + target = new ResponseBidValidator(warn, warn, metrics, 0.01); // when target.validate( @@ -475,7 +472,7 @@ public void validateShouldIncrementSecureValidationErrMetrics() { @Test public void validateShouldIncrementSecureValidationWarnMetrics() { // given - target = new ResponseBidValidator(warn, warn, metrics, jacksonMapper, true, 0.01); + target = new ResponseBidValidator(warn, warn, metrics, 0.01); // when target.validate( @@ -488,189 +485,6 @@ public void validateShouldIncrementSecureValidationWarnMetrics() { verify(metrics).updateSecureValidationMetrics(BIDDER_NAME, ACCOUNT_ID, MetricName.warn); } - @Test - public void validateShouldReturnSuccessfulResultForValidNonDealBid() { - final ValidationResult result = target.validate( - givenVideoBid(identity()), - BIDDER_NAME, - givenAuctionContext(), - bidderAliases); - - assertThat(result.hasErrors()).isFalse(); - } - - @Test - public void validateShouldFailIfBidHasNoDealid() { - final ValidationResult result = target.validate( - givenVideoBid(identity()), - BIDDER_NAME, - givenAuctionContext(givenRequest(identity())), - bidderAliases); - - assertThat(result.getErrors()).hasSize(1) - .containsOnly("Bid \"bidId1\" missing required field 'dealid'"); - } - - @Test - public void validateShouldSuccessIfBidHasDealidAndImpHasNoDeals() { - final ValidationResult result = target.validate( - givenVideoBid(bid -> bid.dealid("dealId1")), - BIDDER_NAME, - givenAuctionContext(givenRequest(identity())), - bidderAliases); - - assertThat(result.getErrors()).isEmpty(); - assertThat(result.getWarnings()).isEmpty(); - } - - @Test - public void validateShouldWarnIfBidHasDealidMissingInImp() { - given(bidderAliases.isSame(eq(BIDDER_NAME), eq(BIDDER_NAME))).willReturn(true); - - final ValidationResult result = target.validate( - givenVideoBid(bid -> bid.dealid("dealId1")), - BIDDER_NAME, - givenAuctionContext(givenRequest(imp -> imp.pmp(pmp(asList( - deal(builder -> builder - .id("dealId2") - .ext(mapper.valueToTree(ExtDeal.of( - ExtDealLine.of(null, null, null, BIDDER_NAME))))), - deal(builder -> builder - .id("dealId3") - .ext(mapper.valueToTree(ExtDeal.of( - ExtDealLine.of(null, null, null, BIDDER_NAME))))), - deal(builder -> builder - .id("dealId4") - .ext(mapper.valueToTree(ExtDeal.of( - ExtDealLine.of(null, null, null, "anotherBidder")))))))))), - bidderAliases); - - assertThat(result.getWarnings()).hasSize(1) - .containsOnly("WARNING: Bid \"bidId1\" has 'dealid' not present in corresponding imp in request." - + " 'dealid' in bid: 'dealId1', deal Ids in imp: 'dealId2,dealId3'"); - } - - @Test - public void validateShouldFailIfBidIsBannerAndImpHasNoBanner() { - target = new ResponseBidValidator(skip, enforce, metrics, jacksonMapper, true, 0.01); - - final ValidationResult result = target.validate( - givenBid(bid -> bid.dealid("dealId1")), - BIDDER_NAME, - givenAuctionContext(givenRequest(imp -> imp - .pmp(pmp(singletonList(deal(builder -> builder.id("dealId1"))))))), - bidderAliases); - - assertThat(result.getErrors()).hasSize(1) - .containsOnly("Bid \"bidId1\" has banner media type but corresponding imp in request is missing " - + "'banner' object"); - } - - @Test - public void validateShouldFailIfBidIsBannerAndSizeHasNoMatchInBannerFormats() { - final ValidationResult result = target.validate( - givenBid(bid -> bid.dealid("dealId1").w(300).h(400)), - BIDDER_NAME, - givenAuctionContext(givenRequest(imp -> imp - .pmp(pmp(singletonList(deal(builder -> builder.id("dealId1"))))) - .banner(Banner.builder() - .format(singletonList(Format.builder().w(400).h(500).build())) - .build()))), - bidderAliases); - - assertThat(result.getErrors()).hasSize(1) - .containsOnly("Bid \"bidId1\" has 'w' and 'h' not supported by corresponding imp in request. Bid " - + "dimensions: '300x400', formats in imp: '400x500'"); - } - - @Test - public void validateShouldFailIfBidIsBannerAndSizeHasNoMatchInLineItem() { - final ValidationResult result = target.validate( - givenBid(bid -> bid.dealid("dealId1").w(300).h(400)), - BIDDER_NAME, - givenAuctionContext(givenRequest(imp -> imp - .pmp(pmp(singletonList(deal(builder -> builder - .id("dealId1") - .ext(mapper.valueToTree(ExtDeal.of(ExtDealLine.of("lineItemId", null, - singletonList(Format.builder().w(500).h(600).build()), null)))))))) - .banner(Banner.builder() - .format(singletonList(Format.builder().w(300).h(400).build())) - .build()))), - bidderAliases); - - assertThat(result.getErrors()).hasSize(1) - .containsOnly("Bid \"bidId1\" has 'w' and 'h' not matched to Line Item. Bid dimensions: '300x400', " - + "Line Item sizes: '500x600'"); - } - - @Test - public void validateShouldFailIfBidIsBannerAndMatchingLineItemDoesNotHaveSizes() { - final ValidationResult result = target.validate( - givenBid(bid -> bid.dealid("dealId1").w(300).h(400)), - BIDDER_NAME, - givenAuctionContext(givenRequest(imp -> imp - .pmp(pmp(singletonList(deal(builder -> builder - .id("dealId1") - .ext(mapper.valueToTree(ExtDeal.of(ExtDealLine.of("lineItemId", null, - null, null)))))))) - .banner(Banner.builder() - .format(singletonList(Format.builder().w(300).h(400).build())) - .build()))), - bidderAliases); - - assertThat(result.getErrors()).hasSize(1) - .containsOnly("Line item sizes were not found for bidId bidId1 and dealId dealId1"); - } - - @Test - public void validateShouldSuccessIfBidIsBannerAndSizeHasNoMatchInLineItemForNonPgDeal() { - final ValidationResult result = target.validate( - givenBid(bid -> bid.dealid("dealId1").w(300).h(400)), - BIDDER_NAME, - givenAuctionContext(givenRequest(imp -> imp - .pmp(pmp(singletonList(deal(builder -> builder - .id("dealId1") - .ext(mapper.valueToTree(ExtDeal.of(ExtDealLine.of(null, null, - singletonList(Format.builder().w(500).h(600).build()), null)))))))) - .banner(Banner.builder() - .format(singletonList(Format.builder().w(300).h(400).build())) - .build()))), - bidderAliases); - - assertThat(result.getErrors()).isEmpty(); - assertThat(result.getWarnings()).isEmpty(); - } - - @Test - public void validateShouldReturnSuccessfulResultForValidDealNonBannerBid() { - final ValidationResult result = target.validate( - givenVideoBid(bid -> bid.dealid("dealId1")), - BIDDER_NAME, - givenAuctionContext(givenRequest(imp -> imp.pmp(pmp(singletonList( - deal(builder -> builder.id("dealId1"))))))), - bidderAliases); - - assertThat(result.hasErrors()).isFalse(); - } - - @Test - public void validateShouldReturnSuccessfulResultForValidDealBannerBid() { - final ValidationResult result = target.validate( - givenBid(bid -> bid.dealid("dealId1").w(300).h(400)), - BIDDER_NAME, - givenAuctionContext(givenRequest(imp -> imp - .pmp(pmp(singletonList(deal(builder -> builder - .id("dealId1") - .ext(mapper.valueToTree(ExtDeal.of(ExtDealLine.of(null, null, - singletonList(Format.builder().w(300).h(400).build()), null)))))))) - .banner(Banner.builder() - .format(singletonList(Format.builder().w(300).h(400).build())) - .build()))), - bidderAliases); - - assertThat(result.hasErrors()).isFalse(); - } - private BidRequest givenRequest(UnaryOperator impCustomizer) { final ObjectNode ext = mapper.createObjectNode().set( "prebid", mapper.createObjectNode().set( diff --git a/src/test/java/org/prebid/server/vast/VastModifierTest.java b/src/test/java/org/prebid/server/vast/VastModifierTest.java index 5593a535028..fed272f1524 100644 --- a/src/test/java/org/prebid/server/vast/VastModifierTest.java +++ b/src/test/java/org/prebid/server/vast/VastModifierTest.java @@ -35,7 +35,6 @@ public class VastModifierTest { private static final String VAST_URL_TRACKING = "http://external-url/event"; private static final String BID_ID = "bidId"; private static final String BID_NURL = "nurl1"; - private static final String LINEITEM_ID = "lineItemId"; private static final long AUCTION_TIMESTAMP = 1000L; @Rule @@ -52,7 +51,7 @@ public class VastModifierTest { @Before public void setUp() { - given(eventsService.vastUrlTracking(any(), any(), any(), any(), any())) + given(eventsService.vastUrlTracking(any(), any(), any(), any())) .willReturn(VAST_URL_TRACKING); given(bidderCatalog.isModifyingVastXmlAllowed(any())).willReturn(true); @@ -97,7 +96,7 @@ public void modifyVastXmlShouldNotModifyVastAndAppendUrlWhenValueWithoutImpressi final JsonNode result = target.modifyVastXml(true, singleton(BIDDER), givenPutObject(vastWithoutImpression), ACCOUNT_ID, INTEGRATION); - verify(eventsService).vastUrlTracking(any(), any(), any(), any(), any()); + verify(eventsService).vastUrlTracking(any(), any(), any(), any()); assertThat(result).isEqualTo(vastWithoutImpression); } @@ -111,11 +110,11 @@ public void modifyVastXmlShouldModifyVastAndAppendUrl() { // then final String modifiedVast = """ - prebid.org wrapper\ - \ - \ - \ - """; + prebid.org wrapper\ + \ + \ + \ + """; assertThat(result).isEqualTo(new TextNode(modifiedVast)); } @@ -127,8 +126,7 @@ public void createBidVastXmlShouldNotModifyWhenBidderNotAllowed() { // when final String result = target - .createBidVastXml(BIDDER, adm(), BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), emptyList(), - LINEITEM_ID); + .createBidVastXml(BIDDER, adm(), BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), emptyList()); // then assertThat(result).isEqualTo(adm()); @@ -137,8 +135,8 @@ public void createBidVastXmlShouldNotModifyWhenBidderNotAllowed() { @Test public void createBidVastXmlShouldInjectBidNurlWhenBidAdmIsNullAndEventsDisabledByAccount() { // when - final String result = target.createBidVastXml(BIDDER, null, BID_NURL, BID_ID, ACCOUNT_ID, - givenEventsContext(false), emptyList(), LINEITEM_ID); + final String result = target + .createBidVastXml(BIDDER, null, BID_NURL, BID_ID, ACCOUNT_ID, givenEventsContext(false), emptyList()); // then assertThat(result).isEqualTo(modifiedAdm(BID_NURL)); @@ -147,8 +145,8 @@ public void createBidVastXmlShouldInjectBidNurlWhenBidAdmIsNullAndEventsDisabled @Test public void createBidVastXmlShouldInjectBidNurlWhenBidAdmIsEmptyAndEventsDisabledByAccount() { // when - final String result = target.createBidVastXml(BIDDER, "", BID_NURL, BID_ID, ACCOUNT_ID, - givenEventsContext(false), emptyList(), LINEITEM_ID); + final String result = target + .createBidVastXml(BIDDER, "", BID_NURL, BID_ID, ACCOUNT_ID, givenEventsContext(false), emptyList()); // then assertThat(result).isEqualTo(modifiedAdm(BID_NURL)); @@ -157,8 +155,8 @@ public void createBidVastXmlShouldInjectBidNurlWhenBidAdmIsEmptyAndEventsDisable @Test public void createBidVastXmlShouldReturnAdmWhenBidAdmIsPresentAndEventsDisabledByAccount() { // when - final String result = target.createBidVastXml(BIDDER, adm(), BID_NURL, BID_ID, ACCOUNT_ID, - givenEventsContext(false), emptyList(), LINEITEM_ID); + final String result = target + .createBidVastXml(BIDDER, adm(), BID_NURL, BID_ID, ACCOUNT_ID, givenEventsContext(false), emptyList()); // then assertThat(result).isEqualTo(adm()); @@ -169,11 +167,10 @@ public void createBidVastXmlShouldBeModifiedWithNewImpressionVastUrlWhenEventsEn // when final String bidAdm = "http:/test.com"; final String result = target - .createBidVastXml(BIDDER, bidAdm, BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), emptyList(), - LINEITEM_ID); + .createBidVastXml(BIDDER, bidAdm, BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), emptyList()); // then - verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, LINEITEM_ID, eventsContext()); + verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, eventsContext()); assertThat(result).isEqualTo("http:/test.com" + ""); @@ -185,11 +182,10 @@ public void createBidVastXmlShouldBeModifiedWithNewImpressionAfterExistingImpres final String bidAdm = "http:/test.com" + "http:/test2.com"; final String result = target - .createBidVastXml(BIDDER, bidAdm, BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), emptyList(), - LINEITEM_ID); + .createBidVastXml(BIDDER, bidAdm, BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), emptyList()); // then - verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, LINEITEM_ID, eventsContext()); + verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, eventsContext()); assertThat(result).isEqualTo("http:/test.com" + "http:/test2.com" @@ -201,11 +197,10 @@ public void createBidVastXmlShouldInsertImpressionTagForEmptyInLine() { // when final String bidAdm = ""; final String result = target - .createBidVastXml(BIDDER, bidAdm, BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), emptyList(), - LINEITEM_ID); + .createBidVastXml(BIDDER, bidAdm, BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), emptyList()); // then - verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, LINEITEM_ID, eventsContext()); + verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, eventsContext()); assertThat(result).isEqualTo(""); } @@ -215,11 +210,10 @@ public void createBidVastXmlShouldNotInsertImpressionTagForNoInLineCloseTag() { // when final String bidAdm = ""; final String result = target - .createBidVastXml(BIDDER, bidAdm, BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), emptyList(), - LINEITEM_ID); + .createBidVastXml(BIDDER, bidAdm, BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), emptyList()); // then - verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, LINEITEM_ID, eventsContext()); + verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, eventsContext()); assertThat(result).isEqualTo(bidAdm); } @@ -229,11 +223,10 @@ public void createBidVastXmlShouldModifyWrapperTagInCaseInsensitiveMode() { // when final String bidAdm = "http:/test.com"; final String result = target - .createBidVastXml(BIDDER, bidAdm, BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), emptyList(), - LINEITEM_ID); + .createBidVastXml(BIDDER, bidAdm, BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), emptyList()); // then - verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, LINEITEM_ID, eventsContext()); + verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, eventsContext()); assertThat(result).isEqualTo("http:/test.com" + ""); @@ -242,13 +235,11 @@ public void createBidVastXmlShouldModifyWrapperTagInCaseInsensitiveMode() { @Test public void createBidVastXmlShouldInsertImpressionTagForEmptyWrapper() { // when - final String result = target - .createBidVastXml(BIDDER, "", BID_NURL, - BID_ID, ACCOUNT_ID, eventsContext(), emptyList(), - LINEITEM_ID); + final String result = target.createBidVastXml( + BIDDER, "", BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), emptyList()); // then - verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, LINEITEM_ID, eventsContext()); + verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, eventsContext()); assertThat(result) .isEqualTo(""); @@ -259,11 +250,10 @@ public void createBidVastXmlShouldNotInsertImpressionTagForNoWrapperCloseTag() { // when final String bidAdm = ""; final String result = target - .createBidVastXml(BIDDER, bidAdm, BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), emptyList(), - LINEITEM_ID); + .createBidVastXml(BIDDER, bidAdm, BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), emptyList()); // then - verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, LINEITEM_ID, eventsContext()); + verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, eventsContext()); assertThat(result).isEqualTo(bidAdm); } @@ -273,11 +263,10 @@ public void createBidVastXmlShouldModifyInlineTagInCaseInsensitiveMode() { // when final String bidAdm = "http:/test.com"; final String result = target - .createBidVastXml(BIDDER, bidAdm, BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), emptyList(), - LINEITEM_ID); + .createBidVastXml(BIDDER, bidAdm, BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), emptyList()); // then - verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, LINEITEM_ID, eventsContext()); + verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, eventsContext()); assertThat(result).isEqualTo("http:/test.com" + ""); @@ -288,11 +277,10 @@ public void createBidVastXmlShouldBeModifiedIfInLineHasNoImpressionTags() { // when final String bidAdm = ""; final String result = target - .createBidVastXml(BIDDER, bidAdm, BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), emptyList(), - LINEITEM_ID); + .createBidVastXml(BIDDER, bidAdm, BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), emptyList()); // then - verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, LINEITEM_ID, eventsContext()); + verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, eventsContext()); assertThat(result).isEqualTo(""); } @@ -303,10 +291,10 @@ public void createBidVastXmlShouldNotBeModifiedIfNoParentTagsPresent() { final String adm = "http:/test.com"; final List warnings = new ArrayList<>(); final String result = target - .createBidVastXml(BIDDER, adm, BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), warnings, LINEITEM_ID); + .createBidVastXml(BIDDER, adm, BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), warnings); // then - verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, LINEITEM_ID, eventsContext()); + verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, eventsContext()); assertThat(result).isEqualTo(adm); assertThat(warnings).containsExactly("VastXml does not contain neither InLine nor Wrapper for bidder response"); verify(metrics).updateAdapterRequestErrorMetric(BIDDER, MetricName.badserverresponse); @@ -316,11 +304,11 @@ public void createBidVastXmlShouldNotBeModifiedIfNoParentTagsPresent() { public void createBidVastXmlShouldNotModifyWhenEventsEnabledAndAdmHaveNoImpression() { // when final String admWithNoImpression = "no impression"; - final String result = target.createBidVastXml(BIDDER, admWithNoImpression, BID_NURL, BID_ID, - ACCOUNT_ID, eventsContext(), new ArrayList<>(), LINEITEM_ID); + final String result = target.createBidVastXml( + BIDDER, admWithNoImpression, BID_NURL, BID_ID, ACCOUNT_ID, eventsContext(), new ArrayList<>()); // then - verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, LINEITEM_ID, eventsContext()); + verify(eventsService).vastUrlTracking(BID_ID, BIDDER, ACCOUNT_ID, eventsContext()); assertThat(result).isEqualTo(admWithNoImpression); } diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-device-targeting.json b/src/test/resources/org/prebid/server/deals/targeting/test-device-targeting.json deleted file mode 100644 index b28efce2c2f..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-device-targeting.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "$and": [ - { - "device.ext.deviceinfoprovider.browser": { - "$in": [ - "Chrome", - "Firefox" - ] - } - }, - { - "device.geo.ext.geoprovider.country": { - "$in": [ - "us", - "jp" - ] - } - } - ] -} diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-and-with-non-array.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-and-with-non-array.json deleted file mode 100644 index 4459a762640..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-and-with-non-array.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "$and": {} -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-category-incompatible-function.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-category-incompatible-function.json deleted file mode 100644 index 8315dec8997..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-category-incompatible-function.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "adunit.size": { - "$in": [] - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-category-incompatible-geo-function.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-category-incompatible-geo-function.json deleted file mode 100644 index 07ac026bd2b..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-category-incompatible-geo-function.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "geo.distance": { - "$intersects": [] - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-category-incompatible-segment-function.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-category-incompatible-segment-function.json deleted file mode 100644 index ea2a189602f..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-category-incompatible-segment-function.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "segment.bluekai": { - "$in": [] - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-category-incompatible-string-function.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-category-incompatible-string-function.json deleted file mode 100644 index b451647996b..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-category-incompatible-string-function.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "adunit.adslot": { - "$intersects": [] - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-category-incompatible-typed-function.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-category-incompatible-typed-function.json deleted file mode 100644 index eddac02192f..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-category-incompatible-typed-function.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "bidp.rubicon.siteId": { - "$within": [] - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-category-non-object.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-category-non-object.json deleted file mode 100644 index f67d1e4a258..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-category-non-object.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "adunit.size": 123 -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-in-integers-non-integer.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-in-integers-non-integer.json deleted file mode 100644 index 19fd40b0906..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-in-integers-non-integer.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "user.ext.time.userhour": { - "$in": [ - "abc" - ] - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-intersects-non-array.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-intersects-non-array.json deleted file mode 100644 index 85710c883e9..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-intersects-non-array.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "adunit.size": { - "$intersects": {} - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-intersects-sizes-empty-size.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-intersects-sizes-empty-size.json deleted file mode 100644 index e3c0b26ba08..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-intersects-sizes-empty-size.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "adunit.size": { - "$intersects": [ - { - } - ] - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-intersects-sizes-non-objects.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-intersects-sizes-non-objects.json deleted file mode 100644 index 91b6c932bde..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-intersects-sizes-non-objects.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "adunit.size": { - "$intersects": [ - 123, - 234 - ] - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-intersects-sizes-non-readable-size.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-intersects-sizes-non-readable-size.json deleted file mode 100644 index 57ef2fce627..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-intersects-sizes-non-readable-size.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "adunit.size": { - "$intersects": [ - { - "w": {} - } - ] - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-intersects-strings-empty.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-intersects-strings-empty.json deleted file mode 100644 index 5a1cd32db73..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-intersects-strings-empty.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "adunit.mediatype": { - "$intersects": [ - "" - ] - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-intersects-strings-non-string.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-intersects-strings-non-string.json deleted file mode 100644 index 974de4e4c1a..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-intersects-strings-non-string.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "adunit.mediatype": { - "$intersects": [ - 123 - ] - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-matches-empty.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-matches-empty.json deleted file mode 100644 index 413e4c7b71f..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-matches-empty.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "adunit.adslot": { - "$matches": "" - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-matches-non-string.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-matches-non-string.json deleted file mode 100644 index 3f2439279d9..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-matches-non-string.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "adunit.adslot": { - "$matches": 123 - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-multiple-fields-boolean-args.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-multiple-fields-boolean-args.json deleted file mode 100644 index d544404457e..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-multiple-fields-boolean-args.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "$and": [ - { - "aaa": {}, - "bbb": {} - } - ] -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-multiple-fields-function.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-multiple-fields-function.json deleted file mode 100644 index f4d51caf96b..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-multiple-fields-function.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "adunit.size": { - "aaa": {}, - "bbb": {} - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-multiple-fields.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-multiple-fields.json deleted file mode 100644 index 186dd09685f..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-multiple-fields.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "aaa": {}, - "bbb": {} -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-non-object.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-non-object.json deleted file mode 100644 index 5862557ee7f..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-non-object.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "$and": 123 -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-not-with-non-object.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-not-with-non-object.json deleted file mode 100644 index 6741ef4d8ef..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-not-with-non-object.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "$not": [] -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-typed-function-incompatible-type.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-typed-function-incompatible-type.json deleted file mode 100644 index edafbc6a05b..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-typed-function-incompatible-type.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "bidp.rubicon.siteId": { - "$in": [ - false - ] - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-typed-function-mixed-types.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-typed-function-mixed-types.json deleted file mode 100644 index 40b94d6ec36..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-typed-function-mixed-types.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "bidp.rubicon.siteId": { - "$in": [ - 123, - "321" - ] - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-unknown-field.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-unknown-field.json deleted file mode 100644 index 81cc228d55f..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-unknown-field.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "aaa": {} -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-unknown-function.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-unknown-function.json deleted file mode 100644 index ccea774510a..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-unknown-function.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "adunit.size": { - "$abc": [] - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-unknown-string-function.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-unknown-string-function.json deleted file mode 100644 index d83962f0989..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-unknown-string-function.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "adunit.adslot": { - "$abc": [] - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-unknown-typed-function.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-unknown-typed-function.json deleted file mode 100644 index 0cc0c3a781b..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-unknown-typed-function.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "bidp.rubicon.siteId": { - "$abc": [] - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-within-empty-georegion.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-within-empty-georegion.json deleted file mode 100644 index 22a638b0b53..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-within-empty-georegion.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "geo.distance": { - "$within": { - } - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-within-non-object.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-within-non-object.json deleted file mode 100644 index d10af646564..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-within-non-object.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "geo.distance": { - "$within": [] - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-within-non-readable-georegion.json b/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-within-non-readable-georegion.json deleted file mode 100644 index b21c6a2523d..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-invalid-targeting-definition-within-non-readable-georegion.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "geo.distance": { - "$within": { - "lat": {} - } - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-not-and-definition.json b/src/test/resources/org/prebid/server/deals/targeting/test-not-and-definition.json deleted file mode 100644 index ddb8501fd06..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-not-and-definition.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "$not": { - "$and": [ - { - "adunit.size": { - "$intersects": [ - { - "w": 450, - "h": 250 - }, - { - "w": 400, - "h": 200 - } - ] - } - }, - { - "adunit.mediatype": { - "$intersects": [ - "banner", - "video" - ] - } - } - ] - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-not-in-integers-definition.json b/src/test/resources/org/prebid/server/deals/targeting/test-not-in-integers-definition.json deleted file mode 100644 index 27284bdc6d3..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-not-in-integers-definition.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "$not": { - "bidp.rubicon.siteId": { - "$in": [ - 785, - 778 - ] - } - } -} diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-not-in-strings-definition.json b/src/test/resources/org/prebid/server/deals/targeting/test-not-in-strings-definition.json deleted file mode 100644 index 011d00d81c1..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-not-in-strings-definition.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "$not": { - "site.domain": { - "$in": [ - "nba.com", - "cnn.com" - ] - } - } -} diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-not-intersects-integer-definition.json b/src/test/resources/org/prebid/server/deals/targeting/test-not-intersects-integer-definition.json deleted file mode 100644 index 08c0b5c166c..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-not-intersects-integer-definition.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "$not": { - "ufpd.data.someId": { - "$intersects": [ - 123, - 321 - ] - } - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-not-intersects-sizes-definition.json b/src/test/resources/org/prebid/server/deals/targeting/test-not-intersects-sizes-definition.json deleted file mode 100644 index 50f0f524a4b..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-not-intersects-sizes-definition.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "$not": { - "adunit.size": { - "$intersects": [ - { - "w": 450, - "h": 250 - }, - { - "w": 400, - "h": 200 - } - ] - } - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-not-matches-definition.json b/src/test/resources/org/prebid/server/deals/targeting/test-not-matches-definition.json deleted file mode 100644 index 4f3d9a69c3f..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-not-matches-definition.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "$not": { - "site.domain": { - "$matches": "*nba.com*" - } - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-not-or-definition.json b/src/test/resources/org/prebid/server/deals/targeting/test-not-or-definition.json deleted file mode 100644 index b8da565c351..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-not-or-definition.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "$not": { - "$or": [ - { - "adunit.size": { - "$intersects": [ - { - "w": 450, - "h": 250 - }, - { - "w": 400, - "h": 200 - } - ] - } - }, - { - "adunit.mediatype": { - "$intersects": [ - "banner", - "video" - ] - } - } - ] - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-not-within-definition.json b/src/test/resources/org/prebid/server/deals/targeting/test-not-within-definition.json deleted file mode 100644 index 98a0670f5fa..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-not-within-definition.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "$not": { - "geo.distance": { - "$within": { - "lat": 2.424744, - "lon": 3.506435, - "radiusMiles": 10 - } - } - } -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/deals/targeting/test-valid-targeting-definition.json b/src/test/resources/org/prebid/server/deals/targeting/test-valid-targeting-definition.json deleted file mode 100644 index cd2acc99523..00000000000 --- a/src/test/resources/org/prebid/server/deals/targeting/test-valid-targeting-definition.json +++ /dev/null @@ -1,354 +0,0 @@ -{ - "$and": [ - { - "adunit.size": { - "$intersects": [ - { - "w": 300, - "h": 250 - }, - { - "w": 400, - "h": 200 - } - ] - } - }, - { - "adunit.mediatype": { - "$intersects": [ - "banner", - "video" - ] - } - }, - { - "$or": [ - { - "site.domain": { - "$matches": "*nba.com*" - } - }, - { - "site.domain": { - "$matches": "nba.com*" - } - }, - { - "site.domain": { - "$in": [ - "nba.com", - "cnn.com" - ] - } - } - ] - }, - { - "$or": [ - { - "site.referrer": { - "$matches": "*sports*" - } - }, - { - "site.referrer": { - "$matches": "http://nba.com/lalakers*" - } - }, - { - "site.referrer": { - "$in": [ - "http://cnn.com/culture", - "http://cnn.com/weather" - ] - } - } - ] - }, - { - "$or": [ - { - "app.bundle": { - "$matches": "*com.google.calendar*" - } - }, - { - "app.bundle": { - "$matches": "com.google.calendar*" - } - }, - { - "app.bundle": { - "$in": [ - "com.google.calendar", - "com.tmz" - ] - } - } - ] - }, - { - "$or": [ - { - "adunit.adslot": { - "$matches": "*/home/top*" - } - }, - { - "adunit.adslot": { - "$matches": "/home/top*" - } - }, - { - "adunit.adslot": { - "$in": [ - "/home/top", - "/home/bottom" - ] - } - } - ] - }, - { - "device.geo.ext.vendor.attribute": { - "$in": [ - "device_geo_ext_value1", - "device_geo_ext_value2" - ] - } - }, - { - "device.geo.ext.vendor.nested.attribute": { - "$in": [ - "device_geo_ext_nested_value1", - "device_geo_ext_nested_value2" - ] - } - }, - { - "device.ext.vendor.attribute": { - "$in": [ - "device_ext_value1", - "device_ext_value2" - ] - } - }, - { - "device.ext.vendor.nested.attribute": { - "$in": [ - "device_ext_nested_value1", - "device_ext_nested_value2" - ] - } - }, - { - "pos": { - "$in": [ - 1, - 3 - ] - } - }, - { - "geo.distance": { - "$within": { - "lat": 123.456, - "lon": 789.123, - "radiusMiles": 10 - } - } - }, - { - "$or": [ - { - "bidp.rubicon.siteId": { - "$in": [ - 123, - 321 - ] - } - }, - { - "bidp.rubicon.siteId": { - "$intersects": [ - 123, - 321 - ] - } - } - ] - }, - { - "$or": [ - { - "bidp.appnexus.placementName": { - "$matches": "*somePlacement*" - } - }, - { - "bidp.appnexus.placementName": { - "$matches": "somePlacement*" - } - }, - { - "bidp.appnexus.placementName": { - "$in": [ - "somePlacement1", - "somePlacement2" - ] - } - }, - { - "bidp.appnexus.placementName": { - "$intersects": [ - "somePlacement1", - "somePlacement2" - ] - } - } - ] - }, - { - "$or": [ - { - "segment.rubicon": { - "$intersects": [ - "123", - "234", - "345" - ] - } - }, - { - "segment.bluekai": { - "$intersects": [ - "123", - "234", - "345" - ] - } - } - ] - }, - { - "$or": [ - { - "ufpd.someId": { - "$in": [ - 123, - 321 - ] - } - }, - { - "ufpd.someId": { - "$intersects": [ - 123, - 321 - ] - } - } - ] - }, - { - "$or": [ - { - "ufpd.sport": { - "$matches": "*hockey*" - } - }, - { - "ufpd.sport": { - "$matches": "hockey*" - } - }, - { - "ufpd.sport": { - "$in": [ - "hockey", - "soccer" - ] - } - }, - { - "ufpd.sport": { - "$intersects": [ - "hockey", - "soccer" - ] - } - } - ] - }, - { - "$or": [ - { - "sfpd.someId": { - "$in": [ - 123, - 321 - ] - } - }, - { - "sfpd.someId": { - "$intersects": [ - 123, - 321 - ] - } - } - ] - }, - { - "$or": [ - { - "sfpd.sport": { - "$matches": "*hockey*" - } - }, - { - "sfpd.sport": { - "$matches": "hockey*" - } - }, - { - "sfpd.sport": { - "$in": [ - "hockey", - "soccer" - ] - } - }, - { - "sfpd.sport": { - "$intersects": [ - "hockey", - "soccer" - ] - } - } - ] - }, - { - "user.ext.time.userdow": { - "$in": [ - 5, - 6 - ] - } - }, - { - "user.ext.time.userhour": { - "$in": [ - 10, - 11, - 12, - 13, - 14 - ] - } - } - ] -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-first-and-second-response.json b/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-first-and-second-response.json deleted file mode 100644 index 19264d25845..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-first-and-second-response.json +++ /dev/null @@ -1,444 +0,0 @@ -{ - "id": "tid", - "seatbid": [ - { - "bid": [ - { - "id": "bidId1", - "impid": "impId1", - "price": 10.6, - "adm": "", - "crid": "crid1", - "dealid": "dealId1", - "w": 300, - "h": 250, - "ext": { - "prebid": { - "type": "banner", - "targeting": { - "hb_pb": "10.60", - "hb_pb_rubicon": "10.60", - "hb_deal_rubicon": "dealId1", - "hb_size": "300x250", - "hb_bidder": "rubicon", - "hb_size_rubicon": "300x250", - "hb_bidder_rubicon": "rubicon", - "hb_deal": "dealId1" - }, - "events": { - "win": "http://localhost:8080/event?t=win&b=bidId1&a=2001&aid=tid&ts=1000&bidder=rubicon&f=i&int=&x=0&l=lineItem1", - "imp": "http://localhost:8080/event?t=imp&b=bidId1&a=2001&aid=tid&ts=1000&bidder=rubicon&f=i&int=&x=0&l=lineItem1" - } - }, - "origbidcpm": 10.6 - } - } - ], - "seat": "rubicon", - "group": 0 - } - ], - "cur": "USD", - "ext": { - "debug": { - "httpcalls": { - "rubicon": [ - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem1\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId1\",\"seatbid\":[{\"seat\":\"seatId\",\"bid\":[{\"id\":\"bidId1\",\"impid\":\"impId1\",\"dealid\":\"dealId1\",\"price\":10.6,\"adm\":\"\",\"crid\":\"crid1\",\"w\":300,\"h\":250}]}]}", - "status": 200 - }, - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem2\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId2\",\"seatbid\":[{\"seat\":\"seatId\",\"bid\":[{\"id\":\"bidId2\",\"impid\":\"impId1\",\"dealid\":\"dealId2\",\"price\":9.6,\"adm\":\"\",\"crid\":\"crid2\",\"w\":300,\"h\":250}]}]}", - "status": 200 - }, - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem3\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}" - } - ], - "userservice": [ - { - "uri": "{{ userservice_uri }}", - "requestbody": "{\"time\":\"{{ userservice_time }}\",\"ids\":[{\"type\":\"khaos\",\"id\":\"J5VLCWQP-26-CWFT\"}]}", - "responsebody": "{\"user\":{\"data\":[{\"id\":\"1111\",\"name\":\"rubicon\",\"segment\":[{\"id\":\"2222\"},{\"id\":\"3333\"}]},{\"id\":\"4444\",\"name\":\"bluekai\",\"segment\":[{\"id\":\"5555\"},{\"id\":\"6666\"}]}],\"ext\":{\"fcapIds\":[\"fcapId3\"]}}}", - "status": 200 - } - ] - }, - "resolvedrequest": { - "id": "tid", - "imp": [ - { - "id": "impId1", - "secure": 1, - "banner": { - "format": [ - { - "w": 300, - "h": 250 - } - ] - }, - "pmp": { - "deals": [ - { - "id": "dealId1", - "ext": { - "line": { - "lineitemid": "lineItem1", - "extlineitemid": "extLineItem1", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - }, - { - "id": "dealId2", - "ext": { - "line": { - "lineitemid": "lineItem2", - "extlineitemid": "extLineItem2", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - }, - { - "id": "dealId3", - "ext": { - "line": { - "lineitemid": "lineItem3", - "extlineitemid": "extLineItem3", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - } - ] - }, - "ext": { - "tid": "someTid", - "prebid": { - "bidder": { - "rubicon": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - } - } - } - } - } - ], - "source": { - "tid": "someTid" - }, - "site": { - "domain": "www.example.com", - "page": "http://www.example.com", - "publisher": { - "domain": "example.com", - "id": "2001" - }, - "ext": { - "amp": 0 - } - }, - "device": { - "ua": "userAgent", - "ip": "185.199.110.0" - }, - "user": { - "data": [ - { - "id": "rubicon", - "segment": [ - { - "id": "2222" - }, - { - "id": "3333" - } - ] - }, - { - "id": "bluekai", - "segment": [ - { - "id": "5555" - }, - { - "id": "6666" - } - ] - } - ], - "consent": "CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA", - "ext": { - "fcapids": [ - "fcapId3" - ], - "time": { - "userdow": "{{ userdow }}", - "userhour": "{{ userhour }}" - } - } - }, - "at": 1, - "tmax": 5000, - "cur": [ - "USD" - ], - "ext": { - "prebid": { - "auctiontimestamp": 1000, - "debug": 1, - "trace": "verbose", - "targeting": { - "pricegranularity": { - "precision": 2, - "ranges": [ - { - "max": 20, - "increment": 0.1 - } - ] - }, - "includewinners": true, - "includebidderkeys": true - }, - "channel": { - "name": "web" - }, - "server": { - "externalurl": "http://localhost:8080", - "gvlid": 1, - "datacenter": "local", - "endpoint": "/openrtb2/auction" - } - } - } - }, - "pgmetrics": { - "sent_to_client": [ - "lineItem1" - ], - "sent_to_client_as_top_match": [ - "lineItem1" - ], - "matched_whole_targeting": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "ready_to_serve": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "sent_to_bidder": { - "rubicon": [ - "lineItem3", - "lineItem1", - "lineItem2" - ] - }, - "sent_to_bidder_as_top_match": { - "rubicon": [ - "lineItem1" - ] - }, - "received_from_bidder": { - "rubicon": [ - "lineItem1", - "lineItem2" - ] - } - }, - "trace": { - "lineitems": { - "lineItem3": [ - { - "lineitemid": "lineItem3", - "time": "2020-04-24T14:08:59.044Z", - "category": "targeting", - "message": "Line Item lineItem3 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem3", - "time": "2020-04-24T14:08:59.061Z", - "category": "pacing", - "message": "Matched Line Item lineItem3 for bidder rubicon ready to serve. relPriority 3" - } - ], - "lineItem1": [ - { - "lineitemid": "lineItem1", - "time": "2020-04-24T14:08:59.048Z", - "category": "targeting", - "message": "Line Item lineItem1 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem1", - "time": "2020-04-24T14:08:59.062Z", - "category": "pacing", - "message": "Matched Line Item lineItem1 for bidder rubicon ready to serve. relPriority 3" - } - ], - "lineItem2": [ - { - "lineitemid": "lineItem2", - "time": "2020-04-24T14:08:59.053Z", - "category": "targeting", - "message": "Line Item lineItem2 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem2", - "time": "2020-04-24T14:08:59.062Z", - "category": "pacing", - "message": "Matched Line Item lineItem2 for bidder rubicon ready to serve. relPriority 3" - } - ] - }, - "activity_infrastructure": [ - { - "description": "Invocation of Activity Infrastructure.", - "activity": "fetchBids", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "fetchBids", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitUfpd", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitUfpd", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitPreciseGeo", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitPreciseGeo", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitTid", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitTid", - "allowed": true - } - ] - } - }, - "responsetimemillis": { - "rubicon": "{{ rubicon.response_time_ms }}" - }, - "tmaxrequest": 5000, - "prebid": { - "auctiontimestamp": 1000 - } - } -} diff --git a/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-first-bid-only-response.json b/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-first-bid-only-response.json deleted file mode 100644 index 297f0518a8e..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-first-bid-only-response.json +++ /dev/null @@ -1,441 +0,0 @@ -{ - "id": "tid", - "seatbid": [ - { - "bid": [ - { - "id": "bidId1", - "impid": "impId1", - "price": 10.6, - "adm": "", - "crid": "crid1", - "dealid": "dealId1", - "w": 300, - "h": 250, - "ext": { - "prebid": { - "type": "banner", - "targeting": { - "hb_pb": "10.60", - "hb_pb_rubicon": "10.60", - "hb_deal_rubicon": "dealId1", - "hb_size": "300x250", - "hb_bidder": "rubicon", - "hb_size_rubicon": "300x250", - "hb_bidder_rubicon": "rubicon", - "hb_deal": "dealId1" - }, - "events": { - "win": "http://localhost:8080/event?t=win&b=bidId1&a=2001&aid=tid&ts=1000&bidder=rubicon&f=i&int=&x=0&l=lineItem1", - "imp": "http://localhost:8080/event?t=imp&b=bidId1&a=2001&aid=tid&ts=1000&bidder=rubicon&f=i&int=&x=0&l=lineItem1" - } - }, - "origbidcpm": 10.6 - } - } - ], - "seat": "rubicon", - "group": 0 - } - ], - "cur": "USD", - "ext": { - "debug": { - "httpcalls": { - "rubicon": [ - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem1\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId1\",\"seatbid\":[{\"seat\":\"seatId\",\"bid\":[{\"id\":\"bidId1\",\"impid\":\"impId1\",\"dealid\":\"dealId1\",\"price\":10.6,\"adm\":\"\",\"crid\":\"crid1\",\"w\":300,\"h\":250}]}]}", - "status": 200 - }, - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem2\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}" - }, - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem3\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}" - } - ], - "userservice": [ - { - "uri": "{{ userservice_uri }}", - "requestbody": "{\"time\":\"{{ userservice_time }}\",\"ids\":[{\"type\":\"khaos\",\"id\":\"J5VLCWQP-26-CWFT\"}]}", - "responsebody": "{\"user\":{\"data\":[{\"id\":\"1111\",\"name\":\"rubicon\",\"segment\":[{\"id\":\"2222\"},{\"id\":\"3333\"}]},{\"id\":\"4444\",\"name\":\"bluekai\",\"segment\":[{\"id\":\"5555\"},{\"id\":\"6666\"}]}],\"ext\":{\"fcapIds\":[\"fcapId3\"]}}}", - "status": 200 - } - ] - }, - "resolvedrequest": { - "id": "tid", - "imp": [ - { - "id": "impId1", - "secure": 1, - "banner": { - "format": [ - { - "w": 300, - "h": 250 - } - ] - }, - "pmp": { - "deals": [ - { - "id": "dealId1", - "ext": { - "line": { - "lineitemid": "lineItem1", - "extlineitemid": "extLineItem1", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - }, - { - "id": "dealId2", - "ext": { - "line": { - "lineitemid": "lineItem2", - "extlineitemid": "extLineItem2", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - }, - { - "id": "dealId3", - "ext": { - "line": { - "lineitemid": "lineItem3", - "extlineitemid": "extLineItem3", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - } - ] - }, - "ext": { - "tid": "someTid", - "prebid": { - "bidder": { - "rubicon": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - } - } - } - } - } - ], - "source": { - "tid": "someTid" - }, - "site": { - "domain": "www.example.com", - "page": "http://www.example.com", - "publisher": { - "id": "2001", - "domain": "example.com" - }, - "ext": { - "amp": 0 - } - }, - "device": { - "ua": "userAgent", - "ip": "185.199.110.0" - }, - "user": { - "data": [ - { - "id": "rubicon", - "segment": [ - { - "id": "2222" - }, - { - "id": "3333" - } - ] - }, - { - "id": "bluekai", - "segment": [ - { - "id": "5555" - }, - { - "id": "6666" - } - ] - } - ], - "consent": "CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA", - "ext": { - "fcapids": [ - "fcapId3" - ], - "time": { - "userdow": "{{ userdow }}", - "userhour": "{{ userhour }}" - } - } - }, - "at": 1, - "tmax": 5000, - "cur": [ - "USD" - ], - "ext": { - "prebid": { - "auctiontimestamp": 1000, - "debug": 1, - "trace": "verbose", - "targeting": { - "pricegranularity": { - "precision": 2, - "ranges": [ - { - "max": 20, - "increment": 0.1 - } - ] - }, - "includewinners": true, - "includebidderkeys": true - }, - "channel": { - "name": "web" - }, - "server": { - "externalurl": "http://localhost:8080", - "gvlid": 1, - "datacenter": "local", - "endpoint": "/openrtb2/auction" - } - } - } - }, - "pgmetrics": { - "sent_to_client": [ - "lineItem1" - ], - "sent_to_client_as_top_match": [ - "lineItem1" - ], - "matched_whole_targeting": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "ready_to_serve": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "sent_to_bidder": { - "rubicon": [ - "lineItem3", - "lineItem1", - "lineItem2" - ] - }, - "sent_to_bidder_as_top_match": { - "rubicon": [ - "lineItem1" - ] - }, - "received_from_bidder": { - "rubicon": [ - "lineItem1" - ] - } - }, - "trace": { - "lineitems": { - "lineItem3": [ - { - "lineitemid": "lineItem3", - "time": "2020-04-24T14:08:59.044Z", - "category": "targeting", - "message": "Line Item lineItem3 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem3", - "time": "2020-04-24T14:08:59.061Z", - "category": "pacing", - "message": "Matched Line Item lineItem3 for bidder rubicon ready to serve. relPriority 3" - } - ], - "lineItem1": [ - { - "lineitemid": "lineItem1", - "time": "2020-04-24T14:08:59.048Z", - "category": "targeting", - "message": "Line Item lineItem1 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem1", - "time": "2020-04-24T14:08:59.062Z", - "category": "pacing", - "message": "Matched Line Item lineItem1 for bidder rubicon ready to serve. relPriority 3" - } - ], - "lineItem2": [ - { - "lineitemid": "lineItem2", - "time": "2020-04-24T14:08:59.053Z", - "category": "targeting", - "message": "Line Item lineItem2 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem2", - "time": "2020-04-24T14:08:59.062Z", - "category": "pacing", - "message": "Matched Line Item lineItem2 for bidder rubicon ready to serve. relPriority 3" - } - ] - }, - "activity_infrastructure": [ - { - "description": "Invocation of Activity Infrastructure.", - "activity": "fetchBids", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "fetchBids", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitUfpd", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitUfpd", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitPreciseGeo", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitPreciseGeo", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitTid", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitTid", - "allowed": true - } - ] - } - }, - "responsetimemillis": { - "rubicon": "{{ rubicon.response_time_ms }}" - }, - "tmaxrequest": 5000, - "prebid": { - "auctiontimestamp": 1000 - } - } -} diff --git a/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-in-order-response.json b/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-in-order-response.json deleted file mode 100644 index 297f0518a8e..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-in-order-response.json +++ /dev/null @@ -1,441 +0,0 @@ -{ - "id": "tid", - "seatbid": [ - { - "bid": [ - { - "id": "bidId1", - "impid": "impId1", - "price": 10.6, - "adm": "", - "crid": "crid1", - "dealid": "dealId1", - "w": 300, - "h": 250, - "ext": { - "prebid": { - "type": "banner", - "targeting": { - "hb_pb": "10.60", - "hb_pb_rubicon": "10.60", - "hb_deal_rubicon": "dealId1", - "hb_size": "300x250", - "hb_bidder": "rubicon", - "hb_size_rubicon": "300x250", - "hb_bidder_rubicon": "rubicon", - "hb_deal": "dealId1" - }, - "events": { - "win": "http://localhost:8080/event?t=win&b=bidId1&a=2001&aid=tid&ts=1000&bidder=rubicon&f=i&int=&x=0&l=lineItem1", - "imp": "http://localhost:8080/event?t=imp&b=bidId1&a=2001&aid=tid&ts=1000&bidder=rubicon&f=i&int=&x=0&l=lineItem1" - } - }, - "origbidcpm": 10.6 - } - } - ], - "seat": "rubicon", - "group": 0 - } - ], - "cur": "USD", - "ext": { - "debug": { - "httpcalls": { - "rubicon": [ - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem1\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId1\",\"seatbid\":[{\"seat\":\"seatId\",\"bid\":[{\"id\":\"bidId1\",\"impid\":\"impId1\",\"dealid\":\"dealId1\",\"price\":10.6,\"adm\":\"\",\"crid\":\"crid1\",\"w\":300,\"h\":250}]}]}", - "status": 200 - }, - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem2\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}" - }, - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem3\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}" - } - ], - "userservice": [ - { - "uri": "{{ userservice_uri }}", - "requestbody": "{\"time\":\"{{ userservice_time }}\",\"ids\":[{\"type\":\"khaos\",\"id\":\"J5VLCWQP-26-CWFT\"}]}", - "responsebody": "{\"user\":{\"data\":[{\"id\":\"1111\",\"name\":\"rubicon\",\"segment\":[{\"id\":\"2222\"},{\"id\":\"3333\"}]},{\"id\":\"4444\",\"name\":\"bluekai\",\"segment\":[{\"id\":\"5555\"},{\"id\":\"6666\"}]}],\"ext\":{\"fcapIds\":[\"fcapId3\"]}}}", - "status": 200 - } - ] - }, - "resolvedrequest": { - "id": "tid", - "imp": [ - { - "id": "impId1", - "secure": 1, - "banner": { - "format": [ - { - "w": 300, - "h": 250 - } - ] - }, - "pmp": { - "deals": [ - { - "id": "dealId1", - "ext": { - "line": { - "lineitemid": "lineItem1", - "extlineitemid": "extLineItem1", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - }, - { - "id": "dealId2", - "ext": { - "line": { - "lineitemid": "lineItem2", - "extlineitemid": "extLineItem2", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - }, - { - "id": "dealId3", - "ext": { - "line": { - "lineitemid": "lineItem3", - "extlineitemid": "extLineItem3", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - } - ] - }, - "ext": { - "tid": "someTid", - "prebid": { - "bidder": { - "rubicon": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - } - } - } - } - } - ], - "source": { - "tid": "someTid" - }, - "site": { - "domain": "www.example.com", - "page": "http://www.example.com", - "publisher": { - "id": "2001", - "domain": "example.com" - }, - "ext": { - "amp": 0 - } - }, - "device": { - "ua": "userAgent", - "ip": "185.199.110.0" - }, - "user": { - "data": [ - { - "id": "rubicon", - "segment": [ - { - "id": "2222" - }, - { - "id": "3333" - } - ] - }, - { - "id": "bluekai", - "segment": [ - { - "id": "5555" - }, - { - "id": "6666" - } - ] - } - ], - "consent": "CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA", - "ext": { - "fcapids": [ - "fcapId3" - ], - "time": { - "userdow": "{{ userdow }}", - "userhour": "{{ userhour }}" - } - } - }, - "at": 1, - "tmax": 5000, - "cur": [ - "USD" - ], - "ext": { - "prebid": { - "auctiontimestamp": 1000, - "debug": 1, - "trace": "verbose", - "targeting": { - "pricegranularity": { - "precision": 2, - "ranges": [ - { - "max": 20, - "increment": 0.1 - } - ] - }, - "includewinners": true, - "includebidderkeys": true - }, - "channel": { - "name": "web" - }, - "server": { - "externalurl": "http://localhost:8080", - "gvlid": 1, - "datacenter": "local", - "endpoint": "/openrtb2/auction" - } - } - } - }, - "pgmetrics": { - "sent_to_client": [ - "lineItem1" - ], - "sent_to_client_as_top_match": [ - "lineItem1" - ], - "matched_whole_targeting": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "ready_to_serve": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "sent_to_bidder": { - "rubicon": [ - "lineItem3", - "lineItem1", - "lineItem2" - ] - }, - "sent_to_bidder_as_top_match": { - "rubicon": [ - "lineItem1" - ] - }, - "received_from_bidder": { - "rubicon": [ - "lineItem1" - ] - } - }, - "trace": { - "lineitems": { - "lineItem3": [ - { - "lineitemid": "lineItem3", - "time": "2020-04-24T14:08:59.044Z", - "category": "targeting", - "message": "Line Item lineItem3 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem3", - "time": "2020-04-24T14:08:59.061Z", - "category": "pacing", - "message": "Matched Line Item lineItem3 for bidder rubicon ready to serve. relPriority 3" - } - ], - "lineItem1": [ - { - "lineitemid": "lineItem1", - "time": "2020-04-24T14:08:59.048Z", - "category": "targeting", - "message": "Line Item lineItem1 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem1", - "time": "2020-04-24T14:08:59.062Z", - "category": "pacing", - "message": "Matched Line Item lineItem1 for bidder rubicon ready to serve. relPriority 3" - } - ], - "lineItem2": [ - { - "lineitemid": "lineItem2", - "time": "2020-04-24T14:08:59.053Z", - "category": "targeting", - "message": "Line Item lineItem2 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem2", - "time": "2020-04-24T14:08:59.062Z", - "category": "pacing", - "message": "Matched Line Item lineItem2 for bidder rubicon ready to serve. relPriority 3" - } - ] - }, - "activity_infrastructure": [ - { - "description": "Invocation of Activity Infrastructure.", - "activity": "fetchBids", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "fetchBids", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitUfpd", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitUfpd", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitPreciseGeo", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitPreciseGeo", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitTid", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitTid", - "allowed": true - } - ] - } - }, - "responsetimemillis": { - "rubicon": "{{ rubicon.response_time_ms }}" - }, - "tmaxrequest": 5000, - "prebid": { - "auctiontimestamp": 1000 - } - } -} diff --git a/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-in-reverse-order-response.json b/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-in-reverse-order-response.json deleted file mode 100644 index 6b0db95f32e..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-in-reverse-order-response.json +++ /dev/null @@ -1,447 +0,0 @@ -{ - "id": "tid", - "seatbid": [ - { - "bid": [ - { - "id": "bidId1", - "impid": "impId1", - "price": 10.6, - "adm": "", - "crid": "crid1", - "dealid": "dealId1", - "w": 300, - "h": 250, - "ext": { - "prebid": { - "type": "banner", - "targeting": { - "hb_pb": "10.60", - "hb_pb_rubicon": "10.60", - "hb_deal_rubicon": "dealId1", - "hb_size": "300x250", - "hb_bidder": "rubicon", - "hb_size_rubicon": "300x250", - "hb_bidder_rubicon": "rubicon", - "hb_deal": "dealId1" - }, - "events": { - "win": "http://localhost:8080/event?t=win&b=bidId1&a=2001&aid=tid&ts=1000&bidder=rubicon&f=i&int=&x=0&l=lineItem1", - "imp": "http://localhost:8080/event?t=imp&b=bidId1&a=2001&aid=tid&ts=1000&bidder=rubicon&f=i&int=&x=0&l=lineItem1" - } - }, - "origbidcpm": 10.6 - } - } - ], - "seat": "rubicon", - "group": 0 - } - ], - "cur": "USD", - "ext": { - "debug": { - "httpcalls": { - "rubicon": [ - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem2\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId2\",\"seatbid\":[{\"seat\":\"seatId\",\"bid\":[{\"id\":\"bidId2\",\"impid\":\"impId1\",\"dealid\":\"dealId2\",\"price\":9.6,\"adm\":\"\",\"crid\":\"crid2\",\"w\":300,\"h\":250}]}]}", - "status": 200 - }, - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem3\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId3\",\"seatbid\":[{\"seat\":\"seatId\",\"bid\":[{\"id\":\"bidId3\",\"impid\":\"impId1\",\"dealid\":\"dealId3\",\"price\":8.6,\"adm\":\"\",\"crid\":\"crid3\",\"w\":300,\"h\":250}]}]}", - "status": 200 - }, - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem1\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId1\",\"seatbid\":[{\"seat\":\"seatId\",\"bid\":[{\"id\":\"bidId1\",\"impid\":\"impId1\",\"dealid\":\"dealId1\",\"price\":10.6,\"adm\":\"\",\"crid\":\"crid1\",\"w\":300,\"h\":250}]}]}", - "status": 200 - } - ], - "userservice": [ - { - "uri": "{{ userservice_uri }}", - "requestbody": "{\"time\":\"{{ userservice_time }}\",\"ids\":[{\"type\":\"khaos\",\"id\":\"J5VLCWQP-26-CWFT\"}]}", - "responsebody": "{\"user\":{\"data\":[{\"id\":\"1111\",\"name\":\"rubicon\",\"segment\":[{\"id\":\"2222\"},{\"id\":\"3333\"}]},{\"id\":\"4444\",\"name\":\"bluekai\",\"segment\":[{\"id\":\"5555\"},{\"id\":\"6666\"}]}],\"ext\":{\"fcapIds\":[\"fcapId3\"]}}}", - "status": 200 - } - ] - }, - "resolvedrequest": { - "id": "tid", - "source": { - "tid": "someTid" - }, - "imp": [ - { - "id": "impId1", - "secure": 1, - "banner": { - "format": [ - { - "w": 300, - "h": 250 - } - ] - }, - "pmp": { - "deals": [ - { - "id": "dealId1", - "ext": { - "line": { - "lineitemid": "lineItem1", - "extlineitemid": "extLineItem1", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - }, - { - "id": "dealId2", - "ext": { - "line": { - "lineitemid": "lineItem2", - "extlineitemid": "extLineItem2", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - }, - { - "id": "dealId3", - "ext": { - "line": { - "lineitemid": "lineItem3", - "extlineitemid": "extLineItem3", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - } - ] - }, - "ext": { - "tid": "someTid", - "prebid": { - "bidder": { - "rubicon": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - } - } - } - } - } - ], - "site": { - "domain": "www.example.com", - "page": "http://www.example.com", - "publisher": { - "id": "2001", - "domain": "example.com" - }, - "ext": { - "amp": 0 - } - }, - "device": { - "ua": "userAgent", - "ip": "185.199.110.0" - }, - "user": { - "data": [ - { - "id": "rubicon", - "segment": [ - { - "id": "2222" - }, - { - "id": "3333" - } - ] - }, - { - "id": "bluekai", - "segment": [ - { - "id": "5555" - }, - { - "id": "6666" - } - ] - } - ], - "consent": "CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA", - "ext": { - "fcapids": [ - "fcapId3" - ], - "time": { - "userdow": "{{ userdow }}", - "userhour": "{{ userhour }}" - } - } - }, - "at": 1, - "tmax": 5000, - "cur": [ - "USD" - ], - "ext": { - "prebid": { - "auctiontimestamp": 1000, - "debug": 1, - "trace": "verbose", - "targeting": { - "pricegranularity": { - "precision": 2, - "ranges": [ - { - "max": 20, - "increment": 0.1 - } - ] - }, - "includewinners": true, - "includebidderkeys": true - }, - "channel": { - "name": "web" - }, - "server": { - "externalurl": "http://localhost:8080", - "gvlid": 1, - "datacenter": "local", - "endpoint": "/openrtb2/auction" - } - } - } - }, - "pgmetrics": { - "sent_to_client": [ - "lineItem1" - ], - "sent_to_client_as_top_match": [ - "lineItem1" - ], - "matched_whole_targeting": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "ready_to_serve": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "sent_to_bidder": { - "rubicon": [ - "lineItem3", - "lineItem1", - "lineItem2" - ] - }, - "sent_to_bidder_as_top_match": { - "rubicon": [ - "lineItem1" - ] - }, - "received_from_bidder": { - "rubicon": [ - "lineItem3", - "lineItem1", - "lineItem2" - ] - } - }, - "trace": { - "lineitems": { - "lineItem3": [ - { - "lineitemid": "lineItem3", - "time": "2020-04-24T14:07:36.045Z", - "category": "targeting", - "message": "Line Item lineItem3 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem3", - "time": "2020-04-24T14:07:36.064Z", - "category": "pacing", - "message": "Matched Line Item lineItem3 for bidder rubicon ready to serve. relPriority 3" - } - ], - "lineItem1": [ - { - "lineitemid": "lineItem1", - "time": "2020-04-24T14:07:36.049Z", - "category": "targeting", - "message": "Line Item lineItem1 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem1", - "time": "2020-04-24T14:07:36.064Z", - "category": "pacing", - "message": "Matched Line Item lineItem1 for bidder rubicon ready to serve. relPriority 3" - } - ], - "lineItem2": [ - { - "lineitemid": "lineItem2", - "time": "2020-04-24T14:07:36.056Z", - "category": "targeting", - "message": "Line Item lineItem2 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem2", - "time": "2020-04-24T14:07:36.064Z", - "category": "pacing", - "message": "Matched Line Item lineItem2 for bidder rubicon ready to serve. relPriority 3" - } - ] - }, - "activity_infrastructure": [ - { - "description": "Invocation of Activity Infrastructure.", - "activity": "fetchBids", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "fetchBids", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitUfpd", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitUfpd", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitPreciseGeo", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitPreciseGeo", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitTid", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitTid", - "allowed": true - } - ] - } - }, - "responsetimemillis": { - "rubicon": "{{ rubicon.response_time_ms }}" - }, - "tmaxrequest": 5000, - "prebid": { - "auctiontimestamp": 1000 - } - } -} diff --git a/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-second-bid-only-response.json b/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-second-bid-only-response.json deleted file mode 100644 index a0ccf324d82..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-second-bid-only-response.json +++ /dev/null @@ -1,445 +0,0 @@ -{ - "id": "tid", - "seatbid": [ - { - "bid": [ - { - "id": "bidId2", - "impid": "impId1", - "price": 9.6, - "adm": "", - "crid": "crid2", - "dealid": "dealId2", - "w": 300, - "h": 250, - "ext": { - "prebid": { - "type": "banner", - "targeting": { - "hb_pb": "9.60", - "hb_pb_rubicon": "9.60", - "hb_deal_rubicon": "dealId2", - "hb_size": "300x250", - "hb_bidder": "rubicon", - "hb_size_rubicon": "300x250", - "hb_bidder_rubicon": "rubicon", - "hb_deal": "dealId2" - }, - "events": { - "win": "http://localhost:8080/event?t=win&b=bidId2&a=2001&aid=tid&ts=1000&bidder=rubicon&f=i&int=&x=0&l=lineItem2", - "imp": "http://localhost:8080/event?t=imp&b=bidId2&a=2001&aid=tid&ts=1000&bidder=rubicon&f=i&int=&x=0&l=lineItem2" - } - }, - "origbidcpm": 9.6 - } - } - ], - "seat": "rubicon", - "group": 0 - } - ], - "cur": "USD", - "ext": { - "debug": { - "httpcalls": { - "rubicon": [ - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem1\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId1\",\"seatbid\":[{\"seat\":\"seatId\",\"bid\":[]}]}", - "status": 200 - }, - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem2\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId2\",\"seatbid\":[{\"seat\":\"seatId\",\"bid\":[{\"id\":\"bidId2\",\"impid\":\"impId1\",\"dealid\":\"dealId2\",\"price\":9.6,\"adm\":\"\",\"crid\":\"crid2\",\"w\":300,\"h\":250}]}]}", - "status": 200 - }, - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem3\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId3\",\"seatbid\":[{\"seat\":\"seatId\",\"bid\":[]}]}", - "status": 200 - } - ], - "userservice": [ - { - "uri": "{{ userservice_uri }}", - "requestbody": "{\"time\":\"{{ userservice_time }}\",\"ids\":[{\"type\":\"khaos\",\"id\":\"J5VLCWQP-26-CWFT\"}]}", - "responsebody": "{\"user\":{\"data\":[{\"id\":\"1111\",\"name\":\"rubicon\",\"segment\":[{\"id\":\"2222\"},{\"id\":\"3333\"}]},{\"id\":\"4444\",\"name\":\"bluekai\",\"segment\":[{\"id\":\"5555\"},{\"id\":\"6666\"}]}],\"ext\":{\"fcapIds\":[\"fcapId3\"]}}}", - "status": 200 - } - ] - }, - "resolvedrequest": { - "id": "tid", - "imp": [ - { - "id": "impId1", - "secure": 1, - "banner": { - "format": [ - { - "w": 300, - "h": 250 - } - ] - }, - "pmp": { - "deals": [ - { - "id": "dealId1", - "ext": { - "line": { - "lineitemid": "lineItem1", - "extlineitemid": "extLineItem1", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - }, - { - "id": "dealId2", - "ext": { - "line": { - "lineitemid": "lineItem2", - "extlineitemid": "extLineItem2", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - }, - { - "id": "dealId3", - "ext": { - "line": { - "lineitemid": "lineItem3", - "extlineitemid": "extLineItem3", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - } - ] - }, - "ext": { - "tid": "someTid", - "prebid": { - "bidder": { - "rubicon": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - } - } - } - } - } - ], - "source": { - "tid": "someTid" - }, - "site": { - "domain": "www.example.com", - "page": "http://www.example.com", - "publisher": { - "id": "2001", - "domain": "example.com" - }, - "ext": { - "amp": 0 - } - }, - "device": { - "ua": "userAgent", - "ip": "185.199.110.0" - }, - "user": { - "data": [ - { - "id": "rubicon", - "segment": [ - { - "id": "2222" - }, - { - "id": "3333" - } - ] - }, - { - "id": "bluekai", - "segment": [ - { - "id": "5555" - }, - { - "id": "6666" - } - ] - } - ], - "consent": "CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA", - "ext": { - "fcapids": [ - "fcapId3" - ], - "time": { - "userdow": "{{ userdow }}", - "userhour": "{{ userhour }}" - } - } - }, - "at": 1, - "tmax": 5000, - "cur": [ - "USD" - ], - "ext": { - "prebid": { - "auctiontimestamp": 1000, - "debug": 1, - "trace": "verbose", - "targeting": { - "pricegranularity": { - "precision": 2, - "ranges": [ - { - "max": 20, - "increment": 0.1 - } - ] - }, - "includewinners": true, - "includebidderkeys": true - }, - "channel": { - "name": "web" - }, - "server": { - "externalurl": "http://localhost:8080", - "gvlid": 1, - "datacenter": "local", - "endpoint": "/openrtb2/auction" - } - } - } - }, - "pgmetrics": { - "sent_to_client": [ - "lineItem2" - ], - "sent_to_client_as_top_match": [ - "lineItem2" - ], - "matched_whole_targeting": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "ready_to_serve": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "sent_to_bidder": { - "rubicon": [ - "lineItem3", - "lineItem1", - "lineItem2" - ] - }, - "sent_to_bidder_as_top_match": { - "rubicon": [ - "lineItem1" - ] - }, - "received_from_bidder": { - "rubicon": [ - "lineItem2" - ] - } - }, - "trace": { - "lineitems": { - "lineItem3": [ - { - "lineitemid": "lineItem3", - "time": "2020-04-24T14:08:59.044Z", - "category": "targeting", - "message": "Line Item lineItem3 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem3", - "time": "2020-04-24T14:08:59.061Z", - "category": "pacing", - "message": "Matched Line Item lineItem3 for bidder rubicon ready to serve. relPriority 3" - } - ], - "lineItem1": [ - { - "lineitemid": "lineItem1", - "time": "2020-04-24T14:08:59.048Z", - "category": "targeting", - "message": "Line Item lineItem1 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem1", - "time": "2020-04-24T14:08:59.062Z", - "category": "pacing", - "message": "Matched Line Item lineItem1 for bidder rubicon ready to serve. relPriority 3" - } - ], - "lineItem2": [ - { - "lineitemid": "lineItem2", - "time": "2020-04-24T14:08:59.053Z", - "category": "targeting", - "message": "Line Item lineItem2 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem2", - "time": "2020-04-24T14:08:59.062Z", - "category": "pacing", - "message": "Matched Line Item lineItem2 for bidder rubicon ready to serve. relPriority 3" - } - ] - }, - "activity_infrastructure": [ - { - "description": "Invocation of Activity Infrastructure.", - "activity": "fetchBids", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "fetchBids", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitUfpd", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitUfpd", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitPreciseGeo", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitPreciseGeo", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitTid", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitTid", - "allowed": true - } - ] - } - }, - "responsetimemillis": { - "rubicon": "{{ rubicon.response_time_ms }}" - }, - "tmaxrequest": 5000, - "prebid": { - "auctiontimestamp": 1000 - } - } -} diff --git a/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-third-and-second-response.json b/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-third-and-second-response.json deleted file mode 100644 index 3fbc3594c12..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-third-and-second-response.json +++ /dev/null @@ -1,446 +0,0 @@ -{ - "id": "tid", - "seatbid": [ - { - "bid": [ - { - "id": "bidId2", - "impid": "impId1", - "price": 9.6, - "adm": "", - "crid": "crid2", - "dealid": "dealId2", - "w": 300, - "h": 250, - "ext": { - "prebid": { - "type": "banner", - "targeting": { - "hb_pb": "9.60", - "hb_pb_rubicon": "9.60", - "hb_deal_rubicon": "dealId2", - "hb_size": "300x250", - "hb_bidder": "rubicon", - "hb_size_rubicon": "300x250", - "hb_bidder_rubicon": "rubicon", - "hb_deal": "dealId2" - }, - "events": { - "win": "http://localhost:8080/event?t=win&b=bidId2&a=2001&aid=tid&ts=1000&bidder=rubicon&f=i&int=&x=0&l=lineItem2", - "imp": "http://localhost:8080/event?t=imp&b=bidId2&a=2001&aid=tid&ts=1000&bidder=rubicon&f=i&int=&x=0&l=lineItem2" - } - }, - "origbidcpm": 9.6 - } - } - ], - "seat": "rubicon", - "group": 0 - } - ], - "cur": "USD", - "ext": { - "debug": { - "httpcalls": { - "rubicon": [ - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem2\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId2\",\"seatbid\":[{\"seat\":\"seatId\",\"bid\":[{\"id\":\"bidId2\",\"impid\":\"impId1\",\"dealid\":\"dealId2\",\"price\":9.6,\"adm\":\"\",\"crid\":\"crid2\",\"w\":300,\"h\":250}]}]}", - "status": 200 - }, - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem1\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId1\",\"seatbid\":[{\"seat\":\"seatId\",\"bid\":[]}]}", - "status": 200 - }, - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem3\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId3\",\"seatbid\":[{\"seat\":\"seatId\",\"bid\":[{\"id\":\"bidId3\",\"impid\":\"impId1\",\"dealid\":\"dealId3\",\"price\":8.6,\"adm\":\"\",\"crid\":\"crid3\",\"w\":300,\"h\":250}]}]}", - "status": 200 - } - ], - "userservice": [ - { - "uri": "{{ userservice_uri }}", - "requestbody": "{\"time\":\"{{ userservice_time }}\",\"ids\":[{\"type\":\"khaos\",\"id\":\"J5VLCWQP-26-CWFT\"}]}", - "responsebody": "{\"user\":{\"data\":[{\"id\":\"1111\",\"name\":\"rubicon\",\"segment\":[{\"id\":\"2222\"},{\"id\":\"3333\"}]},{\"id\":\"4444\",\"name\":\"bluekai\",\"segment\":[{\"id\":\"5555\"},{\"id\":\"6666\"}]}],\"ext\":{\"fcapIds\":[\"fcapId3\"]}}}", - "status": 200 - } - ] - }, - "resolvedrequest": { - "id": "tid", - "imp": [ - { - "id": "impId1", - "secure": 1, - "banner": { - "format": [ - { - "w": 300, - "h": 250 - } - ] - }, - "pmp": { - "deals": [ - { - "id": "dealId1", - "ext": { - "line": { - "lineitemid": "lineItem1", - "extlineitemid": "extLineItem1", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - }, - { - "id": "dealId2", - "ext": { - "line": { - "lineitemid": "lineItem2", - "extlineitemid": "extLineItem2", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - }, - { - "id": "dealId3", - "ext": { - "line": { - "lineitemid": "lineItem3", - "extlineitemid": "extLineItem3", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - } - ] - }, - "ext": { - "tid": "someTid", - "prebid": { - "bidder": { - "rubicon": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - } - } - } - } - } - ], - "source": { - "tid": "someTid" - }, - "site": { - "domain": "www.example.com", - "page": "http://www.example.com", - "publisher": { - "id": "2001", - "domain": "example.com" - }, - "ext": { - "amp": 0 - } - }, - "device": { - "ua": "userAgent", - "ip": "185.199.110.0" - }, - "user": { - "data": [ - { - "id": "rubicon", - "segment": [ - { - "id": "2222" - }, - { - "id": "3333" - } - ] - }, - { - "id": "bluekai", - "segment": [ - { - "id": "5555" - }, - { - "id": "6666" - } - ] - } - ], - "consent": "CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA", - "ext": { - "fcapids": [ - "fcapId3" - ], - "time": { - "userdow": "{{ userdow }}", - "userhour": "{{ userhour }}" - } - } - }, - "at": 1, - "tmax": 5000, - "cur": [ - "USD" - ], - "ext": { - "prebid": { - "auctiontimestamp": 1000, - "debug": 1, - "trace": "verbose", - "targeting": { - "pricegranularity": { - "precision": 2, - "ranges": [ - { - "max": 20, - "increment": 0.1 - } - ] - }, - "includewinners": true, - "includebidderkeys": true - }, - "channel": { - "name": "web" - }, - "server": { - "externalurl": "http://localhost:8080", - "gvlid": 1, - "datacenter": "local", - "endpoint": "/openrtb2/auction" - } - } - } - }, - "pgmetrics": { - "sent_to_client": [ - "lineItem2" - ], - "sent_to_client_as_top_match": [ - "lineItem2" - ], - "matched_whole_targeting": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "ready_to_serve": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "sent_to_bidder": { - "rubicon": [ - "lineItem3", - "lineItem1", - "lineItem2" - ] - }, - "sent_to_bidder_as_top_match": { - "rubicon": [ - "lineItem1" - ] - }, - "received_from_bidder": { - "rubicon": [ - "lineItem3", - "lineItem2" - ] - } - }, - "trace": { - "lineitems": { - "lineItem3": [ - { - "lineitemid": "lineItem3", - "time": "2020-04-24T14:08:59.044Z", - "category": "targeting", - "message": "Line Item lineItem3 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem3", - "time": "2020-04-24T14:08:59.061Z", - "category": "pacing", - "message": "Matched Line Item lineItem3 for bidder rubicon ready to serve. relPriority 3" - } - ], - "lineItem1": [ - { - "lineitemid": "lineItem1", - "time": "2020-04-24T14:08:59.048Z", - "category": "targeting", - "message": "Line Item lineItem1 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem1", - "time": "2020-04-24T14:08:59.062Z", - "category": "pacing", - "message": "Matched Line Item lineItem1 for bidder rubicon ready to serve. relPriority 3" - } - ], - "lineItem2": [ - { - "lineitemid": "lineItem2", - "time": "2020-04-24T14:08:59.053Z", - "category": "targeting", - "message": "Line Item lineItem2 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem2", - "time": "2020-04-24T14:08:59.062Z", - "category": "pacing", - "message": "Matched Line Item lineItem2 for bidder rubicon ready to serve. relPriority 3" - } - ] - }, - "activity_infrastructure": [ - { - "description": "Invocation of Activity Infrastructure.", - "activity": "fetchBids", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "fetchBids", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitUfpd", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitUfpd", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitPreciseGeo", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitPreciseGeo", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitTid", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitTid", - "allowed": true - } - ] - } - }, - "responsetimemillis": { - "rubicon": "{{ rubicon.response_time_ms }}" - }, - "tmaxrequest": 5000, - "prebid": { - "auctiontimestamp": 1000 - } - } -} diff --git a/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-third-bid-only-response.json b/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-third-bid-only-response.json deleted file mode 100644 index 7bea97d3c61..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/premature/responses/test-auction-third-bid-only-response.json +++ /dev/null @@ -1,445 +0,0 @@ -{ - "id": "tid", - "seatbid": [ - { - "bid": [ - { - "id": "bidId3", - "impid": "impId1", - "price": 8.6, - "adm": "", - "crid": "crid3", - "dealid": "dealId3", - "w": 300, - "h": 250, - "ext": { - "prebid": { - "type": "banner", - "targeting": { - "hb_pb": "8.60", - "hb_pb_rubicon": "8.60", - "hb_deal_rubicon": "dealId3", - "hb_size": "300x250", - "hb_bidder": "rubicon", - "hb_size_rubicon": "300x250", - "hb_bidder_rubicon": "rubicon", - "hb_deal": "dealId3" - }, - "events": { - "win": "http://localhost:8080/event?t=win&b=bidId3&a=2001&aid=tid&ts=1000&bidder=rubicon&f=i&int=&x=0&l=lineItem3", - "imp": "http://localhost:8080/event?t=imp&b=bidId3&a=2001&aid=tid&ts=1000&bidder=rubicon&f=i&int=&x=0&l=lineItem3" - } - }, - "origbidcpm": 8.6 - } - } - ], - "seat": "rubicon", - "group": 0 - } - ], - "cur": "USD", - "ext": { - "debug": { - "httpcalls": { - "rubicon": [ - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem1\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId1\",\"seatbid\":[{\"seat\":\"seatId\",\"bid\":[]}]}", - "status": 200 - }, - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem2\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId2\",\"seatbid\":[{\"seat\":\"seatId\",\"bid\":[]}]}", - "status": 200 - }, - { - "uri": "{{ rubicon.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem3\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId3\",\"seatbid\":[{\"seat\":\"seatId\",\"bid\":[{\"id\":\"bidId3\",\"impid\":\"impId1\",\"dealid\":\"dealId3\",\"price\":8.6,\"adm\":\"\",\"crid\":\"crid3\",\"w\":300,\"h\":250}]}]}", - "status": 200 - } - ], - "userservice": [ - { - "uri": "{{ userservice_uri }}", - "requestbody": "{\"time\":\"{{ userservice_time }}\",\"ids\":[{\"type\":\"khaos\",\"id\":\"J5VLCWQP-26-CWFT\"}]}", - "responsebody": "{\"user\":{\"data\":[{\"id\":\"1111\",\"name\":\"rubicon\",\"segment\":[{\"id\":\"2222\"},{\"id\":\"3333\"}]},{\"id\":\"4444\",\"name\":\"bluekai\",\"segment\":[{\"id\":\"5555\"},{\"id\":\"6666\"}]}],\"ext\":{\"fcapIds\":[\"fcapId3\"]}}}", - "status": 200 - } - ] - }, - "resolvedrequest": { - "id": "tid", - "imp": [ - { - "id": "impId1", - "secure": 1, - "banner": { - "format": [ - { - "w": 300, - "h": 250 - } - ] - }, - "pmp": { - "deals": [ - { - "id": "dealId1", - "ext": { - "line": { - "lineitemid": "lineItem1", - "extlineitemid": "extLineItem1", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - }, - { - "id": "dealId2", - "ext": { - "line": { - "lineitemid": "lineItem2", - "extlineitemid": "extLineItem2", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - }, - { - "id": "dealId3", - "ext": { - "line": { - "lineitemid": "lineItem3", - "extlineitemid": "extLineItem3", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - } - ] - }, - "ext": { - "tid": "someTid", - "prebid": { - "bidder": { - "rubicon": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - } - } - } - } - } - ], - "source": { - "tid": "someTid" - }, - "site": { - "domain": "www.example.com", - "page": "http://www.example.com", - "publisher": { - "id": "2001", - "domain": "example.com" - }, - "ext": { - "amp": 0 - } - }, - "device": { - "ua": "userAgent", - "ip": "185.199.110.0" - }, - "user": { - "data": [ - { - "id": "rubicon", - "segment": [ - { - "id": "2222" - }, - { - "id": "3333" - } - ] - }, - { - "id": "bluekai", - "segment": [ - { - "id": "5555" - }, - { - "id": "6666" - } - ] - } - ], - "consent": "CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA", - "ext": { - "fcapids": [ - "fcapId3" - ], - "time": { - "userdow": "{{ userdow }}", - "userhour": "{{ userhour }}" - } - } - }, - "at": 1, - "tmax": 5000, - "cur": [ - "USD" - ], - "ext": { - "prebid": { - "auctiontimestamp": 1000, - "debug": 1, - "trace": "verbose", - "targeting": { - "pricegranularity": { - "precision": 2, - "ranges": [ - { - "max": 20, - "increment": 0.1 - } - ] - }, - "includewinners": true, - "includebidderkeys": true - }, - "channel": { - "name": "web" - }, - "server": { - "externalurl": "http://localhost:8080", - "gvlid": 1, - "datacenter": "local", - "endpoint": "/openrtb2/auction" - } - } - } - }, - "pgmetrics": { - "sent_to_client": [ - "lineItem3" - ], - "sent_to_client_as_top_match": [ - "lineItem3" - ], - "matched_whole_targeting": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "ready_to_serve": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "sent_to_bidder": { - "rubicon": [ - "lineItem3", - "lineItem1", - "lineItem2" - ] - }, - "sent_to_bidder_as_top_match": { - "rubicon": [ - "lineItem1" - ] - }, - "received_from_bidder": { - "rubicon": [ - "lineItem3" - ] - } - }, - "trace": { - "lineitems": { - "lineItem3": [ - { - "lineitemid": "lineItem3", - "time": "2020-04-24T14:08:59.044Z", - "category": "targeting", - "message": "Line Item lineItem3 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem3", - "time": "2020-04-24T14:08:59.061Z", - "category": "pacing", - "message": "Matched Line Item lineItem3 for bidder rubicon ready to serve. relPriority 3" - } - ], - "lineItem1": [ - { - "lineitemid": "lineItem1", - "time": "2020-04-24T14:08:59.048Z", - "category": "targeting", - "message": "Line Item lineItem1 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem1", - "time": "2020-04-24T14:08:59.062Z", - "category": "pacing", - "message": "Matched Line Item lineItem1 for bidder rubicon ready to serve. relPriority 3" - } - ], - "lineItem2": [ - { - "lineitemid": "lineItem2", - "time": "2020-04-24T14:08:59.053Z", - "category": "targeting", - "message": "Line Item lineItem2 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem2", - "time": "2020-04-24T14:08:59.062Z", - "category": "pacing", - "message": "Matched Line Item lineItem2 for bidder rubicon ready to serve. relPriority 3" - } - ] - }, - "activity_infrastructure": [ - { - "description": "Invocation of Activity Infrastructure.", - "activity": "fetchBids", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "fetchBids", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitUfpd", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitUfpd", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitPreciseGeo", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitPreciseGeo", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitTid", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitTid", - "allowed": true - } - ] - } - }, - "responsetimemillis": { - "rubicon": "{{ rubicon.response_time_ms }}" - }, - "tmaxrequest": 5000, - "prebid": { - "auctiontimestamp": 1000 - } - } -} diff --git a/src/test/resources/org/prebid/server/it/deals/premature/test-auction-request.json b/src/test/resources/org/prebid/server/it/deals/premature/test-auction-request.json deleted file mode 100644 index 307b091e591..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/premature/test-auction-request.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "id": "tid", - "imp": [ - { - "id": "impId1", - "banner": { - "format": [ - { - "w": 300, - "h": 250 - } - ] - }, - "ext": { - "tid": "someTid", - "prebid": { - "bidder": { - "rubicon": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - } - } - } - } - } - ], - "cur": [ - "USD" - ], - "user": { - "ext": { - "consent": "CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA" - } - }, - "source": { - "tid": "someTid" - }, - "site": { - "publisher": { - "id": "2001" - } - }, - "ext": { - "prebid": { - "debug": 1, - "trace": "verbose", - "targeting": { - }, - "auctiontimestamp": 1000 - } - } -} diff --git a/src/test/resources/org/prebid/server/it/deals/premature/test-planner-plan-response.json b/src/test/resources/org/prebid/server/it/deals/premature/test-planner-plan-response.json deleted file mode 100644 index d80ece7ad26..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/premature/test-planner-plan-response.json +++ /dev/null @@ -1,209 +0,0 @@ -[ - { - "lineItemId": "lineItem1", - "extLineItemId": "extLineItem1", - "dealId": "dealId1", - "status": "active", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "accountId": "2001", - "source": "rubicon", - "price": { - "cpm": 10.60, - "currency": "USD" - }, - "relativePriority": 3, - "startTimeStamp": "{{ lineItem.startTime }}", - "endTimeStamp": "{{ lineItem.endTime }}", - "updatedTimeStamp": "{{ now }}", - "targeting": { - "$and": [ - { - "adunit.size": { - "$intersects": [ - { - "w": 300, - "h": 250 - } - ] - } - }, - { - "adunit.mediatype": { - "$intersects": [ - "banner" - ] - } - } - ] - }, - "frequencyCaps": [ - { - "fcapId": "fcapId1", - "count": 3, - "periods": 7, - "periodType": "day" - } - ], - "deliverySchedules": [ - { - "planId": "1", - "updatedTimeStamp": "{{ now }}", - "startTimeStamp": "{{ plan.startTime }}", - "endTimeStamp": "{{ plan.endTime }}", - "tokens": [ - { - "class": 1, - "total": 5000 - }, - { - "class": 2, - "total": 125 - } - ] - } - ] - }, - { - "lineItemId": "lineItem2", - "dealId": "dealId2", - "extLineItemId": "extLineItem2", - "status": "active", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "accountId": "2001", - "source": "rubicon", - "price": { - "cpm": 9.60, - "currency": "USD" - }, - "relativePriority": 3, - "startTimeStamp": "{{ lineItem.startTime }}", - "endTimeStamp": "{{ lineItem.endTime }}", - "updatedTimeStamp": "{{ now }}", - "targeting": { - "$and": [ - { - "adunit.size": { - "$intersects": [ - { - "w": 300, - "h": 250 - } - ] - } - }, - { - "adunit.mediatype": { - "$intersects": [ - "banner" - ] - } - } - ] - }, - "frequencyCaps": [ - { - "fcapId": "fcapId2", - "count": 3, - "periods": 7, - "periodType": "day" - } - ], - "deliverySchedules": [ - { - "planId": "1", - "updatedTimeStamp": "{{ now }}", - "startTimeStamp": "{{ plan.startTime }}", - "endTimeStamp": "{{ plan.endTime }}", - "tokens": [ - { - "class": 1, - "total": 5000 - }, - { - "class": 2, - "total": 125 - } - ] - } - ] - }, - { - "lineItemId": "lineItem3", - "extLineItemId": "extLineItem3", - "dealId": "dealId3", - "status": "active", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "accountId": "2001", - "source": "rubicon", - "price": { - "cpm": 8.60, - "currency": "USD" - }, - "relativePriority": 3, - "startTimeStamp": "{{ lineItem.startTime }}", - "endTimeStamp": "{{ lineItem.endTime }}", - "updatedTimeStamp": "{{ now }}", - "targeting": { - "$and": [ - { - "adunit.size": { - "$intersects": [ - { - "w": 300, - "h": 250 - } - ] - } - }, - { - "adunit.mediatype": { - "$intersects": [ - "banner" - ] - } - } - ] - }, - "frequencyCaps": [ - { - "fcapId": "fcapId1", - "count": 3, - "periods": 7, - "periodType": "day" - } - ], - "deliverySchedules": [ - { - "planId": "1", - "updatedTimeStamp": "{{ now }}", - "startTimeStamp": "{{ plan.startTime }}", - "endTimeStamp": "{{ plan.endTime }}", - "tokens": [ - { - "class": 1, - "total": 5000 - }, - { - "class": 2, - "total": 125 - } - ] - } - ] - } -] diff --git a/src/test/resources/org/prebid/server/it/deals/premature/test-rubicon-bid-response-1.json b/src/test/resources/org/prebid/server/it/deals/premature/test-rubicon-bid-response-1.json deleted file mode 100644 index 9b3e45e74e4..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/premature/test-rubicon-bid-response-1.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "id": "bidResponseId1", - "seatbid": [ - { - "seat": "seatId", - "bid": [ - { - "id": "bidId1", - "impid": "impId1", - "dealid": "dealId1", - "price": 10.60, - "adm": "", - "crid": "crid1", - "w": 300, - "h": 250 - } - ] - } - ] -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/it/deals/premature/test-rubicon-bid-response-2.json b/src/test/resources/org/prebid/server/it/deals/premature/test-rubicon-bid-response-2.json deleted file mode 100644 index ba3e19d5887..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/premature/test-rubicon-bid-response-2.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "id": "bidResponseId2", - "seatbid": [ - { - "seat": "seatId", - "bid": [ - { - "id": "bidId2", - "impid": "impId1", - "dealid": "dealId2", - "price": 9.60, - "adm": "", - "crid": "crid2", - "w": 300, - "h": 250 - } - ] - } - ] -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/it/deals/premature/test-rubicon-bid-response-3.json b/src/test/resources/org/prebid/server/it/deals/premature/test-rubicon-bid-response-3.json deleted file mode 100644 index 3583fa59b7f..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/premature/test-rubicon-bid-response-3.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "id": "bidResponseId3", - "seatbid": [ - { - "seat": "seatId", - "bid": [ - { - "id": "bidId3", - "impid": "impId1", - "dealid": "dealId3", - "price": 8.60, - "adm": "", - "crid": "crid3", - "w": 300, - "h": 250 - } - ] - } - ] -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/it/deals/premature/test-rubicon-no-bid-response-1.json b/src/test/resources/org/prebid/server/it/deals/premature/test-rubicon-no-bid-response-1.json deleted file mode 100644 index 533d6537f8f..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/premature/test-rubicon-no-bid-response-1.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "id": "bidResponseId1", - "seatbid": [ - { - "seat": "seatId", - "bid": [ - - ] - } - ] -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/it/deals/premature/test-rubicon-no-bid-response-2.json b/src/test/resources/org/prebid/server/it/deals/premature/test-rubicon-no-bid-response-2.json deleted file mode 100644 index b3c9444dd24..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/premature/test-rubicon-no-bid-response-2.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "id": "bidResponseId2", - "seatbid": [ - { - "seat": "seatId", - "bid": [ - - ] - } - ] -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/it/deals/premature/test-rubicon-no-bid-response-3.json b/src/test/resources/org/prebid/server/it/deals/premature/test-rubicon-no-bid-response-3.json deleted file mode 100644 index 5363e36c8f9..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/premature/test-rubicon-no-bid-response-3.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "id": "bidResponseId3", - "seatbid": [ - { - "seat": "seatId", - "bid": [ - ] - } - ] -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/it/deals/simulation/test-auction-request.json b/src/test/resources/org/prebid/server/it/deals/simulation/test-auction-request.json deleted file mode 100644 index ba27f286b81..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/simulation/test-auction-request.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "id": "tid", - "imp": [ - { - "id": "impId1", - "banner": { - "format": [ - { - "w": 300, - "h": 250 - } - ] - }, - "ext": { - "tid": "someTid", - "prebid": { - "bidder": { - "rubicon": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - } - } - } - } - } - ], - "cur": [ - "USD" - ], - "source": { - "tid": "someTid" - }, - "site": { - "publisher": { - "id": "2001" - } - }, - "user": { - "ext": { - "consent": "CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA" - } - }, - "ext": { - "prebid": { - "debug": 1, - "trace": "verbose", - "targeting": { - }, - "auctiontimestamp": 1000 - } - } -} diff --git a/src/test/resources/org/prebid/server/it/deals/simulation/test-auction-response-1.json b/src/test/resources/org/prebid/server/it/deals/simulation/test-auction-response-1.json deleted file mode 100644 index 6d8a30fe28b..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/simulation/test-auction-response-1.json +++ /dev/null @@ -1,349 +0,0 @@ -{ - "id": "tid", - "seatbid": [ - { - "bid": [ - { - "id": "impId1-lineItem1", - "impid": "impId1", - "price": 10.0, - "adm": "", - "crid": "crid", - "dealid": "dealId1", - "w": 300, - "h": 250, - "ext": { - "prebid": { - "type": "banner", - "targeting": { - "hb_pb": "10.00", - "hb_pb_rubicon": "10.00", - "hb_deal_rubicon": "dealId1", - "hb_size": "300x250", - "hb_bidder": "rubicon", - "hb_size_rubicon": "300x250", - "hb_bidder_rubicon": "rubicon", - "hb_deal": "dealId1" - }, - "events": { - "win": "http://localhost:8080/event?t=win&b=impId1-lineItem1&a=2001&aid=tid&ts=1000&bidder=rubicon&f=i&int=&x=0&l=lineItem1", - "imp": "http://localhost:8080/event?t=imp&b=impId1-lineItem1&a=2001&aid=tid&ts=1000&bidder=rubicon&f=i&int=&x=0&l=lineItem1" - } - }, - "origbidcpm": 10.0, - "origbidcur": "USD" - } - } - ], - "seat": "rubicon", - "group": 0 - } - ], - "cur": "USD", - "ext": { - "debug": { - "resolvedrequest": { - "id": "tid", - "imp": [ - { - "id": "impId1", - "secure": 1, - "banner": { - "format": [ - { - "w": 300, - "h": 250 - } - ] - }, - "pmp": { - "deals": [ - { - "id": "dealId3", - "ext": { - "line": { - "lineitemid": "lineItem3", - "extlineitemid": "extLineItem3", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - }, - { - "id": "dealId1", - "ext": { - "line": { - "lineitemid": "lineItem1", - "extlineitemid": "extLineItem1", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - }, - { - "id": "dealId2", - "ext": { - "line": { - "lineitemid": "lineItem2", - "extlineitemid": "extLineItem2", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - } - ] - }, - "ext": { - "tid": "someTid", - "prebid": { - "bidder": { - "rubicon": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - } - } - } - } - } - ], - "source": { - "tid": "someTid" - }, - "site": { - "domain": "www.example.com", - "page": "http://www.example.com", - "publisher": { - "id": "2001", - "domain": "example.com" - }, - "ext": { - "amp": 0 - } - }, - "device": { - "ua": "userAgent", - "ip": "185.199.110.0" - }, - "user": { - "consent": "CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA", - "ext": { - "fcapids": [], - "time": { - "userdow": "{{ userdow }}", - "userhour": "{{ userhour }}" - } - } - }, - "at": 1, - "tmax": 5000, - "cur": [ - "USD" - ], - "ext": { - "prebid": { - "debug": 1, - "server": { - "externalurl": "http://localhost:8080", - "gvlid": 1, - "datacenter": "local", - "endpoint": "/openrtb2/auction" - }, - "trace": "verbose", - "targeting": { - "pricegranularity": { - "precision": 2, - "ranges": [ - { - "max": 20, - "increment": 0.1 - } - ] - }, - "includewinners": true, - "includebidderkeys": true - }, - "auctiontimestamp": 1000, - "channel": { - "name": "web" - } - } - } - }, - "pgmetrics": { - "sent_to_client": [ - "lineItem1" - ], - "sent_to_client_as_top_match": [ - "lineItem1" - ], - "matched_whole_targeting": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "ready_to_serve": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "sent_to_bidder": { - "rubicon": [ - "lineItem3", - "lineItem1", - "lineItem2" - ] - }, - "sent_to_bidder_as_top_match": { - "rubicon": [ - "lineItem3" - ] - }, - "received_from_bidder": { - "rubicon": [ - "lineItem1", - "lineItem2" - ] - } - }, - "trace": { - "lineitems": { - "lineItem3": [ - { - "lineitemid": "lineItem3", - "time": "2020-04-24T13:54:17.715Z", - "category": "targeting", - "message": "Line Item lineItem3 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem3", - "time": "2020-04-24T13:54:17.733Z", - "category": "pacing", - "message": "Matched Line Item lineItem3 for bidder rubicon ready to serve. relPriority 3" - } - ], - "lineItem1": [ - { - "lineitemid": "lineItem1", - "time": "2020-04-24T13:54:17.72Z", - "category": "targeting", - "message": "Line Item lineItem1 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem1", - "time": "2020-04-24T13:54:17.734Z", - "category": "pacing", - "message": "Matched Line Item lineItem1 for bidder rubicon ready to serve. relPriority 3" - } - ], - "lineItem2": [ - { - "lineitemid": "lineItem2", - "time": "2020-04-24T13:54:17.725Z", - "category": "targeting", - "message": "Line Item lineItem2 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem2", - "time": "2020-04-24T13:54:17.734Z", - "category": "pacing", - "message": "Matched Line Item lineItem2 for bidder rubicon ready to serve. relPriority 3" - } - ] - }, - "activity_infrastructure": [ - { - "description": "Invocation of Activity Infrastructure.", - "activity": "fetchBids", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "fetchBids", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitUfpd", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitUfpd", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitPreciseGeo", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitPreciseGeo", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitTid", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitTid", - "allowed": true - } - ] - } - }, - "responsetimemillis": { - "rubicon": "{{ rubicon.response_time_ms }}" - }, - "tmaxrequest": 5000, - "prebid": { - "auctiontimestamp": 1000 - } - } -} diff --git a/src/test/resources/org/prebid/server/it/deals/simulation/test-auction-response-2.json b/src/test/resources/org/prebid/server/it/deals/simulation/test-auction-response-2.json deleted file mode 100644 index cb8373269fd..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/simulation/test-auction-response-2.json +++ /dev/null @@ -1,333 +0,0 @@ -{ - "id": "tid", - "seatbid": [ - { - "bid": [ - { - "id": "impId1-lineItem2", - "impid": "impId1", - "price": 7.0, - "adm": "", - "crid": "crid", - "dealid": "dealId2", - "w": 300, - "h": 250, - "ext": { - "prebid": { - "type": "banner", - "targeting": { - "hb_pb": "7.00", - "hb_pb_rubicon": "7.00", - "hb_deal_rubicon": "dealId2", - "hb_size": "300x250", - "hb_bidder": "rubicon", - "hb_size_rubicon": "300x250", - "hb_bidder_rubicon": "rubicon", - "hb_deal": "dealId2" - }, - "events": { - "win": "http://localhost:8080/event?t=win&b=impId1-lineItem2&a=2001&aid=tid&ts=1000&bidder=rubicon&f=i&int=&x=0&l=lineItem2", - "imp": "http://localhost:8080/event?t=imp&b=impId1-lineItem2&a=2001&aid=tid&ts=1000&bidder=rubicon&f=i&int=&x=0&l=lineItem2" - } - }, - "origbidcpm": 7.0, - "origbidcur": "USD" - } - } - ], - "seat": "rubicon", - "group": 0 - } - ], - "cur": "USD", - "ext": { - "debug": { - "resolvedrequest": { - "id": "tid", - "imp": [ - { - "id": "impId1", - "secure": 1, - "banner": { - "format": [ - { - "w": 300, - "h": 250 - } - ] - }, - "pmp": { - "deals": [ - { - "id": "dealId3", - "ext": { - "line": { - "lineitemid": "lineItem3", - "extlineitemid": "extLineItem3", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - }, - { - "id": "dealId2", - "ext": { - "line": { - "lineitemid": "lineItem2", - "extlineitemid": "extLineItem2", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "rubicon" - } - } - } - ] - }, - "ext": { - "tid": "someTid", - "prebid": { - "bidder": { - "rubicon": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - } - } - } - } - } - ], - "source": { - "tid": "someTid" - }, - "site": { - "domain": "www.example.com", - "page": "http://www.example.com", - "publisher": { - "id": "2001", - "domain": "example.com" - }, - "ext": { - "amp": 0 - } - }, - "device": { - "ua": "userAgent", - "ip": "185.199.110.0" - }, - "user": { - "consent": "CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA", - "ext": { - "fcapids": [], - "time": { - "userdow": "{{ userdow }}", - "userhour": "{{ userhour }}" - } - } - }, - "at": 1, - "tmax": 5000, - "cur": [ - "USD" - ], - "ext": { - "prebid": { - "debug": 1, - "trace": "verbose", - "server": { - "externalurl": "http://localhost:8080", - "gvlid": 1, - "datacenter": "local", - "endpoint": "/openrtb2/auction" - }, - "targeting": { - "pricegranularity": { - "precision": 2, - "ranges": [ - { - "max": 20, - "increment": 0.1 - } - ] - }, - "includewinners": true, - "includebidderkeys": true - }, - "auctiontimestamp": 1000, - "channel": { - "name": "web" - } - } - } - }, - "pgmetrics": { - "sent_to_client": [ - "lineItem2" - ], - "sent_to_client_as_top_match": [ - "lineItem2" - ], - "matched_whole_targeting": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "ready_to_serve": [ - "lineItem3", - "lineItem2" - ], - "pacing_deferred": [ - "lineItem1" - ], - "sent_to_bidder": { - "rubicon": [ - "lineItem3", - "lineItem2" - ] - }, - "sent_to_bidder_as_top_match": { - "rubicon": [ - "lineItem3" - ] - }, - "received_from_bidder": { - "rubicon": [ - "lineItem2" - ] - } - }, - "trace": { - "lineitems": { - "lineItem3": [ - { - "lineitemid": "lineItem3", - "time": "2020-04-24T14:03:17.986Z", - "category": "targeting", - "message": "Line Item lineItem3 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem3", - "time": "2020-04-24T14:03:18.002Z", - "category": "pacing", - "message": "Matched Line Item lineItem3 for bidder rubicon ready to serve. relPriority 3" - } - ], - "lineItem1": [ - { - "lineitemid": "lineItem1", - "time": "2020-04-24T14:03:17.993Z", - "category": "targeting", - "message": "Line Item lineItem1 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem1", - "time": "2020-04-24T14:03:18.002Z", - "category": "pacing", - "message": "Matched Line Item lineItem1 for bidder rubicon not ready to serve. Will be ready at never, current time is 2019-10-10T00:16:00.000Z" - } - ], - "lineItem2": [ - { - "lineitemid": "lineItem2", - "time": "2020-04-24T14:03:18.001Z", - "category": "targeting", - "message": "Line Item lineItem2 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem2", - "time": "2020-04-24T14:03:18.003Z", - "category": "pacing", - "message": "Matched Line Item lineItem2 for bidder rubicon ready to serve. relPriority 3" - } - ] - }, - "activity_infrastructure": [ - { - "description": "Invocation of Activity Infrastructure.", - "activity": "fetchBids", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "fetchBids", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitUfpd", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitUfpd", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitPreciseGeo", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitPreciseGeo", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitTid", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "rubicon" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitTid", - "allowed": true - } - ] - } - }, - "responsetimemillis": { - "rubicon": "{{ rubicon.response_time_ms }}" - }, - "tmaxrequest": 5000, - "prebid": { - "auctiontimestamp": 1000 - } - } -} diff --git a/src/test/resources/org/prebid/server/it/deals/simulation/test-bid-rates.json b/src/test/resources/org/prebid/server/it/deals/simulation/test-bid-rates.json deleted file mode 100644 index fe32f4a040e..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/simulation/test-bid-rates.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "lineItem1": 1.00, - "lineItem2": 1.00, - "lineItem3": 0.00 -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/it/deals/simulation/test-delivery-stats-progress-request-1.json b/src/test/resources/org/prebid/server/it/deals/simulation/test-delivery-stats-progress-request-1.json deleted file mode 100644 index 07187887734..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/simulation/test-delivery-stats-progress-request-1.json +++ /dev/null @@ -1,149 +0,0 @@ -{ - "reportTimeStamp": "2019-10-10T00:00:03.000Z", - "dataWindowStartTimeStamp": "2019-10-10T00:00:02.000Z", - "dataWindowEndTimeStamp": "2019-10-10T00:00:03.000Z", - "instanceId": "localhost", - "vendor": "local", - "region": "local", - "clientAuctions": 1, - "lineItemStatus": [ - { - "lineItemSource": "rubicon", - "lineItemId": "lineItem2", - "dealId": "dealId2", - "extLineItemId": "extLineItem2", - "accountAuctions": 1, - "domainMatched": 0, - "targetMatched": 1, - "targetMatchedButFcapped": 0, - "targetMatchedButFcapLookupFailed": 0, - "pacingDeferred": 0, - "sentToBidder": 1, - "sentToBidderAsTopMatch": 0, - "receivedFromBidder": 1, - "receivedFromBidderInvalidated": 0, - "sentToClient": 0, - "sentToClientAsTopMatch": 0, - "lostToLineItems": [ - { - "lineItemSource": "rubicon", - "lineItemId": "lineItem3", - "count": 1 - }, - { - "lineItemSource": "rubicon", - "lineItemId": "lineItem1", - "count": 1 - } - ], - "events": [], - "deliverySchedule": [ - { - "planId": "1", - "planStartTimeStamp": "2019-10-10T00:00:00.000Z", - "planExpirationTimeStamp": "2019-10-10T00:10:00.000Z", - "planUpdatedTimeStamp": "2019-10-10T00:00:00.000Z", - "tokens": [ - { - "class": 1, - "total": 5000, - "spent": 0 - }, - { - "class": 2, - "total": 125, - "spent": 0 - } - ] - } - ] - }, - { - "lineItemSource": "rubicon", - "lineItemId": "lineItem3", - "dealId": "dealId3", - "extLineItemId": "extLineItem3", - "accountAuctions": 1, - "domainMatched": 0, - "targetMatched": 1, - "targetMatchedButFcapped": 0, - "targetMatchedButFcapLookupFailed": 0, - "pacingDeferred": 0, - "sentToBidder": 1, - "sentToBidderAsTopMatch": 1, - "receivedFromBidder": 0, - "receivedFromBidderInvalidated": 0, - "sentToClient": 0, - "sentToClientAsTopMatch": 0, - "events": [], - "deliverySchedule": [ - { - "planId": "1", - "planStartTimeStamp": "2019-10-10T00:00:00.000Z", - "planExpirationTimeStamp": "2019-10-10T00:10:00.000Z", - "planUpdatedTimeStamp": "2019-10-10T00:00:00.000Z", - "tokens": [ - { - "class": 1, - "total": 5000, - "spent": 0 - }, - { - "class": 2, - "total": 125, - "spent": 0 - } - ] - } - ] - }, - { - "lineItemSource": "rubicon", - "lineItemId": "lineItem1", - "dealId": "dealId1", - "extLineItemId": "extLineItem1", - "accountAuctions": 1, - "domainMatched": 0, - "targetMatched": 1, - "targetMatchedButFcapped": 0, - "targetMatchedButFcapLookupFailed": 0, - "pacingDeferred": 0, - "sentToBidder": 1, - "sentToBidderAsTopMatch": 0, - "receivedFromBidder": 1, - "receivedFromBidderInvalidated": 0, - "sentToClient": 1, - "sentToClientAsTopMatch": 1, - "lostToLineItems": [ - { - "lineItemSource": "rubicon", - "lineItemId": "lineItem3", - "count": 1 - } - ], - "events": [], - "deliverySchedule": [ - { - "planId": "1", - "planStartTimeStamp": "2019-10-10T00:00:00.000Z", - "planExpirationTimeStamp": "2019-10-10T00:10:00.000Z", - "planUpdatedTimeStamp": "2019-10-10T00:00:00.000Z", - "tokens": [ - { - "class": 2, - "total": 125, - "spent": 0, - "totalSpent": 0 - }, - { - "class": 1, - "total": 5000, - "spent": 1, - "totalSpent": 1 - } - ] - } - ] - } - ] -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/it/deals/simulation/test-delivery-stats-progress-request-2.json b/src/test/resources/org/prebid/server/it/deals/simulation/test-delivery-stats-progress-request-2.json deleted file mode 100644 index ab3a570202f..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/simulation/test-delivery-stats-progress-request-2.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "reportTimeStamp": "2019-10-10T00:17:00.000Z", - "dataWindowStartTimeStamp": "2019-10-10T00:00:03.000Z", - "dataWindowEndTimeStamp": "2019-10-10T00:17:00.000Z", - "instanceId": "localhost", - "vendor": "local", - "region": "local", - "clientAuctions": 1, - "lineItemStatus": [ - { - "lineItemSource": "rubicon", - "lineItemId": "lineItem2", - "dealId": "dealId2", - "extLineItemId": "extLineItem2", - "accountAuctions": 1, - "domainMatched": 0, - "targetMatched": 1, - "targetMatchedButFcapped": 0, - "targetMatchedButFcapLookupFailed": 0, - "pacingDeferred": 0, - "sentToBidder": 1, - "sentToBidderAsTopMatch": 0, - "receivedFromBidder": 1, - "receivedFromBidderInvalidated": 0, - "sentToClient": 1, - "sentToClientAsTopMatch": 1, - "lostToLineItems": [ - { - "lineItemSource": "rubicon", - "lineItemId": "lineItem3", - "count": 1 - } - ], - "events": [], - "deliverySchedule": [ - { - "planId": "2", - "planStartTimeStamp": "2019-10-10T00:10:00.000Z", - "planExpirationTimeStamp": "2019-10-10T00:20:00.000Z", - "planUpdatedTimeStamp": "2019-10-10T00:10:00.000Z", - "tokens": [ - { - "class": 2, - "total": 125, - "spent": 0, - "totalSpent": 0 - }, - { - "class": 1, - "total": 5000, - "spent": 1, - "totalSpent": 1 - } - ] - } - ] - }, - { - "lineItemSource": "rubicon", - "lineItemId": "lineItem3", - "dealId": "dealId3", - "extLineItemId": "extLineItem3", - "accountAuctions": 1, - "domainMatched": 0, - "targetMatched": 1, - "targetMatchedButFcapped": 0, - "targetMatchedButFcapLookupFailed": 0, - "pacingDeferred": 0, - "sentToBidder": 1, - "sentToBidderAsTopMatch": 1, - "receivedFromBidder": 0, - "receivedFromBidderInvalidated": 0, - "sentToClient": 0, - "sentToClientAsTopMatch": 0, - "events": [], - "deliverySchedule": [ - { - "planId": "2", - "planStartTimeStamp": "2019-10-10T00:10:00.000Z", - "planExpirationTimeStamp": "2019-10-10T00:20:00.000Z", - "planUpdatedTimeStamp": "2019-10-10T00:10:00.000Z", - "tokens": [ - { - "class": 2, - "total": 125, - "spent": 0 - }, - { - "class": 1, - "total": 5000, - "spent": 0 - } - ] - } - ] - } - ] -} diff --git a/src/test/resources/org/prebid/server/it/deals/simulation/test-planner-plan-response-1.json b/src/test/resources/org/prebid/server/it/deals/simulation/test-planner-plan-response-1.json deleted file mode 100644 index 4dc1db3ce10..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/simulation/test-planner-plan-response-1.json +++ /dev/null @@ -1,257 +0,0 @@ -[ - { - "lineItemId": "lineItem1", - "extLineItemId": "extLineItem1", - "dealId": "dealId1", - "status": "active", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "accountId": "2001", - "source": "rubicon", - "price": { - "cpm": 10.00, - "currency": "USD" - }, - "relativePriority": 3, - "startTimeStamp": "2019-10-10T00:00:00Z", - "endTimeStamp": "2019-10-10T00:20:00Z", - "updatedTimeStamp": "2019-10-10T00:00:00Z", - "targeting": { - "$and": [ - { - "adunit.size": { - "$intersects": [ - { - "w": 300, - "h": 250 - } - ] - } - }, - { - "adunit.mediatype": { - "$intersects": [ - "banner" - ] - } - } - ] - }, - "frequencyCaps": [ - { - "fcapId": "fcapId1", - "count": 3, - "periods": 7, - "periodType": "day" - } - ], - "deliverySchedules": [ - { - "planId": "1", - "updatedTimeStamp": "2019-10-10T00:00:00Z", - "startTimeStamp": "2019-10-10T00:00:00Z", - "endTimeStamp": "2019-10-10T00:10:00Z", - "tokens": [ - { - "class": 1, - "total": 5000 - }, - { - "class": 2, - "total": 125 - } - ] - }, - { - "planId": "2", - "updatedTimeStamp": "2019-10-10T00:10:00Z", - "startTimeStamp": "2019-10-10T00:20:00Z", - "endTimeStamp": "2019-10-10T00:30:00Z", - "tokens": [ - { - "class": 1, - "total": 5000 - }, - { - "class": 2, - "total": 125 - } - ] - } - ] - }, - { - "lineItemId": "lineItem2", - "dealId": "dealId2", - "extLineItemId": "extLineItem2", - "status": "active", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "accountId": "2001", - "source": "rubicon", - "price": { - "cpm": 7.00, - "currency": "USD" - }, - "relativePriority": 3, - "startTimeStamp": "2019-10-10T00:00:00Z", - "endTimeStamp": "2019-10-10T00:20:00Z", - "updatedTimeStamp": "2019-10-10T00:00:00Z", - "targeting": { - "$and": [ - { - "adunit.size": { - "$intersects": [ - { - "w": 300, - "h": 250 - } - ] - } - }, - { - "adunit.mediatype": { - "$intersects": [ - "banner" - ] - } - } - ] - }, - "frequencyCaps": [ - { - "fcapId": "fcapId2", - "count": 3, - "periods": 7, - "periodType": "day" - } - ], - "deliverySchedules": [ - { - "planId": "1", - "updatedTimeStamp": "2019-10-10T00:00:00Z", - "startTimeStamp": "2019-10-10T00:00:00Z", - "endTimeStamp": "2019-10-10T00:10:00Z", - "tokens": [ - { - "class": 1, - "total": 5000 - }, - { - "class": 2, - "total": 125 - } - ] - }, - { - "planId": "2", - "updatedTimeStamp": "2019-10-10T00:10:00Z", - "startTimeStamp": "2019-10-10T00:10:00Z", - "endTimeStamp": "2019-10-10T00:20:00Z", - "tokens": [ - { - "class": 1, - "total": 5000 - }, - { - "class": 2, - "total": 125 - } - ] - } - ] - }, - { - "lineItemId": "lineItem3", - "extLineItemId": "extLineItem3", - "dealId": "dealId3", - "status": "active", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "accountId": "2001", - "source": "rubicon", - "price": { - "cpm": 15.00, - "currency": "USD" - }, - "relativePriority": 3, - "startTimeStamp": "2019-10-10T00:00:00Z", - "endTimeStamp": "2019-10-10T00:20:00Z", - "updatedTimeStamp": "2019-10-10T00:00:00Z", - "targeting": { - "$and": [ - { - "adunit.size": { - "$intersects": [ - { - "w": 300, - "h": 250 - } - ] - } - }, - { - "adunit.mediatype": { - "$intersects": [ - "banner" - ] - } - } - ] - }, - "frequencyCaps": [ - { - "fcapId": "fcapId1", - "count": 3, - "periods": 7, - "periodType": "day" - } - ], - "deliverySchedules": [ - { - "planId": "1", - "updatedTimeStamp": "2019-10-10T00:00:00Z", - "startTimeStamp": "2019-10-10T00:00:00Z", - "endTimeStamp": "2019-10-10T00:10:00Z", - "tokens": [ - { - "class": 1, - "total": 5000 - }, - { - "class": 2, - "total": 125 - } - ] - }, - { - "planId": "2", - "updatedTimeStamp": "2019-10-10T00:10:00Z", - "startTimeStamp": "2019-10-10T00:10:00Z", - "endTimeStamp": "2019-10-10T00:20:00Z", - "tokens": [ - { - "class": 1, - "total": 5000 - }, - { - "class": 2, - "total": 125 - } - ] - } - ] - } -] diff --git a/src/test/resources/org/prebid/server/it/deals/simulation/test-planner-register-request-1.json b/src/test/resources/org/prebid/server/it/deals/simulation/test-planner-register-request-1.json deleted file mode 100644 index c8aa1a6e300..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/simulation/test-planner-register-request-1.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "healthIndex": 0.43, - "hostInstanceId": "localhost", - "region": "local", - "vendor": "local" -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/it/deals/test-auction-request.json b/src/test/resources/org/prebid/server/it/deals/test-auction-request.json deleted file mode 100644 index bfc31ef4604..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/test-auction-request.json +++ /dev/null @@ -1,133 +0,0 @@ -{ - "id": "tid", - "regs": { - "gdpr": 0 - }, - "imp": [ - { - "id": "impId1", - "banner": { - "format": [ - { - "w": 300, - "h": 250 - } - ] - }, - "ext": { - "tid": "someTid", - "prebid": { - "bidder": { - "generic": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - } - } - } - } - }, - { - "id": "impId2", - "banner": { - "format": [ - { - "w": 320, - "h": 320 - } - ] - }, - "ext": { - "tid": "someTid", - "prebid": { - "bidder": { - "generic": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - } - } - } - } - }, - { - "id": "impId3", - "banner": { - "format": [ - { - "w": 300, - "h": 600 - } - ] - }, - "ext": { - "tid": "someTid", - "prebid": { - "bidder": { - "generic": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001, - "dealsonly": true, - "pgdealsonly": true - } - } - } - } - }, - { - "id": "impId4", - "banner": { - "format": [ - { - "w": 300, - "h": 250 - } - ] - }, - "ext": { - "tid": "someTid", - "prebid": { - "bidder": { - "generic": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - } - } - } - } - } - ], - "cur": [ - "USD" - ], - "source": { - "tid": "someTid" - }, - "site": { - "publisher": { - "id": "2001" - } - }, - "user": { - "ext": { - "consent": "CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA" - } - }, - "ext": { - "prebid": { - "debug": 1, - "trace": "verbose", - "targeting": { - }, - "cache": { - "bids": {}, - "vastxml": { - "ttlseconds": 120 - } - }, - "auctiontimestamp": 1000 - } - } -} diff --git a/src/test/resources/org/prebid/server/it/deals/test-auction-response.json b/src/test/resources/org/prebid/server/it/deals/test-auction-response.json deleted file mode 100644 index 23703e850eb..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/test-auction-response.json +++ /dev/null @@ -1,860 +0,0 @@ -{ - "id": "tid", - "seatbid": [ - { - "bid": [ - { - "id": "bidId1", - "impid": "impId1", - "price": 8.43, - "adm": "", - "crid": "crid1", - "dealid": "dealId1", - "w": 300, - "h": 250, - "ext": { - "prebid": { - "type": "banner", - "targeting": { - "hb_deal_generic": "dealId1", - "hb_cache_id": "3f37ff80-b395-449f-a80e-c21a38bb6eec", - "hb_cache_path_generic": "/cache", - "hb_cache_host_generic": "{{ cache.host }}", - "hb_pb": "8.40", - "hb_pb_generic": "8.40", - "hb_cache_id_generic": "3f37ff80-b395-449f-a80e-c21a38bb6eec", - "hb_cache_path": "/cache", - "hb_size": "300x250", - "hb_bidder": "generic", - "hb_size_generic": "300x250", - "hb_bidder_generic": "generic", - "hb_cache_host": "{{ cache.host }}", - "hb_deal": "dealId1" - }, - "cache": { - "bids": { - "url": "{{ cache.resource_url }}3f37ff80-b395-449f-a80e-c21a38bb6eec", - "cacheId": "3f37ff80-b395-449f-a80e-c21a38bb6eec" - } - }, - "events": { - "win": "http://localhost:8080/event?t=win&b=bidId1&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem1", - "imp": "http://localhost:8080/event?t=imp&b=bidId1&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem1" - } - }, - "origbidcpm": 8.43 - } - }, - { - "id": "bidId2", - "impid": "impId2", - "price": 8.43, - "adm": "", - "crid": "crid2", - "dealid": "dealId2", - "w": 320, - "h": 320, - "ext": { - "prebid": { - "type": "banner", - "targeting": { - "hb_deal_generic": "dealId2", - "hb_size_generic": "320x320", - "hb_cache_id": "13e78248-7339-4e35-b297-874d0031bc1a", - "hb_cache_path_generic": "/cache", - "hb_cache_host_generic": "{{ cache.host }}", - "hb_pb": "8.40", - "hb_pb_generic": "8.40", - "hb_cache_id_generic": "13e78248-7339-4e35-b297-874d0031bc1a", - "hb_cache_path": "/cache", - "hb_size": "320x320", - "hb_bidder": "generic", - "hb_bidder_generic": "generic", - "hb_cache_host": "{{ cache.host }}", - "hb_deal": "dealId2" - }, - "cache": { - "bids": { - "url": "{{ cache.resource_url }}13e78248-7339-4e35-b297-874d0031bc1a", - "cacheId": "13e78248-7339-4e35-b297-874d0031bc1a" - } - }, - "events": { - "win": "http://localhost:8080/event?t=win&b=bidId2&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem2", - "imp": "http://localhost:8080/event?t=imp&b=bidId2&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem2" - } - }, - "origbidcpm": 8.43 - } - }, - { - "id": "bidId4", - "impid": "impId4", - "price": 8.43, - "adm": "", - "crid": "crid1", - "dealid": "dealId3", - "w": 300, - "h": 250, - "ext": { - "prebid": { - "type": "banner", - "targeting": { - "hb_deal_generic": "dealId3", - "hb_size_generic": "300x250", - "hb_cache_id": "1cdcf339-e59b-4e2c-8382-1fb845d4961c", - "hb_cache_path_generic": "/cache", - "hb_cache_host_generic": "{{ cache.host }}", - "hb_pb": "8.40", - "hb_pb_generic": "8.40", - "hb_cache_id_generic": "1cdcf339-e59b-4e2c-8382-1fb845d4961c", - "hb_cache_path": "/cache", - "hb_size": "300x250", - "hb_bidder": "generic", - "hb_bidder_generic": "generic", - "hb_cache_host": "{{ cache.host }}", - "hb_deal": "dealId3" - }, - "cache": { - "bids": { - "url": "{{ cache.resource_url }}1cdcf339-e59b-4e2c-8382-1fb845d4961c", - "cacheId": "1cdcf339-e59b-4e2c-8382-1fb845d4961c" - } - }, - "events": { - "win": "http://localhost:8080/event?t=win&b=bidId4&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem3", - "imp": "http://localhost:8080/event?t=imp&b=bidId4&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem3" - } - }, - "origbidcpm": 8.43 - } - } - ], - "seat": "generic", - "group": 0 - } - ], - "cur": "USD", - "ext": { - "debug": { - "httpcalls": { - "cache": [ - { - "uri": "{{ cache.endpoint }}", - "requestheaders": { - "Accept": [ - "application/json" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"puts\":[{\"type\":\"json\",\"value\":{\"id\":\"bidId1\",\"impid\":\"impId1\",\"price\":8.43,\"adm\":\"\",\"crid\":\"crid1\",\"dealid\":\"dealId1\",\"w\":300,\"h\":250,\"ext\":{\"origbidcpm\":8.43,\"prebid\":{\"type\":\"banner\",\"events\":{\"win\":\"http://localhost:8080/event?t=win&b=bidId1&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem1\",\"imp\":\"http://localhost:8080/event?t=imp&b=bidId1&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem1\"}}},\"wurl\":\"http://localhost:8080/event?t=win&b=bidId1&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem1\"},\"aid\":\"tid\"},{\"type\":\"json\",\"value\":{\"id\":\"bidId4\",\"impid\":\"impId4\",\"price\":8.43,\"adm\":\"\",\"crid\":\"crid1\",\"dealid\":\"dealId3\",\"w\":300,\"h\":250,\"ext\":{\"origbidcpm\":8.43,\"prebid\":{\"type\":\"banner\",\"events\":{\"win\":\"http://localhost:8080/event?t=win&b=bidId4&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem3\",\"imp\":\"http://localhost:8080/event?t=imp&b=bidId4&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem3\"}}},\"wurl\":\"http://localhost:8080/event?t=win&b=bidId4&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem3\"},\"aid\":\"tid\"},{\"type\":\"json\",\"value\":{\"id\":\"bidId2\",\"impid\":\"impId2\",\"price\":8.43,\"adm\":\"\",\"crid\":\"crid2\",\"dealid\":\"dealId2\",\"w\":320,\"h\":320,\"ext\":{\"origbidcpm\":8.43,\"prebid\":{\"type\":\"banner\",\"events\":{\"win\":\"http://localhost:8080/event?t=win&b=bidId2&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem2\",\"imp\":\"http://localhost:8080/event?t=imp&b=bidId2&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem2\"}}},\"wurl\":\"http://localhost:8080/event?t=win&b=bidId2&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem2\"},\"aid\":\"tid\"}]}", - "responsebody": "{\"responses\":[{\"uuid\":\"13e78248-7339-4e35-b297-874d0031bc1a\"},{\"uuid\":\"3f37ff80-b395-449f-a80e-c21a38bb6eec\"},{\"uuid\":\"1cdcf339-e59b-4e2c-8382-1fb845d4961c\"}]}", - "status": 200 - } - ], - "generic": [ - { - "uri": "{{ generic.exchange_uri }}", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId4\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem3\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId4\",\"seatbid\":[{\"seat\":\"seatId4\",\"bid\":[{\"id\":\"bidId4\",\"impid\":\"impId4\",\"dealid\":\"dealId3\",\"price\":8.43,\"adm\":\"\",\"crid\":\"crid1\",\"w\":300,\"h\":250}]}]}", - "status": 200 - }, - { - "uri": "{{ generic.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem1\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId1\",\"seatbid\":[{\"seat\":\"seatId1\",\"bid\":[{\"id\":\"bidId1\",\"impid\":\"impId1\",\"dealid\":\"dealId1\",\"price\":8.43,\"adm\":\"\",\"crid\":\"crid1\",\"w\":300,\"h\":250}]}]}", - "status": 200 - }, - { - "uri": "{{ generic.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId2\",\"banner\":{\"format\":[{\"w\":320,\"h\":320}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId2\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem2\",\"extlineitemid\":\"extLineItem2\",\"sizes\":[{\"w\":320,\"h\":320}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem2\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId2\",\"seatbid\":[{\"seat\":\"seatId2\",\"bid\":[{\"id\":\"bidId2\",\"impid\":\"impId2\",\"dealid\":\"dealId2\",\"price\":8.43,\"adm\":\"\",\"crid\":\"crid2\",\"w\":320,\"h\":320}]}]}", - "status": 200 - }, - { - "uri": "{{ generic.exchange_uri }}?tk_xint=rp-pbs", - "requestheaders": { - "Accept": [ - "application/json" - ], - "x-prebid": [ - "pbs-java/1.70.0" - ], - "User-Agent": [ - "prebid-server/1.0" - ], - "Content-Type": [ - "application/json;charset=utf-8" - ] - }, - "requestbody": "{\"id\":\"tid\",\"imp\":[{\"id\":\"impId1\",\"banner\":{\"format\":[{\"w\":300,\"h\":250}],\"ext\":{\"rp\":{\"mime\":\"text/html\"}}},\"pmp\":{\"deals\":[{\"id\":\"dealId1\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem1\",\"extlineitemid\":\"extLineItem1\",\"sizes\":[{\"w\":300,\"h\":250}]}}},{\"id\":\"dealId3\",\"ext\":{\"line\":{\"lineitemid\":\"lineItem3\",\"extlineitemid\":\"extLineItem3\",\"sizes\":[{\"w\":300,\"h\":250}]}}}]},\"secure\":1,\"ext\":{\"rp\":{\"zone_id\":4001,\"target\":{\"page\":[\"http://www.example.com\"],\"line_item\":\"extLineItem3\"},\"track\":{\"mint\":\"\",\"mint_version\":\"\"}},\"maxbids\":1}}],\"site\":{\"domain\":\"www.example.com\",\"page\":\"http://www.example.com\",\"publisher\":{\"ext\":{\"rp\":{\"account_id\":2001}}},\"ext\":{\"amp\":0,\"rp\":{\"site_id\":3001}}},\"device\":{\"ua\":\"userAgent\",\"ip\":\"185.199.110.0\",\"ext\":{\"rp\":{}}},\"user\":{\"buyeruid\":\"J5VLCWQP-26-CWFT\",\"consent\":\"CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA\",\"ext\":{\"fcapids\":[\"fcapId3\"],\"time\":{\"userdow\":{{ userdow }},\"userhour\":{{ userhour }}}}},\"at\":1,\"tmax\":5000,\"source\":{\"tid\":\"someTid\"}}", - "responsebody": "{\"id\":\"bidResponseId3\",\"seatbid\":[{\"seat\":\"seatId3\",\"bid\":[{\"id\":\"bidId3\",\"impid\":\"impId1\",\"dealid\":\"dealId3\",\"price\":8.43,\"adm\":\"\",\"crid\":\"crid3\",\"w\":300,\"h\":250}]}]}", - "status": 200 - } - ], - "userservice": [ - { - "uri": "{{ userservice_uri }}", - "requestbody": "{\"time\":\"{{ userservice_time }}\",\"ids\":[{\"type\":\"khaos\",\"id\":\"J5VLCWQP-26-CWFT\"}]}", - "responsebody": "{\"user\":{\"data\":[{\"id\":\"1111\",\"name\":\"generic\",\"segment\":[{\"id\":\"2222\"},{\"id\":\"3333\"}]},{\"id\":\"4444\",\"name\":\"bluekai\",\"segment\":[{\"id\":\"5555\"},{\"id\":\"6666\"}]}],\"ext\":{\"fcapIds\":[\"fcapId3\"]}}}", - "status": 200 - } - ] - }, - "resolvedrequest": { - "id": "tid", - "regs": { - "gdpr": 0 - }, - "imp": [ - { - "id": "impId1", - "secure": 1, - "banner": { - "format": [ - { - "w": 300, - "h": 250 - } - ] - }, - "pmp": { - "deals": [ - { - "id": "dealId1", - "ext": { - "line": { - "lineitemid": "lineItem1", - "extlineitemid": "extLineItem1", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "generic" - } - } - }, - { - "id": "dealId3", - "ext": { - "line": { - "lineitemid": "lineItem3", - "extlineitemid": "extLineItem3", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "generic" - } - } - } - ] - }, - "ext": { - "tid": "someTid", - "prebid": { - "bidder": { - "generic": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - } - } - } - } - }, - { - "id": "impId2", - "secure": 1, - "banner": { - "format": [ - { - "w": 320, - "h": 320 - } - ] - }, - "pmp": { - "deals": [ - { - "id": "dealId2", - "ext": { - "line": { - "lineitemid": "lineItem2", - "extlineitemid": "extLineItem2", - "sizes": [ - { - "w": 320, - "h": 320 - } - ], - "bidder": "generic" - } - } - } - ] - }, - "ext": { - "tid": "someTid", - "prebid": { - "bidder": { - "generic": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - } - } - } - } - }, - { - "id": "impId3", - "secure": 1, - "banner": { - "format": [ - { - "w": 300, - "h": 600 - } - ] - }, - "ext": { - "tid": "someTid", - "prebid": { - "bidder": { - "generic": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001, - "dealsonly": true, - "pgdealsonly": true - } - } - } - } - }, - { - "id": "impId4", - "secure": 1, - "banner": { - "format": [ - { - "w": 300, - "h": 250 - } - ] - }, - "pmp": { - "deals": [ - { - "id": "dealId3", - "ext": { - "line": { - "lineitemid": "lineItem3", - "extlineitemid": "extLineItem3", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "bidder": "generic" - } - } - } - ] - }, - "ext": { - "tid": "someTid", - "prebid": { - "bidder": { - "generic": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - } - } - } - } - } - ], - "source": { - "tid": "someTid" - }, - "site": { - "domain": "www.example.com", - "page": "http://www.example.com", - "publisher": { - "id": "2001", - "domain": "example.com" - }, - "ext": { - "amp": 0 - } - }, - "device": { - "ua": "userAgent", - "ip": "185.199.110.0" - }, - "user": { - "data": [ - { - "id": "generic", - "segment": [ - { - "id": "2222" - }, - { - "id": "3333" - } - ] - }, - { - "id": "bluekai", - "segment": [ - { - "id": "5555" - }, - { - "id": "6666" - } - ] - } - ], - "consent": "CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA", - "ext": { - "fcapids": [ - "fcapId3" - ], - "time": { - "userdow": "{{ userdow }}", - "userhour": "{{ userhour }}" - } - } - }, - "at": 1, - "tmax": 5000, - "cur": [ - "USD" - ], - "ext": { - "prebid": { - "debug": 1, - "server": { - "externalurl": "http://localhost:8080", - "gvlid": 1, - "datacenter": "local", - "endpoint": "/openrtb2/auction" - }, - "trace": "verbose", - "targeting": { - "pricegranularity": { - "precision": 2, - "ranges": [ - { - "max": 20, - "increment": 0.1 - } - ] - }, - "includewinners": true, - "includebidderkeys": true - }, - "cache": { - "bids": {}, - "vastxml": { - "ttlseconds": 120 - } - }, - "auctiontimestamp": 1000, - "channel": { - "name": "web" - } - } - } - }, - "pgmetrics": { - "sent_to_client": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "sent_to_client_as_top_match": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "matched_whole_targeting": [ - "lineItem3", - "lineItem4", - "lineItem1", - "lineItem2" - ], - "matched_targeting_fcapped": [ - "lineItem4" - ], - "ready_to_serve": [ - "lineItem3", - "lineItem1", - "lineItem2" - ], - "sent_to_bidder": { - "generic": [ - "lineItem3", - "lineItem1", - "lineItem2" - ] - }, - "sent_to_bidder_as_top_match": { - "generic": [ - "lineItem3", - "lineItem1", - "lineItem2" - ] - }, - "received_from_bidder": { - "generic": [ - "lineItem3", - "lineItem1", - "lineItem2" - ] - } - }, - "trace": { - "lineitems": { - "lineItem3": [ - { - "lineitemid": "lineItem3", - "time": "2020-04-27T13:08:03.963Z", - "category": "targeting", - "message": "Line Item lineItem3 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem3", - "time": "2020-04-27T13:08:03.981Z", - "category": "pacing", - "message": "Matched Line Item lineItem3 for bidder generic ready to serve. relPriority 3" - }, - { - "lineitemid": "lineItem3", - "time": "2020-04-27T13:08:03.992Z", - "category": "targeting", - "message": "Line Item lineItem3 targeting did not match imp with id impId2" - }, - { - "lineitemid": "lineItem3", - "time": "2020-04-27T13:08:04.009Z", - "category": "targeting", - "message": "Line Item lineItem3 targeting did not match imp with id impId3" - }, - { - "lineitemid": "lineItem3", - "time": "2020-04-27T13:08:04.029Z", - "category": "targeting", - "message": "Line Item lineItem3 targeting matched imp with id impId4" - }, - { - "lineitemid": "lineItem3", - "time": "2020-04-27T13:08:04.043Z", - "category": "pacing", - "message": "Matched Line Item lineItem3 for bidder generic ready to serve. relPriority 3" - } - ], - "lineItem4": [ - { - "lineitemid": "lineItem4", - "time": "2020-04-27T13:08:03.967Z", - "category": "targeting", - "message": "Line Item lineItem4 targeting did not match imp with id impId1" - }, - { - "lineitemid": "lineItem4", - "time": "2020-04-27T13:08:03.995Z", - "category": "targeting", - "message": "Line Item lineItem4 targeting did not match imp with id impId2" - }, - { - "lineitemid": "lineItem4", - "time": "2020-04-27T13:08:04.014Z", - "category": "targeting", - "message": "Line Item lineItem4 targeting matched imp with id impId3" - }, - { - "lineitemid": "lineItem4", - "time": "2020-04-27T13:08:04.024Z", - "category": "pacing", - "message": "Matched Line Item lineItem4 for bidder generic is frequency capped by fcap id fcapId3." - }, - { - "lineitemid": "lineItem4", - "time": "2020-04-27T13:08:04.033Z", - "category": "targeting", - "message": "Line Item lineItem4 targeting did not match imp with id impId4" - } - ], - "lineItem1": [ - { - "lineitemid": "lineItem1", - "time": "2020-04-27T13:08:03.971Z", - "category": "targeting", - "message": "Line Item lineItem1 targeting matched imp with id impId1" - }, - { - "lineitemid": "lineItem1", - "time": "2020-04-27T13:08:03.981Z", - "category": "pacing", - "message": "Matched Line Item lineItem1 for bidder generic ready to serve. relPriority 3" - }, - { - "lineitemid": "lineItem1", - "time": "2020-04-27T13:08:03.999Z", - "category": "targeting", - "message": "Line Item lineItem1 targeting did not match imp with id impId2" - }, - { - "lineitemid": "lineItem1", - "time": "2020-04-27T13:08:04.019Z", - "category": "targeting", - "message": "Line Item lineItem1 targeting did not match imp with id impId3" - }, - { - "lineitemid": "lineItem1", - "time": "2020-04-27T13:08:04.038Z", - "category": "targeting", - "message": "Line Item lineItem1 targeting matched imp with id impId4" - }, - { - "lineitemid": "lineItem1", - "time": "2020-04-27T13:08:04.043Z", - "category": "pacing", - "message": "Matched Line Item lineItem1 for bidder generic ready to serve. relPriority 3" - }, - { - "lineitemid": "lineItem1", - "time": "2020-04-27T13:08:04.044Z", - "category": "cleanup", - "message": "LineItem lineItem1 was dropped from imp with id impId4 because it was top match in another imp" - } - ], - "lineItem2": [ - { - "lineitemid": "lineItem2", - "time": "2020-04-27T13:08:03.975Z", - "category": "targeting", - "message": "Line Item lineItem2 targeting did not match imp with id impId1" - }, - { - "lineitemid": "lineItem2", - "time": "2020-04-27T13:08:04.004Z", - "category": "targeting", - "message": "Line Item lineItem2 targeting matched imp with id impId2" - }, - { - "lineitemid": "lineItem2", - "time": "2020-04-27T13:08:04.004Z", - "category": "pacing", - "message": "Matched Line Item lineItem2 for bidder generic ready to serve. relPriority 3" - }, - { - "lineitemid": "lineItem2", - "time": "2020-04-27T13:08:04.024Z", - "category": "targeting", - "message": "Line Item lineItem2 targeting did not match imp with id impId3" - }, - { - "lineitemid": "lineItem2", - "time": "2020-04-27T13:08:04.043Z", - "category": "targeting", - "message": "Line Item lineItem2 targeting did not match imp with id impId4" - } - ] - }, - "activity_infrastructure": [ - { - "description": "Invocation of Activity Infrastructure.", - "activity": "fetchBids", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "generic" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "fetchBids", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "fetchBids", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "generic" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "fetchBids", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "fetchBids", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "generic" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "fetchBids", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "fetchBids", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "generic" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "fetchBids", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitUfpd", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "generic" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitUfpd", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitPreciseGeo", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "generic" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitPreciseGeo", - "allowed": true - }, - { - "description": "Invocation of Activity Infrastructure.", - "activity": "transmitTid", - "activity_invocation_payload": { - "component_type": "BIDDER", - "component_name": "generic" - } - }, - { - "description": "Setting the default invocation result.", - "allow_by_default": true - }, - { - "description": "Activity Infrastructure invocation result.", - "activity": "transmitTid", - "allowed": true - } - ] - } - }, - "warnings": { - "prebid": [ - { - "code": 999, - "message": "Not calling generic bidder for impressions impId3 due to pgdealsonly flag and no available PG line items." - } - ] - }, - "responsetimemillis": { - "generic": "{{ generic.response_time_ms }}", - "cache": "{{ cache.response_time_ms }}" - }, - "tmaxrequest": 5000, - "prebid": { - "auctiontimestamp": 1000 - } - } -} diff --git a/src/test/resources/org/prebid/server/it/deals/test-cache-deals-request.json b/src/test/resources/org/prebid/server/it/deals/test-cache-deals-request.json deleted file mode 100644 index 5461e5a9cd7..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/test-cache-deals-request.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "puts": [ - { - "type": "json", - "value": { - "id": "bidId4", - "impid": "impId4", - "price": 8.43, - "adm": "", - "crid": "crid1", - "dealid": "dealId3", - "w": 300, - "h": 250, - "ext": { - "origbidcpm": 8.43, - "prebid": { - "type": "banner", - "events": { - "win": "http://localhost:8080/event?t=win&b=bidId4&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem3", - "imp": "http://localhost:8080/event?t=imp&b=bidId4&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem3" - } - } - }, - "wurl": "http://localhost:8080/event?t=win&b=bidId4&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem3" - }, - "aid": "tid" - }, - { - "type": "json", - "value": { - "id": "bidId2", - "impid": "impId2", - "price": 8.43, - "adm": "", - "crid": "crid2", - "dealid": "dealId2", - "w": 320, - "h": 320, - "ext": { - "origbidcpm": 8.43, - "prebid": { - "type": "banner", - "events": { - "win": "http://localhost:8080/event?t=win&b=bidId2&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem2", - "imp": "http://localhost:8080/event?t=imp&b=bidId2&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem2" - } - } - }, - "wurl": "http://localhost:8080/event?t=win&b=bidId2&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem2" - }, - "aid": "tid" - }, - { - "type": "json", - "value": { - "id": "bidId1", - "impid": "impId1", - "price": 8.43, - "adm": "", - "crid": "crid1", - "dealid": "dealId1", - "w": 300, - "h": 250, - "ext": { - "origbidcpm": 8.43, - "prebid": { - "type": "banner", - "events": { - "win": "http://localhost:8080/event?t=win&b=bidId1&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem1", - "imp": "http://localhost:8080/event?t=imp&b=bidId1&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem1" - } - } - }, - "wurl": "http://localhost:8080/event?t=win&b=bidId1&a=2001&aid=tid&ts=1000&bidder=generic&f=i&int=&x=0&l=lineItem1" - }, - "aid": "tid" - } - ] -} diff --git a/src/test/resources/org/prebid/server/it/deals/test-cache-matcher.json b/src/test/resources/org/prebid/server/it/deals/test-cache-matcher.json deleted file mode 100644 index 6ce206a9f25..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/test-cache-matcher.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "bidId2@8.43": "13e78248-7339-4e35-b297-874d0031bc1a", - "bidId1@8.43": "3f37ff80-b395-449f-a80e-c21a38bb6eec", - "bidId4@8.43": "1cdcf339-e59b-4e2c-8382-1fb845d4961c" -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/it/deals/test-deals-application.properties b/src/test/resources/org/prebid/server/it/deals/test-deals-application.properties deleted file mode 100644 index 4f6d1b5ab41..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/test-deals-application.properties +++ /dev/null @@ -1,46 +0,0 @@ -server.http.port=8070 -admin.port=9060 -hostname=localhost -auction.ad-server-currency=USD -admin-endpoints.currency-rates.enabled=true -admin-endpoints.currency-rates.on-application-port=true -admin-endpoints.currency-rates.protected=false -admin-endpoints.e2eadmin.enabled=true -admin-endpoints.e2eadmin.on-application-port=true -admin-endpoints.e2eadmin.protected=false -admin-endpoints.lineitem-status.enabled=true -admin-endpoints.lineitem-status.on-application-port=true -admin-endpoints.lineitem-status.protected=false -admin-endpoints.deals-status.enabled=true -admin-endpoints.deals-status.on-application-port=true -admin-endpoints.deals-status.protected=false -deals.enabled=true -deals.planner.plan-endpoint=http://localhost:8090/planner-plan -deals.planner.register-endpoint=http://localhost:8090/planner-register -deals.planner.username=username -deals.planner.password=password -deals.planner.update-period=*/1 * * * * * -deals.delivery-stats.endpoint=http://localhost:8090/delivery-stats-progress -deals.delivery-stats.delivery-period=*/5 * * * * * -deals.delivery-stats.timeout-ms=1000 -deals.delivery-stats.username=username -deals.delivery-stats.password=password -deals.delivery-stats.reports-interval-ms=0 -deals.delivery-progress.report-reset-period=*/5 * * * * * -deals.user-data.user-details-endpoint=http://localhost:8090/user-data-details -deals.user-data.win-event-endpoint=http://localhost:8090/user-data-win-event -deals.user-data.timeout=1000 -deals.user-data.user-ids[0].type=khaos -deals.user-data.user-ids[0].source=uid -deals.user-data.user-ids[0].location=rubicon -deals.max-deals-per-bidder=3 -deals.alert-proxy.enabled=false -deals.alert-proxy.url=http://localhost -deals.alert-proxy.timeout-sec=5 -deals.alert-proxy.username=username -deals.alert-proxy.password=password -profile=test -infra=vm -data-center=aws -system=PBS -sub-system=Prebid Server diff --git a/src/test/resources/org/prebid/server/it/deals/test-deals-simulation-application.properties b/src/test/resources/org/prebid/server/it/deals/test-deals-simulation-application.properties deleted file mode 100644 index fe11da5609d..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/test-deals-simulation-application.properties +++ /dev/null @@ -1,3 +0,0 @@ -server.http.port=10080 -admin.port=10060 -deals.simulation.enabled=true diff --git a/src/test/resources/org/prebid/server/it/deals/test-delivery-stats-progress-request.json b/src/test/resources/org/prebid/server/it/deals/test-delivery-stats-progress-request.json deleted file mode 100644 index 1fd1cbf6c7a..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/test-delivery-stats-progress-request.json +++ /dev/null @@ -1,203 +0,0 @@ -{ - "instanceId": "localhost", - "vendor": "local", - "region": "local", - "clientAuctions": 1, - "lineItemStatus": [ - { - "lineItemSource": "generic", - "lineItemId": "lineItem4", - "dealId": "dealId4", - "extLineItemId": "extLineItem4", - "accountAuctions": 1, - "domainMatched": 0, - "targetMatched": 1, - "targetMatchedButFcapped": 1, - "targetMatchedButFcapLookupFailed": 0, - "pacingDeferred": 0, - "sentToBidder": 0, - "sentToBidderAsTopMatch": 0, - "receivedFromBidder": 0, - "receivedFromBidderInvalidated": 0, - "sentToClient": 0, - "sentToClientAsTopMatch": 0, - "events": [], - "deliverySchedule": [ - { - "planId": "1", - "tokens": [ - { - "class": 1, - "total": 5000, - "spent": 0 - }, - { - "class": 2, - "total": 125, - "spent": 0 - } - ] - } - ] - }, - { - "lineItemSource": "generic", - "lineItemId": "lineItem1", - "dealId": "dealId1", - "extLineItemId": "extLineItem1", - "accountAuctions": 1, - "domainMatched": 0, - "targetMatched": 1, - "targetMatchedButFcapped": 0, - "targetMatchedButFcapLookupFailed": 0, - "pacingDeferred": 0, - "sentToBidder": 1, - "sentToBidderAsTopMatch": 1, - "receivedFromBidder": 1, - "receivedFromBidderInvalidated": 0, - "sentToClient": 1, - "sentToClientAsTopMatch": 1, - "events": [ - { - "type": "win", - "count": 1 - } - ], - "deliverySchedule": [ - { - "planId": "1", - "tokens": [ - { - "class": 2, - "total": 125, - "spent": 0, - "totalSpent": 0 - }, - { - "class": 1, - "total": 5000, - "spent": 1, - "totalSpent": 1 - } - ] - } - ] - }, - { - "lineItemSource": "generic", - "lineItemId": "lineItem2", - "dealId": "dealId2", - "extLineItemId": "extLineItem2", - "accountAuctions": 1, - "domainMatched": 0, - "targetMatched": 1, - "targetMatchedButFcapped": 0, - "targetMatchedButFcapLookupFailed": 0, - "pacingDeferred": 0, - "sentToBidder": 1, - "sentToBidderAsTopMatch": 1, - "receivedFromBidder": 1, - "receivedFromBidderInvalidated": 0, - "sentToClient": 1, - "sentToClientAsTopMatch": 1, - "events": [], - "deliverySchedule": [ - { - "planId": "1", - "tokens": [ - { - "class": 2, - "total": 125, - "spent": 0, - "totalSpent": 0 - }, - { - "class": 1, - "total": 5000, - "spent": 1, - "totalSpent": 1 - } - ] - } - ] - }, - { - "lineItemSource": "generic", - "lineItemId": "lineItem5", - "dealId": "dealId5", - "extLineItemId": "extLineItem5", - "domainMatched": 0, - "targetMatched": 0, - "targetMatchedButFcapped": 0, - "targetMatchedButFcapLookupFailed": 0, - "pacingDeferred": 0, - "sentToBidder": 0, - "sentToBidderAsTopMatch": 0, - "receivedFromBidder": 0, - "receivedFromBidderInvalidated": 0, - "sentToClient": 0, - "sentToClientAsTopMatch": 0, - "events": [], - "deliverySchedule": [ - { - "planId": "1", - "tokens": [ - { - "class": 2, - "total": 125, - "spent": 0 - }, - { - "class": 1, - "total": 5000, - "spent": 0 - } - ] - } - ] - }, - { - "lineItemSource": "generic", - "lineItemId": "lineItem3", - "dealId": "dealId3", - "extLineItemId": "extLineItem3", - "accountAuctions": 1, - "domainMatched": 0, - "targetMatched": 1, - "targetMatchedButFcapped": 0, - "targetMatchedButFcapLookupFailed": 0, - "pacingDeferred": 0, - "sentToBidder": 1, - "sentToBidderAsTopMatch": 1, - "receivedFromBidder": 1, - "receivedFromBidderInvalidated": 0, - "sentToClient": 1, - "sentToClientAsTopMatch": 1, - "lostToLineItems": [ - { - "lineItemSource": "generic", - "lineItemId": "lineItem1", - "count": 1 - } - ], - "events": [], - "deliverySchedule": [ - { - "planId": "1", - "tokens": [ - { - "class": 1, - "total": 5000, - "spent": 1 - }, - { - "class": 2, - "total": 125, - "spent": 0 - } - ] - } - ] - } - ] -} diff --git a/src/test/resources/org/prebid/server/it/deals/test-generic-bid-request.json b/src/test/resources/org/prebid/server/it/deals/test-generic-bid-request.json deleted file mode 100644 index feed83c02c2..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/test-generic-bid-request.json +++ /dev/null @@ -1,236 +0,0 @@ -{ - "id": "tid", - "imp": [ - { - "id": "impId1", - "secure": 1, - "banner": { - "format": [ - { - "w": 300, - "h": 250 - } - ] - }, - "pmp": { - "deals": [ - { - "id": "dealId1", - "ext": { - "line": { - "lineitemid": "lineItem1", - "extlineitemid": "extLineItem1", - "sizes": [ - { - "w": 300, - "h": 250 - } - ] - } - } - }, - { - "id": "dealId3", - "ext": { - "line": { - "lineitemid": "lineItem3", - "extlineitemid": "extLineItem3", - "sizes": [ - { - "w": 300, - "h": 250 - } - ] - } - } - } - ] - }, - "ext": { - "bidder": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - }, - "tid": "someTid" - } - }, - { - "id": "impId2", - "secure": 1, - "banner": { - "format": [ - { - "w": 320, - "h": 320 - } - ] - }, - "pmp": { - "deals": [ - { - "id": "dealId2", - "ext": { - "line": { - "lineitemid": "lineItem2", - "extlineitemid": "extLineItem2", - "sizes": [ - { - "w": 320, - "h": 320 - } - ] - } - } - } - ] - }, - "ext": { - "bidder": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - }, - "tid": "someTid" - } - }, - { - "id": "impId4", - "secure": 1, - "banner": { - "format": [ - { - "w": 300, - "h": 250 - } - ] - }, - "pmp": { - "deals": [ - { - "id": "dealId3", - "ext": { - "line": { - "lineitemid": "lineItem3", - "extlineitemid": "extLineItem3", - "sizes": [ - { - "w": 300, - "h": 250 - } - ] - } - } - } - ] - }, - "ext": { - "bidder": { - "accountId": 2001, - "siteId": 3001, - "zoneId": 4001 - }, - "tid": "someTid" - } - } - ], - "cur": [ - "USD" - ], - "source": { - "tid": "someTid" - }, - "site": { - "domain": "www.example.com", - "ext": { - "amp": 0 - }, - "page": "http://www.example.com", - "publisher": { - "domain": "example.com", - "id": "2001" - } - }, - "user": { - "data": [ - { - "id": "generic", - "segment": [ - { - "id": "2222" - }, - { - "id": "3333" - } - ] - }, - { - "id": "bluekai", - "segment": [ - { - "id": "5555" - }, - { - "id": "6666" - } - ] - } - ], - "ext": { - "consent": "CPBCa-mPBCa-mAAAAAENA0CAAEAAAAAAACiQAaQAwAAgAgABoAAAAAA", - "fcapids": [ - "fcapId3" - ], - "time": { - "userdow": "${json-unit.any-number}", - "userhour": "${json-unit.any-number}" - } - } - }, - "device": { - "ua": "userAgent", - "ip": "185.199.110.0" - }, - "regs": { - "ext": { - "gdpr": 0 - } - }, - "at": 1, - "tmax": "${json-unit.any-number}", - "ext": { - "prebid": { - "debug": 1, - "trace": "verbose", - "targeting": { - "includebidderkeys": true, - "includewinners": true, - "pricegranularity": { - "precision": 2, - "ranges": [ - { - "increment": 0.1, - "max": 20 - } - ] - } - }, - "cache": { - "bids": {}, - "vastxml": { - "ttlseconds": 120 - } - }, - "auctiontimestamp": 1000, - "channel": { - "name": "web" - }, - "server": { - "datacenter": "local", - "endpoint": "/openrtb2/auction", - "externalurl": "http://localhost:8080", - "gvlid": 1 - } - } - } -} diff --git a/src/test/resources/org/prebid/server/it/deals/test-generic-bid-response.json b/src/test/resources/org/prebid/server/it/deals/test-generic-bid-response.json deleted file mode 100644 index 95a6159efab..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/test-generic-bid-response.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "id": "bidResponseId", - "seatbid": [ - { - "seat": "seatId1", - "bid": [ - { - "id": "bidId1", - "impid": "impId1", - "dealid": "dealId1", - "price": 8.43, - "adm": "", - "crid": "crid1", - "w": 300, - "h": 250 - }, - { - "id": "bidId2", - "impid": "impId2", - "dealid": "dealId2", - "price": 8.43, - "adm": "", - "crid": "crid2", - "w": 320, - "h": 320 - }, - { - "id": "bidId4", - "impid": "impId4", - "dealid": "dealId3", - "price": 8.43, - "adm": "", - "crid": "crid1", - "w": 300, - "h": 250 - } - ] - } - ] -} diff --git a/src/test/resources/org/prebid/server/it/deals/test-planner-plan-response.json b/src/test/resources/org/prebid/server/it/deals/test-planner-plan-response.json deleted file mode 100644 index 462a5d6f1f2..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/test-planner-plan-response.json +++ /dev/null @@ -1,347 +0,0 @@ -[ - { - "lineItemId": "lineItem1", - "extLineItemId": "extLineItem1", - "dealId": "dealId1", - "status": "active", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "accountId": "2001", - "source": "generic", - "price": { - "cpm": 5.60, - "currency": "USD" - }, - "relativePriority": 3, - "startTimeStamp": "{{ lineItem.startTime }}", - "endTimeStamp": "{{ lineItem.endTime }}", - "updatedTimeStamp": "{{ now }}", - "targeting": { - "$and": [ - { - "adunit.size": { - "$intersects": [ - { - "w": 300, - "h": 250 - } - ] - } - }, - { - "adunit.mediatype": { - "$intersects": [ - "banner" - ] - } - } - ] - }, - "frequencyCaps": [ - { - "fcapId": "fcapId1", - "count": 3, - "periods": 7, - "periodType": "day" - } - ], - "deliverySchedules": [ - { - "planId": "1", - "updatedTimeStamp": "{{ now }}", - "startTimeStamp": "{{ plan.startTime }}", - "endTimeStamp": "{{ plan.endTime }}", - "tokens": [ - { - "class": 1, - "total": 5000 - }, - { - "class": 2, - "total": 125 - } - ] - } - ] - }, - { - "lineItemId": "lineItem2", - "dealId": "dealId2", - "extLineItemId": "extLineItem2", - "status": "active", - "sizes": [ - { - "w": 320, - "h": 320 - } - ], - "accountId": "2001", - "source": "generic", - "price": { - "cpm": 5.60, - "currency": "USD" - }, - "relativePriority": 3, - "startTimeStamp": "{{ lineItem.startTime }}", - "endTimeStamp": "{{ lineItem.endTime }}", - "updatedTimeStamp": "{{ now }}", - "targeting": { - "$and": [ - { - "adunit.size": { - "$intersects": [ - { - "w": 320, - "h": 320 - } - ] - } - }, - { - "adunit.mediatype": { - "$intersects": [ - "banner" - ] - } - } - ] - }, - "frequencyCaps": [ - { - "fcapId": "fcapId2", - "count": 3, - "periods": 7, - "periodType": "day" - } - ], - "deliverySchedules": [ - { - "planId": "1", - "updatedTimeStamp": "{{ now }}", - "startTimeStamp": "{{ plan.startTime }}", - "endTimeStamp": "{{ plan.endTime }}", - "tokens": [ - { - "class": 1, - "total": 5000 - }, - { - "class": 2, - "total": 125 - } - ] - } - ] - }, - { - "lineItemId": "lineItem3", - "extLineItemId": "extLineItem3", - "dealId": "dealId3", - "status": "active", - "sizes": [ - { - "w": 300, - "h": 250 - } - ], - "accountId": "2001", - "source": "generic", - "price": { - "cpm": 4.60, - "currency": "USD" - }, - "relativePriority": 3, - "startTimeStamp": "{{ lineItem.startTime }}", - "endTimeStamp": "{{ lineItem.endTime }}", - "updatedTimeStamp": "{{ now }}", - "targeting": { - "$and": [ - { - "adunit.size": { - "$intersects": [ - { - "w": 300, - "h": 250 - } - ] - } - }, - { - "adunit.mediatype": { - "$intersects": [ - "banner" - ] - } - } - ] - }, - "frequencyCaps": [ - { - "fcapId": "fcapId1", - "count": 3, - "periods": 7, - "periodType": "day" - } - ], - "deliverySchedules": [ - { - "planId": "1", - "updatedTimeStamp": "{{ now }}", - "startTimeStamp": "{{ plan.startTime }}", - "endTimeStamp": "{{ plan.endTime }}", - "tokens": [ - { - "class": 1, - "total": 5000 - }, - { - "class": 2, - "total": 125 - } - ] - } - ] - }, - { - "lineItemId": "lineItem4", - "extLineItemId": "extLineItem4", - "dealId": "dealId4", - "status": "active", - "sizes": [ - { - "w": 300, - "h": 600 - } - ], - "accountId": "2001", - "source": "generic", - "price": { - "cpm": 5.60, - "currency": "USD" - }, - "relativePriority": 3, - "startTimeStamp": "{{ lineItem.startTime }}", - "endTimeStamp": "{{ lineItem.endTime }}", - "updatedTimeStamp": "{{ now }}", - "targeting": { - "$and": [ - { - "adunit.size": { - "$intersects": [ - { - "w": 300, - "h": 600 - } - ] - } - }, - { - "adunit.mediatype": { - "$intersects": [ - "banner" - ] - } - } - ] - }, - "frequencyCaps": [ - { - "fcapId": "fcapId3", - "count": 10, - "periods": 7, - "periodType": "day" - } - ], - "deliverySchedules": [ - { - "planId": "1", - "updatedTimeStamp": "{{ now }}", - "startTimeStamp": "{{ plan.startTime }}", - "endTimeStamp": "{{ plan.endTime }}", - "tokens": [ - { - "class": 1, - "total": 5000 - }, - { - "class": 2, - "total": 125 - } - ] - } - ] - }, - { - "lineItemId": "lineItem5", - "extLineItemId": "extLineItem5", - "dealId": "dealId5", - "status": "active", - "sizes": [ - { - "w": 300, - "h": 600 - } - ], - "accountId": "2002", - "source": "generic", - "price": { - "cpm": 5.60, - "currency": "USD" - }, - "relativePriority": 3, - "startTimeStamp": "{{ lineItem.startTime }}", - "endTimeStamp": "{{ lineItem.endTime }}", - "updatedTimeStamp": "{{ now }}", - "targeting": { - "$and": [ - { - "adunit.size": { - "$intersects": [ - { - "w": 300, - "h": 600 - } - ] - } - }, - { - "adunit.mediatype": { - "$intersects": [ - "banner" - ] - } - } - ] - }, - "frequencyCaps": [ - { - "fcapId": "fcapId5", - "count": 10, - "periods": 7, - "periodType": "day" - } - ], - "deliverySchedules": [ - { - "planId": "1", - "updatedTimeStamp": "{{ now }}", - "startTimeStamp": "{{ plan.startTime }}", - "endTimeStamp": "{{ plan.endTime }}", - "tokens": [ - { - "class": 1, - "total": 5000 - }, - { - "class": 2, - "total": 125 - } - ] - } - ] - } -] diff --git a/src/test/resources/org/prebid/server/it/deals/test-planner-register-request.json b/src/test/resources/org/prebid/server/it/deals/test-planner-register-request.json deleted file mode 100644 index ca88dd51e89..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/test-planner-register-request.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "healthIndex": 1, - "status": { - "dealsStatus": { - "instanceId": "localhost", - "vendor": "local", - "region": "local", - "clientAuctions": 0, - "lineItemStatus": [] - } - }, - "hostInstanceId": "localhost", - "region": "local", - "vendor": "local" -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/it/deals/test-planner-register-response.json b/src/test/resources/org/prebid/server/it/deals/test-planner-register-response.json deleted file mode 100644 index 456c5fa32f7..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/test-planner-register-response.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "tracer": { - "cmd": "start", - "raw": "true", - "durationInSeconds": "300", - "filters": { - "accountId": "1001", - "bidderCode": "pgRubicon", - "lineItemId": "642534" - } - } -} diff --git a/src/test/resources/org/prebid/server/it/deals/test-user-data-details-generic-response.json b/src/test/resources/org/prebid/server/it/deals/test-user-data-details-generic-response.json deleted file mode 100644 index ef7c135d760..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/test-user-data-details-generic-response.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "user": { - "data": [ - { - "id": "1111", - "name": "generic", - "segment": [ - { - "id": "2222" - }, - { - "id": "3333" - } - ] - }, - { - "id": "4444", - "name": "bluekai", - "segment": [ - { - "id": "5555" - }, - { - "id": "6666" - } - ] - } - ], - "ext": { - "fcapIds": [ - "fcapId3" - ] - } - } -} diff --git a/src/test/resources/org/prebid/server/it/deals/test-user-data-details-request.json b/src/test/resources/org/prebid/server/it/deals/test-user-data-details-request.json deleted file mode 100644 index 57e3a12ceec..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/test-user-data-details-request.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "ids": [ - { - "type": "khaos", - "id": "J5VLCWQP-26-CWFT" - } - ] -} \ No newline at end of file diff --git a/src/test/resources/org/prebid/server/it/deals/test-user-data-details-rubicon-response.json b/src/test/resources/org/prebid/server/it/deals/test-user-data-details-rubicon-response.json deleted file mode 100644 index 098785643ee..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/test-user-data-details-rubicon-response.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "user": { - "data": [ - { - "id": "1111", - "name": "rubicon", - "segment": [ - { - "id": "2222" - }, - { - "id": "3333" - } - ] - }, - { - "id": "4444", - "name": "bluekai", - "segment": [ - { - "id": "5555" - }, - { - "id": "6666" - } - ] - } - ], - "ext": { - "fcapIds": [ - "fcapId3" - ] - } - } -} diff --git a/src/test/resources/org/prebid/server/it/deals/test-user-data-win-event-request.json b/src/test/resources/org/prebid/server/it/deals/test-user-data-win-event-request.json deleted file mode 100644 index 71f6551cc46..00000000000 --- a/src/test/resources/org/prebid/server/it/deals/test-user-data-win-event-request.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "bidderCode": "generic", - "bidId": "bidId", - "lineItemId": "lineItem1", - "region" : "local", - "userIds": [ - { - "type": "khaos", - "id": "J5VLCWQP-26-CWFT" - } - ], - "frequencyCaps": [ - { - "fcapId": "fcapId1", - "count": 3, - "periods": 7, - "periodType": "day" - } - ] -} diff --git a/src/test/resources/org/prebid/server/it/test-application.properties b/src/test/resources/org/prebid/server/it/test-application.properties index 2bef5e71ca2..90a4c6fc75d 100644 --- a/src/test/resources/org/prebid/server/it/test-application.properties +++ b/src/test/resources/org/prebid/server/it/test-application.properties @@ -499,8 +499,6 @@ admin-endpoints.logging-changelevel.protected=false admin-endpoints.tracelog.enabled=true admin-endpoints.tracelog.protected=false admin-endpoints.e2eadmin.enabled=false -admin-endpoints.lineitem-status.enabled=false -admin-endpoints.deals-status.enabled=false status-response=ok analytics.log.enabled=true gdpr.host-vendor-id=1