diff --git a/.gitignore b/.gitignore index bb5e892b7..cd9787469 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,8 @@ allure-results/ log4j.log src/test/resources/test.properties src/test/java/com/kaltura/client/test/tests/Sandbox.java +src/test/resources/db_utils_list.txt +src/test/resources/utils_list.txt +src/test/resources/testXml.xml +logs/ +surefire/ diff --git a/pom.xml b/pom.xml index 7d59c6d0b..ebbdf4a73 100644 --- a/pom.xml +++ b/pom.xml @@ -15,7 +15,7 @@ jar - 1.8 + 1.10 1.8.10 @@ -134,7 +134,14 @@ - + + com.sun.mail + javax.mail + 1.6.1 + test + + + junit junit 4.12 @@ -144,7 +151,7 @@ org.testng testng - 6.14.2 + 6.14.3 test @@ -165,7 +172,7 @@ org.awaitility awaitility - 3.1.0 + 3.1.2 test @@ -201,13 +208,40 @@ com.fasterxml.jackson.core jackson-databind 2.9.5 + test + + + + com.google.guava + guava + 26.0-jre + test + + + + commons-dbutils + commons-dbutils + 1.7 + test + + + + org.jsoup + jsoup + 1.11.3 + + + + org.projectlombok + lombok + 1.18.0 + provided - @@ -221,12 +255,14 @@ true + + org.apache.maven.plugins maven-compiler-plugin - 2.3.2 + 3.8.0 - 1.8 - 1.8 + 1.10 + 1.10 @@ -240,11 +276,12 @@ usedefaultlisteners - false + true src\test\resources\testng.xml + ${project.basedir}/target false @@ -318,7 +355,6 @@ - io.qameta.allure allure-maven @@ -328,7 +364,6 @@ - diff --git a/src/main/java/com/kaltura/client/enums/WatchStatus.java b/src/main/java/com/kaltura/client/enums/WatchStatus.java index e4fee43c9..3d465b1d3 100644 --- a/src/main/java/com/kaltura/client/enums/WatchStatus.java +++ b/src/main/java/com/kaltura/client/enums/WatchStatus.java @@ -54,8 +54,7 @@ public void setValue(String value) { } public static WatchStatus get(String value) { - if(value == null) - { + if(value == null) { return null; } diff --git a/src/main/java/com/kaltura/client/types/AssetStructMeta.java b/src/main/java/com/kaltura/client/types/AssetStructMeta.java index a31c95be2..8d9028d53 100644 --- a/src/main/java/com/kaltura/client/types/AssetStructMeta.java +++ b/src/main/java/com/kaltura/client/types/AssetStructMeta.java @@ -55,7 +55,6 @@ public interface Tokenizer extends ObjectBase.Tokenizer { String defaultIngestValue(); String createDate(); String updateDate(); - String isInherited(); } /** @@ -88,10 +87,6 @@ public interface Tokenizer extends ObjectBase.Tokenizer { as epoch. */ private Long updateDate; - /** - * Is inherited - */ - private Boolean isInherited; // assetStructId: public Long getAssetStructId(){ @@ -145,18 +140,6 @@ public Long getCreateDate(){ public Long getUpdateDate(){ return this.updateDate; } - // isInherited: - public Boolean getIsInherited(){ - return this.isInherited; - } - public void setIsInherited(Boolean isInherited){ - this.isInherited = isInherited; - } - - public void isInherited(String multirequestToken){ - setToken("isInherited", multirequestToken); - } - public AssetStructMeta() { super(); @@ -175,7 +158,6 @@ public AssetStructMeta(JsonObject jsonObject) throws APIException { defaultIngestValue = GsonParser.parseString(jsonObject.get("defaultIngestValue")); createDate = GsonParser.parseLong(jsonObject.get("createDate")); updateDate = GsonParser.parseLong(jsonObject.get("updateDate")); - isInherited = GsonParser.parseBoolean(jsonObject.get("isInherited")); } @@ -185,7 +167,6 @@ public Params toParams() { kparams.add("ingestReferencePath", this.ingestReferencePath); kparams.add("protectFromIngest", this.protectFromIngest); kparams.add("defaultIngestValue", this.defaultIngestValue); - kparams.add("isInherited", this.isInherited); return kparams; } diff --git a/src/main/java/com/kaltura/client/types/BaseSearchAssetFilter.java b/src/main/java/com/kaltura/client/types/BaseSearchAssetFilter.java index ded0ce441..50af14695 100644 --- a/src/main/java/com/kaltura/client/types/BaseSearchAssetFilter.java +++ b/src/main/java/com/kaltura/client/types/BaseSearchAssetFilter.java @@ -74,7 +74,7 @@ only assets that the user defined as his interests (by tags and metas) will (not), ~ (like), !~, ^ (any word starts with), ^= (phrase starts with), + (exists), !+ (not exists). Logical conjunction: and, or. Search values are limited to 20 characters each for the next operators: ~, - !~, ^, ^= (maximum length of entire filter is 4096 characters) + !~, ^, ^= (maximum length of entire filter is 2048 characters) */ private String kSql; /** diff --git a/src/main/java/com/kaltura/client/types/ChannelFilter.java b/src/main/java/com/kaltura/client/types/ChannelFilter.java index e70d5a88f..b6726b58d 100644 --- a/src/main/java/com/kaltura/client/types/ChannelFilter.java +++ b/src/main/java/com/kaltura/client/types/ChannelFilter.java @@ -79,7 +79,7 @@ only assets that the user defined as his interests (by tags and metas) will (not), ~ (like), !~, ^ (any word starts with), ^= (phrase starts with), + (exists), !+ (not exists). Logical conjunction: and, or. Search values are limited to 20 characters each for the next operators: ~, - !~, ^, ^= (maximum length of entire filter is 4096 characters) + !~, ^, ^= (maximum length of entire filter is 2048 characters) */ private String kSql; /** diff --git a/src/main/java/com/kaltura/client/types/DynamicChannel.java b/src/main/java/com/kaltura/client/types/DynamicChannel.java index b1acd9906..27d5044bb 100644 --- a/src/main/java/com/kaltura/client/types/DynamicChannel.java +++ b/src/main/java/com/kaltura/client/types/DynamicChannel.java @@ -75,7 +75,7 @@ only assets that the user defined as his interests (by tags and metas) will =, != (not), ~ (like), !~, ^ (any word starts with), ^= (phrase starts with), + (exists), !+ (not exists). Logical conjunction: and, or. Search values are limited to 20 characters each. (maximum length - of entire filter is 4096 characters) + of entire filter is 2048 characters) */ private String kSql; /** diff --git a/src/main/java/com/kaltura/client/types/Household.java b/src/main/java/com/kaltura/client/types/Household.java index 0eb47f43b..65a904fb2 100644 --- a/src/main/java/com/kaltura/client/types/Household.java +++ b/src/main/java/com/kaltura/client/types/Household.java @@ -31,7 +31,6 @@ import com.kaltura.client.Params; import com.kaltura.client.enums.HouseholdRestriction; import com.kaltura.client.enums.HouseholdState; -import com.kaltura.client.types.ObjectBase; import com.kaltura.client.utils.GsonParser; import com.kaltura.client.utils.request.MultiRequestBuilder; @@ -238,7 +237,6 @@ public Household(JsonObject jsonObject) throws APIException { frequencyNextUserAction = GsonParser.parseLong(jsonObject.get("frequencyNextUserAction")); restriction = HouseholdRestriction.get(GsonParser.parseString(jsonObject.get("restriction"))); roleId = GsonParser.parseInt(jsonObject.get("roleId")); - } public Params toParams() { diff --git a/src/main/java/com/kaltura/client/types/PersonalList.java b/src/main/java/com/kaltura/client/types/PersonalList.java index 1baf1b2ef..a2718fcb5 100644 --- a/src/main/java/com/kaltura/client/types/PersonalList.java +++ b/src/main/java/com/kaltura/client/types/PersonalList.java @@ -88,7 +88,7 @@ only assets that the user defined as his interests (by tags and metas) will (not), ~ (like), !~, ^ (any word starts with), ^= (phrase starts with), + (exists), !+ (not exists). Logical conjunction: and, or. Search values are limited to 20 characters each for the next operators: ~, - !~, ^, ^= (maximum length of entire filter is 4096 characters) + !~, ^, ^= (maximum length of entire filter is 2048 characters) */ private String ksql; /** diff --git a/src/test/java/com/kaltura/client/test/CancelTest.java b/src/test/java/com/kaltura/client/test/CancelTest.java deleted file mode 100644 index 26d8b5ff5..000000000 --- a/src/test/java/com/kaltura/client/test/CancelTest.java +++ /dev/null @@ -1,44 +0,0 @@ - -package com.kaltura.client.test; - -import com.kaltura.client.APIOkRequestsExecutor; -import com.kaltura.client.services.FavoriteService; -import com.kaltura.client.services.FavoriteService.ListFavoriteBuilder; -import com.kaltura.client.types.Favorite; -import com.kaltura.client.types.ListResponse; -import com.kaltura.client.utils.response.OnCompletion; -import com.kaltura.client.utils.response.base.Response; - -import org.awaitility.Awaitility; -import org.awaitility.core.ConditionTimeoutException; -import org.junit.Assert; -import org.junit.Test; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -public class CancelTest extends TestCommon { - - AtomicBoolean beenHere = new AtomicBoolean(false); - - @Test(timeout = 3000, expected = ConditionTimeoutException.class) - public void testCancel() throws InterruptedException, ExecutionException { - logger.info("testCancelRequest"); - - ListFavoriteBuilder requestBuilder = FavoriteService.list(); - APIOkRequestsExecutor actionsQueue = APIOkRequestsExecutor.getExecutor(); - String reqId = actionsQueue.queue(requestBuilder.setCompletion(new OnCompletion>>() { - @Override - public void onComplete(Response> result) { - beenHere.set(true); - } - }).build(client)); - - actionsQueue.cancelRequest(reqId); - - Awaitility.await().timeout(2, TimeUnit.SECONDS); - - Assert.assertFalse(beenHere.get()); - } -} diff --git a/src/test/java/com/kaltura/client/test/IngestConstants.java b/src/test/java/com/kaltura/client/test/IngestConstants.java deleted file mode 100644 index cc72c7955..000000000 --- a/src/test/java/com/kaltura/client/test/IngestConstants.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.kaltura.client.test; - -public class IngestConstants { - - public static final String INGEST_ACTION_INSERT = "insert"; - public static final String INGEST_ACTION_DELETE = "delete"; - - public static final Long MAX_RANDOM_GENERATED_VALUE_4_INGEST = 9999999999L; - public static final String INGEST_VOD_DEFAULT_THUMB = "http://opengameart.org/sites/default/files/styles/thumbnail/public/pictures/picture-1760-1321510314.png"; - - // currency - public static final String CURRENCY_EUR = "EUR"; - - // life cycles periods - public static final String FIVE_MINUTES_PERIOD = "5 Minutes"; - - // media types // TODO: ask if these types (from TVM edit VOD page) are default for all accounts - public static final String MOVIE_MEDIA_TYPE = "Movie"; - public static final String EPISODE_MEDIA_TYPE = "Episode"; - public static final String LINEAR_MEDIA_TYPE = "Linear"; - - // PG adapter data - /*public static final String PG_DEFAULT_ADAPTER_URL = "http://172.31.6.89:90/PGAdapter/Service.svc"; - public static final String PG_DEFAULT_RENEW_URL = PG_DEFAULT_ADAPTER_URL + "?StateCode=0"; - public static final String PG_DEFAULT_SHARED_SECRET = "123456"; - public static final int PG_DEFAULT_PENDING_INTERVAL = 0; - public static final int PG_DEFAULT_PENDING_RETRIES = 0; - public static final int PG_DEFAULT_RENEW_INTERVAL_MINUTES = 15; - public static final int PG_DEFAULT_RENEW_START_MINUTES =-5; - public static final String PG_DEFAULT_PG_SETTINGS = "{}";*/ -} diff --git a/src/test/java/com/kaltura/client/test/KalturaTestSuite.java b/src/test/java/com/kaltura/client/test/KalturaTestSuite.java deleted file mode 100644 index 3dacf4024..000000000 --- a/src/test/java/com/kaltura/client/test/KalturaTestSuite.java +++ /dev/null @@ -1,44 +0,0 @@ -// =================================================================================================== -// _ __ _ _ -// | |/ /__ _| | |_ _ _ _ _ __ _ -// | ' . -// -// @ignore -// =================================================================================================== -package com.kaltura.client.test; - -import junit.framework.Test; -import junit.framework.TestSuite; - -public class KalturaTestSuite extends TestSuite -{ - public static Test suite() - { - TestSuite suite = new TestSuite(); - suite.addTestSuite(CancelTest.class); - suite.addTestSuite(SingleRequestTest.class); - suite.addTestSuite(MultiRequestTest.class); - - return suite; - } -} diff --git a/src/test/java/com/kaltura/client/test/MultiRequestTest.java b/src/test/java/com/kaltura/client/test/MultiRequestTest.java deleted file mode 100644 index 433becacc..000000000 --- a/src/test/java/com/kaltura/client/test/MultiRequestTest.java +++ /dev/null @@ -1,147 +0,0 @@ -package com.kaltura.client.test; - -import com.kaltura.client.APIOkRequestsExecutor; -import com.kaltura.client.enums.AssetOrderBy; -import com.kaltura.client.enums.AssetReferenceType; -import com.kaltura.client.services.AssetService; -import com.kaltura.client.services.AssetService.GetAssetBuilder; -import com.kaltura.client.services.OttUserService; -import com.kaltura.client.services.OttUserService.GetOttUserBuilder; -import com.kaltura.client.services.OttUserService.LoginOttUserBuilder; -import com.kaltura.client.types.Asset; -import com.kaltura.client.types.FilterPager; -import com.kaltura.client.types.ListResponse; -import com.kaltura.client.types.LoginResponse; -import com.kaltura.client.types.OTTUser; -import com.kaltura.client.types.SearchAssetFilter; -import com.kaltura.client.utils.request.MultiRequestBuilder; -import com.kaltura.client.utils.response.OnCompletion; -import com.kaltura.client.utils.response.base.ApiCompletion; -import com.kaltura.client.utils.response.base.Response; - -import org.awaitility.Awaitility; -import org.junit.Test; - -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Created by tehilarozin on 11/09/2016. - */ -public class MultiRequestTest extends TestCommon { - - private AtomicBoolean done; - - public void setUp() throws Exception { - super.setUp(); - done = new AtomicBoolean(false); - } - - @Test - public void testMultiRequest() throws InterruptedException, ExecutionException { - logger.info("testMultiRequest\n"); - - //final CountDownLatch doneSignal = new CountDownLatch(1); - - final AtomicInteger counter = new AtomicInteger(0); - //DataFactory.UserLogin userLogin = DataFactory.getUser(); - - LoginOttUserBuilder ottUserLoginRequestBuilder = OttUserService.login(testConfig.getPartnerId(), - testConfig.getUserName(), testConfig.getUserPassword()) - .setCompletion(new ApiCompletion() { - - @Override - public void onComplete(Response result) { - - assertNotNull(result); - assertNull(result.error); - counter.incrementAndGet(); - } - }); - - GetAssetBuilder assetGetRequestBuilder = AssetService.get(testConfig.getMediaId(), AssetReferenceType.MEDIA) - .setCompletion(new ApiCompletion() { - - @Override - public void onComplete(Response result) { - assertNotNull(result); - assertNull(result.error); - counter.incrementAndGet(); - } - }); - - GetOttUserBuilder ottUserGetRequestBuilder = OttUserService.get() - .setCompletion(new ApiCompletion() { - - @Override - public void onComplete(Response result) { - - assertNotNull(result); - assertNull(result.error); - counter.incrementAndGet(); - } - }); - - MultiRequestBuilder requestBuilder = new MultiRequestBuilder(ottUserLoginRequestBuilder, assetGetRequestBuilder, ottUserGetRequestBuilder); - requestBuilder.link(ottUserLoginRequestBuilder, assetGetRequestBuilder, "loginSession.ks", "ks"); - requestBuilder.link(ottUserLoginRequestBuilder, ottUserGetRequestBuilder, "loginSession.ks", "ks"); - - requestBuilder.setCompletion(new ApiCompletion>() { - - @Override - public void onComplete(Response> result) { - assertNotNull(result); - assertNull(result.error); - assertEquals(3, counter.get()); - assertEquals(3, result.results.size()); - - done.set(true); - - } - }); - APIOkRequestsExecutor.getExecutor().queue(requestBuilder.build(client)); - Awaitility.await().atMost(30, TimeUnit.SECONDS).untilTrue(done); - - assertTrue(done.get()); - } - - @Test - public void testListResponse(){ - SearchAssetFilter searchAssetFilter = new SearchAssetFilter(); - searchAssetFilter.setOrderBy(AssetOrderBy.RELEVANCY_DESC.name()); - searchAssetFilter.setTypeIn("420, 423, 421, 0, 422"); - - FilterPager filterPager = new FilterPager(); - filterPager.setPageSize(10); - filterPager.setPageIndex(1); - final ListResponse assets = new ListResponse<>(); - - MultiRequestBuilder multiRequestBuilder = OttUserService.login(testConfig.getPartnerId(), - testConfig.getUserName(), testConfig.getUserPassword()) - .add(AssetService.list(searchAssetFilter, filterPager)) - .link(0, 1, "loginSession.ks", "ks") - .setCompletion(new OnCompletion>>() { - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public void onComplete(Response> result) { - try { - assets.setObjects(((ListResponse)result.results.get(1)).getObjects()); - } catch (Exception e) { - e.printStackTrace(); - } - done.set(true); - } - }); - - APIOkRequestsExecutor.getExecutor().queue(multiRequestBuilder.build(client)); - - Awaitility.await().atMost(30, TimeUnit.SECONDS).untilTrue(done); - - assertTrue(done.get()); - assertFalse(assets.getObjects().isEmpty()); - } - -} diff --git a/src/test/java/com/kaltura/client/test/Properties.java b/src/test/java/com/kaltura/client/test/Properties.java index baa2f66e7..14e35439b 100644 --- a/src/test/java/com/kaltura/client/test/Properties.java +++ b/src/test/java/com/kaltura/client/test/Properties.java @@ -19,6 +19,8 @@ public class Properties { // Request properties public static final String PARTNER_ID = "partner_id"; + public static final String OPC_PARTNER_ID = "opc_partner_id"; + public static final String DEFAULT_TIMEOUT_IN_SEC = "default_timeout_in_sec"; // global users public static final String DEFAULT_USER_PASSWORD = "default_user_password"; @@ -27,22 +29,47 @@ public class Properties { public static final String WEB_FILE_TYPE = "web_file_type"; public static final String MOBILE_FILE_TYPE = "mobile_file_type"; - // media types ids - public static final String MOVIE_MEDIA_TYPE_ID = "movie_media_type_id"; - public static final String EPISODE_MEDIA_TYPE_ID = "episode_media_type_id"; - - // ingest - public static final String INGEST_USER_USERNAME = "ingest_user_username"; - public static final String INGEST_USER_PASSWORD = "ingest_user_password"; + // channels + public static final String DEFAULT_CHANNEL = "default_channel"; + // automatic channel with "Cut Tags Type"="Or", Tags "Series name"="Shay_Series;" and "Free"="Shay_Series;" - public static final String INGEST_BUSINESS_MODULE_USER_USERNAME = "ingest_business_module_user_username"; - public static final String INGEST_BUSINESS_MODULE_USER_PASSWORD = "ingest_business_module_user_password"; + // collections + public static final String DEFAULT_COLLECTION = "default_collection"; - // channels - public static final String DEFAULT_CHANNEL = "default_channel"; // automatic channel with "Cut Tags Type"="Or", Tags "Series name"="Shay_Series;" and "Free"="Shay_Series;" + // discount code id + public static final String DISCOUNT_CODE_ID = "discount_code_id"; - // price codes + // price codes values public static final String PRICE_CODE_AMOUNT = "price_code_amount"; // 4.99 + public static final String COMMON_PRICE_CODE_AMOUNT = "5"; // TODO: should we document it as requirement? + + // maximum objects at list response for validating JSON schema + public static final int MAX_OBJECTS_AT_LIST_RESPONSE = 20; + + // paymentGateway adapter url + public static final String PAYMENT_GATEWAY_ADAPTER_URL = "http://172.31.6.89:90/PGAdapter/Service.svc"; + + // price plans + // INGEST doesn't allow create PP with multi-currencies + // TODO: should we document it as requirement? price plan having few locales (EUR + few others) with different prices + // should we leave there name or id if we do use name in ingest + public static final String PRICE_PLAN_WITH_MULTI_CURRENCIES = "lior's PriceCode price plan"; + // TODO: should we document it as requirement? price plan having few locales (USD + few others) with different prices and discount for subscriptions 50% + // should we leave there name or id if we do use name in ingest + public static final String PRICE_PLAN_WITH_MULTI_CURRENCIES_AND_DISCOUNT_PERCENTS = "shmulik_multi_currency_with_discount"; + // TODO: should we document it as requirement? price plan having few locales (USD + few others) with different prices and fixed discount for subscriptions 1 + // should we leave there name or id if we do use name in ingest + public static final String PRICE_PLAN_WITH_MULTI_CURRENCIES_AND_DISCOUNT_FIXED = "shmulik_multi_currency_with_discount (fixed amount)"; + + // PPVs + // Ingest doesn't allow create PP with multi currencies + // TODO: should we document it as requirement? + public static final String PPV_WITH_MULTI_CURRENCIES_AND_DISCOUNT_PERCENTS = "multi price code with 50% discount"; + // TODO: should we document it as requirement? + public static final String PPV_WITH_MULTI_CURRENCIES_AND_FIXED_DISCOUNT = "multi price code with fixed amount discount"; + + //cycles + public static final int CYCLE_1_DAY = 1440; // in minutes // usage modules public static final String DEFAULT_USAGE_MODULE_4_INGEST_PPV = "default_usage_module_4_ingest_ppv"; // module has 10 Minutes life cycles, 0 maximum views @@ -51,16 +78,35 @@ public class Properties { // product codes public static final String DEFAULT_PRODUCT_CODE = "default_product_code"; + // payment gateway external id + public static final String PAYMENT_GATEWAY_EXTERNAL_ID = "payment_gateway_external_id"; + + // performance report + public static final String LOGS_BASE_URL = "logs_base_url"; + public static final String LOGS_DIR = "logs_dir"; + public static final String REGRESSION_LOGS_FILE = "regression_logs_file"; + public static final String PERFORMANCE_REPORT_FILE = "performance_report_file"; + public static final String WRITE_REGRESSION_LOGS = "write_regression_logs"; + public static final String MAX_CODE_PERCENTAGE = "max_code_percentage"; + public static final String MAX_EXECUTION_TIME_IN_SEC = "max_execution_time_in_sec"; + + // permissions management + public static final String PERMISSION_LOG_FILE = "permission_log_file"; + public static final String PERMISSION_CONSOLE_UTIL_FILE = "permission_console_util_file"; + public static String getProperty(String propertyKey) { if (resourceBundle == null) { resourceBundle = ResourceBundle.getBundle("test"); } return resourceBundle.getString(propertyKey); } + + // playback context options + public static final String MEDIA_PROTOCOL = "http"; + public static final String STREAMER_TYPE = "applehttp"; } // todo global list // TODO: 3/12/2018 open conference page with all the documentation problems // TODO: 12/MAR/2018 decide if we need that autoskip logic for tests with known opened bugs: // https://dzone.com/articles/how-to-automatically-skip-tests-based-on-defects-s -// TODO: 3/19/2018 update readme file with project structure and list of services diff --git a/src/test/java/com/kaltura/client/test/RequestsTestSuite.java b/src/test/java/com/kaltura/client/test/RequestsTestSuite.java deleted file mode 100644 index b96ea0635..000000000 --- a/src/test/java/com/kaltura/client/test/RequestsTestSuite.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.kaltura.client.test; -// =================================================================================================== -// _ __ _ _ -// | |/ /__ _| | |_ _ _ _ _ __ _ -// | ' . -// -// @ignore -// =================================================================================================== - -import junit.framework.Test; -import junit.framework.TestSuite; - -public class RequestsTestSuite extends TestSuite -{ - public static Test suite() - { - TestSuite suite = new TestSuite(); - suite.addTestSuite(CancelTest.class); - suite.addTestSuite(SingleRequestTest.class); - suite.addTestSuite(MultiRequestTest.class); - - return suite; - } -} diff --git a/src/test/java/com/kaltura/client/test/SingleRequestTest.java b/src/test/java/com/kaltura/client/test/SingleRequestTest.java deleted file mode 100644 index c09e8529c..000000000 --- a/src/test/java/com/kaltura/client/test/SingleRequestTest.java +++ /dev/null @@ -1,110 +0,0 @@ - -package com.kaltura.client.test; - -import com.kaltura.client.APIOkRequestsExecutor; -import com.kaltura.client.services.FavoriteService; -import com.kaltura.client.services.FavoriteService.ListFavoriteBuilder; -import com.kaltura.client.services.OttUserService; -import com.kaltura.client.services.OttUserService.GetOttUserBuilder; -import com.kaltura.client.services.OttUserService.LoginOttUserBuilder; -import com.kaltura.client.types.Favorite; -import com.kaltura.client.types.ListResponse; -import com.kaltura.client.types.LoginResponse; -import com.kaltura.client.types.OTTUser; -import com.kaltura.client.utils.response.base.ApiCompletion; -import com.kaltura.client.utils.response.base.Response; - -import org.awaitility.Awaitility; -import org.junit.Test; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Created by tehilarozin on 11/09/2016. - */ -public class SingleRequestTest extends TestCommon{ - - @Test - /** - * synced requests: activates login request and if succeeded, activating another request to fetch user data - */ - public void testRequestWithinRequest() throws InterruptedException, ExecutionException{ - logger.info("testLogin"); - - final AtomicBoolean done = new AtomicBoolean(false); - - LoginOttUserBuilder requestBuilder = OttUserService.login(testConfig.getPartnerId(), testConfig.getUserName(), testConfig.getUserPassword()) - .setCompletion(new ApiCompletion() { - - @Override - public void onComplete(Response result) { - - assertNotNull(result); - assertNull(result.error); - - client.setKs(result.results.getLoginSession().getKs()); - - OTTUser ottUser = result.results.getUser(); - logger.debug("Hello " + ottUser.getFirstName() + " " + ottUser.getLastName() + ", username: " + ottUser.getUsername() + ", "); - - logger.debug("fetching user info: "); - GetOttUserBuilder requestBuilder = OttUserService.get() - .setCompletion(new ApiCompletion() { - - @Override - public void onComplete(Response result) { - - assertNotNull(result); - assertNull(result.error); - done.set(true); - } - }); - APIOkRequestsExecutor.getExecutor().queue(requestBuilder.build(client)); - } - }); - APIOkRequestsExecutor.getExecutor().queue(requestBuilder.build(client)); - Awaitility.await().atMost(20, TimeUnit.SECONDS).untilTrue(done); - - assertTrue(done.get()); - } - - @Test - public void testList() throws InterruptedException, ExecutionException { - logger.info("testCancelRequest"); - - final AtomicBoolean done = new AtomicBoolean(false); - - LoginOttUserBuilder requestBuilder = OttUserService.login(testConfig.getPartnerId(), - testConfig.getUserName(), testConfig.getUserPassword()) - .setCompletion(new ApiCompletion() { - - @Override - public void onComplete(Response result) { - - assertNotNull(result); - assertNull(result.error); - - client.setKs(result.results.getLoginSession().getKs()); - - ListFavoriteBuilder requestBuilder = FavoriteService.list() - .setCompletion(new ApiCompletion>() { - - @Override - public void onComplete(Response> result) { - - assertNotNull(result); - assertNull(result.error); - done.set(true); - } - }); - APIOkRequestsExecutor.getExecutor().queue(requestBuilder.build(client)); - } - }); - APIOkRequestsExecutor.getExecutor().queue(requestBuilder.build(client)); - Awaitility.await().atMost(20, TimeUnit.SECONDS).untilTrue(done); - - assertTrue(done.get()); - } -} diff --git a/src/test/java/com/kaltura/client/test/TestAPIOkRequestsExecutor.java b/src/test/java/com/kaltura/client/test/TestAPIOkRequestsExecutor.java index 1c112932d..851ce5a8e 100644 --- a/src/test/java/com/kaltura/client/test/TestAPIOkRequestsExecutor.java +++ b/src/test/java/com/kaltura/client/test/TestAPIOkRequestsExecutor.java @@ -1,32 +1,54 @@ package com.kaltura.client.test; +import com.google.common.primitives.Ints; import com.kaltura.client.APIOkRequestsExecutor; import com.kaltura.client.ILogger; import com.kaltura.client.Logger; +import com.kaltura.client.types.APIException; +import com.kaltura.client.types.ListResponse; import com.kaltura.client.utils.request.RequestBuilder; import com.kaltura.client.utils.request.RequestElement; import com.kaltura.client.utils.response.base.ApiCompletion; import com.kaltura.client.utils.response.base.Response; import com.kaltura.client.utils.response.base.ResponseElement; +import org.apache.commons.io.FileUtils; +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; import java.util.concurrent.atomic.AtomicBoolean; +import static com.kaltura.client.test.Properties.*; +import static com.kaltura.client.test.tests.BaseTest.LOG_HEADERS; import static com.kaltura.client.test.tests.BaseTest.client; +import static com.kaltura.client.utils.ErrorElement.*; import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath; import static org.awaitility.Awaitility.await; import static org.hamcrest.MatcherAssert.assertThat; +//import static com.kaltura.client.test.tests.BaseTest.objectType2JsonValidationSchemaFile4Lists; + /** * @hide That class allows to validate json schemas of responses */ // public class TestAPIOkRequestsExecutor extends APIOkRequestsExecutor { - public static final String TAG = "TestAPIOkRequestsExecutor"; - private static ILogger logger = Logger.getLogger(TAG); + private static final String TAG = "TestAPIOkRequestsExecutor"; + private static ILogger logger = Logger.getLogger(TAG); private static TestAPIOkRequestsExecutor executor; + private final int[] genericErrors = { + ConnectionError.getCode(), + BadRequestError.getCode(), + GeneralError.getCode(), + NotFound.getCode(), + LoadError.getCode(), + ServiceUnavailableError.getCode(), + SessionError.getCode() + }; + private TestAPIOkRequestsExecutor() { } @@ -42,7 +64,10 @@ public static TestAPIOkRequestsExecutor getExecutor() { protected ResponseElement onGotResponse(okhttp3.Response okhttpResponse, RequestElement action) { ResponseElement responseElement = super.onGotResponse(okhttpResponse, action); // logger.debug("response body:\n" + responseElement.getResponse()); // was found in base class -// logger.debug("response headers:\n" + okhttpResponse.headers()); + + if (LOG_HEADERS) { + logger.debug("Session: " + okhttpResponse.headers().get("X-Kaltura-Session")); + } if (responseElement.isSuccess()) { Response response = action.parseResponse(responseElement); @@ -52,7 +77,27 @@ protected ResponseElement onGotResponse(okhttp3.Response okhttpResponse, Request String s2 = response.results.getClass().getSimpleName(); String s3 = ".json"; + // if returned list empty or greater than 'MAX_OBJECTS_AT_LIST_RESPONSE' skip schema validation + if (s2.equals("ListResponse")) { + com.kaltura.client.utils.response.base.Response listResponse = response; + if (listResponse.results.getTotalCount() == 0 || + listResponse.results.getTotalCount() > MAX_OBJECTS_AT_LIST_RESPONSE) { + return responseElement; + } + /* TODO: COMPLETE PART OF MAX TASK RELATED JSON VALIDATION + //choose proper json validation schema by object type from response + String objectType = getObjectType(responseElement.getResponse()); + if (StringUtils.isNotEmpty(objectType)) { + s2 = objectType2JsonValidationSchemaFile4Lists.get(objectType); + s3 = ""; + } else { + logger.error("objectType in list wasn't recognized"); + return responseElement; + }*/ + } + String schema = s1 + s2 + s3; + // TODO: COMPLETE PART OF MAX TASK RELATED JSON VALIDATION Logger.getLogger(TestAPIOkRequestsExecutor.class).debug(schema + " schema"); Logger.getLogger(TestAPIOkRequestsExecutor.class).debug(s2 + " schema"); /*SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()); Date date = new Date(); @@ -60,11 +105,36 @@ protected ResponseElement onGotResponse(okhttp3.Response okhttpResponse, Request assertThat(responseElement.getResponse(), matchesJsonSchemaInClasspath(schema)); /*date = new Date(); System.out.println("AFTER VALIDATION: " + formatter.format(date));*/ + + if ("true".equals(getProperty(WRITE_REGRESSION_LOGS))) { + String serviceMethod = action.getUrl().split("service")[1]; + String kalturaSession = okhttpResponse.headers().get("X-Kaltura-Session"); + writeLogs(serviceMethod, kalturaSession); + } } } return responseElement; } + /* TODO: COMPLETE PART OF MAX TASK RELATED JSON VALIDATION + private String getObjectType(String response) { + JsonParser jsonParser = new JsonParser(); + JsonElement objectType = jsonParser.parse(response) + .getAsJsonObject().get("result") + .getAsJsonObject().get("objectType"); + return objectType.getAsString(); + }*/ + + private void writeLogs(String serviceMethod, String kalturaSession) { + File logFile = new File(getProperty(LOGS_DIR) + getProperty(REGRESSION_LOGS_FILE)); + + try { + FileUtils.writeStringToFile(logFile, serviceMethod + ":" + kalturaSession + "\n", Charset.forName("UTF-8"), true); + } catch (IOException e) { + e.printStackTrace(); + } + } + public Response executeSync(RequestBuilder requestBuilder) { SyncExecutor syncExecutor = new SyncExecutor<>(); return syncExecutor.exec(requestBuilder); @@ -85,6 +155,15 @@ public Response exec(RequestBuilder requestBuilder) { await().untilTrue(done); done.set(false); + APIException error = response.error; + if (error != null) { + int errorCode = Integer.parseInt(error.getCode()); + if (Ints.asList(genericErrors).contains(errorCode)) { + logger.error(error.getMessage() + " : " + error.getCode()); + try { throw error; } catch (APIException e) { e.printStackTrace(); } + } + } + return response; } } diff --git a/src/test/java/com/kaltura/client/test/TestCommon.java b/src/test/java/com/kaltura/client/test/TestCommon.java deleted file mode 100644 index 292a2cdd3..000000000 --- a/src/test/java/com/kaltura/client/test/TestCommon.java +++ /dev/null @@ -1,49 +0,0 @@ - -package com.kaltura.client.test; - -import com.kaltura.client.Client; -import com.kaltura.client.Configuration; -import com.kaltura.client.ILogger; -import com.kaltura.client.Logger; - -import junit.framework.TestCase; - -public abstract class TestCommon extends TestCase { - - protected static ILogger logger = Logger.getLogger("java-test"); - - Client client; - TestConfig testConfig; - - - @SuppressWarnings("serial") - protected class CompletionException extends Exception { - - public CompletionException(String message) { - super(message); - } - - @Override - public String toString() { - return getMessage(); - } - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - /* if (logger.isEnabled()) - logger.info("Starting test: " + getClass().getName() + "." + getName());*/ - - testConfig = new TestConfig(); - - Configuration config = new Configuration(); - config.setEndpoint(testConfig.getServiceUrl()); - config.setAcceptGzipEncoding(false); - - client = new Client(config); - - } - -} diff --git a/src/test/java/com/kaltura/client/test/TestConfig.java b/src/test/java/com/kaltura/client/test/TestConfig.java deleted file mode 100644 index c488f07bd..000000000 --- a/src/test/java/com/kaltura/client/test/TestConfig.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.kaltura.client.test; -// =================================================================================================== -// _ __ _ _ -// | |/ /__ _| | |_ _ _ _ _ __ _ -// | ' . -// -// @ignore -// =================================================================================================== - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -public class TestConfig { - private static Properties properties; - - private static final String PARTNER_ID = "partnerId"; - private static final String ENDPOINT = "serviceUrl"; - private static final String USER_NAME = "userName"; - private static final String USER_PASSWORD = "userPassword"; - private static final String MEDIA_ID = "mediaId"; - - TestConfig() throws IOException{ - if(properties == null){ - InputStream inputStream = getClass().getClassLoader().getResourceAsStream("resources/ott.test.properties"); - properties = new Properties(); - properties.load(inputStream); - } - } - - int getPartnerId(){ - return Integer.parseInt(properties.getProperty(PARTNER_ID)); - } - - String getServiceUrl(){ - return properties.getProperty(ENDPOINT); - } - - String getUserName(){ - return properties.getProperty(USER_NAME); - } - - String getUserPassword(){ - return properties.getProperty(USER_PASSWORD); - } - - String getMediaId() { - return properties.getProperty(MEDIA_ID); - } -} diff --git a/src/test/java/com/kaltura/client/test/tests/BaseTest.java b/src/test/java/com/kaltura/client/test/tests/BaseTest.java index 036cc7817..923872969 100644 --- a/src/test/java/com/kaltura/client/test/tests/BaseTest.java +++ b/src/test/java/com/kaltura/client/test/tests/BaseTest.java @@ -2,103 +2,366 @@ import com.kaltura.client.Client; import com.kaltura.client.Configuration; -import com.kaltura.client.services.OttUserService; +import com.kaltura.client.Logger; +import com.kaltura.client.services.ChannelService.AddChannelBuilder; import com.kaltura.client.test.TestAPIOkRequestsExecutor; -import com.kaltura.client.test.utils.DBUtils; -import com.kaltura.client.test.utils.IngestUtils; +import com.kaltura.client.test.utils.PerformanceUtils; +import com.kaltura.client.test.utils.annotations.Shared; +import com.kaltura.client.test.utils.dbUtils.DBUtils; +import com.kaltura.client.test.utils.dbUtils.IngestFixtureData; import com.kaltura.client.types.*; +import com.kaltura.client.types.Collection; import com.kaltura.client.utils.response.base.Response; -import org.testng.annotations.BeforeSuite; - -import java.util.List; +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.ArrayUtils; +import org.testng.ITestContext; +import org.testng.annotations.*; +import org.testng.xml.XmlSuite; +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; + +import java.io.File; +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.nio.file.Files; +import java.util.*; import java.util.Optional; import java.util.concurrent.TimeUnit; +import static com.google.common.base.Verify.verify; +import static com.kaltura.client.services.ChannelService.add; +import static com.kaltura.client.services.ChannelService.get; +import static com.kaltura.client.services.OttUserService.anonymousLogin; import static com.kaltura.client.services.OttUserService.login; -import static com.kaltura.client.test.IngestConstants.CURRENCY_EUR; -import static com.kaltura.client.test.IngestConstants.FIVE_MINUTES_PERIOD; +import static com.kaltura.client.services.SubscriptionService.list; import static com.kaltura.client.test.Properties.*; -import static com.kaltura.client.test.utils.HouseholdUtils.createHousehold; -import static com.kaltura.client.test.utils.HouseholdUtils.getUsersListFromHouseHold; -import static com.kaltura.client.test.utils.OttUserUtils.getUserById; +import static com.kaltura.client.test.tests.enums.Currency.EUR; +import static com.kaltura.client.test.utils.BaseUtils.getRandomValue; +import static com.kaltura.client.test.utils.BaseUtils.setTranslationToken; +import static com.kaltura.client.test.utils.HouseholdUtils.*; +import static com.kaltura.client.test.utils.OttUserUtils.getOttUserById; +import static com.kaltura.client.test.utils.SubscriptionUtils.getAssetsListBySubscription; +import static com.kaltura.client.test.utils.ingestUtils.BaseIngestUtils.FIVE_MINUTES_PERIOD; +import static com.kaltura.client.test.utils.ingestUtils.IngestEpgUtils.EpgData; +import static com.kaltura.client.test.utils.ingestUtils.IngestEpgUtils.insertEpg; +import static com.kaltura.client.test.utils.ingestUtils.IngestMppUtils.MppData; +import static com.kaltura.client.test.utils.ingestUtils.IngestMppUtils.insertMpp; +import static com.kaltura.client.test.utils.ingestUtils.IngestPpUtils.PpData; +import static com.kaltura.client.test.utils.ingestUtils.IngestPpUtils.insertPp; +import static com.kaltura.client.test.utils.ingestUtils.IngestPpvUtils.PpvData; +import static com.kaltura.client.test.utils.ingestUtils.IngestPpvUtils.insertPpv; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.*; import static org.awaitility.Awaitility.setDefaultTimeout; public class BaseTest { + public static final boolean LOG_HEADERS = true; + public static Client client; public static Configuration config; public static TestAPIOkRequestsExecutor executor = TestAPIOkRequestsExecutor.getExecutor(); - private static Response loginResponse; + private static int numOfSuites = getNumOfSuites(); + /*================================================================================ + Shared Test Params - used as a helper common params across tests + ================================================================================*/ // shared common params public static int partnerId; + public static boolean isOpcGroup; public static String defaultUserPassword; // shared ks's - private static String administratorKs, operatorKs, managerKs, anonymousKs; + @Shared private static String administratorKs, operatorKs, managerKs, anonymousKs; + + // shared ingest users data + @Shared private static String ingestAssetUserUsername, ingestAssetUserPassword, ingestBusinessModuleUserUsername, + ingestBusinessModuleUserPassword, ingestVirtualAssetUserUsername, ingestVirtualAssetUserPassword; // shared VOD - private static MediaAsset mediaAsset; + @Shared private static MediaAsset mediaAsset; + + // shared channel name + @Shared private static String epgChannelName; + + // shared EPG program + @Shared private static Asset epgProgram; // shared files - private static MediaFile webMediaFile; - private static MediaFile mobileMediaFile; + @Shared private static MediaFile webMediaFile; + @Shared private static MediaFile mobileMediaFile; // shared MPP - private static Subscription fiveMinRenewableSubscription; + @Shared private static Subscription fiveMinRenewableSubscription; - /*================================================================================ - testing shared params list - used as a helper common params across tests + // shared ingested PP + @Shared private static PricePlan sharedCommonPricePlan; - int partnerId - String defaultUserPassword + // shared discount module for shared PP + @Shared private static DiscountModule sharedCommonDiscountModule; - String administratorKs - String operatorKs - String managerKs - String anonymousKs + // shared ingested subscription + @Shared private static Subscription sharedCommonSubscription; - MediaAsset mediaAsset + // shared collection + @Shared private static Collection sharedCommonCollection; - MediaFile webMediaFile - MediaFile mobileMediaFile + // shared ingested PPV + @Shared private static Ppv sharedCommonPpv; - Subscription fiveMinRenewableSubscription + // cycles map with values related view/full life cycles of price plans + private static Map cycles = new HashMap<>(); + { + // TODO: complete other values + cycles.put(1440, "1 Day"); + } - Household sharedHousehold - HouseholdUser sharedMasterUser - HouseholdUser sharedUser - String sharedMasterUserKs - String sharedUserKs + /*================================================================================ + Shared Test Params - end ================================================================================*/ + @Parameters({"accountType"}) + @BeforeSuite(alwaysRun = true) + public void baseTest_beforeSuite(@org.testng.annotations.Optional("opc") String accountType, ITestContext testContext) { + XmlSuite suite = testContext.getCurrentXmlTest().getSuite(); + Logger.getLogger(BaseTest.class).debug("Start suite >>> Suite: " + suite.getName()); - @BeforeSuite - public void base_test_before_suite() { // set configuration - config = new Configuration(); + config = new Configuration(); config.setEndpoint(getProperty(API_BASE_URL) + "/" + getProperty(API_VERSION)); config.setAcceptGzipEncoding(false); + config.setReadTimeout(Integer.valueOf(getProperty(DEFAULT_TIMEOUT_IN_SEC))*1000); // set client client = new Client(config); // set default awaitility timeout - setDefaultTimeout(30, TimeUnit.SECONDS); + setDefaultTimeout(Long.parseLong(getProperty(DEFAULT_TIMEOUT_IN_SEC)), TimeUnit.SECONDS); - // set shared common params - partnerId = Integer.parseInt(getProperty(PARTNER_ID)); + // set default users password defaultUserPassword = getProperty(DEFAULT_USER_PASSWORD); + + // set shared common params + if ("opc".equals(accountType)) { + isOpcGroup = true; + partnerId = Integer.parseInt(getProperty(OPC_PARTNER_ID)); + } else { + isOpcGroup = false; + partnerId = Integer.parseInt(getProperty(PARTNER_ID)); + } + + // set performance report + if ("true".equals(getProperty(WRITE_REGRESSION_LOGS)) && numOfSuites == getNumOfSuites()) { + File logsDir = new File(getProperty(LOGS_DIR)); + if (Files.exists(logsDir.toPath())) { + try { + FileUtils.cleanDirectory(new File(getProperty(LOGS_DIR))); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + // decrement numOfSuites in order to generate the performance report after all suites finish + numOfSuites--; + } + + @BeforeMethod(alwaysRun = true) + public void baseTest_beforeMethod(Method method) { + Logger.getLogger(BaseTest.class).debug("Start test >>> Class: " + getClass().getSimpleName() + ", Test: " + method.getName()); + } + + @AfterMethod(alwaysRun = true) + public void baseTest_afterMethod(Method method) { + Logger.getLogger(BaseTest.class).debug("End test >>> Class: " + getClass().getSimpleName() + ", Test: " + method.getName()); + } + + /** + * Regression requires existing of Price Plan with specific parameters. + * Price should be 5 Euros + * Discount percent should be equal 100% + *

+ * In case item is not found in DB it will be ingested. + * Can't work in case proper Discount and PriceCode aren't found in DB + * + * @return common shared Price Plan with mentioned parameters + */ + public static PricePlan getSharedCommonPricePlan() { + if (sharedCommonPricePlan == null) { + sharedCommonPricePlan = IngestFixtureData.loadPricePlan(Double.valueOf(COMMON_PRICE_CODE_AMOUNT), EUR.getValue(), getSharedCommonDiscount()); + if (sharedCommonPricePlan == null) { + PpData ppData = new PpData() + .fullLifeCycle(cycles.get(CYCLE_1_DAY)) + .viewLifeCycle(cycles.get(CYCLE_1_DAY)) + .maxViews(0) + .price(COMMON_PRICE_CODE_AMOUNT) + .currency(EUR.getValue()) + .discount(IngestFixtureData.getDiscountByPercentAndCurrency(EUR.getValue(), getSharedCommonDiscount().getPercent().intValue())) + .isRenewable(true) + .recurringPeriods(0); + + sharedCommonPricePlan = insertPp(ppData); + } + } + return sharedCommonPricePlan; + } + + /** + * Regression requires existing of Price Plan with specific parameters. + * One of them: + * Discount percent should be equal 100% + * Can't work in case proper Discount and PriceCode aren't found in DB + * + * @return common shared Discount Module with mentioned parameters + */ + public static DiscountModule getSharedCommonDiscount() { + double defaultDiscountPrice = 0.0; + double defaultDiscountPercentValue = 100.0; + if (sharedCommonDiscountModule == null) { + sharedCommonDiscountModule = IngestFixtureData.loadDiscount(defaultDiscountPrice, defaultDiscountPercentValue); + } + return sharedCommonDiscountModule; + } + + /** + * Regression requires existing of MPP with specific parameters. + * Price Plan should be as for method public static PricePlan getSharedCommonPricePlan() + *

+ * MPP shouldn't be renewed and with discount (internal items) 100% + * + * @return MPP with mentioned parameters + */ + public static Subscription getSharedCommonSubscription() { + double defaultDiscountPercentValue = 100.0; + if (sharedCommonSubscription == null) { + sharedCommonSubscription = IngestFixtureData.loadSharedCommonSubscription(getSharedCommonPricePlan()); + if (sharedCommonSubscription == null) { + MppData mppData = new MppData() + .pricePlanCode1(getSharedCommonPricePlan().getName()) + .internalDiscount(IngestFixtureData.getDiscountByPercentAndCurrency(EUR.getValue(), (int) defaultDiscountPercentValue)); + sharedCommonSubscription = insertMpp(mppData); + } + + // it should have at least 1 VOD + if (getAssetsListBySubscription(Integer.valueOf(sharedCommonSubscription.getId()), Optional.empty(), true) == null || + getAssetsListBySubscription(Integer.valueOf(sharedCommonSubscription.getId()), Optional.empty(), true).size() == 0) { + ingestVODIntoSubscription(sharedCommonSubscription); + } + } + return sharedCommonSubscription; + } + + /** + * Regression requires existence of Collection with specific parameters. + * Price should be as for method public static PricePlan getSharedCommonPricePlan() + * Usage Module should be as for method public static PricePlan getSharedCommonPricePlan() + *

+ * Collection should be with discount (internal items) 100% + * + * @return Collection with mentioned parameters + */ + public static Collection getSharedCommonCollection() { + if (sharedCommonCollection == null) { + sharedCommonCollection = IngestFixtureData.loadSharedCommonCollection(getSharedCommonPricePlan()); + if (sharedCommonCollection == null) { + Logger.getLogger(BaseTest.class).error("Collection with defined parameters should exist in DB!"); + } + } + return sharedCommonCollection; + } + + /** + * Regression requires existing of PPV with specific parameters. + * Price Plan should be as for method public static PricePlan getSharedCommonPricePlan() + * + * PPV should be with discount (internal items) 50% + * + * @return PPV with mentioned parameters + */ + public static Ppv getSharedCommonPpv(){ + double discountPercentValue = 50.0; + if (sharedCommonPpv == null) { + sharedCommonPpv = IngestFixtureData.loadSharedCommonPpv(getSharedCommonPricePlan()); + if (sharedCommonPpv == null) { + PpvData ppvData = new PpvData() + .discountCode(IngestFixtureData.getDiscountByPercentAndCurrency(EUR.getValue(), (int) discountPercentValue)) + .usageModule(getSharedCommonPricePlan().getName()); + sharedCommonPpv = insertPpv(ppvData); + } + } + return sharedCommonPpv; + } + + public static String getIngestBusinessModuleUserName() { + if (ingestBusinessModuleUserUsername == null) { + String userInfo = IngestFixtureData.getIngestItemUserData(partnerId); + ingestBusinessModuleUserUsername = userInfo.split(":")[0]; + ingestBusinessModuleUserPassword = userInfo.split(":")[1]; + } + return ingestBusinessModuleUserUsername; + } + + public static String getIngestBusinessModuleUserPassword() { + if (ingestBusinessModuleUserPassword == null) { + String userInfo = IngestFixtureData.getIngestItemUserData(partnerId); + ingestBusinessModuleUserUsername = userInfo.split(":")[0]; + ingestBusinessModuleUserPassword = userInfo.split(":")[1]; + } + return ingestBusinessModuleUserPassword; + } + + public static String getIngestAssetUserName() { + if (ingestAssetUserUsername == null) { + String userInfo = isOpcGroup + ? IngestFixtureData.getIngestItemUserData(partnerId) + : IngestFixtureData.getIngestItemUserData(partnerId + 1); + ingestAssetUserUsername = userInfo.split(":")[0]; + ingestAssetUserPassword = userInfo.split(":")[1]; + } + return ingestAssetUserUsername; + } + + public static String getIngestAssetUserPassword() { + if (ingestAssetUserPassword == null) { + String userInfo = isOpcGroup + ? IngestFixtureData.getIngestItemUserData(partnerId) + : IngestFixtureData.getIngestItemUserData(partnerId + 1); + ingestAssetUserUsername = userInfo.split(":")[0]; + ingestAssetUserPassword = userInfo.split(":")[1]; + } + return ingestAssetUserPassword; + } + + public static String getIngestVirtualAssetUserName() { + if (ingestVirtualAssetUserUsername == null) { + String userInfo = isOpcGroup + ? IngestFixtureData.getIngestItemUserData(partnerId) + : IngestFixtureData.getIngestItemUserData(partnerId + 2); + ingestVirtualAssetUserUsername = userInfo.split(":")[0]; + ingestVirtualAssetUserPassword = userInfo.split(":")[1]; + } + return ingestVirtualAssetUserUsername; + } + + public static String getIngestVirualAssetUserPassword() { + if (ingestVirtualAssetUserPassword == null) { + String userInfo = isOpcGroup + ? IngestFixtureData.getIngestItemUserData(partnerId) + : IngestFixtureData.getIngestItemUserData(partnerId + 2); + ingestVirtualAssetUserUsername = userInfo.split(":")[0]; + ingestVirtualAssetUserPassword = userInfo.split(":")[1]; + } + return ingestVirtualAssetUserPassword; } // getters for shared params public static String getAdministratorKs() { if (administratorKs == null) { - String[] userInfo = DBUtils.getUserDataByRole("Administrator").split(":"); - loginResponse = executor.executeSync(login(partnerId, userInfo[0], userInfo[1], - null,null)); + String[] userInfo = DBUtils.getUserData("Administrator").split(":"); + loginResponse = executor.executeSync(login(partnerId, userInfo[0], userInfo[1])); administratorKs = loginResponse.results.getLoginSession().getKs(); } return administratorKs; @@ -106,9 +369,8 @@ public static String getAdministratorKs() { public static String getOperatorKs() { if (operatorKs == null) { - String[] userInfo = DBUtils.getUserDataByRole("Operator").split(":"); - loginResponse = executor.executeSync(login(partnerId, userInfo[0], userInfo[1], - null,null)); + String[] userInfo = DBUtils.getUserData("Operator").split(":"); + loginResponse = executor.executeSync(login(partnerId, userInfo[0], userInfo[1])); operatorKs = loginResponse.results.getLoginSession().getKs(); } return operatorKs; @@ -116,9 +378,8 @@ public static String getOperatorKs() { public static String getManagerKs() { if (managerKs == null) { - String[] userInfo = DBUtils.getUserDataByRole("Manager").split(":"); - loginResponse = executor.executeSync(login(partnerId, userInfo[0], userInfo[1], - null,null)); + String[] userInfo = DBUtils.getUserData("Manager").split(":"); + loginResponse = executor.executeSync(login(partnerId, userInfo[0], userInfo[1])); managerKs = loginResponse.results.getLoginSession().getKs(); } return managerKs; @@ -126,7 +387,7 @@ public static String getManagerKs() { public static String getAnonymousKs() { if (anonymousKs == null) { - Response loginSession = executor.executeSync(OttUserService.anonymousLogin(partnerId)); + Response loginSession = executor.executeSync(anonymousLogin(partnerId)); anonymousKs = loginSession.results.getKs(); } return anonymousKs; @@ -134,54 +395,159 @@ public static String getAnonymousKs() { public static MediaAsset getSharedMediaAsset() { if (mediaAsset == null) { - mediaAsset = IngestUtils.ingestVOD(Optional.empty(), Optional.empty(), true, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), - Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()); + VodData vodData = new VodData(); + mediaAsset = insertVod(vodData, true); } return mediaAsset; } + public static String getSharedEpgChannelName() { + if (epgChannelName == null) { + epgChannelName = DBUtils.getLinearAssetIdAndEpgChannelNameJsonArray().getJSONObject(0).getString("name"); + } + return epgChannelName; + } + + public static ProgramAsset getSharedEpgProgram() { + if (epgProgram == null) { + epgProgram = insertEpg(new EpgData(getSharedEpgChannelName())).get(0); + } + return (ProgramAsset) epgProgram; + } + + public static MediaFile getSharedWebMediaFile() { if (webMediaFile == null) { - if (getProperty(WEB_FILE_TYPE).equals(getSharedMediaAsset().getMediaFiles().get(0).getType())) { - webMediaFile = mediaAsset.getMediaFiles().get(0); - } else { - webMediaFile = mediaAsset.getMediaFiles().get(1); - } + webMediaFile = getMediaFileByType(getSharedMediaAsset(), getProperty(WEB_FILE_TYPE)); } return webMediaFile; } public static MediaFile getSharedMobileMediaFile() { if (mobileMediaFile == null) { - if (getProperty(MOBILE_FILE_TYPE).equals(getSharedMediaAsset().getMediaFiles().get(0).getType())) { - mobileMediaFile = mediaAsset.getMediaFiles().get(0); - } else { - mobileMediaFile = mediaAsset.getMediaFiles().get(1); - } + mobileMediaFile = getMediaFileByType(getSharedMediaAsset(), getProperty(MOBILE_FILE_TYPE)); } return mobileMediaFile; } + public static MediaFile getMediaFileByType(MediaAsset asset, String fileType) { + MediaFile mediaFile; + if (fileType.equals(asset.getMediaFiles().get(0).getType())) { + mediaFile = mediaAsset.getMediaFiles().get(0); + } else { + mediaFile = mediaAsset.getMediaFiles().get(1); + } + return mediaFile; + } + public static Subscription get5MinRenewableSubscription() { if (fiveMinRenewableSubscription == null) { - PricePlan pricePlan = IngestUtils.ingestPP(Optional.empty(), Optional.empty(), Optional.empty(), - Optional.of(FIVE_MINUTES_PERIOD), Optional.of(FIVE_MINUTES_PERIOD), Optional.empty(), - Optional.of(getProperty(PRICE_CODE_AMOUNT)), Optional.of(CURRENCY_EUR), Optional.of(""), - Optional.of(true), Optional.of(3)); - fiveMinRenewableSubscription = IngestUtils.ingestMPP(Optional.empty(), Optional.empty(), Optional.empty(), - Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), - Optional.of(true), Optional.empty(), Optional.of(pricePlan.getName()), Optional.empty(), Optional.empty(), Optional.empty(), - Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()); + fiveMinRenewableSubscription = IngestFixtureData.loadShared5MinutesRenewableSubscription(); + // it should have at least 1 VOD + if (getAssetsListBySubscription(Integer.valueOf(fiveMinRenewableSubscription.getId()), Optional.empty(), true) == null || + getAssetsListBySubscription(Integer.valueOf(fiveMinRenewableSubscription.getId()), Optional.empty(), true).size() == 0) { + ingestVODIntoSubscription(fiveMinRenewableSubscription); + } + + if (fiveMinRenewableSubscription == null) { + PpData ppData = new PpData() + .fullLifeCycle(FIVE_MINUTES_PERIOD) + .viewLifeCycle(FIVE_MINUTES_PERIOD) + .price(PRICE_CODE_AMOUNT) + .currency(EUR.getValue()) + .isRenewable(true) + .recurringPeriods(3); + + PricePlan pricePlan = insertPp(ppData); + + // it should have at least 1 VOD + DynamicChannel channel = loadDefaultChannel(); + channel.setKSql("name='" + getSharedMediaAsset().getName() + "'"); + AddChannelBuilder addChannelBuilder = add(channel); + Response channelResponse = executor.executeSync(addChannelBuilder.setKs(getManagerKs())); + if (channelResponse.results != null && channelResponse.results.getName() != null) { + MppData mppData = new MppData() + .pricePlanCode1(pricePlan.getName()) + .channel2(channelResponse.results.getName()); + fiveMinRenewableSubscription = insertMpp(mppData); + } + } } return fiveMinRenewableSubscription; } + private static void ingestVODIntoSubscription(Subscription subscription) { + // getting channel + SubscriptionFilter filter = new SubscriptionFilter(); + filter.setSubscriptionIdIn(subscription.getId()); + Response> listResponse = executor.executeSync(list(filter) + .setKs(getOperatorKs())); + + verify(listResponse.results.getObjects().get(0).getChannels().size() > 0); + int channelId = listResponse.results.getObjects().get(0).getChannels().get(0).getId().intValue(); + + // get channel + DynamicChannel channel = (DynamicChannel) executor.executeSync(get(channelId) + .setKs(getOperatorKs())) + .results; + + String[] parameters; + String tag = null; + String name = null; + + if (channel.getKSql() == null || channel.getKSql().equals("")) { + // automatic channel + String automaticChannelExpression = IngestFixtureData.getAutomaticChannelExpression(channelId); + parameters = automaticChannelExpression.split(":"); + verify(parameters.length == 2); + tag = parameters[0]; + } else { + // KSQL channel + parameters = channel.getKSql().split("="); + verify(parameters.length == 2); + if ("name".equals(parameters[0].toLowerCase())) { + // ingest VOD with mentioned name + name = parameters[0]; + } else { + // ingest VOD with Tag/Meta (currently supports only tags!!!) + tag = parameters[0]; + } + } + if (name != null) { + // ingest VOD by name + VodData vodData = new VodData(); + MediaAsset mediaAsset = insertVod(vodData, true); + + vodData.name(name); + updateVod(mediaAsset.getName(), vodData); + } + if (tag != null) { + // ingest VOD by tag + Map> tags = new HashMap<>(); + List values = new ArrayList<>(); + values.add(parameters[1].replaceAll("'", "")); + tags.put(tag, values); + + VodData vodData = new VodData().tags(tags); + insertVod(vodData, true); + } + } + + private static DynamicChannel loadDefaultChannel() { + DynamicChannel channel = new DynamicChannel(); + channel.setMultilingualName(setTranslationToken(getRandomValue("Channel_"))); + channel.setMultilingualDescription(setTranslationToken("Description of " + channel.getName())); + channel.setIsActive(true); + channel.setAssetTypes(null); + return channel; + } + // shared household public static class SharedHousehold { - private static Household sharedHousehold; - private static HouseholdUser sharedMasterUser, sharedUser; - private static String sharedMasterUserKs, sharedUserKs; + @Shared private static Household sharedHousehold; + @Shared private static HouseholdUser sharedMasterUser, sharedUser; + @Shared private static String sharedMasterUserKs, sharedUserKs; public static Household getSharedHousehold() { @@ -190,23 +556,24 @@ public static Household getSharedHousehold() { if (sharedHousehold == null) { sharedHousehold = createHousehold(numOfUsers, numOfDevices, true); - List sharedHouseholdUsers = getUsersListFromHouseHold(sharedHousehold); + List sharedHouseholdUsers = getUsersList(sharedHousehold); for (HouseholdUser user : sharedHouseholdUsers) { if (user.getIsMaster() != null && user.getIsMaster()) { sharedMasterUser = user; } - // TODO: ask Alon if we have cases when commented part should be there? What tests related to that logic? - if (user.getIsMaster() == null/* && user.getIsDefault() == null*/) { + if (user.getIsMaster() == null && user.getIsDefault() == null) { sharedUser = user; } } - String sharedMasterUserName = getUserById(Integer.parseInt(sharedMasterUser.getUserId())).getUsername(); - loginResponse = executor.executeSync(login(partnerId, sharedMasterUserName, defaultUserPassword,null,null)); + List sharedHouseholdDevices = getDevicesList(sharedHousehold); + String sharedMasterUserName = getOttUserById(Integer.parseInt(sharedMasterUser.getUserId())).getUsername(); + loginResponse = executor.executeSync(login(partnerId, sharedMasterUserName, defaultUserPassword,null,sharedHouseholdDevices.get(0).getUdid())); sharedMasterUserKs = loginResponse.results.getLoginSession().getKs(); - String sharedUserName = getUserById(Integer.parseInt(sharedUser.getUserId())).getUsername(); - loginResponse = executor.executeSync(login(partnerId, sharedUserName, defaultUserPassword,null,null)); + String sharedUserName = getOttUserById(Integer.parseInt(sharedUser.getUserId())).getUsername(); + loginResponse = executor.executeSync(login(partnerId, sharedUserName, defaultUserPassword,null,sharedHouseholdDevices.get(1).getUdid())); + sharedUserKs = loginResponse.results.getLoginSession().getKs(); } return sharedHousehold; @@ -232,4 +599,50 @@ public static HouseholdUser getSharedUser() { return sharedUser; } } + + @AfterSuite(alwaysRun = true) + public void baseTest_afterSuite(ITestContext testContext) { + XmlSuite suite = testContext.getCurrentXmlTest().getSuite(); + Logger.getLogger(BaseTest.class).debug("End suite >>> Suite: " + suite.getName()); + + // reset shared params + resetSharedParams(); + + // generate performance report + if ("true".equals(getProperty(WRITE_REGRESSION_LOGS)) && numOfSuites == 0) { + PerformanceUtils.generatePerformanceReport(); + } + + // TODO: 8/14/2018 cleanup: delete generated shared resources and data! + } + + private static int getNumOfSuites() { + Document doc = getDocument("src/test/resources/testng.xml"); + NodeList suites = doc.getElementsByTagName("suite-file"); + return suites.getLength(); + } + + void resetSharedParams() { + Logger.getLogger(BaseTest.class).debug("start resetSharedParams()"); + + // TODO: 9/5/2018 make dynamic in case more inner classes will be added + Field[] baseTestFields = BaseTest.class.getDeclaredFields(); + Field[] sharedHouseholdFields = SharedHousehold.class.getDeclaredFields(); + Field[] fields = ArrayUtils.addAll(baseTestFields, sharedHouseholdFields); + + for (Field field : fields) { + for (Annotation annotation : field.getDeclaredAnnotations()) { + if (annotation instanceof Shared) { + try { + field.setAccessible(true); + field.set(this, null); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + } + } + + Logger.getLogger(BaseTest.class).debug("finish resetSharedParams()"); + } } diff --git a/src/test/java/com/kaltura/client/test/tests/enums/AssetStructMetaType.java b/src/test/java/com/kaltura/client/test/tests/enums/AssetStructMetaType.java new file mode 100644 index 000000000..3a5366c01 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/enums/AssetStructMetaType.java @@ -0,0 +1,83 @@ +package com.kaltura.client.test.tests.enums; + +import com.kaltura.client.enums.EnumAsString; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public enum AssetStructMetaType implements EnumAsString { + MULTI_LINGUAL_TEXT("Text"), + STRING("String"), + NUMBER("Number"), + DATE("Date"), + BOOLEAN("Boolean"), + //TAG("tag"), + ALL("All"); + + private String value; + private static List idsOfMetaTypes = null; +// private static Map types2IdsInDb = null; + + /*Data chosen from that ENUM provided by Lior + public enum MetaType + { + All = 0, + String = 1, + Number = 2, + Bool = 3, + Tag = 4, + DateTime = 5, + MultilingualString = 6 + }*/ + public static List getIdsOfMetaTypes() { + if (idsOfMetaTypes == null) { + idsOfMetaTypes = new ArrayList<>(); + idsOfMetaTypes.add(6); // text multilingual + idsOfMetaTypes.add(2); // number + idsOfMetaTypes.add(5); // date + idsOfMetaTypes.add(3); // boolean + idsOfMetaTypes.add(1); // String + } + return idsOfMetaTypes; + } + +// public static Map getTypes2IdsInDb() { +// if (types2IdsInDb == null) { +// types2IdsInDb.put("Text", 6); +// types2IdsInDb.put("Number", 2); +// types2IdsInDb.put("Date", 5); +// types2IdsInDb.put("Boolean", 3); +// types2IdsInDb.put("String", 1); +// } +// return types2IdsInDb; +// } + + AssetStructMetaType(String value) { + this.value = value; + } + + @Override + public String getValue() { + return this.value; + } + + public void setValue(String value) { + this.value = value; + } + + public static AssetStructMetaType get(String value) { + if(value == null) { + return null; + } + + // goes over defined values and compare the inner value with the given one: + for(AssetStructMetaType item: values()) { + if(item.getValue().equals(value)) { + return item; + } + } + // in case the requested value was not found in the enum values, we return the first item as default. + return AssetStructMetaType.values().length > 0 ? AssetStructMetaType.values()[0]: null; + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/enums/ChannelType.java b/src/test/java/com/kaltura/client/test/tests/enums/ChannelType.java new file mode 100644 index 000000000..96de7d6c2 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/enums/ChannelType.java @@ -0,0 +1,40 @@ +package com.kaltura.client.test.tests.enums; + +import com.kaltura.client.enums.EnumAsString; + +public enum ChannelType implements EnumAsString { + AUTOMATIC_CHANNEL_TYPE("1"), + KSQL_CHANNEL_TYPE("4"), + MANUAL_CHANNEL_TYPE("2"); + + private String value; + + ChannelType(String value) { + this.value = value; + } + + @Override + public String getValue() { + return this.value; + } + + public void setValue(String value) { + this.value = value; + } + + public static ChannelType get(String value) { + if(value == null) + { + return null; + } + + // goes over Channel types defined values and compare the inner value with the given one: + for(ChannelType item: values()) { + if(item.getValue().equals(value)) { + return item; + } + } + // in case the requested value was not found in the enum values, we return the first item as default. + return ChannelType.values().length > 0 ? ChannelType.values()[0]: null; + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/enums/Currency.java b/src/test/java/com/kaltura/client/test/tests/enums/Currency.java new file mode 100644 index 000000000..8b23a2570 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/enums/Currency.java @@ -0,0 +1,40 @@ +package com.kaltura.client.test.tests.enums; + +import com.kaltura.client.enums.EnumAsString; + +public enum Currency implements EnumAsString { + EUR("EUR"), + ILS("ILS"), + CLP("CLP"), + USD("USD"); + + private String value; + + Currency(String value) { + this.value = value; + } + + @Override + public String getValue() { + return this.value; + } + + public void setValue(String value) { + this.value = value; + } + + public static Currency get(String value) { + if(value == null) { + return null; + } + + // goes over Currency defined values and compare the inner value with the given one: + for(Currency item: values()) { + if(item.getValue().equals(value)) { + return item; + } + } + // in case the requested value was not found in the enum values, we return the first item as default. + return Currency.values().length > 0 ? Currency.values()[0]: null; + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/enums/DurationPeriod.java b/src/test/java/com/kaltura/client/test/tests/enums/DurationPeriod.java new file mode 100644 index 000000000..c3a54b497 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/enums/DurationPeriod.java @@ -0,0 +1,40 @@ +package com.kaltura.client.test.tests.enums; + +import com.kaltura.client.enums.EnumAsString; + +public enum DurationPeriod implements EnumAsString { + DAYS("days"), + HOURS("hours"), + MINUTES("minutes"), + SECONDS("seconds"); + + private String value; + + DurationPeriod(String value) { + this.value = value; + } + + @Override + public String getValue() { + return this.value; + } + + public void setValue(String value) { + this.value = value; + } + + public static DurationPeriod get(String value) { + if(value == null) { + return null; + } + + // goes over Currency defined values and compare the inner value with the given one: + for(DurationPeriod item: values()) { + if(item.getValue().equals(value)) { + return item; + } + } + // in case the requested value was not found in the enum values, we return the first item as default. + return Currency.values().length > 0 ? DurationPeriod.values()[0]: null; + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/enums/IngestAction.java b/src/test/java/com/kaltura/client/test/tests/enums/IngestAction.java new file mode 100644 index 000000000..d55dc819c --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/enums/IngestAction.java @@ -0,0 +1,39 @@ +package com.kaltura.client.test.tests.enums; + +import com.kaltura.client.enums.EnumAsString; + +public enum IngestAction implements EnumAsString { + INSERT("insert"), + UPDATE("update"), + DELETE("delete"); + + private String value; + + IngestAction(String value) { + this.value = value; + } + + @Override + public String getValue() { + return this.value; + } + + public void setValue(String value) { + this.value = value; + } + + public static IngestAction get(String value) { + if(value == null) { + return null; + } + + // goes over IngestAction defined values and compare the inner value with the given one: + for(IngestAction item: values()) { + if(item.getValue().equals(value)) { + return item; + } + } + // in case the requested value was not found in the enum values, we return the first item as default. + return IngestAction.values().length > 0 ? IngestAction.values()[0]: null; + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/enums/KsqlKey.java b/src/test/java/com/kaltura/client/test/tests/enums/KsqlKey.java new file mode 100644 index 000000000..36201220e --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/enums/KsqlKey.java @@ -0,0 +1,48 @@ +package com.kaltura.client.test.tests.enums; + +import com.kaltura.client.enums.EnumAsString; + +public enum KsqlKey implements EnumAsString { + + NAME("name"), + START_DATE("start_date"), + END_DATE("end_date"), + GEO_BLOCK("geo_block"), + PARENTAL_RULES("parental_rules"), + USER_INTERESTS("user_interests"), + EPG_CHANNEL_ID("epg_channel_id"), + EPG_ID("epg_id"), + MEDIA_ID("media_id"), + ENTITLED_ASSETS("entitled_assets"), + ASSET_TYPE("asset_type"); + + private String value; + + KsqlKey(String value) { + this.value = value; + } + + @Override + public String getValue() { + return this.value; + } + + public void setValue(String value) { + this.value = value; + } + + public static KsqlKey get(String value) { + if(value == null) { + return null; + } + + // goes over Currency defined values and compare the inner value with the given one: + for(KsqlKey item: values()) { + if(item.getValue().equals(value)) { + return item; + } + } + // in case the requested value was not found in the enum values, we return the first item as default. + return Currency.values().length > 0 ? KsqlKey.values()[0]: null; + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/enums/MediaType.java b/src/test/java/com/kaltura/client/test/tests/enums/MediaType.java new file mode 100644 index 000000000..0e78e531d --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/enums/MediaType.java @@ -0,0 +1,41 @@ +package com.kaltura.client.test.tests.enums; + +import com.kaltura.client.enums.EnumAsString; + +public enum MediaType implements EnumAsString { + MOVIE("Movie"), + SERIES("Series"), + EPISODE("Episode"), + LINEAR("Linear"), + PACKAGE("Package"); + + private String value; + + MediaType(String value) { + this.value = value; + } + + @Override + public String getValue() { + return this.value; + } + + public void setValue(String value) { + this.value = value; + } + + public static MediaType get(String value) { + if(value == null) { + return null; + } + + // goes over Currency defined values and compare the inner value with the given one: + for(MediaType item: values()) { + if(item.getValue().equals(value)) { + return item; + } + } + // in case the requested value was not found in the enum values, we return the first item as default. + return Currency.values().length > 0 ? MediaType.values()[0]: null; + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/enums/PremiumService.java b/src/test/java/com/kaltura/client/test/tests/enums/PremiumService.java new file mode 100644 index 000000000..8ca00d71d --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/enums/PremiumService.java @@ -0,0 +1,41 @@ +package com.kaltura.client.test.tests.enums; + +import com.kaltura.client.enums.EnumAsString; + +public enum PremiumService implements EnumAsString { + CATCH_UP("1"), + START_OVER("2"), + NPVR("3"), + DOWNLOAD("4"), + AD_CONTROL("5"); + + private String value; + + PremiumService(String value) { + this.value = value; + } + + @Override + public String getValue() { + return this.value; + } + + public void setValue(String value) { + this.value = value; + } + + public static PremiumService get(String value) { + if(value == null) { + return null; + } + + // goes over Currency defined values and compare the inner value with the given one: + for(PremiumService item: values()) { + if(item.getValue().equals(value)) { + return item; + } + } + // in case the requested value was not found in the enum values, we return the first item as default. + return Currency.values().length > 0 ? PremiumService.values()[0]: null; + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/featuresTests/productPriceTests/ListTests.java b/src/test/java/com/kaltura/client/test/tests/featuresTests/productPriceTests/ListTests.java deleted file mode 100644 index 4211b5d5b..000000000 --- a/src/test/java/com/kaltura/client/test/tests/featuresTests/productPriceTests/ListTests.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.kaltura.client.test.tests.featuresTests.productPriceTests; - -import com.kaltura.client.Client; -import com.kaltura.client.test.tests.BaseTest; -import org.testng.annotations.BeforeClass; - -public class ListTests extends BaseTest { - - private Client client; - - @BeforeClass - public void beforeClass() { - - /*Ppv ppv = IngestUtils.ingestPPV(INGEST_ACTION_INSERT, true, "My ingest PPV", getProperty(FIFTY_PERCENTS_ILS_DISCOUNT_NAME), - Double.valueOf(getProperty(PRICE_CODE_AMOUNT_4_99)), CURRENCY_EUR, getProperty(DEFAULT_USAGE_MODULE_4_INGEST_PPV), false, false, - getProperty(DEFAULT_PRODUCT_CODE), getProperty(WEB_FILE_TYPE), getProperty(MOBILE_FILE_TYPE));*/ - - /*Response> ingestedProgrammes = IngestUtils.ingestEPG("Shmulik_Series_1", Optional.of(2), Optional.empty(), Optional.of(30), - Optional.of("minutes"), Optional.empty(), Optional.of(1), Optional.empty(), Optional.empty(), Optional.empty()); - System.out.println("ID:" + ingestedProgrammes.results.getObjects().get(0).getId());*/ - } -} diff --git a/src/test/java/com/kaltura/client/test/tests/featuresTests/versions/five_zero_three/ParentChildMetadataInheritanceTests.java b/src/test/java/com/kaltura/client/test/tests/featuresTests/versions/five_zero_three/ParentChildMetadataInheritanceTests.java new file mode 100644 index 000000000..84806399a --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/featuresTests/versions/five_zero_three/ParentChildMetadataInheritanceTests.java @@ -0,0 +1,671 @@ +package com.kaltura.client.test.tests.featuresTests.versions.five_zero_three; + +import com.kaltura.client.enums.AssetReferenceType; +import com.kaltura.client.services.*; +import com.kaltura.client.services.AssetStructService.*; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.tests.enums.MediaType; +import com.kaltura.client.test.utils.dbUtils.DBUtils; +import com.kaltura.client.test.utils.ingestUtils.IngestVodUtils; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Link; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static com.kaltura.client.test.tests.enums.AssetStructMetaType.ALL; +import static com.kaltura.client.test.tests.enums.IngestAction.INSERT; +import static com.kaltura.client.test.utils.AssetStructMetaUtils.loadAssetStructMeta; +import static com.kaltura.client.test.utils.AssetStructUtils.copyAssetStructObject; +import static com.kaltura.client.test.utils.AssetStructUtils.getAssetStruct; +import static com.kaltura.client.test.utils.AssetStructUtils.setInheritanceFieldsInAssetStruct; +import static com.kaltura.client.test.utils.AssetUtils.getMediaAsset; +import static com.kaltura.client.test.utils.BaseUtils.getCurrentDateInFormat; +import static com.kaltura.client.test.utils.ingestUtils.BaseIngestUtils.DEFAULT_LANGUAGE; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodOpcUtils.getVodData; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.deleteVod; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.insertVod; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.updateVod; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * + * Class to test functionality described in https://kaltura.atlassian.net/browse/BEO-5423 + */ +@Link(name = "Parent Child Metadata Inheritance", url = "BEO-5423") +@Test(groups = { "opc", "Parent Child Metadata Inheritance" }) +public class ParentChildMetadataInheritanceTests extends BaseTest { + + private String metaIds; + private String allMetaIds; + private Response> sharedAssetStructListResponse; + private AssetStruct sharedAssetStruct1, sharedAssetStruct2; + private AssetStructMeta sharedMetaString1, sharedMetaString2, sharedMetaNumber1, sharedMetaNumber2; + private AssetStructMeta sharedMetaDate1, sharedMetaDate2, sharedMetaBoolean1, sharedMetaBoolean2; + private String sharedBasicMetaIds; + private String language1; + private Map> partMetas = new HashMap<>(); + private Map> allMetas = new HashMap<>(); + private Map> allUpdatedMetas = new HashMap<>(); + + @BeforeClass() + public void setUp() { + List languages = executor.executeSync(LanguageService.list(new LanguageFilter()) + .setKs(getOperatorKs())).results.getObjects(); + language1 = languages.get(0).getCode(); + // TODO: check if assetStructList be useful at the end + // assetStructList to fill default metaIds +// AssetStructFilter filter = new AssetStructFilter(); +// ListAssetStructBuilder listAssetStructBuilder = AssetStructService.list(filter); +// sharedAssetStructListResponse = executor.executeSync(listAssetStructBuilder +// .setKs(getOperatorKs())); +// assertThat(sharedAssetStructListResponse.results.getTotalCount()).isGreaterThan(0); +// metaIds = sharedAssetStructListResponse.results.getObjects().get(0).getMetaIds(); + + // identify shared assetStructMetas + List assetStructNames = DBUtils.getAssetStructMetas(ALL, 2); + sharedMetaString1 = loadAssetStructMeta(assetStructNames.get(0)); + sharedMetaString2 = loadAssetStructMeta(assetStructNames.get(1)); + sharedMetaNumber1 = loadAssetStructMeta(assetStructNames.get(2)); + sharedMetaNumber2 = loadAssetStructMeta(assetStructNames.get(3)); + sharedMetaDate1 = loadAssetStructMeta(assetStructNames.get(4)); + sharedMetaDate2 = loadAssetStructMeta(assetStructNames.get(5)); + sharedMetaBoolean1 = loadAssetStructMeta(assetStructNames.get(6)); + sharedMetaBoolean2 = loadAssetStructMeta(assetStructNames.get(7)); + // TODO: ask Lior why ONLY these ids are obvious when DB has more basic partMetas? + sharedBasicMetaIds = "58,629,1482,1493,1494,1495,1496,1497,566";//loadBasicAssetStructMetaId(); + + // fill allMetaIds with fixture partMetas + allMetaIds = getAllFixtureMetaIds(); + + // TODO: check if type of partMetas should be updated???? + partMetas.put(assetStructNames.get(0), Map.of(language1, "Default string value1")); + //partMetas.put(assetStructNames.get(1), Map.of(language1, "Default string value2")); + partMetas.put(assetStructNames.get(2), Map.of(language1, "1111")); + //partMetas.put(assetStructNames.get(3), Map.of(language1, "1112")); + partMetas.put(assetStructNames.get(4), Map.of(language1, "01/01/2001")); + //partMetas.put(assetStructNames.get(5), Map.of(language1, "01/01/2002")); + partMetas.put(assetStructNames.get(6), Map.of(language1, "true")); + //partMetas.put(assetStructNames.get(7), Map.of(language1, "false")); + + allMetas.putAll(partMetas); + allMetas.put(assetStructNames.get(1), Map.of(language1, "Default string value2")); + allMetas.put(assetStructNames.get(3), Map.of(language1, "1112")); + allMetas.put(assetStructNames.get(5), Map.of(language1, "01/01/2002")); + allMetas.put(assetStructNames.get(7), Map.of(language1, "false")); + + allUpdatedMetas.putAll(allMetas); + allUpdatedMetas.put(assetStructNames.get(1), Map.of(language1, "Default string value22")); + allUpdatedMetas.put(assetStructNames.get(3), Map.of(language1, "11122")); + allUpdatedMetas.put(assetStructNames.get(5), Map.of(language1, "01/01/2022")); + allUpdatedMetas.put(assetStructNames.get(7), Map.of(language1, "true")); + + // create shared assetStruct1 + String prefix = "AssetStruct_" + getCurrentDateInFormat("yyMMddHHmmss"); + String metaIds = sharedMetaString1.getMetaId().toString() + "," + sharedBasicMetaIds; + sharedAssetStruct1 = createAssetStruct(prefix, metaIds); + + // create shared assetStruct2 + prefix = "AssetStruct_" + getCurrentDateInFormat("yyMMddHHmmss") + "2"; + metaIds = sharedMetaString2.getMetaId().toString() + "," + sharedBasicMetaIds; + sharedAssetStruct2 = createAssetStruct(prefix, metaIds); + } + + String getAllFixtureMetaIds() { + StringBuilder allMetaIdsSb = new StringBuilder(); + allMetaIdsSb + .append(sharedMetaString1.getMetaId().toString()) + .append(",") + .append(sharedMetaString2.getMetaId().toString()) + .append(",") + .append(sharedMetaNumber1.getMetaId().toString()) + .append(",") + .append(sharedMetaNumber2.getMetaId().toString()) + .append(",") + .append(sharedMetaDate1.getMetaId().toString()) + .append(",") + .append(sharedMetaDate2.getMetaId().toString()) + .append(",") + .append(sharedMetaBoolean1.getMetaId().toString()) + .append(",") + .append(sharedMetaBoolean2.getMetaId().toString()); + return allMetaIdsSb.toString(); + } + + @Test + public void testAssetStructListSecurity() { + // assetStructList Master + AssetStructFilter filter = new AssetStructFilter(); + ListAssetStructBuilder listAssetStructBuilder = AssetStructService.list(filter); + Response> assetStructListResponse = executor.executeSync(listAssetStructBuilder + .setKs(SharedHousehold.getSharedMasterUserKs())); + assertThat(assetStructListResponse.error.getMessage()).isEqualToIgnoringCase("Service Forbidden"); + + // assetStructList Operator + filter = new AssetStructFilter(); + listAssetStructBuilder = AssetStructService.list(filter); + assetStructListResponse = executor.executeSync(listAssetStructBuilder + .setKs(getOperatorKs())); + assertThat(assetStructListResponse.results).isNotNull(); + assertThat(assetStructListResponse.error).isNull(); + } + + @Test + public void testCreateInheritance() { + // create assetStruct1 + String metaIds = sharedMetaString1.getMetaId().toString() + "," + sharedBasicMetaIds; + String prefix = "AssetStruct_" + getCurrentDateInFormat("yyMMddHHmmss"); + AssetStruct assetStruct1 = createAssetStruct(prefix, metaIds); + // create assetStruct2 + metaIds = sharedMetaString2.getMetaId().toString() + "," + sharedBasicMetaIds; + prefix = "AssetStruct_" + getCurrentDateInFormat("yyMMddHHmmss") + "2"; + AssetStruct assetStruct2 = createAssetStruct(prefix, metaIds); + + // set inheritance + AssetStruct assetStruct2Update = copyAssetStructObject(assetStruct2); + setInheritanceFieldsInAssetStruct(assetStruct2Update, assetStruct1.getId(), + sharedMetaString1.getMetaId(), sharedMetaString2.getMetaId()); + updateAssetStruct(assetStruct2.getId(), assetStruct2Update, false); + + // check parent doesn't have changes in related inheritance fields + AssetStructFilter filter = new AssetStructFilter(); + filter.setIdIn(assetStruct1.getId().toString()); + ListAssetStructBuilder listAssetStructBuilder = AssetStructService.list(filter); + Response> assetStructListResponse = executor.executeSync(listAssetStructBuilder + .setKs(getOperatorKs())); + AssetStruct assetStructFromResponse = assetStructListResponse.results.getObjects().get(0); + assertThat(assetStructFromResponse.getParentId()).isEqualTo(0L); + assertThat(assetStructFromResponse.getConnectedParentMetaId()).isEqualTo(0L); + assertThat(assetStructFromResponse.getConnectingMetaId()).isEqualTo(0L); + + // check children asset struct has changes + filter.setIdIn(assetStruct2.getId().toString()); + listAssetStructBuilder = AssetStructService.list(filter); + assetStructListResponse = executor.executeSync(listAssetStructBuilder + .setKs(getOperatorKs())); + assetStructFromResponse = assetStructListResponse.results.getObjects().get(0); + assertThat(assetStructFromResponse.getParentId()).isEqualTo(assetStruct1.getId()); + assertThat(assetStructFromResponse.getConnectedParentMetaId()).isEqualTo(sharedMetaString1.getMetaId()); + assertThat(assetStructFromResponse.getConnectingMetaId()).isEqualTo(sharedMetaString2.getMetaId()); + + // remove assetStructs + deleteAssetStruct(assetStruct2.getId()); // firstly should be deleted children + deleteAssetStruct(assetStruct1.getId()); + } + + @Test(enabled = false) // TODO: remove after deletion + public void testInheritance4TextAndNumericFieldsOnly() { + // create assetStruct1 + String metaIds = sharedMetaString1.getMetaId().toString() + "," + sharedBasicMetaIds; + String prefix = "AssetStruct_" + getCurrentDateInFormat("yyMMddHHmmss"); + AssetStruct assetStruct1 = createAssetStruct(prefix, metaIds); + // create assetStruct2 + metaIds = sharedMetaString2.getMetaId().toString() + "," + sharedBasicMetaIds; + prefix = "AssetStruct_" + getCurrentDateInFormat("yyMMddHHmmss") + "2"; + AssetStruct assetStruct2 = createAssetStruct(prefix, metaIds); + + // set inheritance // to try set inheritance between different types of meta + AssetStruct assetStruct2Update = copyAssetStructObject(assetStruct2); + setInheritanceFieldsInAssetStruct(assetStruct2Update, assetStruct1.getId(), + sharedMetaString1.getMetaId(), sharedMetaDate2.getMetaId()); + updateAssetStruct(assetStruct2.getId(), assetStruct2Update, true); + + // TODO: wait response from Anat and depends on it continue the test with other types + // check children asset struct has changes +// AssetStructFilter filter = new AssetStructFilter(); +// filter.setIdIn(assetStruct2.getId().toString()); +// ListAssetStructBuilder listAssetStructBuilder = AssetStructService.list(filter); +// Response> assetStructListResponse = executor.executeSync(listAssetStructBuilder +// .setKs(getOperatorKs())); +// AssetStruct assetStructFromResponse = assetStructListResponse.results.getObjects().get(0); +// assertThat(assetStructFromResponse.getParentId()).isEqualTo(assetStruct1.getId()); +// assertThat(assetStructFromResponse.getConnectedParentMetaId()).isEqualTo(sharedMetaString1.getMetaId()); +// assertThat(assetStructFromResponse.getConnectingMetaId()).isEqualTo(sharedMetaString2.getMetaId()); + + // remove assetStructs + deleteAssetStruct(assetStruct2.getId()); // firstly should be deleted children + deleteAssetStruct(assetStruct1.getId()); + } + + @Test + public void testInheritance3Levels() { + // create granpa + String metaIds = sharedMetaString1.getMetaId().toString() + "," + sharedBasicMetaIds; + String prefix = "AssetStruct_" + getCurrentDateInFormat("yyMMddHHmmss"); + AssetStruct assetStructGrandParent = createAssetStruct(prefix, metaIds); + // create parent + metaIds = sharedMetaString2.getMetaId().toString() + "," + sharedBasicMetaIds; + prefix = "AssetStruct_" + getCurrentDateInFormat("yyMMddHHmmss") + "2"; + AssetStruct assetStructParent = createAssetStruct(prefix, metaIds); + // create children + metaIds = sharedMetaString1.getMetaId().toString() + "," + sharedMetaString2.getMetaId().toString() + "," + sharedBasicMetaIds; + prefix = "AssetStruct_" + getCurrentDateInFormat("yyMMddHHmmss") + "3"; + AssetStruct assetStructChildren = createAssetStruct(prefix, metaIds); + + // set inheritance between Children and Parent + AssetStruct assetStruct2Update = copyAssetStructObject(assetStructChildren); + setInheritanceFieldsInAssetStruct(assetStruct2Update, assetStructParent.getId(), + sharedMetaString2.getMetaId(), sharedMetaDate2.getMetaId()); + updateAssetStruct(assetStructChildren.getId(), assetStruct2Update, false); + + // set inheritance between Parent and GrandParent + assetStruct2Update = copyAssetStructObject(assetStructParent); + setInheritanceFieldsInAssetStruct(assetStruct2Update, assetStructGrandParent.getId(), + sharedMetaString1.getMetaId(), sharedMetaDate2.getMetaId()); + updateAssetStruct(assetStructParent.getId(), assetStruct2Update, false); + + // check children asset struct has changes + AssetStructFilter filter = new AssetStructFilter(); + filter.setIdIn(assetStructChildren.getId().toString()); + ListAssetStructBuilder listAssetStructBuilder = AssetStructService.list(filter); + Response> assetStructListResponse = executor.executeSync(listAssetStructBuilder + .setKs(getOperatorKs())); + AssetStruct assetStructFromResponse = assetStructListResponse.results.getObjects().get(0); + assertThat(assetStructFromResponse.getParentId()).isEqualTo(assetStructParent.getId()); + assertThat(assetStructFromResponse.getConnectedParentMetaId()).isEqualTo(sharedMetaString2.getMetaId()); + assertThat(assetStructFromResponse.getConnectingMetaId()).isEqualTo(sharedMetaString2.getMetaId()); + + // check parent asset struct has changes + filter = new AssetStructFilter(); + filter.setIdIn(assetStructParent.getId().toString()); + listAssetStructBuilder = AssetStructService.list(filter); + assetStructListResponse = executor.executeSync(listAssetStructBuilder + .setKs(getOperatorKs())); + assetStructFromResponse = assetStructListResponse.results.getObjects().get(0); + assertThat(assetStructFromResponse.getParentId()).isEqualTo(assetStructGrandParent.getId()); + assertThat(assetStructFromResponse.getConnectedParentMetaId()).isEqualTo(sharedMetaString1.getMetaId()); + assertThat(assetStructFromResponse.getConnectingMetaId()).isEqualTo(sharedMetaString2.getMetaId()); + + // remove assetStructs + deleteAssetStruct(assetStructChildren.getId()); // firstly should be deleted children + deleteAssetStruct(assetStructParent.getId()); // secondly should be deleted parent + deleteAssetStruct(assetStructGrandParent.getId()); + } + + // checking that on BE level it is doesn't supported limitation about 1 children maximum + @Test + public void testInheritanceParentWith2Childrens() { + // create parent + String metaIds = sharedMetaString1.getMetaId().toString() + "," + sharedBasicMetaIds; + String prefix = "AssetStruct_" + getCurrentDateInFormat("yyMMddHHmmss"); + AssetStruct assetStructParent = createAssetStruct(prefix, metaIds); + // create children1 + metaIds = sharedMetaString2.getMetaId().toString() + "," + sharedBasicMetaIds; + prefix = "AssetStruct_" + getCurrentDateInFormat("yyMMddHHmmss") + "2"; + AssetStruct assetStructChildren1 = createAssetStruct(prefix, metaIds); + // create children2 + metaIds = sharedMetaString1.getMetaId().toString() + "," + sharedMetaString2.getMetaId().toString() + "," + sharedBasicMetaIds; + prefix = "AssetStruct_" + getCurrentDateInFormat("yyMMddHHmmss") + "3"; + AssetStruct assetStructChildren2 = createAssetStruct(prefix, metaIds); + + // set inheritance between Children2 and Parent + AssetStruct assetStruct2Update = copyAssetStructObject(assetStructChildren2); + setInheritanceFieldsInAssetStruct(assetStruct2Update, assetStructParent.getId(), + sharedMetaString1.getMetaId(), sharedMetaDate2.getMetaId()); + updateAssetStruct(assetStructChildren2.getId(), assetStruct2Update, false); + + // set inheritance between Children1 and Parent + assetStruct2Update = copyAssetStructObject(assetStructChildren1); + setInheritanceFieldsInAssetStruct(assetStruct2Update, assetStructParent.getId(), + sharedMetaString1.getMetaId(), sharedMetaDate2.getMetaId()); + updateAssetStruct(assetStructChildren1.getId(), assetStruct2Update, false); + + // check children asset2 struct has changes + AssetStructFilter filter = new AssetStructFilter(); + filter.setIdIn(assetStructChildren2.getId().toString()); + ListAssetStructBuilder listAssetStructBuilder = AssetStructService.list(filter); + Response> assetStructListResponse = executor.executeSync(listAssetStructBuilder + .setKs(getOperatorKs())); + AssetStruct assetStructFromResponse = assetStructListResponse.results.getObjects().get(0); + assertThat(assetStructFromResponse.getParentId()).isEqualTo(assetStructParent.getId()); + assertThat(assetStructFromResponse.getConnectedParentMetaId()).isEqualTo(sharedMetaString1.getMetaId()); + assertThat(assetStructFromResponse.getConnectingMetaId()).isEqualTo(sharedMetaString2.getMetaId()); + + // check children asset1 struct has changes + filter = new AssetStructFilter(); + filter.setIdIn(assetStructChildren1.getId().toString()); + listAssetStructBuilder = AssetStructService.list(filter); + assetStructListResponse = executor.executeSync(listAssetStructBuilder + .setKs(getOperatorKs())); + assetStructFromResponse = assetStructListResponse.results.getObjects().get(0); + assertThat(assetStructFromResponse.getParentId()).isEqualTo(assetStructParent.getId()); + assertThat(assetStructFromResponse.getConnectedParentMetaId()).isEqualTo(sharedMetaString1.getMetaId()); + assertThat(assetStructFromResponse.getConnectingMetaId()).isEqualTo(sharedMetaString2.getMetaId()); + + // remove assetStructs + deleteAssetStruct(assetStructChildren2.getId()); // firstly should be deleted childrens + deleteAssetStruct(assetStructChildren1.getId()); // firstly should be deleted childrens + deleteAssetStruct(assetStructParent.getId()); + } + + @Test // TODO: wait response from Anat why children wasn't changed + public void testInheritanceWithIngest() { + // create parent + String metaIds = allMetaIds + "," + sharedBasicMetaIds; + String prefix = "AssetStruct_" + getCurrentDateInFormat("yyMMddHHmmss"); + AssetStruct assetStructParent = createAssetStruct(prefix, metaIds); + // create children1 + metaIds = allMetaIds + "," + sharedBasicMetaIds; + prefix = "AssetStruct_" + getCurrentDateInFormat("yyMMddHHmmss") + "2"; + AssetStruct assetStructChildren = createAssetStruct(prefix, metaIds); + + // set inheritance between Children and Parent + AssetStruct assetStruct2Update = copyAssetStructObject(assetStructChildren); + setInheritanceFieldsInAssetStruct(assetStruct2Update, assetStructParent.getId(), + sharedMetaString1.getMetaId(), sharedMetaString1.getMetaId()); + updateAssetStruct(assetStructChildren.getId(), assetStruct2Update, false); + + // ingest all metas of needed type // TODO: it does not work with NULL - discuss with Alon what MediaType use instead of it + IngestVodUtils.VodData parentVodData = getVodData(MediaType.PACKAGE, INSERT) + .multilingualStringsMeta(partMetas) + .customMediaType(assetStructParent.getSystemName()); + MediaAsset parentAsset = insertVod(parentVodData, false); + assertThat(parentAsset.getExternalId()).isNotNull(); + + IngestVodUtils.VodData childrenVodData = getVodData(MediaType.PACKAGE, INSERT) + .multilingualStringsMeta(allMetas) + .customMediaType(assetStructChildren.getSystemName()); + MediaAsset childrenAsset = insertVod(childrenVodData, false); + assertThat(childrenAsset.getExternalId()).isNotNull(); + // TODO: check metas on children + + String coguid = parentAsset.getExternalId(); + parentVodData = new IngestVodUtils.VodData() + .multilingualStringsMeta(allUpdatedMetas) + .customMediaType(assetStructParent.getSystemName()); + parentAsset = updateVod(coguid, parentVodData); + + // TODO: check metas on children after parent update + + AssetService.GetAssetBuilder getAssetBuilder = AssetService.get(childrenAsset.getId().toString(), AssetReferenceType.MEDIA); + Response assetResponse = executor.executeSync(getAssetBuilder + .setKs(getOperatorKs())); + assertThat(assetResponse.results).isNotNull(); + + // remove assetStructs + deleteVod(childrenAsset.getExternalId()); + deleteVod(parentAsset.getExternalId()); + deleteAssetStruct(assetStructChildren.getId()); // firstly should be deleted children + deleteAssetStruct(assetStructParent.getId()); + } + +// @Test //TODO: after ingest +// public void testIngestRules() { +// IngestVodUtils.VodData vodData = getVodData(SERIES, INSERT); +// MediaAsset series = insertVod(vodData, true); +// assertThat(series.getExternalId()).isNotNull(); +// +// vodData = getVodData(EPISODE, INSERT); +// MediaAsset episode = insertVod(vodData, true); +// assertThat(episode.getExternalId()).isNotNull(); +// +// vodData = getVodData(MOVIE, INSERT); +// MediaAsset movie = insertVod(vodData, true); +// assertThat(movie.getExternalId()).isNotNull(); +// +// vodData = getVodData(LINEAR, INSERT); +// MediaAsset linear = insertVod(vodData, true); +// assertThat(linear.getExternalId()).isNotNull(); +// +// System.out.println("SERIES POLICY: " + series.getInheritancePolicy().getValue()); +// System.out.println("EPISODE POLICY: " + episode.getInheritancePolicy().getValue()); +// System.out.println("MOVIE POLICY: " + movie.getInheritancePolicy().getValue()); +// System.out.println("LINEAR POLICY: " + linear.getInheritancePolicy().getValue()); +// +// // cleanup +// deleteVod(linear.getExternalId()); +// deleteVod(movie.getExternalId()); +// deleteVod(series.getExternalId()); +// deleteVod(episode.getExternalId()); +// } + + @Test + public void testApiCreationOfAssetsWithInheritance() { + // create parent + String metaIds = sharedMetaString1.getMetaId().toString() + "," + sharedBasicMetaIds; + String prefix = "AssetStruct_" + getCurrentDateInFormat("yyMMddHHmmss"); + AssetStruct assetStructParent = createAssetStruct(prefix, metaIds); + // create children + metaIds = sharedMetaString1.getMetaId().toString() + "," + sharedBasicMetaIds; + prefix = "AssetStruct_" + getCurrentDateInFormat("yyMMddHHmmss") + "2"; + AssetStruct assetStructChildren = createAssetStruct(prefix, metaIds); + Map metas = new HashMap<>(); + metas.put(DBUtils.getMetaNameById(sharedMetaString1.getMetaId(), false), "some default value"); + // set inheritance between Children and Parent + AssetStruct assetStruct2Update = copyAssetStructObject(assetStructChildren); + setInheritanceFieldsInAssetStruct(assetStruct2Update, assetStructParent.getId(), + sharedMetaString1.getMetaId(), sharedMetaDate2.getMetaId()); + updateAssetStruct(assetStructChildren.getId(), assetStruct2Update, false); + + // TODO: complete + MediaAsset asset = getMediaAsset(assetStructParent.getId(), "testName", "testDescription"); + asset.setMetas(loadMetas(metas)); + AssetService.AddAssetBuilder addAssetBuilder = AssetService.add(asset); + Response response = executor.executeSync(addAssetBuilder + .setKs(getOperatorKs()) + .setLanguage("*")); + asset = (MediaAsset) response.results; + + MediaAsset asset2 = getMediaAsset(assetStructChildren.getId(), "testName2", "testDescription2"); + asset2.setMetas(loadMetas(metas)); + addAssetBuilder = AssetService.add(asset2); + response = executor.executeSync(addAssetBuilder + .setKs(getOperatorKs()) + .setLanguage("*")); + asset2 = (MediaAsset) response.results; +// +// // check children asset1 struct has changes +// AssetStructFilter filter = new AssetStructFilter(); +// filter.setIdIn(assetStructChildren.getId().toString()); +// ListAssetStructBuilder listAssetStructBuilder = AssetStructService.list(filter); +// Response> assetStructListResponse = executor.executeSync(listAssetStructBuilder +// .setKs(getOperatorKs())); +// AssetStruct assetStructFromResponse = assetStructListResponse.results.getObjects().get(0); +// assertThat(assetStructFromResponse.getParentId()).isEqualTo(assetStructParent.getId()); +// assertThat(assetStructFromResponse.getConnectedParentMetaId()).isEqualTo(sharedMetaString1.getMetaId()); +// assertThat(assetStructFromResponse.getConnectingMetaId()).isEqualTo(sharedMetaString2.getMetaId()); + + // 4rent folder has some logic + + // remove assetStructs + deleteVod(asset.getExternalId()); + deleteVod(asset2.getExternalId()); + deleteAssetStruct(assetStructChildren.getId()); // firstly should be deleted children + deleteAssetStruct(assetStructParent.getId()); + } + + // TODO: find better name and option to use it in the whole project + private Map loadMetas(Map metas) { + Map result = new HashMap<>(); + for (Map.Entry entry: metas.entrySet()) { + StringValue value = new StringValue(); + value.setValue(entry.getValue()); + //value.value(entry.getValue()); + result.put(entry.getKey(), value); + } + + return result; + } + + + // TODO: Check if it used after implementation + private List loadAssetStructsWithoutHierarchy(int countOfAssetStructs, List listOfAssetStructs) { + List result = new ArrayList<>(); + for (AssetStruct assetStruct: listOfAssetStructs) { + if ((result.size() < countOfAssetStructs) && (assetStruct.getParentId() == 0)) { + result.add(assetStruct); + } + } + return result; + } + + // added to play with methods that are going to be checked +// @Test +// public void sandbox() { +// String prefix = "MaxTest_assetStruct_"; +// +// Long assetStructId = sharedAssetStructListResponse.results.getObjects().get(0).getId(); +// +// AssetStructMetaFilter assetStructMetaFilter = new AssetStructMetaFilter(); +// assetStructMetaFilter.setAssetStructIdEqual(assetStructId); +// ListAssetStructMetaBuilder listAssetStructMetaBuilder = AssetStructMetaService.list(assetStructMetaFilter); +// Response> listAssetMetaStructResponse = executor.executeSync(listAssetStructMetaBuilder +// .setKs(getOperatorKs())); +// assertThat(listAssetMetaStructResponse.results.getTotalCount()).isGreaterThan(0); +// Long metaId = listAssetMetaStructResponse.results.getObjects().get(0).getMetaId(); +// +// String defaultIngestValue = prefix + "_defaultIngestValue"; +// String ingestReferencePath = prefix + "ingestReferencePath"; +// boolean isProtectFromIngest = false; +// boolean isInherited = true; +// AssetStructMeta assetStructMeta = getAssetStructMeta(defaultIngestValue, +// ingestReferencePath, isProtectFromIngest, isInherited); +// UpdateAssetStructMetaBuilder updateAssetStructMetaBuilder = +// new UpdateAssetStructMetaBuilder(assetStructId, metaId, assetStructMeta); +// Response assetStructMetaResponse = executor.executeSync(updateAssetStructMetaBuilder +// .setKs(getOperatorKs())); +// assertThat(assetStructMetaResponse.results.getAssetStructId()).isEqualTo(assetStructId); +// assertThat(assetStructMetaResponse.results.getMetaId()).isEqualTo(metaId); +// assertThat(assetStructMetaResponse.results.getDefaultIngestValue()).isEqualToIgnoringCase(defaultIngestValue); +// assertThat(assetStructMetaResponse.results.getIngestReferencePath()).isEqualToIgnoringCase(ingestReferencePath); +// assertThat(assetStructMetaResponse.results.getProtectFromIngest()).isEqualTo(isProtectFromIngest); +// //TODO: update library to have options compare it +// //assertThat(assetStructMetaResponse.results.getInherited()).isEqualTo(isInherited); +// +// // assetStructAdd +// AssetStruct assetStruct = getAssetStruct(prefix, DEFAULT_LANGUAGE, false, metaIds, null, null, null); +// AddAssetStructBuilder addAssetStructBuilder = AssetStructService.add(assetStruct); +// Response assetStructResponse = executor.executeSync(addAssetStructBuilder +// .setKs(getOperatorKs()).setLanguage("*")); +// AssetStruct assetStructFromResponse = assetStructResponse.results; +// assertThat(assetStructResponse.results.getSystemName()).isEqualToIgnoringCase(prefix + "_System_name"); +// +// assetStruct.setSystemName(prefix + "_System_name_upd"); +// +// // assetStructUpdate +// UpdateAssetStructBuilder updateAssetStructBuilder = AssetStructService.update(assetStructFromResponse.getId(), assetStruct); +// assetStructResponse = executor.executeSync(updateAssetStructBuilder +// .setKs(getOperatorKs()) +// .setLanguage("*")); +// assertThat(assetStructResponse.results.getSystemName()).isEqualToIgnoringCase(prefix + "_System_name_upd"); +// +// // assetStructDelete +// DeleteAssetStructBuilder deleteAssetStructBuilder = AssetStructService.delete(assetStructFromResponse.getId()); +// Response deleteAssetStructResponse = executor.executeSync(deleteAssetStructBuilder +// .setKs(getOperatorKs())); +// assertThat(deleteAssetStructResponse.results.booleanValue()).isEqualTo(true); +// } + +// @Test +// public void sandboxRemoveMetasAndTags() { +// IngestVodUtils.VodData vodData = getVodData(MOVIE, INSERT); +// MediaAsset movie = insertVod(vodData, true); +// +// assertThat(movie.getName()).isEqualTo(movie.getExternalId()); +// assertThat(movie.getDescription()).isEqualTo("description of " + movie.getExternalId()); +// // get all metas +// Set movieMetasNames = movie.getMetas().keySet(); +// int metasSizeAfterCreation = movieMetasNames.size(); +// int nonBasicMediaMetasCount = 0; +// assertThat(metasSizeAfterCreation).isGreaterThan(0); +// +// // get all tags +// Set movieTagsNames = movie.getTags().keySet(); +// int tagsSizeAfterCreation = movieTagsNames.size(); +// assertThat(tagsSizeAfterCreation).isGreaterThan(0); +// +// // get all metas and tags info to remove them from media +// List metaIds = new ArrayList<>(); +// int metaId; +// for (String metaName: movieMetasNames) { +// metaId = getMetaIdByName(metaName, false); +// if (metaId !=-1) { +// metaIds.add(String.valueOf(metaId)); +// nonBasicMediaMetasCount++; +// } +// } +// for (String metaName: movieTagsNames) { +// metaId = getMetaIdByName(metaName, true); +// if (metaId !=-1) { +// metaIds.add(String.valueOf(metaId)); +// } +// } +// String metaIdsIn = String.join(",", metaIds); +// +// // removeMetasAndTags +// RemoveMetasAndTagsAssetBuilder removeMetasAndTagsAssetBuilder = +// AssetService.removeMetasAndTags(movie.getId(), AssetReferenceType.MEDIA, metaIdsIn); +// Response booleanResponse = executor.executeSync(removeMetasAndTagsAssetBuilder +// .setKs(getOperatorKs())); +// assertThat(booleanResponse.results).isEqualTo(true); +// +// // check results +// GetAssetBuilder getAssetBuilder = AssetService.get(movie.getId().toString(), AssetReferenceType.MEDIA); +// Response assetResponse = executor.executeSync(getAssetBuilder +// .setKs(getOperatorKs())); +// movie = (MediaAsset) assetResponse.results; +// +// assertThat(movie.getName()).isEqualTo(movie.getExternalId()); +// assertThat(movie.getDescription()).isEqualTo("description of " + movie.getExternalId()); +// assertThat(movie.getMetas().keySet().size()).isEqualTo(metasSizeAfterCreation - nonBasicMediaMetasCount); +// assertThat(movie.getTags().keySet().size()).isEqualTo(0); +// +// // cleanup +// deleteVod(movie.getExternalId()); +// } + +// @Test +// public void sandboxDelete() { +// DeleteAssetStructBuilder deleteAssetStructBuilder = AssetStructService.delete(2381); +// Response deleteAssetStructResponse = executor.executeSync(deleteAssetStructBuilder +// .setKs(getOperatorKs())); +// assertThat(deleteAssetStructResponse.results.booleanValue()).isEqualTo(true); +// } + + @AfterClass() + public void tearDown() { + // cleaning created shared assetStructs + deleteAssetStruct(sharedAssetStruct1.getId()); + deleteAssetStruct(sharedAssetStruct2.getId()); + } + + void deleteAssetStruct(Long assetStructId) { + DeleteAssetStructBuilder deleteAssetStructBuilder = AssetStructService.delete(assetStructId); + Response deleteAssetStructResponse = executor.executeSync(deleteAssetStructBuilder + .setKs(getOperatorKs())); + assertThat(deleteAssetStructResponse.results.booleanValue()).isEqualTo(true); + } + + AssetStruct createAssetStruct(String prefix, String metaIds) { + AssetStruct result = getAssetStruct(prefix, DEFAULT_LANGUAGE, false, metaIds, null, + null, null); + + AddAssetStructBuilder addAssetStructBuilder = AssetStructService.add(result); + Response assetStructResponse = executor.executeSync(addAssetStructBuilder + .setKs(getOperatorKs()).setLanguage("*")); + result = assetStructResponse.results; + + assertThat(result.getSystemName()).isEqualToIgnoringCase(prefix + "_System_name"); + + return result; + } + + Response updateAssetStruct(Long assetStructId, AssetStruct updatedAssetStruct, boolean isErrorExpected) { + UpdateAssetStructBuilder updateAssetStructBuilder = AssetStructService.update( + assetStructId, updatedAssetStruct); + Response assetStructResponse = executor.executeSync(updateAssetStructBuilder + .setKs(getOperatorKs()).setLanguage("*")); + if (isErrorExpected) { + assertThat(assetStructResponse.error).isNotNull(); + } else { + assertThat(assetStructResponse.results).isNotNull(); + } + + return assetStructResponse; + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/featuresTests/versions/five_zero_two/IngestVodOpcTests.java b/src/test/java/com/kaltura/client/test/tests/featuresTests/versions/five_zero_two/IngestVodOpcTests.java new file mode 100644 index 000000000..bd2d88a5d --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/featuresTests/versions/five_zero_two/IngestVodOpcTests.java @@ -0,0 +1,652 @@ +package com.kaltura.client.test.tests.featuresTests.versions.five_zero_two; + +import com.kaltura.client.enums.AssetReferenceType; +import com.kaltura.client.services.LanguageService; +import com.kaltura.client.services.PpvService; +import com.kaltura.client.services.ProductPriceService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.BaseUtils; +import com.kaltura.client.test.utils.KsqlBuilder; +import com.kaltura.client.test.utils.dbUtils.DBUtils; +import com.kaltura.client.types.*; +import io.qameta.allure.Issue; +import io.qameta.allure.Link; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import io.restassured.response.Response; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import static com.kaltura.client.services.AssetService.*; +import static com.kaltura.client.services.AssetService.get; +import static com.kaltura.client.test.tests.enums.IngestAction.*; +import static com.kaltura.client.test.tests.enums.KsqlKey.MEDIA_ID; +import static com.kaltura.client.test.tests.enums.MediaType.*; +import static com.kaltura.client.test.utils.BaseUtils.*; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodOpcUtils.delayBetweenRetriesInSeconds; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodOpcUtils.*; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodOpcUtils.maxTimeExpectingValidResponseInSeconds; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.*; +import static io.restassured.path.xml.XmlPath.from; +import static java.util.TimeZone.getTimeZone; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.awaitility.Awaitility.await; + +/** + * + * Class to test functionality described in https://kaltura.atlassian.net/browse/BEO-5428 + */ +@Link(name = "OPC VOD Ingest", url = "BEO-5428") +@Test(groups = { "opc", "OPC VOD Ingest" }) +public class IngestVodOpcTests extends BaseTest { + private int movieType; + private int episodeType; + private int seriesType; + + @BeforeClass() + public void ingestVodOpcTests_beforeClass() { + movieType = DBUtils.getMediaTypeId(MOVIE); + episodeType = DBUtils.getMediaTypeId(EPISODE); + seriesType = DBUtils.getMediaTypeId(SERIES); + } + + @Severity(SeverityLevel.CRITICAL) + @Test(description = "ingest VOD with filled base meta fields") + public void insertVodMediaTagFieldName() { + VodData vodData = getVodData(MOVIE, INSERT); + MediaAsset movie = insertVod(vodData, true); + + assertThat(movie.getName()).isEqualTo(vodData.name()); + assertThat(movie.getDescription()).isEqualTo(vodData.description()); + assertThat(((MultilingualStringValue)movie.getMetas().get(mediaTextFieldName)).getValue()).isEqualTo(vodData.stringsMeta().get(mediaTextFieldName)); + assertThat(((DoubleValue)movie.getMetas().get(mediaNumberFieldName)).getValue()).isEqualTo(vodData.numbersMeta().get(mediaNumberFieldName)); + assertThat(getFormattedDate(((LongValue)movie.getMetas().get(mediaDateFieldName)).getValue(), getTimeZone("UTC"), "MM/dd/yyyy")).isEqualTo(vodData.datesMeta().get(mediaDateFieldName)); + assertThat(((BooleanValue)movie.getMetas().get(mediaBooleanFieldName)).getValue()).isEqualTo(vodData.booleansMeta().get(mediaBooleanFieldName)); + assertThat(movie.getTags().get(mediaTagFieldName).getObjects()).extracting("value").containsExactlyElementsOf(vodData.tags().get(mediaTagFieldName)); + assertFiles(vodData.files(), movie.getId().toString()); + assertThat(movie.getImages()).extracting("ratio").containsAll(vodData.thumbRatios()); + + // cleanup + deleteVod(movie.getExternalId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Test(description = "update VOD with filled base meta fields and erase = true") + public void updateVodMediaBaseFieldsWithErase() { + String coguid = getCoguidOfActiveMediaAsset(movieType); + VodData vodData = new VodData() + .name(String.valueOf(getEpochInMillis())) + .isErase(true); + + MediaAsset movie = updateVod(coguid, vodData); + + assertThat(movie.getName()).isEqualTo(vodData.name()); + assertThat(movie.getDescription()).isEqualTo(""); + + fail("ask Shir why some of the old data return while some being delete as expected"); + +// assertThat(((MultilingualStringValue)movie.getMetas().get(mediaTextFieldName)).getValue()).isEqualTo(vodData.strings().get(mediaTextFieldName)); +// assertThat(((DoubleValue)movie.getMetas().get(mediaNumberFieldName)).getValue()).isEqualTo(vodData.numbers().get(mediaNumberFieldName)); +// assertThat(getFormattedDate(((LongValue)movie.getMetas().get(mediaDateFieldName)).getValue(), getTimeZone("UTC"), "MM/dd/yyyy")).isEqualTo(vodData.dates().get(mediaDateFieldName)); +// assertThat(((BooleanValue)movie.getMetas().get(mediaBooleanFieldName)).getValue()).isEqualTo(vodData.booleans().get(mediaBooleanFieldName)); +// assertThat(movie.getTags().get(mediaTagFieldName).getObjects()).extracting("value").containsExactlyElementsOf(vodData.tags().get(mediaTagFieldName)); +// assertFiles(vodData.files(), movie.getId().toString()); +// assertThat(movie.getImages()).extracting("ratio").containsAll(vodData.thumbRatios()); + + } + + @Severity(SeverityLevel.CRITICAL) + @Test(description = "update VOD with filled base meta fields and erase = false") + public void updateVodMediaBaseFieldsWithoutErase() { + String coguid = getCoguidOfActiveMediaAsset(movieType); + VodData vodData = getVodData(MOVIE, UPDATE); + + MediaAsset movie = updateVod(coguid, vodData); + + assertThat(movie.getName()).isEqualTo(vodData.name()); + assertThat(movie.getDescription()).isEqualTo(vodData.description()); + assertThat(((MultilingualStringValue)movie.getMetas().get(mediaTextFieldName)).getValue()).isEqualTo(vodData.stringsMeta().get(mediaTextFieldName)); + assertThat(((DoubleValue)movie.getMetas().get(mediaNumberFieldName)).getValue()).isEqualTo(vodData.numbersMeta().get(mediaNumberFieldName)); + assertThat(getFormattedDate(((LongValue)movie.getMetas().get(mediaDateFieldName)).getValue(), getTimeZone("UTC"), "MM/dd/yyyy")).isEqualTo(vodData.datesMeta().get(mediaDateFieldName)); + assertThat(((BooleanValue)movie.getMetas().get(mediaBooleanFieldName)).getValue()).isEqualTo(vodData.booleansMeta().get(mediaBooleanFieldName)); + assertThat(movie.getTags().get(mediaTagFieldName).getObjects()).extracting("value").containsExactlyElementsOf(vodData.tags().get(mediaTagFieldName)); + assertFiles(vodData.files(), movie.getId().toString()); + assertThat(movie.getImages()).extracting("ratio").containsAll(vodData.thumbRatios()); + } + + @Severity(SeverityLevel.CRITICAL) + @Test(description = "ingest VOD with filled base meta fields") + public void insertVodEpisodeBaseFields() { + VodData vodData = getVodData(EPISODE, INSERT); + MediaAsset episode = insertVod(vodData, true); + + assertThat(episode.getName()).isEqualTo(vodData.name()); + assertThat(episode.getDescription()).isEqualTo(vodData.description()); + assertThat(((MultilingualStringValue) episode.getMetas().get(episodeTextFieldName)).getValue()).isEqualTo(vodData.stringsMeta().get(episodeTextFieldName)); + assertThat(((DoubleValue) episode.getMetas().get(episodeNumberFieldName)).getValue()).isEqualTo(vodData.numbersMeta().get(episodeNumberFieldName)); + assertThat(getFormattedDate(((LongValue) episode.getMetas().get(episodeDateFieldName)).getValue(), getTimeZone("UTC"), "MM/dd/yyyy")).isEqualTo(vodData.datesMeta().get(episodeDateFieldName)); + assertThat(((BooleanValue) episode.getMetas().get(episodeBooleanFieldName)).getValue()).isEqualTo(vodData.booleansMeta().get(episodeBooleanFieldName)); + assertThat(episode.getTags().get(episodeTagFieldName).getObjects()).extracting("value").containsExactlyElementsOf(vodData.tags().get(episodeTagFieldName)); + assertFiles(vodData.files(), episode.getId().toString()); + assertThat(episode.getImages()).extracting("ratio").containsAll(vodData.thumbRatios()); + + // cleanup + deleteVod(episode.getExternalId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Test(description = "ingest VOD with filled base meta fields") + public void insertVodSeriesBaseFields() { + VodData vodData = getVodData(SERIES, INSERT); + MediaAsset series = insertVod(vodData, true); + + assertThat(series.getName()).isEqualTo(vodData.name()); + assertThat(series.getDescription()).isEqualTo(vodData.description()); + assertThat(((StringValue) series.getMetas().get(seriesTextFieldName)).getValue()).isEqualTo(vodData.stringsMeta().get(seriesTextFieldName)); + assertThat(((DoubleValue) series.getMetas().get(seriesNumberFieldName)).getValue()).isEqualTo(vodData.numbersMeta().get(seriesNumberFieldName)); + assertThat(getFormattedDate(((LongValue) series.getMetas().get(seriesDateFieldName)).getValue(), getTimeZone("UTC"), "MM/dd/yyyy")).isEqualTo(vodData.datesMeta().get(seriesDateFieldName)); + assertThat(((BooleanValue) series.getMetas().get(seriesBooleanFieldName)).getValue()).isEqualTo(vodData.booleansMeta().get(seriesBooleanFieldName)); + assertThat(series.getTags().get(seriesTagFieldName).getObjects()).extracting("value").containsExactlyElementsOf(vodData.tags().get(seriesTagFieldName)); + assertFiles(vodData.files(), series.getId().toString()); + assertThat(series.getImages()).extracting("ratio").containsAll(vodData.thumbRatios()); + + // cleanup + deleteVod(series.getExternalId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Test(description = "update VOD episode with filled base meta fields") + public void updateVodEpisodeBaseFields() { + VodData vodData = getVodData(EPISODE, UPDATE); + + String coguid = getCoguidOfActiveMediaAsset(episodeType); + MediaAsset episode = updateVod(coguid, vodData); + + assertThat(episode.getName()).isEqualTo(vodData.name()); + assertThat(episode.getDescription()).isEqualTo(vodData.description()); + assertThat(((MultilingualStringValue) episode.getMetas().get(episodeTextFieldName)).getValue()).isEqualTo(vodData.stringsMeta().get(episodeTextFieldName)); + assertThat(((DoubleValue) episode.getMetas().get(episodeNumberFieldName)).getValue()).isEqualTo(vodData.numbersMeta().get(episodeNumberFieldName)); + assertThat(getFormattedDate(((LongValue) episode.getMetas().get(episodeDateFieldName)).getValue(), getTimeZone("UTC"), "MM/dd/yyyy")).isEqualTo(vodData.datesMeta().get(episodeDateFieldName)); + assertThat(((BooleanValue) episode.getMetas().get(episodeBooleanFieldName)).getValue()).isEqualTo(vodData.booleansMeta().get(episodeBooleanFieldName)); + assertThat(episode.getTags().get(episodeTagFieldName).getObjects()).extracting("value").containsExactlyElementsOf(vodData.tags().get(episodeTagFieldName)); +// assertFiles(vodData.files(), episode.getId().toString()); + assertThat(episode.getImages()).extracting("ratio").containsAll(vodData.thumbRatios()); + } + + @Severity(SeverityLevel.CRITICAL) + @Test(description = "update VOD series with filled base meta fields") + public void updateVodSeriesBaseFields() { + VodData vodData = getVodData(SERIES, UPDATE); + + String coguid = getCoguidOfActiveMediaAsset(seriesType); + MediaAsset series = updateVod(coguid, vodData); + + assertThat(series.getName()).isEqualTo(vodData.name()); + assertThat(series.getDescription()).isEqualTo(vodData.description()); + assertThat(((StringValue) series.getMetas().get(seriesTextFieldName)).getValue()).isEqualTo(vodData.stringsMeta().get(seriesTextFieldName)); + assertThat(((DoubleValue) series.getMetas().get(seriesNumberFieldName)).getValue()).isEqualTo(vodData.numbersMeta().get(seriesNumberFieldName)); + assertThat(getFormattedDate(((LongValue) series.getMetas().get(seriesDateFieldName)).getValue(), getTimeZone("UTC"), "MM/dd/yyyy")).isEqualTo(vodData.datesMeta().get(seriesDateFieldName)); + assertThat(((BooleanValue) series.getMetas().get(seriesBooleanFieldName)).getValue()).isEqualTo(vodData.booleansMeta().get(seriesBooleanFieldName)); + assertThat(series.getTags().get(seriesTagFieldName).getObjects()).extracting("value").containsExactlyElementsOf(vodData.tags().get(seriesTagFieldName)); +// assertFiles(vodData.files(), series.getId().toString()); + assertThat(series.getImages()).extracting("ratio").containsAll(vodData.thumbRatios()); + } + + @Severity(SeverityLevel.CRITICAL) + @Test(description = "delete movie") + public void deleteMovie() { + String coguid = getCoguidOfActiveMediaAsset(movieType); + assertVodDeletion(coguid); + } + + @Severity(SeverityLevel.CRITICAL) + @Test(description = "delete episode") + public void deleteEpisode() { + String coguid = getCoguidOfActiveMediaAsset(episodeType); + assertVodDeletion(coguid); + } + + @Severity(SeverityLevel.CRITICAL) + @Test(description = "delete series") + public void deleteSeries() { + String coguid = getCoguidOfActiveMediaAsset(seriesType); + assertVodDeletion(coguid); + } + + @Severity(SeverityLevel.NORMAL) + @Test(description = "try insert without coguid") + public void insertWithEmptyCoguid() { + // insert with empty coguid + VodData vodData = getVodData(MOVIE, INSERT).coguid(""); + String invalidXml = buildIngestVodXml(vodData, INSERT); + Response resp = executeIngestVodRequest(invalidXml); + + assertThat(from(resp.asString()).getString(ingestAssetStatusMessagePath)).contains("External identifier is missing"); + + // insert without coguid attribute + invalidXml = invalidXml.replaceAll("co_guid=\"\"", ""); + resp = executeIngestVodRequest(invalidXml); + + assertThat(from(resp.asString()).getString(ingestAssetStatusMessagePath)).contains("External identifier is missing"); + } + + @Severity(SeverityLevel.NORMAL) + @Test(description = "try delete without coguid") + public void deleteWithEmptyCoguid() { + // delete with empty coguid + String invalidXml = buildIngestVodXml(new VodData(), DELETE); + Response resp = executeIngestVodRequest(invalidXml); + + assertThat(from(resp.asString()).getString(ingestAssetStatusMessagePath)).contains("External identifier is missing"); + + // delete with missing coguid attribute + invalidXml = invalidXml.replaceAll("co_guid=\"\"", ""); + resp = executeIngestVodRequest(invalidXml); + + assertThat(from(resp.asString()).getString(ingestAssetStatusMessagePath)).contains("External identifier is missing"); + } + + @Severity(SeverityLevel.NORMAL) + @Test(description = "try delete with non-existed coguid") + public void deleteWithNonExistedCoguid() { + String invalidCoguid = "123456"; + VodData vodData = new VodData().coguid(invalidCoguid); + String invalidXml = buildIngestVodXml(vodData, DELETE); + Response resp = executeIngestVodRequest(invalidXml); + + assertThat(from(resp.asString()).getString(ingestAssetStatusWarningMessagePath)).contains("Media Id not exist"); + } + + @Severity(SeverityLevel.MINOR) + @Test(description = "try insert with empty entry_id") + public void insertWithEmptyEntryId() { + VodData vodData = getVodData(MOVIE, INSERT); + String ingestInsertXml = buildIngestVodXml(vodData, INSERT); + + // entry_id tag empty + String invalidXml = ingestInsertXml.replaceAll("entry_id=\"entry_" + vodData.coguid() + "\"", "entry_id=\"\""); + Response resp = executeIngestVodRequest(invalidXml); + + assertThat(from(resp.asString()).getString(ingestAssetStatusWarningMessagePath)).contains("entry_id is missing"); + + // without entry_id tag + invalidXml = ingestInsertXml.replaceAll("entry_id=\"entry_" + vodData.coguid() + "\"", ""); + resp = executeIngestVodRequest(invalidXml); + + assertThat(from(resp.asString()).getString(ingestAssetStatusWarningMessagePath)).contains("entry_id is missing"); + } + + @Severity(SeverityLevel.MINOR) + @Test(description = "try insert inactive item") + public void insertInactiveItem() { + VodData vodData = getVodData(MOVIE, INSERT).isActive(false); + String invalidXml = buildIngestVodXml(vodData, INSERT); + + Response resp = executeIngestVodRequest(invalidXml); + String id = from(resp.asString()).get(ingestAssetIdPath).toString(); + + SearchAssetFilter assetFilter = new SearchAssetFilter(); + String query = new KsqlBuilder().equal(MEDIA_ID.getValue(), id).toString(); + assetFilter.setKSql(query); + + ListResponse assetListResponse = executor.executeSync(list(assetFilter) + .setKs(getAnonymousKs())) + .results; + assertThat(assetListResponse.getTotalCount()).isEqualTo(0); + } + + @Severity(SeverityLevel.MINOR) + @Test(description = "try insert with empty isActive parameter") + public void insertEmptyIsActive() { + String ingestInsertXml = buildIngestVodXml(getVodData(MOVIE, INSERT), INSERT); + String invalidXml = ingestInsertXml.replaceAll("is_active=\"true\"", "is_active=\"\""); + + Response resp = executeIngestVodRequest(invalidXml); + assertThat(from(resp.asString()).getString(ingestAssetStatusMessagePath)).isEqualTo("media.IsActive cannot be empty"); + } + + @Severity(SeverityLevel.MINOR) + @Test(description = "try insert with empty name") + public void insertWithEmptyName() { + // empty name value tag + VodData vodData = new VodData().mediaType(MOVIE).coguid(String.valueOf(getEpochInMillis())).name(""); + String invalidXml = buildIngestVodXml(vodData, INSERT); + + Response resp = executeIngestVodRequest(invalidXml); + assertThat(from(resp.asString()).getString(ingestAssetStatusMessagePath)).isEqualTo("media.basic.name.value.text cannot be empty"); + + // empty name tag + VodData vodData1 = new VodData().mediaType(MOVIE).coguid(String.valueOf(getEpochInMillis())); + invalidXml = buildIngestVodXml(vodData1, INSERT); + + resp = executeIngestVodRequest(invalidXml); + assertThat(from(resp.asString()).getString(ingestAssetStatusMessagePath)).isEqualTo("media.basic.name cannot be empty"); + } + + @Severity(SeverityLevel.NORMAL) + @Test(description = "try insert with invalid credentials") + public void insertWithInvalidCredentials() { + String statusMessage = "Invalid credentials"; + String status = "ERROR"; + String ingestInsertXml = buildIngestVodXml(new VodData(), INSERT); + + // TODO: 9/17/2018 fix the test to support dynamic accounts + + // invalid user name + String invalidXml = ingestInsertXml.replaceAll("Name>Test_API_27_03<", "Name>aTest_API_27_03<"); + Response resp = executeIngestVodRequest(invalidXml); + + assertThat(from(resp.asString()).getString(ingestStatusMessagePath)).isEqualTo(statusMessage); + assertThat(from(resp.asString()).getString(ingestStatusPath)).isEqualTo(status); + + // invalid password + invalidXml = ingestInsertXml.replaceAll("passWord>Test_API_27_03<", "passWord>aTest_API_27_03<"); + resp = executeIngestVodRequest(invalidXml); + + assertThat(from(resp.asString()).getString(ingestStatusMessagePath)).isEqualTo(statusMessage); + assertThat(from(resp.asString()).getString(ingestStatusPath)).isEqualTo(status); + } + + @Severity(SeverityLevel.NORMAL) + @Test(description = "try insert with invalid meta or tag field") + public void insertWithInvalidMetaOrTagField() { + String suffix = "_" + getEpoch(); + VodData vodData = getVodData(MOVIE, INSERT); + + String updatedField = mediaNumberFieldName + suffix; + vodData.numbersMeta(Map.of(updatedField, getRandomDouble())); + assertInvalidMovieField(vodData, updatedField, "meta"); + vodData.numbersMeta(Map.of()); + + updatedField = mediaBooleanFieldName + suffix; + vodData.booleansMeta(Map.of(updatedField, getRandomBoolean())); + assertInvalidMovieField(vodData, updatedField, "meta"); + vodData.booleansMeta(Map.of()); + + updatedField = mediaTagFieldName + suffix; + vodData.tags(Map.of(updatedField, List.of(String.valueOf(getEpochInMillis())))); + assertInvalidMovieField(vodData, updatedField, "tag"); + vodData.tags(Map.of()); + + updatedField = mediaTextFieldName + suffix; + vodData.stringsMeta(Map.of(updatedField, getRandomString())); + assertInvalidMovieField(vodData, updatedField, "meta"); + vodData.stringsMeta(Map.of()); + + updatedField = mediaDateFieldName + suffix; + vodData.datesMeta(Map.of(updatedField, BaseUtils.getCurrentDateInFormat("yyyyMMddHHmmss"))); + assertInvalidMovieField(vodData, updatedField, "meta"); + vodData.datesMeta(Map.of()); + } + + @Severity(SeverityLevel.NORMAL) + @Test(description = "insert multilingual fields", enabled = true) + public void insertMultiLingualFields() { + // TODO: 9/17/2018 complete test + // set multi languages + List languages = executor.executeSync(LanguageService.list(new LanguageFilter()) + .setKs(getOperatorKs())) + .results + .getObjects(); + String lang1 = languages.get(0).getCode(); + String lang2 = languages.get(1).getCode(); + + // prepare data + String lang1Name = getRandomString(); + String lang2Name = getRandomString(); + String lang1Description = "description_" + lang1Name; + String lang2Description = "description_" + lang2Name; + String lang1Meta = "meta_" + lang1Name; + String lang2Meta = "meta_" + lang2Name; + String lang1Tag = "tag_" + lang1Name; + String lang2Tag = "tag_" + lang2Name; + + // set strings meta + List metaNames = Arrays.asList("shmulik_str3", "BoxOffice", "alon_test2"); + Map> metas = new HashMap<>(); + metas.put(metaNames.get(0), Map.of(lang1, lang1Meta, lang2, lang2Meta)); + metas.put(metaNames.get(1), Map.of(lang1, lang1Meta, lang2, lang2Meta)); + metas.put(metaNames.get(2), Map.of(lang1, lang1Meta, lang2, lang2Meta)); + + // set tags + Map>> tags = new HashMap<>(); + tags.put("Actors", Arrays.asList(Map.of(lang1, lang1Tag, lang2, lang2Tag), Map.of(lang1, lang1Tag, lang2, lang2Tag), Map.of(lang1, lang1Tag, lang2, lang2Tag))); + tags.put("TagsTest", Arrays.asList(Map.of(lang1, lang1Tag, lang2, lang2Tag), Map.of(lang1, lang1Tag, lang2, lang2Tag), Map.of(lang1, lang1Tag, lang2, lang2Tag))); + + // ingest vod + VodData vodData = getVodData(MOVIE, INSERT) + .multilingualName(Map.of(lang1, lang1Name, lang2, lang2Name)) + .multilingualDescription(Map.of(lang1, lang1Description, lang2, lang2Description)) + .multilingualStringsMeta(metas) + .multilingualTags(tags); + MediaAsset asset = insertVod(vodData, false); + + // assert multilingual data + // assert lang1 asset + Asset lang1Asset = executor.executeSync(get(String.valueOf(asset.getId()), AssetReferenceType.MEDIA) + .setKs(getAnonymousKs()) + .setLanguage(lang1)) + .results; + + // assert name + assertThat(lang1Asset.getName()).isEqualTo(lang1Name); + + // assert description + assertThat(lang1Asset.getDescription()).isEqualTo(lang1Description); + + // aasert metas + assertThat(lang1Asset.getMetas().keySet()).containsAll(metaNames); + lang1Asset.getMetas().forEach((s, value) -> System.out.println(s + "_" + value.getDescription())); +// assertThat(((MultilingualStringValue)asset.getMetas().get(mediaTextFieldName)).getValue()) +// .isEqualTo(stringMetaDataValue + JAP); + + // assert tags +// boolean isTagValueFound = isTagValueFound(tagValue1 + JAP, asset); +// assertThat(isTagValueFound).isEqualTo(true); + + // lang2 + Asset lang2Asset = executor.executeSync(get(String.valueOf(asset.getId()), AssetReferenceType.MEDIA) + .setKs(getAnonymousKs()) + .setLanguage(lang2)) + .results; + + assertThat(lang2Asset.getName()).isEqualTo(lang2Name); + assertThat(lang2Asset.getDescription()).isEqualTo(lang2Description); +// assertThat(((MultilingualStringValue)asset.getMetas().get(mediaTextFieldName)).getValue()).isEqualTo(stringMetaDataValue); +// // check tag value +// isTagValueFound = isTagValueFound(tagValue1, asset); +// assertThat(isTagValueFound).isEqualTo(true); + } + + @Severity(SeverityLevel.MINOR) + @Test(description = "ingest VOD with empty images urls") + public void insertVodMediaBaseWithEmptyImageUrl() { + // empty thumb tag + VodData vodData = getVodData(MOVIE, INSERT).thumbUrl(""); + String ingestXml = buildIngestVodXml(vodData, INSERT); + + Response resp = executeIngestVodRequest(ingestXml); + assertThat(from(resp.asString()).getString(ingestAssetStatusWarningMessagePath)).contains("InvalidUrlForImageInvalidUrlForImage"); + } + + @Severity(SeverityLevel.MINOR) + @Test(description = "ingest VOD files with same coguid") + public void insertVodMediaBaseFilesWithSameCoguid() { + // empty images tag + VodData vodData = getVodData(MOVIE, INSERT); + long epoch = getEpoch(); + vodData.files().get(0).coguid(String.valueOf(epoch)); + vodData.files().get(1).coguid(String.valueOf(epoch)); + String ingestXml = buildIngestVodXml(vodData, INSERT); + + Response resp = executeIngestVodRequest(ingestXml); + assertThat(from(resp.asString()).getString(ingestAssetStatusWarningMessagePath)).contains("MediaFileExternalIdMustBeUnique"); + } + + @Issue("BEO-5584") + @Severity(SeverityLevel.CRITICAL) + @Test(description = "ingest VOD with different Ppv", enabled = false) + public void updateVodMediaPpv() { + List ppvNames = DBUtils.getPpvNames(4); + + // insert vod + List files = getDefaultAssetFiles(ppvNames.get(0), ppvNames.get(1)); + VodData vodData = getVodData(MOVIE, INSERT).files(files); + MediaAsset movie = insertVod(vodData, true); + + // update ppvs + files.get(0).ppvModule(ppvNames.get(2)); + files.get(1).ppvModule(ppvNames.get(3)); + vodData = new VodData().files(files); + movie = updateVod(movie.getExternalId(), vodData); + + List mediaFiles = movie.getMediaFiles(); + assertThat(mediaFiles.size()).isEqualTo(2); + + // assert ppvs update + ProductPriceFilter filter = new ProductPriceFilter(); + List fileIds = Arrays.asList(String.valueOf(mediaFiles.get(0).getId()), String.valueOf(mediaFiles.get(1).getId())); + filter.setFileIdIn(getConcatenatedString(fileIds)); + + com.kaltura.client.utils.response.base.Response> productPriceListResponse = executor.executeSync(ProductPriceService.list(filter).setKs(getAnonymousKs())); + PpvPrice ppvPrice1 = (PpvPrice) productPriceListResponse.results.getObjects().get(0); + + String ppvName1 = executor.executeSync(PpvService.get(Long.parseLong(ppvPrice1 + .getPpvModuleId())) + .setKs(getAnonymousKs())) + .results + .getName(); + + System.out.println(ppvName1); + + // TODO: 9/17/2018 complete the test after the bug will be fixed + } + + @Severity(SeverityLevel.CRITICAL) + @Test(description = "update VOD images") + public void updateImages() { + // insert vod + VodData vodData = getVodData(MOVIE, INSERT); + MediaAsset mediaAsset = insertVod(vodData, true); + + // get list of original images + List originalImages = mediaAsset.getImages(); + assertThat(originalImages.size()).isEqualTo(3); + + // update vod images - enter 2 new images + List newRatios = Arrays.asList("2:1", "2:3"); + String fakeImageUrl = "https://picsum.photos/200/300/?random"; + + VodData updateVodData = new VodData() + .thumbUrl(fakeImageUrl) + .thumbRatios(newRatios); + mediaAsset = updateVod(mediaAsset.getExternalId(), updateVodData); + + // assert update + List images = mediaAsset.getImages(); + assertThat(images.size()).isEqualTo(5); + + List newImages = images.stream() + .filter(image -> originalImages.stream() + .map(MediaImage::getRatio) + .noneMatch(s1 -> s1.equals(image.getRatio()))) + .collect(Collectors.toList()); + + newImages.forEach(image -> assertThat(image.getUrl()).isNotEmpty()); + assertThat(newImages).extracting("ratio").containsExactlyInAnyOrderElementsOf(newRatios); + } + + @Issue("BEO-5536") + @Severity(SeverityLevel.CRITICAL) + @Test(description = "update VOD files") + public void updateFiles() { + // insert vod + List fileTypeNames = DBUtils.getMediaFileTypeNames(2); + List ppvNames = DBUtils.getPpvNames(2); + + VodData vodData = getVodData(MOVIE, INSERT); + List files = get2AssetFiles(fileTypeNames.get(0), fileTypeNames.get(1), ppvNames.get(0), ppvNames.get(1)); + vodData.files(files); + MediaAsset mediaAsset = insertVod(vodData, true); + + // update vod images + long e = getEpoch(); + String r = String.valueOf(getRandomLong()); + + String coguid1 = "file_1_" + e + "_" + r; + String coguid2 = "file_2_" + e + "_" + r; + + files.get(0).coguid(coguid1).assetDuration("5"); + files.get(1).coguid(coguid2).assetDuration("5"); + + VodData updateVodData = new VodData() + .files(files); + List mediaFiles = updateVod(mediaAsset.getExternalId(), updateVodData).getMediaFiles(); + + // assert update + assertThat(mediaFiles.size()).isEqualTo(2); + mediaFiles.forEach(file -> assertThat(file.getDuration()).isEqualTo(5)); + assertThat(mediaFiles).extracting("externalId").containsExactlyInAnyOrder(coguid1, coguid2); + + // cleanup + deleteVod(mediaAsset.getExternalId()); + } + + + // help methods + void assertInvalidMovieField(VodData vodData, String fieldName, String fieldType) { + Response resp = executeIngestVodRequest(buildIngestVodXml(vodData, INSERT)); + + assertThat(from(resp.asString()).getString(ingestAssetStatusMessagePath)) + .isEqualTo(fieldType + ": " + fieldName + " does not exist for group"); + } + + void assertVodDeletion(String coguid) { + SearchAssetFilter assetFilter = new SearchAssetFilter(); + assetFilter.setKSql(new KsqlBuilder().equal("externalId", coguid).toString()); + + com.kaltura.client.utils.response.base.Response> assetListResponse = executor.executeSync(list(assetFilter) + .setKs(getAnonymousKs())); + + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(1); + + deleteVod(coguid); + + ListAssetBuilder listAssetBuilder = list(assetFilter).setKs(getAnonymousKs()); + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() -> (executor.executeSync(listAssetBuilder).results.getTotalCount() == 0)); + } + + // to check that ingested file data are corresponding to getAsset file data + private void assertFiles(List ingestAssetFiles, String assetId) { + boolean isFileWasFound = false; + + GetAssetBuilder assetBuilder = get(assetId, AssetReferenceType.MEDIA).setKs(getAnonymousKs()); + com.kaltura.client.utils.response.base.Response assetGetResponse = executor.executeSync(assetBuilder); + List getMediaFiles = assetGetResponse.results.getMediaFiles(); + + for (VodFile ingestFile: ingestAssetFiles) { + for (MediaFile getFile: getMediaFiles) { + if (getFile.getType().equals(ingestFile.type())) { + isFileWasFound = true; + assertThat(getFile.getDuration().toString()).isEqualTo(ingestFile.assetDuration()); + assertThat(getFile.getUrl()).isEqualTo(ingestFile.cdn_code()); + assertThat(getFile.getAltStreamingCode()).isEqualTo(ingestFile.alt_cdn_code()); + assertThat(getFile.getExternalStoreId()).isEqualTo(ingestFile.product_code()); + assertThat(getFile.getExternalId()).isEqualTo(ingestFile.coguid()); + } + } + } + assertThat(isFileWasFound).isEqualTo(true); + } +} \ No newline at end of file diff --git a/src/test/java/com/kaltura/client/test/tests/featuresTests/versions/four_eight/PermissionsManagementTests.java b/src/test/java/com/kaltura/client/test/tests/featuresTests/versions/four_eight/PermissionsManagementTests.java new file mode 100644 index 000000000..e6b742035 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/featuresTests/versions/four_eight/PermissionsManagementTests.java @@ -0,0 +1,497 @@ +package com.kaltura.client.test.tests.featuresTests.versions.four_eight; + +import com.kaltura.client.test.utils.BaseUtils; +import com.kaltura.client.test.utils.PermissionManagementUtils; +import com.kaltura.client.test.utils.dbUtils.PermissionsManagementDBUtils; +import io.qameta.allure.Issue; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.apache.commons.io.FileUtils; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import java.io.*; +import java.util.List; +import static com.kaltura.client.test.utils.BaseUtils.deleteFile; +import static com.kaltura.client.test.utils.BaseUtils.getFileContent; +import static com.kaltura.client.test.utils.PermissionManagementUtils.*; +import static com.kaltura.client.test.utils.dbUtils.PermissionsManagementDBUtils.*; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Class to test functionality described in https://kaltura.atlassian.net/browse/BEO-4885 + * started in 4_8 and completed in 5_0_3 + */ +@Test(groups = {"Permission management"}) +public class PermissionsManagementTests { + + // these files added into project + String importOnly4TablesFilePath; + String path2EmptyFile; + + @BeforeClass + public void setUp() { + ClassLoader classLoader = PermissionsManagementTests.class.getClassLoader(); + File file = new File(classLoader.getResource("permission_management_data/empty_file.txt").getFile()); + path2EmptyFile = file.getAbsolutePath(); + file = new File(classLoader.getResource("permission_management_data/importOnly4Tables.txt").getFile()); + importOnly4TablesFilePath = file.getAbsolutePath(); + } + + public static final String EXPORT_KEY = "e="; + public static final String IMPORT_KEY = "i="; + public static final String DELETE_KEY = "d="; + public static final String EXPORT_JSON_KEY = "n="; + public static final String IMPORT_JSON_KEY = "l="; + + @Severity(SeverityLevel.MINOR) + @Test(description = "execute console util without parameters") + public void runningWithoutParameters() { + List commands = getConsoleCommand(fullPath2Util, ""); + String consoleOutput = executeCommandsInConsole(commands); + + assertThat(consoleOutput).contains("Permissions deployment tool"); + assertThat(consoleOutput).contains("Shortcut: e"); + assertThat(consoleOutput).contains("Shortcut: i"); + assertThat(consoleOutput).contains("Shortcut: d"); + assertThat(consoleOutput).contains("Shortcut: n"); + assertThat(consoleOutput).contains("Shortcut: l"); + } + + @Severity(SeverityLevel.MINOR) + @Issue("BEO-5504") + @Test(description = "execute console util to export without mentioned file") + public void runningExportWithoutFile() { + List commands = getConsoleCommand(fullPath2Util, EXPORT_KEY); + String consoleOutput = executeCommandsInConsole(commands); + + assertThat(consoleOutput).contains("The system cannot find the file specified"); + } + + @Severity(SeverityLevel.MINOR) + @Issue("BEO-5504") + @Test(description = "execute console util to import without mentioned file") + public void runningImportWithoutFile() { + List commands = getConsoleCommand(fullPath2Util, IMPORT_KEY); + String consoleOutput = executeCommandsInConsole(commands); + + assertThat(consoleOutput).contains("The system cannot find the file specified"); + } + + @Severity(SeverityLevel.MINOR) + @Issue("BEO-5504") + @Test(description = "execute console util to delete without mentioned file") + public void runningDeleteWithoutFile() { + List commands = getConsoleCommand(fullPath2Util, DELETE_KEY); + String consoleOutput = executeCommandsInConsole(commands); + + assertThat(consoleOutput).contains("The system cannot find the file specified"); + } + + @Severity(SeverityLevel.CRITICAL) + @Test(description = "execute console util to export data from DB into file") + public void export() { + // prepare data inserting them in DB using stored procedures + String suffix = String.valueOf(BaseUtils.getEpoch()); + String roleName = "MaxTest" + suffix; + String permissionItemName = "Asset_List_Max" + suffix; + PermissionManagementUtils.insertDataInAllTables(generatedDataFilePath, roleName, "partner*", + permissionItemName, "asset", "list", "permissionItemObject" + suffix, + "parameter" + suffix, false); + + // export from DB + List commands = getConsoleCommand(fullPath2Util, EXPORT_KEY + dataFilePath); + executeCommandsInConsole(commands); + + // checks that created file contains inserted data + String fileContent = getFileContent(dataFilePath); + assertThat(fileContent).contains(roleName); + assertThat(fileContent).contains(permissionItemName); + assertThat(fileContent).contains("permissionItemObject" + suffix); + assertThat(fileContent).contains("parameter" + suffix); + + // cleaning + int idRoleHavingName = getIdRecordHavingRoleNameInRoles(roleName, 0); + PermissionsManagementDBUtils.deleteRoleAndItsPermissions(idRoleHavingName); + int idPermissionItemHavingName = getIdRecordHavingNameInPermissionItems(permissionItemName); + PermissionsManagementDBUtils.deletePermissionItem(idPermissionItemHavingName); + int idPermissionHavingName = getIdRecordHavingRoleNameInPermissions(roleName, 0); + PermissionsManagementDBUtils.deletePermission(idPermissionHavingName); + } + + @Severity(SeverityLevel.MINOR) + @Test(description = "execute console util to import data into DB from file having only 4 tables instead of 5") + public void runningImportFromFileNotHavingAllTables() { + // remove log file + deleteFile(path2Log); + + // try to import into DB + List commands = getConsoleCommand(fullPath2Util, IMPORT_KEY + importOnly4TablesFilePath); + executeCommandsInConsole(commands); + + String fileContent = getFileContent(path2Log); + assertThat(fileContent).contains("Import failed: reading from XML resulted in empty data set or data set with less than 5 tables"); + } + + @Severity(SeverityLevel.MINOR) + @Test(description = "execute console util to try import data into DB from empty file") + public void runningImportFromEmptyFile() { + // remove log file + deleteFile(path2Log); + + // try to import into DB + List commands = getConsoleCommand(fullPath2Util, IMPORT_KEY + path2EmptyFile); + executeCommandsInConsole(commands); + + String fileContent = getFileContent(path2Log); + assertThat(fileContent).contains("Failed importing permissions, ex = System.Xml.XmlException: Root element is missing"); + } + + @Severity(SeverityLevel.MINOR) + @Test(description = "execute console util to try delete data from DB using empty file") + public void runningDeleteUsingEmptyFile() { + // remove log file + deleteFile(path2Log); + + // try to import into DB + List commands = getConsoleCommand(fullPath2Util, DELETE_KEY + path2EmptyFile); + executeCommandsInConsole(commands); + + String fileContent = getFileContent(path2Log); + assertThat(fileContent).contains("Failed deleting permissions, ex = System.Xml.XmlException: Root element is missing"); + } + + @Severity(SeverityLevel.CRITICAL) + @Test(description = "execute console util to import data into DB from valid file") + public void importFromFile() { + String suffix = String.valueOf(BaseUtils.getEpoch()); + String roleName = "MaxTest" + suffix; + String permissionItemName = "Asset_List_Max" + suffix; + PermissionManagementUtils.generateFileWithInsertedIntoDBData(generatedDataFilePath, roleName, "partner*", + permissionItemName, "asset", "list", "permissionItemObject" + suffix, + "parameter" + suffix, 1, 2, 3, 4, 5, false); + + // import into DB + List commands = getConsoleCommand(fullPath2Util, IMPORT_KEY + generatedDataFilePath); + executeCommandsInConsole(commands); + + // check data in DB + int rowsInRolesHavingName = getCountRowsHavingRoleNameInRoles(roleName, 0); + assertThat(rowsInRolesHavingName).isEqualTo(1); + int idRoleHavingName = getIdRecordHavingRoleNameInRoles(roleName, 0); + + int rowsInPermissionsHavingName = getCountRowsHavingRoleNameInPermissions(roleName, 0); + assertThat(rowsInPermissionsHavingName).isEqualTo(1); + int idPermissionHavingName = getIdRecordHavingRoleNameInPermissions(roleName, 0); + + int idRolePermission = getCountSpecificRowsFromRolesPermissions(idRoleHavingName, idPermissionHavingName, 0); + assertThat(idRolePermission).isEqualTo(1); + + int rowsInPermissionItemsHavingName = getCountRowsHavingNameInPermissionItems(permissionItemName); + assertThat(rowsInPermissionItemsHavingName).isEqualTo(1); + int idPermissionItemHavingName = getIdRecordHavingNameInPermissionItems(permissionItemName); + + int rowsInPermissionsPermissions = getCountSpecificRowsFromPermissionsPermissionsItems(idPermissionHavingName, + idPermissionItemHavingName, 0); + assertThat(rowsInPermissionsPermissions).isEqualTo(1); + + // cleaning + PermissionsManagementDBUtils.deleteRoleAndItsPermissions(idRoleHavingName); + PermissionsManagementDBUtils.deletePermissionItem(idPermissionItemHavingName); + PermissionsManagementDBUtils.deletePermission(idPermissionHavingName); + } + + @Severity(SeverityLevel.NORMAL) + @Test(description = "execute console util to check items from DB not mentioned in import file should be mentioned in log") + public void runningImportToCheckLogHasItemsFromDBNotMentionedInFile() { + // remove log file + deleteFile(path2Log); + + // insert data in DB to check they will be mentioned in log file + String suffix1 = String.valueOf(BaseUtils.getEpoch()) + "inserted"; + String roleName1 = "MaxTest" + suffix1; + String permissionItemName1 = "Asset_List_Max" + suffix1; + PermissionManagementUtils.insertDataInAllTables(generatedDataFilePath, roleName1, "partner*", + permissionItemName1, "asset", "list", "permissionItemObject" + suffix1, + "parameter" + suffix1, false); + String filePath2Check = generatedDataFilePath; + + // generate import file data + String suffix = String.valueOf(BaseUtils.getEpoch()); + String roleName = "MaxTest" + suffix; + String permissionItemName = "Asset_List_Max" + suffix; + PermissionManagementUtils.generateFileWithInsertedIntoDBData(generatedDataFilePath, roleName, "partner*", + permissionItemName, "asset", "list", "permissionItemObject" + suffix, + "parameter" + suffix, 1, 2, 3, 4, 5, false); + + // import into DB + List commands = getConsoleCommand(fullPath2Util, IMPORT_KEY + generatedDataFilePath); + executeCommandsInConsole(commands); + + String fileContent = getFileContent(path2Log); + int idRoleHavingName = getIdRecordHavingRoleNameInRoles(roleName1, 0); + assertThat(fileContent).contains("!!NOT EXISTS IN SOURCE!! Table : role Id : " + idRoleHavingName + " Name : " + "MaxTest" + suffix1); + + // cleaning + PermissionsManagementDBUtils.deleteRoleAndItsPermissions(idRoleHavingName); + int idPermissionItemHavingName = getIdRecordHavingNameInPermissionItems(permissionItemName1); + PermissionsManagementDBUtils.deletePermissionItem(idPermissionItemHavingName); + int idPermissionHavingName = getIdRecordHavingRoleNameInPermissions(roleName1, 0); + PermissionsManagementDBUtils.deletePermission(idPermissionHavingName); + + idRoleHavingName = getIdRecordHavingRoleNameInRoles(roleName, 0); + PermissionsManagementDBUtils.deleteRoleAndItsPermissions(idRoleHavingName); + idPermissionItemHavingName = getIdRecordHavingNameInPermissionItems(permissionItemName); + PermissionsManagementDBUtils.deletePermissionItem(idPermissionItemHavingName); + idPermissionHavingName = getIdRecordHavingRoleNameInPermissions(roleName, 0); + PermissionsManagementDBUtils.deletePermission(idPermissionHavingName); + + } + + @Severity(SeverityLevel.CRITICAL) + @Test(description = "execute console util to delete data from DB") + public void deleteFromDB() { + String suffix = String.valueOf(BaseUtils.getEpoch()); + String roleName = "MaxTest" + suffix; + String permissionItemName = "Asset_List_Max" + suffix; + PermissionManagementUtils.generateFileWithInsertedIntoDBData(generatedDataFilePath, roleName, "partner*", + permissionItemName, "asset", "list", "permissionItemObject" + suffix, + "parameter" + suffix, 1, 2, 3, 4, 5, false); + + // import into DB + List commands = getConsoleCommand(fullPath2Util, IMPORT_KEY + generatedDataFilePath); + executeCommandsInConsole(commands); + + // check data in DB + int rowsInRolesHavingName = getCountRowsHavingRoleNameInRoles(roleName, 0); + assertThat(rowsInRolesHavingName).isEqualTo(1); + int idRoleHavingName = getIdRecordHavingRoleNameInRoles(roleName, 0); + + int rowsInPermissionsHavingName = getCountRowsHavingRoleNameInPermissions(roleName, 0); + assertThat(rowsInPermissionsHavingName).isEqualTo(1); + int idPermissionHavingName = getIdRecordHavingRoleNameInPermissions(roleName, 0); + + int idRolePermission = getCountSpecificRowsFromRolesPermissions(idRoleHavingName, idPermissionHavingName, 0); + assertThat(idRolePermission).isEqualTo(1); + + int rowsInPermissionItemsHavingName = getCountRowsHavingNameInPermissionItems(permissionItemName); + assertThat(rowsInPermissionItemsHavingName).isEqualTo(1); + int idPermissionItemHavingName = getIdRecordHavingNameInPermissionItems(permissionItemName); + + int rowsInPermissionsPermissions = getCountSpecificRowsFromPermissionsPermissionsItems(idPermissionHavingName, + idPermissionItemHavingName, 0); + assertThat(rowsInPermissionsPermissions).isEqualTo(1); + + // remove log file + deleteFile(path2Log); + + // delete from DB + commands = getConsoleCommand(fullPath2Util, DELETE_KEY + generatedDataFilePath); + executeCommandsInConsole(commands); + + // DB should be empty + rowsInRolesHavingName = getCountRowsHavingRoleNameInRoles(roleName, 0); + assertThat(rowsInRolesHavingName).isEqualTo(0); + + rowsInPermissionsHavingName = getCountRowsHavingRoleNameInPermissions(roleName, 0); + assertThat(rowsInPermissionsHavingName).isEqualTo(0); + + rowsInPermissionItemsHavingName = getCountRowsHavingNameInPermissionItems(permissionItemName + suffix); + assertThat(rowsInPermissionItemsHavingName).isEqualTo(0); + } + + @Severity(SeverityLevel.CRITICAL) + @Test(description = "execute console util to import already existed data into DB from valid file") + public void importAlreadyExistedFromFile() { + String suffix = String.valueOf(BaseUtils.getEpoch()); + String roleName = "MaxTest" + suffix; + String permissionItemName = "Asset_List_Max" + suffix; + PermissionManagementUtils.generateFileWithInsertedIntoDBData(generatedDataFilePath, roleName, "partner*", + permissionItemName, "asset", "list", "permissionItemObject" + suffix, + "parameter" + suffix, 1, 2, 3, 4, 5, false); + + // import into DB + List commands = getConsoleCommand(fullPath2Util, IMPORT_KEY + generatedDataFilePath); + executeCommandsInConsole(commands); + + // retry import + executeCommandsInConsole(commands); + + // check data in DB + int rowsInRolesHavingName = getCountRowsHavingRoleNameInRoles(roleName, 0); + assertThat(rowsInRolesHavingName).isEqualTo(1); + int idRoleHavingName = getIdRecordHavingRoleNameInRoles(roleName, 0); + + int rowsInPermissionsHavingName = getCountRowsHavingRoleNameInPermissions(roleName, 0); + assertThat(rowsInPermissionsHavingName).isEqualTo(1); + int idPermissionHavingName = getIdRecordHavingRoleNameInPermissions(roleName, 0); + + int idRolePermission = getCountSpecificRowsFromRolesPermissions(idRoleHavingName, idPermissionHavingName, 0); + assertThat(idRolePermission).isEqualTo(1); + + int rowsInPermissionItemsHavingName = getCountRowsHavingNameInPermissionItems(permissionItemName); + assertThat(rowsInPermissionItemsHavingName).isEqualTo(1); + int idPermissionItemHavingName = getIdRecordHavingNameInPermissionItems(permissionItemName); + + int rowsInPermissionsPermissions = getCountSpecificRowsFromPermissionsPermissionsItems(idPermissionHavingName, + idPermissionItemHavingName, 0); + assertThat(rowsInPermissionsPermissions).isEqualTo(1); + + // cleaning + PermissionsManagementDBUtils.deleteRoleAndItsPermissions(idRoleHavingName); + PermissionsManagementDBUtils.deletePermissionItem(idPermissionItemHavingName); + PermissionsManagementDBUtils.deletePermission(idPermissionHavingName); + } + + @Severity(SeverityLevel.NORMAL) + @Test(description = "execute console util to try delete data in DB using file with invalid tags") + public void runningDeleteUsingFileWithInvalidTags() { + // insert role in DB + String suffix = String.valueOf(BaseUtils.getEpoch()); + String roleName = "MaxTest" + suffix; + PermissionsManagementDBUtils.insertRole(roleName); + int idRoleHavingName = getIdRecordHavingRoleNameInRoles("MaxTest" + suffix, 0); + + PermissionManagementUtils.generateFileWithInvalidTagForRole(generatedDataFilePath, roleName, idRoleHavingName); + + // try delete + List commands = getConsoleCommand(fullPath2Util, DELETE_KEY + generatedDataFilePath); + executeCommandsInConsole(commands); + + // check data still in DB + int rowsInRolesHavingName = getCountRowsHavingRoleNameInRoles(roleName, 0); + assertThat(rowsInRolesHavingName).isEqualTo(1); + } + + @Severity(SeverityLevel.NORMAL) + @Test(description = "execute console util to delete data in 1 related table of DB") + public void deleteOnlyFromOneTable() { + // insert role in DB + String suffix = String.valueOf(BaseUtils.getEpoch()); + String roleName = "MaxTest" + suffix; + PermissionsManagementDBUtils.insertRole(roleName); + int idRoleHavingName = getIdRecordHavingRoleNameInRoles(roleName, 0); + + PermissionManagementUtils.generateFileForRole(generatedDataFilePath, roleName, idRoleHavingName); + + // delete + List commands = getConsoleCommand(fullPath2Util, DELETE_KEY + generatedDataFilePath); + executeCommandsInConsole(commands); + + // check data deleted from DB + int rowsInRolesHavingName = getCountRowsHavingRoleNameInRoles(roleName, 0); + assertThat(rowsInRolesHavingName).isEqualTo(0); + } + + @Severity(SeverityLevel.MINOR) + @Issue("BEO-5504") + @Test(description = "execute console util to export in JSON without mentioned file") + public void runningExportJsonWithoutFile() { + List commands = getConsoleCommand(fullPath2Util, EXPORT_JSON_KEY); + String consoleOutput = executeCommandsInConsole(commands); + + assertThat(consoleOutput).contains("The system cannot find the file specified"); + } + + @Severity(SeverityLevel.MINOR) + @Issue("BEO-5504") + @Test(description = "execute console util to import in JSON without mentioned file") + public void runningImportJsonWithoutFile() { + List commands = getConsoleCommand(fullPath2Util, IMPORT_JSON_KEY); + String consoleOutput = executeCommandsInConsole(commands); + + assertThat(consoleOutput).contains("The system cannot find the file specified"); + } + + @Severity(SeverityLevel.CRITICAL) + @Test(description = "execute console util to export in JSON from DB") + public void exportJson() throws IOException { + // clean folder with logs + FileUtils.cleanDirectory(new File(path2JsonFolder)); + + // prepare data inserting them in DB using stored procedures + String suffix = String.valueOf(BaseUtils.getEpoch()); + String roleName = "MaxTest" + suffix; + String permissionItemName = "Asset_List_Max" + suffix; + String serviceName = "asset"; + PermissionManagementUtils.insertDataInAllTables(generatedDataFilePath, roleName, "partner*", + permissionItemName, serviceName, "list", "permissionItemObject" + suffix, + "parameter" + suffix, true); + // command + List commands = getConsoleCommand(fullPath2Util, EXPORT_JSON_KEY + path2JsonFolder); + executeCommandsInConsole(commands); + + String importFileContent = getFileContent(generatedDataFilePath); + assertThat(importFileContent).contains(roleName); + assertThat(importFileContent).contains(permissionItemName); + checkActionResult(serviceName, importFileContent); + + // cleaning + int idRoleHavingName = getIdRecordHavingRoleNameInRoles(roleName, 0); + PermissionsManagementDBUtils.deleteRoleAndItsPermissions(idRoleHavingName); + int idPermissionItemHavingName = getIdRecordHavingNameInPermissionItems(permissionItemName); + PermissionsManagementDBUtils.deletePermissionItem(idPermissionItemHavingName); + int idPermissionHavingName = getIdRecordHavingRoleNameInPermissions(roleName, 0); + PermissionsManagementDBUtils.deletePermission(idPermissionHavingName); + } + + @Severity(SeverityLevel.CRITICAL) + @Test(description = "execute console util to import from JSON into DB") + public void importJson() throws IOException { + // clean folder with logs + FileUtils.cleanDirectory(new File(path2JsonFolder)); + + // export command to get results and not break the system + List commands = getConsoleCommand(fullPath2Util, EXPORT_JSON_KEY + path2JsonFolder); + executeCommandsInConsole(commands); + + // prepare data + String suffix = String.valueOf(BaseUtils.getEpoch()); + String roleName = "MaxTest" + suffix; + String permissionItemName = "Asset_List_Max" + suffix; + String serviceName = "asset"; + PermissionManagementUtils.fillFilesWithImportData(roleName, permissionItemName, "partner*", serviceName, "list"); + + // import command + commands = getConsoleCommand(fullPath2Util, IMPORT_JSON_KEY + path2JsonFolder); + executeCommandsInConsole(commands); + + // find new records in DB after the import + int idRoleHavingName = getIdRecordHavingRoleNameInRoles(roleName, 0); + int idPermissionItemHavingName = getIdRecordHavingNameInPermissionItems(permissionItemName); + int idPermissionHavingName = getIdRecordHavingRoleNameInPermissions(roleName, 0); + assertThat(idRoleHavingName).isGreaterThan(0); + assertThat(idPermissionItemHavingName).isGreaterThan(0); + assertThat(idPermissionHavingName).isGreaterThan(0); + + // cleaning + PermissionsManagementDBUtils.deleteRoleAndItsPermissions(idRoleHavingName); + PermissionsManagementDBUtils.deletePermissionItem(idPermissionItemHavingName); + PermissionsManagementDBUtils.deletePermission(idPermissionHavingName); + } + + // method checks that all related files contain information related to service + /** + * + * @param serviceName - name of service (e.g.: "asset") + * @param importFileContent - file created during adding data into DB by util PermissionManagementUtils.insertDataInAllTables + * data in that file related to data from files with roles info, permissions info and methods info and separated by symbol ";" + */ + void checkActionResult(String serviceName, String importFileContent) { + // data prepared so that they splitted by symbol ";" + String[] results = importFileContent.split(";"); + String contentOfJsonFile = getFileContent(path2JsonRoles) + .replaceAll(" ", ""); + //.replaceAll("\\t", ""); + assertThat(contentOfJsonFile).contains(results[0] + .replaceAll(" ", "")); + contentOfJsonFile = getFileContent(path2JsonPermissions) + .replaceAll(" ", ""); + //.replaceAll("\\t", ""); + assertThat(contentOfJsonFile).contains(results[1] + .replaceAll(" ", "")); + contentOfJsonFile = getFileContent(path2JsonMethods + serviceName + ".json") + .replaceAll(" ", ""); + //.replaceAll("\\t", ""); + assertThat(contentOfJsonFile).contains(results[2].replaceAll(" ", "")); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetHistoryTests/AssetHistoryActionCleanLists.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetHistoryTests/AssetHistoryActionCleanLists.java deleted file mode 100644 index eda434237..000000000 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetHistoryTests/AssetHistoryActionCleanLists.java +++ /dev/null @@ -1,205 +0,0 @@ -package com.kaltura.client.test.tests.servicesTests.AssetHistoryTests; - -import com.kaltura.client.enums.BookmarkActionType; -import com.kaltura.client.enums.WatchStatus; -import com.kaltura.client.services.AssetHistoryService; -import com.kaltura.client.test.tests.BaseTest; -import com.kaltura.client.test.utils.AssetHistoryUtils; -import com.kaltura.client.types.AssetHistory; -import com.kaltura.client.types.AssetHistoryFilter; -import com.kaltura.client.types.Household; -import com.kaltura.client.types.ListResponse; -import com.kaltura.client.utils.response.base.Response; -import io.qameta.allure.Description; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import static com.kaltura.client.services.AssetHistoryService.CleanAssetHistoryBuilder; -import static com.kaltura.client.services.AssetHistoryService.ListAssetHistoryBuilder; -import static com.kaltura.client.test.IngestConstants.EPISODE_MEDIA_TYPE; -import static com.kaltura.client.test.IngestConstants.MOVIE_MEDIA_TYPE; -import static com.kaltura.client.test.Properties.EPISODE_MEDIA_TYPE_ID; -import static com.kaltura.client.test.Properties.getProperty; -import static com.kaltura.client.test.utils.HouseholdUtils.createHousehold; -import static com.kaltura.client.test.utils.HouseholdUtils.getHouseholdMasterUserKs; -import static org.assertj.core.api.Assertions.assertThat; - -public class AssetHistoryActionCleanLists extends BaseTest { - - private final int position1 = 10; - private final int position2 = 20; - private final int numbOfDevices = 1; - private final int numOfUsers = 1; - - - @BeforeClass - // TODO: 5/3/2018 change before method name - private void add_tests_before_class() { - - } - - @Description("/assetHistory/action/clean - no filtering") - @Test - private void cleanHistory() { - - Household household = createHousehold(numOfUsers, numbOfDevices, false); - String masterUserKs = getHouseholdMasterUserKs(household, null); - String userKs = getHouseholdMasterUserKs(household, null); - - // Ingest and bookmark first asset - AssetHistoryUtils.ingestAssetAndPerformBookmark(userKs, MOVIE_MEDIA_TYPE, position1, BookmarkActionType.FIRST_PLAY); - // Ingest and bookmark second asset - AssetHistoryUtils.ingestAssetAndPerformBookmark(userKs, MOVIE_MEDIA_TYPE, position2, BookmarkActionType.FIRST_PLAY); - - AssetHistoryFilter assetHistoryFilter = AssetHistoryUtils.getAssetHistoryFilter(null, null, WatchStatus.ALL, null); - - //assetHistory/action/list - both assets should returned - ListAssetHistoryBuilder listAssetHistoryBuilder = AssetHistoryService.list(assetHistoryFilter, null) - .setKs(masterUserKs); - Response> assetHistoryListResponse = executor.executeSync(listAssetHistoryBuilder); - - assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(2); - - //assetHistory/action/clean - CleanAssetHistoryBuilder cleanAssetHistoryBuilder = AssetHistoryService.clean(assetHistoryFilter); - cleanAssetHistoryBuilder.setKs(masterUserKs); - executor.executeSync(cleanAssetHistoryBuilder); - - // assetHistory/action/list - after clean - no object returned - listAssetHistoryBuilder = AssetHistoryService.list(assetHistoryFilter, null) - .setKs(masterUserKs); - assetHistoryListResponse = executor.executeSync(listAssetHistoryBuilder); - - assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(0); - } - - @Description("/assetHistory/action/clean - filtered by asset id") - @Test - private void cleanSpecifcAssetHistory() { - - Household household = createHousehold(numOfUsers, numbOfDevices, false); - String masterUserKs = getHouseholdMasterUserKs(household, null); - String userKs = getHouseholdMasterUserKs(household, null); - - // Ingest and bookmark first asset - Long assetId1 = AssetHistoryUtils.ingestAssetAndPerformBookmark(userKs, MOVIE_MEDIA_TYPE, position1, BookmarkActionType.FIRST_PLAY); - // Ingest and bookmark second asset - Long assetId2 = AssetHistoryUtils.ingestAssetAndPerformBookmark(userKs, MOVIE_MEDIA_TYPE, position2, BookmarkActionType.FIRST_PLAY); - - AssetHistoryFilter assetHistoryFilter = AssetHistoryUtils.getAssetHistoryFilter(String.valueOf(assetId1), null, WatchStatus.ALL, null); - - //assetHistory/action/clean - CleanAssetHistoryBuilder cleanAssetHistoryBuilder = AssetHistoryService.clean(assetHistoryFilter); - cleanAssetHistoryBuilder.setKs(masterUserKs); - executor.executeSync(cleanAssetHistoryBuilder); - - // Update assetHistoryFilter object (assetIdIn = null) - assetHistoryFilter = AssetHistoryUtils.getAssetHistoryFilter(null, null, WatchStatus.ALL, null); - - // assetHistory/action/list - after clean - only asset id 2 returned (was not cleaned) - ListAssetHistoryBuilder listAssetHistoryBuilder = AssetHistoryService.list(assetHistoryFilter, null); - listAssetHistoryBuilder.setKs(masterUserKs); - Response> assetHistoryListResponse = executor.executeSync(listAssetHistoryBuilder); - - assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(1); - assertThat(assetHistoryListResponse.results.getObjects().get(0).getAssetId()).isEqualTo(assetId2); - } - - @Description("/assetHistory/action/clean - filtered by asset type") - @Test - private void cleanSpecifcAssetTypeHistory() { - - Household household = createHousehold(numOfUsers, numbOfDevices, false); - String masterUserKs = getHouseholdMasterUserKs(household, null); - String userKs = getHouseholdMasterUserKs(household, null); - - // Ingest and bookmark first asset - Long assetId1 = AssetHistoryUtils.ingestAssetAndPerformBookmark(userKs, MOVIE_MEDIA_TYPE, position1, BookmarkActionType.FIRST_PLAY); - // Ingest and bookmark second asset - Long assetId2 = AssetHistoryUtils.ingestAssetAndPerformBookmark(userKs, EPISODE_MEDIA_TYPE, position2, BookmarkActionType.FIRST_PLAY); - - AssetHistoryFilter assetHistoryFilter = AssetHistoryUtils.getAssetHistoryFilter(null, null, WatchStatus.ALL, getProperty(EPISODE_MEDIA_TYPE_ID)); - - //assetHistory/action/clean - only episode type (asset id 2) - - CleanAssetHistoryBuilder cleanAssetHistoryBuilder = AssetHistoryService.clean(assetHistoryFilter); - cleanAssetHistoryBuilder.setKs(masterUserKs); - executor.executeSync(cleanAssetHistoryBuilder); - - // Update assetHistoryFilter object (assetIdIn = null) - assetHistoryFilter = AssetHistoryUtils.getAssetHistoryFilter(null, null, WatchStatus.ALL, null); - - // assetHistory/action/list - after clean - only asset id 1 returned (was not cleaned) - - ListAssetHistoryBuilder listAssetHistoryBuilder = AssetHistoryService.list(assetHistoryFilter, null); - listAssetHistoryBuilder.setKs(masterUserKs); - Response> assetHistoryListResponse = executor.executeSync(listAssetHistoryBuilder); - - assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(1); - assertThat(assetHistoryListResponse.results.getObjects().get(0).getAssetId()).isEqualTo(assetId1); - } - - @Description("/assetHistory/action/clean - filtered by asset progress") - @Test - private void cleanAssetsAccordingToWatchStatusDone() { - - Household household = createHousehold(numOfUsers, numbOfDevices, false); - String masterUserKs = getHouseholdMasterUserKs(household, null); - String userKs = getHouseholdMasterUserKs(household, null); - - // Ingest and bookmark first asset - Long assetId1 = AssetHistoryUtils.ingestAssetAndPerformBookmark(userKs, MOVIE_MEDIA_TYPE, position1, BookmarkActionType.FIRST_PLAY); - // Ingest and bookmark second asset - Long assetId2 = AssetHistoryUtils.ingestAssetAndPerformBookmark(userKs, EPISODE_MEDIA_TYPE, position2, BookmarkActionType.FINISH); - - AssetHistoryFilter assetHistoryFilter = AssetHistoryUtils.getAssetHistoryFilter(null, null, WatchStatus.DONE, null); - - //assetHistory/action/clean - only asset that were finished (asset 2) - - CleanAssetHistoryBuilder cleanAssetHistoryBuilder = AssetHistoryService.clean(assetHistoryFilter); - cleanAssetHistoryBuilder.setKs(masterUserKs); - executor.executeSync(cleanAssetHistoryBuilder); - - assetHistoryFilter = AssetHistoryUtils.getAssetHistoryFilter(null, null, WatchStatus.ALL, null); - - // assetHistory/action/list - after clean - only asset id 1 returned (was not cleaned) - - ListAssetHistoryBuilder listAssetHistoryBuilder = AssetHistoryService.list(assetHistoryFilter, null); - listAssetHistoryBuilder.setKs(masterUserKs); - Response> assetHistoryListResponse = executor.executeSync(listAssetHistoryBuilder); - - assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(1); - assertThat(assetHistoryListResponse.results.getObjects().get(0).getAssetId()).isEqualTo(assetId1); - } - - @Description("/assetHistory/action/clean - filtered by asset progress") - @Test - private void cleanAssetsAccordingToWatchStatusProgress() { - - Household household = createHousehold(numOfUsers, numbOfDevices, false); - String masterUserKs = getHouseholdMasterUserKs(household, null); - String userKs = getHouseholdMasterUserKs(household, null); - - // Ingest and bookmark first asset - Long assetId1 = AssetHistoryUtils.ingestAssetAndPerformBookmark(userKs, MOVIE_MEDIA_TYPE, position1, BookmarkActionType.FIRST_PLAY); - // Ingest and bookmark second asset - Long assetId2 = AssetHistoryUtils.ingestAssetAndPerformBookmark(userKs, EPISODE_MEDIA_TYPE, position2, BookmarkActionType.FINISH); - - AssetHistoryFilter assetHistoryFilter = AssetHistoryUtils.getAssetHistoryFilter(null, null, WatchStatus.PROGRESS, null); - - //assetHistory/action/clean - only asset that in progress (asset 1) - CleanAssetHistoryBuilder cleanAssetHistoryBuilder = AssetHistoryService.clean(assetHistoryFilter); - cleanAssetHistoryBuilder.setKs(masterUserKs); - executor.executeSync(cleanAssetHistoryBuilder); - - assetHistoryFilter = AssetHistoryUtils.getAssetHistoryFilter(null, null, WatchStatus.ALL, null); - - // assetHistory/action/list - after clean - only asset id 2 returned (was not cleaned) - ListAssetHistoryBuilder listAssetHistoryBuilder = AssetHistoryService.list(assetHistoryFilter, null); - listAssetHistoryBuilder.setKs(masterUserKs); - Response> assetHistoryListResponse = executor.executeSync(listAssetHistoryBuilder); - - assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(1); - assertThat(assetHistoryListResponse.results.getObjects().get(0).getAssetId()).isEqualTo(assetId2); - } -} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetHistoryTests/AssetHistoryListTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetHistoryTests/AssetHistoryListTests.java deleted file mode 100644 index 4d172a71f..000000000 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetHistoryTests/AssetHistoryListTests.java +++ /dev/null @@ -1,206 +0,0 @@ -package com.kaltura.client.test.tests.servicesTests.AssetHistoryTests; - -import com.kaltura.client.enums.AssetType; -import com.kaltura.client.enums.BookmarkActionType; -import com.kaltura.client.enums.WatchStatus; -import com.kaltura.client.test.tests.BaseTest; -import com.kaltura.client.test.utils.AssetHistoryUtils; -import com.kaltura.client.types.AssetHistory; -import com.kaltura.client.types.AssetHistoryFilter; -import com.kaltura.client.types.Household; -import com.kaltura.client.types.ListResponse; -import com.kaltura.client.utils.response.base.Response; -import io.qameta.allure.Description; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.List; - -import static com.kaltura.client.services.AssetHistoryService.*; -import static com.kaltura.client.test.IngestConstants.EPISODE_MEDIA_TYPE; -import static com.kaltura.client.test.IngestConstants.MOVIE_MEDIA_TYPE; -import static com.kaltura.client.test.Properties.MOVIE_MEDIA_TYPE_ID; -import static com.kaltura.client.test.Properties.getProperty; -import static com.kaltura.client.test.utils.BaseUtils.getConcatenatedString; -import static com.kaltura.client.test.utils.BaseUtils.getTimeInEpoch; -import static com.kaltura.client.test.utils.HouseholdUtils.createHousehold; -import static com.kaltura.client.test.utils.HouseholdUtils.getHouseholdMasterUserKs; -import static org.assertj.core.api.Assertions.assertThat; - -public class AssetHistoryListTests extends BaseTest { - - private final int position1 = 10; - private final int position2 = 20; - private final int numbOfDevices = 1; - private final int numOfUsers = 1; - - - @Description("/AssetHistory/action/list - with no filter") - @Test - private void vodAssetHistory() { - Household household = createHousehold(numOfUsers, numbOfDevices, false); - String masterUserKs = getHouseholdMasterUserKs(household, null); - - // Ingest and bookmark first asset - Long assetId1 = AssetHistoryUtils.ingestAssetAndPerformBookmark(masterUserKs, MOVIE_MEDIA_TYPE, position1, BookmarkActionType.FIRST_PLAY); - // Ingest and bookmark second asset - Long assetId2 = AssetHistoryUtils.ingestAssetAndPerformBookmark(masterUserKs, MOVIE_MEDIA_TYPE, position2, BookmarkActionType.FIRST_PLAY); - - AssetHistoryFilter assetHistoryFilter = AssetHistoryUtils.getAssetHistoryFilter(null, null, WatchStatus.ALL, null); - - //assetHistory/action/list - both assets should returned - ListAssetHistoryBuilder listAssetHistoryBuilder = list(assetHistoryFilter, null) - .setKs(masterUserKs); - Response> assetHistoryListResponse = executor.executeSync(listAssetHistoryBuilder); - - // First object - AssetHistory assetHistoryObject1 = assetHistoryListResponse.results.getObjects().get(0); - // Second object - AssetHistory assetHistoryObject2 = assetHistoryListResponse.results.getObjects().get(1); - - // Assertions for first object returned - assertThat(assetHistoryObject1.getAssetId()).isEqualTo(assetId2); - assertThat(assetHistoryObject1.getAssetType()).isEqualTo(AssetType.MEDIA); - assertThat(assetHistoryObject1.getPosition()).isEqualTo(position2); - assertThat(assetHistoryObject1.getDuration()).isGreaterThan(0); - - // Verify that flag is set to false (user hasn't finish watching the asset) - assertThat(assetHistoryObject1.getFinishedWatching()).isFalse(); - assertThat(assetHistoryObject1.getWatchedDate()).isLessThanOrEqualTo(getTimeInEpoch(0)); - - // Assertions for second object returned - assertThat(assetHistoryObject2.getAssetId()).isEqualTo(assetId1); - assertThat(assetHistoryObject2.getAssetType()).isEqualTo(AssetType.MEDIA); - assertThat(assetHistoryObject2.getPosition()).isEqualTo(position1); - - // Assert total count = 2 (two bookmarks) - assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(2); - - // clean - clean_asset_history(assetHistoryFilter, household); - } - - @Description("/AssetHistory/action/list -filtered by movie asset id") - @Test - private void vodAssetHistoryFilteredByAssetId() { - - Household household = createHousehold(numOfUsers, numbOfDevices, false); - String masterUserKs = getHouseholdMasterUserKs(household, null); - - List assetIds = new ArrayList<>(); - int numOfBookmarks = 3; - for (int i = 0; i < numOfBookmarks; i++) { - long assetId = AssetHistoryUtils.ingestAssetAndPerformBookmark(masterUserKs, MOVIE_MEDIA_TYPE, position1, BookmarkActionType.FIRST_PLAY); - assetIds.add(assetId); - } - - // Ingest and bookmark first asset - AssetHistoryFilter assetHistoryFilter = AssetHistoryUtils.getAssetHistoryFilter(String.valueOf(assetIds.get(1)), null, WatchStatus.ALL, null); - - //assetHistory/action/list - filter by asset 2 id - ListAssetHistoryBuilder listAssetHistoryBuilder = list(assetHistoryFilter, null) - .setKs(masterUserKs); - Response> assetHistoryListResponse = executor.executeSync(listAssetHistoryBuilder); - - assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(1); - assertThat(assetHistoryListResponse.results.getObjects().get(0).getAssetId()).isEqualTo(assetIds.get(1)); - - String concatenatedString = getConcatenatedString(String.valueOf(assetIds.get(1)), String.valueOf(assetIds.get(2))); - - //assetHistory/action/list - filter by asset 2 and asset 3 ids - assetHistoryFilter = AssetHistoryUtils.getAssetHistoryFilter(concatenatedString, null, WatchStatus.ALL, null); - - listAssetHistoryBuilder = list(assetHistoryFilter, null) - .setKs(masterUserKs); - assetHistoryListResponse = executor.executeSync(listAssetHistoryBuilder); - - List assetHistoryList = assetHistoryListResponse.results.getObjects(); - assertThat(assetHistoryList); - - List assetHistoryIdsList = new ArrayList<>(); - for (AssetHistory assetHistory : assetHistoryList) { - assetHistoryIdsList.add(assetHistory.getAssetId()); - } - assertThat(assetHistoryIdsList).containsOnly(assetIds.get(1), assetIds.get(2)); - - // clean - clean_asset_history(assetHistoryFilter, household); - } - - @Description("/AssetHistory/action/list -filtered by movie type id") - @Test - private void vodAssetHistoryFilteredByAssetType() { - - Household household = createHousehold(numOfUsers, numbOfDevices, false); - String userKs = getHouseholdMasterUserKs(household, null); - - - // Ingest and bookmark first asset (movie in first play) - Long assetId1 = AssetHistoryUtils.ingestAssetAndPerformBookmark(userKs, MOVIE_MEDIA_TYPE, 10, BookmarkActionType.FIRST_PLAY); - // Ingest and bookmark second asset (movie in finish action) - Long assetId2 = AssetHistoryUtils.ingestAssetAndPerformBookmark(userKs, EPISODE_MEDIA_TYPE, 10, BookmarkActionType.FIRST_PLAY); - - AssetHistoryFilter assetHistoryFilter = AssetHistoryUtils.getAssetHistoryFilter(null, null, WatchStatus.ALL, - getProperty(MOVIE_MEDIA_TYPE_ID)); - - //assetHistory/action/list - filter by in progress assets only - - ListAssetHistoryBuilder listAssetHistoryBuilder = list(assetHistoryFilter, null); - listAssetHistoryBuilder.setKs(getHouseholdMasterUserKs(household, null)); - Response> assetHistoryListResponse = executor.executeSync(listAssetHistoryBuilder); - - assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(1); - assertThat(assetHistoryListResponse.results.getObjects().get(0).getAssetId()).isEqualTo(assetId1); - - // clean - clean_asset_history(assetHistoryFilter, household); - } - - - @Description("/AssetHistory/action/list -filtered by assets progress") - @Test - private void vodAssetHistoryFilteredByAssetProgress() { - - Household household = createHousehold(numOfUsers, numbOfDevices, false); - String userKs = getHouseholdMasterUserKs(household, null); - - - // Ingest and bookmark first asset (movie in first play) - Long assetId1 = AssetHistoryUtils.ingestAssetAndPerformBookmark(userKs, MOVIE_MEDIA_TYPE, 10, BookmarkActionType.FIRST_PLAY); - // Ingest and bookmark second asset (movie in finish action) - Long assetId2 = AssetHistoryUtils.ingestAssetAndPerformBookmark(userKs, EPISODE_MEDIA_TYPE, 100, BookmarkActionType.FINISH); - - AssetHistoryFilter assetHistoryFilter = AssetHistoryUtils.getAssetHistoryFilter(null, null, WatchStatus.PROGRESS, null); - - //assetHistory/action/list - filter by in progress assets only - - ListAssetHistoryBuilder listAssetHistoryBuilder = list(assetHistoryFilter, null); - listAssetHistoryBuilder.setKs(getHouseholdMasterUserKs(household, null)); - Response> assetHistoryListResponse = executor.executeSync(listAssetHistoryBuilder); - - assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(1); - assertThat(assetHistoryListResponse.results.getObjects().get(0).getAssetId()).isEqualTo(assetId1); - - assetHistoryFilter = AssetHistoryUtils.getAssetHistoryFilter(null, null, WatchStatus.DONE, null); - - //assetHistory/action/list - filter by finished assets only - - listAssetHistoryBuilder = list(assetHistoryFilter, null); - assetHistoryListResponse = executor.executeSync(listAssetHistoryBuilder); - - assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(1); - assertThat(assetHistoryListResponse.results.getObjects().get(0).getAssetId()).isEqualTo(assetId2); - - // clean - clean_asset_history(assetHistoryFilter, household); - } - - - private void clean_asset_history(AssetHistoryFilter assetHistoryFilter, Household household) { - CleanAssetHistoryBuilder cleanAssetHistoryBuilder = clean(assetHistoryFilter); - cleanAssetHistoryBuilder.setKs(getHouseholdMasterUserKs(household, null)); - executor.executeSync(cleanAssetHistoryBuilder); - } - - //todo - Currently EPG program not returned in response (Ticket was opened to Omer - BEO-4594] -} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetCountTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetCountTests.java new file mode 100644 index 000000000..4e6239b88 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetCountTests.java @@ -0,0 +1,293 @@ +package com.kaltura.client.test.tests.servicesTests.AssetTests; +import com.kaltura.client.services.AssetService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.tests.enums.MediaType; +import com.kaltura.client.test.utils.KsqlBuilder; + +import com.kaltura.client.test.utils.dbUtils.DBUtils; +import com.kaltura.client.test.utils.ingestUtils.IngestEpgUtils; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + + +import static com.kaltura.client.services.AssetService.*; +import static com.kaltura.client.test.utils.dbUtils.DBUtils.getMediaTypeId; +import static com.kaltura.client.test.utils.ingestUtils.IngestEpgUtils.*; +import static com.kaltura.client.test.tests.enums.KsqlKey.EPG_ID; +import static com.kaltura.client.test.tests.enums.KsqlKey.MEDIA_ID; +import static com.kaltura.client.test.tests.enums.MediaType.MOVIE; +import static com.kaltura.client.test.utils.BaseUtils.getRandomValue; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.*; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.insertVod; +import static org.assertj.core.api.Assertions.assertThat; + +public class AssetCountTests extends BaseTest { + + private ProgramAsset program, program2; + private MediaAsset asset, asset2; + + //TODO - Change all hardcoded values after Alon will add DB meta anf tags utils. + + private final String metaName1 = "synopsis"; + private final String metaValue1 = metaName1 + getRandomValue("_"); + + private final String metaName2 = "runtime"; + private final String metaValue2 = metaName2 + getRandomValue("_"); + private final String metaValue3 = metaName2 + getRandomValue("_"); + + private final String tagName = "Studio"; + private final String tagValue = tagName + getRandomValue("_"); + + private final String epgMetaName = "Country"; + private final String epgMetaValue = epgMetaName + getRandomValue("_"); + + private final String sharedTagName = "Director"; + private final String sharedTagValue = sharedTagName + getRandomValue("_"); + + @BeforeClass + private void asset_count_before_class() { + + // Metas + HashMap stringMetaMap = new HashMap<>(); + stringMetaMap.put(metaName1, metaValue1); + stringMetaMap.put(metaName2,metaValue2); + + // Tags + HashMap> stringTagMap = new HashMap<>(); + stringTagMap.put(sharedTagName, Arrays.asList(sharedTagValue)); + stringTagMap.put(tagName,Arrays.asList(tagValue)); + + // ingest asset 1 + VodData vodData1 = new VodData() + .mediaType(MOVIE) + .stringsMeta(stringMetaMap) + .tags(stringTagMap); + asset = insertVod(vodData1, true); + + HashMap stringMetaMap2 = new HashMap<>(); + stringMetaMap2.put(metaName1, metaValue1); + stringMetaMap2.put(metaName2,metaValue3); + stringTagMap.put(tagName,Arrays.asList(tagValue)); + + // ingest asset 2 + VodData vodData2 = new VodData() + .mediaType(MOVIE) + .stringsMeta(stringMetaMap2); + asset2 = insertVod(vodData2, true); + + HashMap epgMetas = new HashMap<>(); + epgMetas.put(epgMetaName, epgMetaValue); + + HashMap epgTags = new HashMap<>(); + epgTags.put(sharedTagName, sharedTagValue); + + // ingest epg programs + EpgData epgData = new EpgData(getSharedEpgChannelName()); + epgData.seasonsNum(1); + epgData.episodesNum(2); + epgData.metas(epgMetas); + epgData.tags(epgTags); + + List programsList = IngestEpgUtils.insertEpg(epgData); + program = programsList.get(0); + program2 = programsList.get(1); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("2 VOD assets with the same meta (synopsis) value and pass the meta name in the count request") + @Test + private void groupByVodMeta() { + String query = new KsqlBuilder() + .openOr() + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset.getId())) + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset2.getId())) + .closeOr() + .toString(); + + SearchAssetFilter searchAssetFilter = new SearchAssetFilter(); + searchAssetFilter.setKSql(query); + searchAssetFilter.setTypeIn(String.valueOf(DBUtils.getMediaTypeId(MediaType.MOVIE))); + + ArrayList arrayList = new ArrayList<>(); + AssetMetaOrTagGroupBy assetMetaOrTagGroupBy = new AssetMetaOrTagGroupBy(); + assetMetaOrTagGroupBy.setValue(metaName1); + arrayList.add(assetMetaOrTagGroupBy); + + searchAssetFilter.setGroupBy(arrayList); + AssetService.CountAssetBuilder countAssetBuilder = AssetService.count(searchAssetFilter) + .setKs(BaseTest.getAnonymousKs()); + + // asset/action/count - 2 VOD assets in count + Response assetCountResponse = executor.executeSync(countAssetBuilder); + assertThat(assetCountResponse.results.getCount()).isEqualTo(2); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("2 VOD assets with the same tag (Genre) value and pass the tag name in the count request") + @Test + private void groupByVodTag() { + String query = new KsqlBuilder() + .openOr() + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset.getId())) + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset2.getId())) + .closeOr() + .toString(); + + SearchAssetFilter searchAssetFilter = new SearchAssetFilter(); + searchAssetFilter.setKSql(query); + searchAssetFilter.setTypeIn(String.valueOf(DBUtils.getMediaTypeId(MediaType.MOVIE))); + + ArrayList arrayList = new ArrayList<>(); + AssetMetaOrTagGroupBy assetMetaOrTagGroupBy = new AssetMetaOrTagGroupBy(); + assetMetaOrTagGroupBy.setValue(tagName); + arrayList.add(assetMetaOrTagGroupBy); + + searchAssetFilter.setGroupBy(arrayList); + AssetService.CountAssetBuilder countAssetBuilder = AssetService.count(searchAssetFilter) + .setKs(BaseTest.getAnonymousKs()); + + // asset/action/count - 2 VOD assets in count + Response assetCountResponse = executor.executeSync(countAssetBuilder); + assertThat(assetCountResponse.results.getCount()).isEqualTo(2); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("2 VOD assets with different meta (Runtime) value and pass the meta name in the count request") + @Test + private void groupByVodMetaWithDifferentValues() { + String query = new KsqlBuilder() + .openOr() + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset.getId())) + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset2.getId())) + .closeOr() + .toString(); + + SearchAssetFilter searchAssetFilter = new SearchAssetFilter(); + searchAssetFilter.setKSql(query); + searchAssetFilter.setTypeIn(String.valueOf(DBUtils.getMediaTypeId(MediaType.MOVIE))); + + ArrayList arrayList = new ArrayList<>(); + AssetMetaOrTagGroupBy assetMetaOrTagGroupBy = new AssetMetaOrTagGroupBy(); + assetMetaOrTagGroupBy.setValue(metaName2); + arrayList.add(assetMetaOrTagGroupBy); + + searchAssetFilter.setGroupBy(arrayList); + AssetService.CountAssetBuilder countAssetBuilder = AssetService.count(searchAssetFilter) + .setKs(BaseTest.getAnonymousKs()); + + // asset/action/count - 2 VOD assets in count + Response assetCountResponse = executor.executeSync(countAssetBuilder); + assertThat(assetCountResponse.results.getCount()).isEqualTo(2); + assertThat(assetCountResponse.results.getSubs().get(0).getObjects().get(0).getCount()).isEqualTo(1); + assertThat(assetCountResponse.results.getSubs().get(0).getObjects().get(0).getValue()).isEqualTo(metaValue3); + assertThat(assetCountResponse.results.getSubs().get(0).getObjects().get(1).getCount()).isEqualTo(1); + assertThat(assetCountResponse.results.getSubs().get(0).getObjects().get(1).getValue()).isEqualTo(metaValue2); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("2 EPG programs with the same meta (Country) value and pass the meta name in the count request") + @Test + private void groupByEPGMeta() { + String query = new KsqlBuilder() + .openOr() + .equal(EPG_ID.getValue(), String.valueOf(program.getId())) + .equal(EPG_ID.getValue(),String.valueOf(program2.getId())) + .closeOr() + .toString(); + + SearchAssetFilter searchAssetFilter = new SearchAssetFilter(); + searchAssetFilter.setKSql(query); + searchAssetFilter.setTypeIn("0"); + + ArrayList arrayList = new ArrayList<>(); + AssetMetaOrTagGroupBy assetMetaOrTagGroupBy = new AssetMetaOrTagGroupBy(); + assetMetaOrTagGroupBy.setValue(epgMetaName); + arrayList.add(assetMetaOrTagGroupBy); + + searchAssetFilter.setGroupBy(arrayList); + CountAssetBuilder countAssetBuilder = AssetService.count(searchAssetFilter) + .setKs(BaseTest.getAnonymousKs()); + + // asset/action/count - 2 EPG in count + Response assetCountResponse = executor.executeSync(countAssetBuilder); + assertThat(assetCountResponse.results.getCount()).isEqualTo(2); + } + + // TODO + @Description("2 EPG programs with the same tag (Director) value and pass the tag name in the count request") + @Test + private void groupByEPGTag() { + String query = new KsqlBuilder() + .openOr() + .equal(EPG_ID.getValue(), String.valueOf(program.getId())) + .equal(EPG_ID.getValue(),String.valueOf(program2.getId())) + .closeOr() + .toString(); + + SearchAssetFilter searchAssetFilter = new SearchAssetFilter(); + searchAssetFilter.setKSql(query); + searchAssetFilter.setTypeIn("0"); + + ArrayList arrayList = new ArrayList<>(); + AssetMetaOrTagGroupBy assetMetaOrTagGroupBy = new AssetMetaOrTagGroupBy(); + assetMetaOrTagGroupBy.setValue(sharedTagName); + arrayList.add(assetMetaOrTagGroupBy); + + searchAssetFilter.setGroupBy(arrayList); + CountAssetBuilder countAssetBuilder = AssetService.count(searchAssetFilter) + .setKs(BaseTest.getAnonymousKs()); + + // asset/action/count - 2 EPG in count + Response assetCountResponse = executor.executeSync(countAssetBuilder); + assertThat(assetCountResponse.results.getCount()).isEqualTo(2); + } + + + @Description("VOD and EPG program with the same tag value") + @Test + private void groupByEPGAndVODTag() { + String query = new KsqlBuilder() + .equal(sharedTagName, sharedTagValue) + .toString(); + + SearchAssetFilter searchAssetFilter = new SearchAssetFilter(); + searchAssetFilter.setKSql(query); + + ArrayList arrayList = new ArrayList<>(); + AssetMetaOrTagGroupBy assetMetaOrTagGroupBy = new AssetMetaOrTagGroupBy(); + assetMetaOrTagGroupBy.setValue(sharedTagName); + arrayList.add(assetMetaOrTagGroupBy); + + searchAssetFilter.setGroupBy(arrayList); + CountAssetBuilder countAssetBuilder = AssetService.count(searchAssetFilter) + .setKs(BaseTest.getAnonymousKs()); + + // asset/action/count - no filtering (1 VOD asset and 2 EPG programs in count) + Response assetCountResponse = executor.executeSync(countAssetBuilder); + assertThat(assetCountResponse.results.getCount()).isEqualTo(3); + + // asset/action/count - filter by movie type id (1 VOD asset in count) + searchAssetFilter.setTypeIn(String.valueOf(getMediaTypeId(MediaType.MOVIE))); + countAssetBuilder = AssetService.count(searchAssetFilter) + .setKs(BaseTest.getAnonymousKs()); + assetCountResponse = executor.executeSync(countAssetBuilder); + assertThat(assetCountResponse.results.getCount()).isEqualTo(1); + + // asset/action/count - filter by EPG type id (2 EPG programs in count) + searchAssetFilter.setTypeIn("0"); + countAssetBuilder = AssetService.count(searchAssetFilter) + .setKs(BaseTest.getAnonymousKs()); + assetCountResponse = executor.executeSync(countAssetBuilder); + assertThat(assetCountResponse.results.getCount()).isEqualTo(2); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetGetTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetGetTests.java new file mode 100644 index 000000000..76d1cd958 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetGetTests.java @@ -0,0 +1,90 @@ +package com.kaltura.client.test.tests.servicesTests.AssetTests; + +import com.kaltura.client.enums.AssetReferenceType; +import com.kaltura.client.services.AssetService; +import com.kaltura.client.test.tests.BaseTest; + +import com.kaltura.client.test.utils.AssetUtils; +import com.kaltura.client.test.utils.dbUtils.DBUtils; +import com.kaltura.client.types.Asset; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + + +import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; +import static org.assertj.core.api.Assertions.assertThat; +import static com.kaltura.client.services.AssetService.*; + +public class AssetGetTests extends BaseTest { + + private Long assetId; + private int fileId1; + private int fileId2; + private Long epgProgram; + + + @BeforeClass + private void Asset_get_before_class() { + assetId = BaseTest.getSharedMediaAsset().getId(); + fileId1 = AssetUtils.getAssetFileIds(String.valueOf(assetId)).get(0); + fileId2 = AssetUtils.getAssetFileIds(String.valueOf(assetId)).get(1); + epgProgram = BaseTest.getSharedEpgProgram().getId(); + + } + + @Severity(SeverityLevel.CRITICAL) + @Description("Asset/action/get - VOD") + @Test + private void getVodAsset() { + GetAssetBuilder getAssetBuilder = AssetService.get(String.valueOf(assetId), AssetReferenceType.MEDIA) + .setKs(BaseTest.SharedHousehold.getSharedMasterUserKs()); + Response assetGetResponse = executor.executeSync(getAssetBuilder); + + assertThat(assetGetResponse.results.getId()).isEqualTo(assetId); + assertThat(assetGetResponse.results.getMediaFiles().get(0).getId()).isEqualTo(fileId1); + assertThat(assetGetResponse.results.getMediaFiles().get(1).getId()).isEqualTo(fileId2); + } + + + @Severity(SeverityLevel.CRITICAL) + @Description("Asset/action/get - EPG") + @Test + private void getEpgProgram() { + GetAssetBuilder getAssetBuilder = AssetService.get(String.valueOf(epgProgram), AssetReferenceType.EPG_INTERNAL) + .setKs(BaseTest.SharedHousehold.getSharedMasterUserKs()); + Response assetGetResponse = executor.executeSync(getAssetBuilder); + + assertThat(assetGetResponse.results.getId()).isEqualTo(epgProgram); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("Asset/action/get - un active vod") + @Test + private void getUnactiveVodAsset() { + + int unactiveAssetId = DBUtils.getUnActiveAsset(); + + GetAssetBuilder getAssetBuilder = AssetService.get(String.valueOf(unactiveAssetId), AssetReferenceType.MEDIA) + .setKs(BaseTest.SharedHousehold.getSharedMasterUserKs()); + Response assetGetResponse = executor.executeSync(getAssetBuilder); + + // KalturaAPIException - code: 500007, message: "Asset not found" + assertThat(assetGetResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500007).getCode()); + } + + @Severity(SeverityLevel.MINOR) + @Description("Asset/action/get - invalid asset id") + @Test + private void getWithInvalidAssetId() { + GetAssetBuilder getAssetBuilder = AssetService.get(String.valueOf(assetId + "1"), AssetReferenceType.MEDIA) + .setKs(BaseTest.SharedHousehold.getSharedMasterUserKs()); + Response assetGetResponse = executor.executeSync(getAssetBuilder); + + // KalturaAPIException - code: 500007, message: "Asset not found" + assertThat(assetGetResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500007).getCode()); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetListTests/BundleFilterTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetListTests/BundleFilterTests.java new file mode 100644 index 000000000..8d70fff54 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetListTests/BundleFilterTests.java @@ -0,0 +1,226 @@ +package com.kaltura.client.test.tests.servicesTests.AssetTests.AssetListTests; + +import com.kaltura.client.enums.AssetOrderBy; +import com.kaltura.client.enums.BundleType; +import com.kaltura.client.services.ChannelService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.KsqlBuilder; +import com.kaltura.client.test.utils.ingestUtils.IngestMppUtils; +import com.kaltura.client.types.*; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.List; + +import static com.kaltura.client.services.AssetService.list; +import static com.kaltura.client.services.ChannelService.add; +import static com.kaltura.client.test.Properties.DEFAULT_COLLECTION; +import static com.kaltura.client.test.Properties.getProperty; +import static com.kaltura.client.test.tests.enums.KsqlKey.MEDIA_ID; +import static com.kaltura.client.test.tests.enums.MediaType.*; +import static com.kaltura.client.test.utils.AssetUtils.getAssets; +import static com.kaltura.client.test.utils.dbUtils.DBUtils.*; +import static com.kaltura.client.test.utils.ingestUtils.IngestMppUtils.MppData; +import static com.kaltura.client.test.utils.ingestUtils.IngestMppUtils.insertMpp; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +public class BundleFilterTests extends BaseTest { + private MediaAsset movie1, movie2; + private MediaAsset series1, series2; + private MediaAsset episode1, episode2; + private DynamicChannel channel1, channel2; + private Subscription subscription; + + + @BeforeClass + private void asset_list_bundleFilter_before_class() { + // get movie + List medias = getAssets(2, MOVIE); + movie1 = medias.get(0); + movie2 = medias.get(1); + + // get series + List series = getAssets(2, SERIES); + series1 = series.get(0); + series2 = series.get(1); + + // get episode + List episodes = getAssets(2, EPISODE); + episode1 = episodes.get(0); + episode2 = episodes.get(1); + + // add assets to channel query 1 + String channel1Query = new KsqlBuilder() + .openOr() + .equal(MEDIA_ID.getValue(), String.valueOf(movie1.getId())) + .equal(MEDIA_ID.getValue(), String.valueOf(series1.getId())) + .equal(MEDIA_ID.getValue(), String.valueOf(episode1.getId())) + .closeOr() + .toString(); + + // add assets to channel query 2 + String channel2Query = new KsqlBuilder() + .openOr() + .equal(MEDIA_ID.getValue(), String.valueOf(movie2.getId())) + .equal(MEDIA_ID.getValue(), String.valueOf(series2.getId())) + .equal(MEDIA_ID.getValue(), String.valueOf(episode2.getId())) + .closeOr() + .toString(); + + // add channel1 + channel1 = new DynamicChannel(); + channel1.setMultilingualName(setTranslationToken("channel_" + getEpoch())); + channel1.setMultilingualDescription(setTranslationToken("Description of " + channel1.getName())); + channel1.setSystemName(channel1.getMultilingualName().get(0).getValue() + getRandomValue("")); + channel1.setIsActive(true); + channel1.setKSql(channel1Query); + + channel1 = (DynamicChannel) executor.executeSync(add(channel1) + .setKs(getOperatorKs()) + .setLanguage("*")) + .results; + + // add channel2 + channel2 = new DynamicChannel(); + channel2.setMultilingualName(setTranslationToken("channel_" + getEpoch())); + channel2.setMultilingualDescription(setTranslationToken("Description of " + channel2.getName())); + channel2.setSystemName(channel2.getMultilingualName().get(0).getValue() + getRandomValue("")); + channel2.setIsActive(true); + channel2.setKSql(channel2Query); + + channel2 = (DynamicChannel) executor.executeSync(add(channel2) + .setKs(getOperatorKs()) + .setLanguage("*")) + .results; + + // ingest subscription with 2 new channels + MppData mppData = new MppData() + .channel1(channel1.getMultilingualName().get(0).getValue()) + .channel2(channel2.getMultilingualName().get(0).getValue()); + subscription = insertMpp(mppData); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - bundleFilter - idEqual - subscription") + @Test + private void list_assets_with_bundleFilter_subscription_by_idEqual() { + // set bundleFilter + BundleFilter filter = new BundleFilter(); + filter.setIdEqual(Integer.valueOf(subscription.getId())); + filter.setOrderBy(AssetOrderBy.NAME_ASC.getValue()); + + // get list + ListResponse assetListResponse = executor.executeSync(list(filter) + .setKs(getAnonymousKs())).results; + + // assert response + assertThat(assetListResponse.getTotalCount()).isEqualTo(6); + + assertThat(assetListResponse.getObjects()).extracting("id") + .containsExactlyInAnyOrder(movie1.getId(), episode1.getId(), series1.getId(), movie2.getId(), + episode2.getId(), series2.getId()); + + assertThat(assetListResponse.getObjects()).extracting("name") + .isSorted(); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - bundleFilter - idEqual and typeIn - subscription") + @Test + private void list_assets_with_bundleFilter_subscription_by_idEqual_and_typeIn() { + // adding "MOVIE", "SERIES" and "LINEAR" to string types (excluding "EPISODE") + String types = getConcatenatedString(String.valueOf(getMediaTypeId(MOVIE)), + String.valueOf(getMediaTypeId(SERIES)), + String.valueOf(getMediaTypeId(LINEAR))); + + // set bundleFilter + BundleFilter filter = new BundleFilter(); + filter.setBundleTypeEqual(BundleType.SUBSCRIPTION); + filter.setIdEqual(Integer.valueOf(subscription.getId())); + filter.setTypeIn(types); + + // get list + ListResponse assetListResponse = executor.executeSync(list(filter) + .setKs(getAnonymousKs())).results; + + // assert response + assertThat(assetListResponse.getTotalCount()).isEqualTo(4); + + assertThat(assetListResponse.getObjects()).extracting("id") + .containsExactlyInAnyOrder(movie1.getId(), movie2.getId(), series1.getId(), series2.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - bundleFilter - idEqual and typeIn - collection") + @Test + private void list_assets_with_bundleFilter_collection_by_idEqual_and_typeIn() { + // set bundleFilter + BundleFilter filter = new BundleFilter(); + filter.setBundleTypeEqual(BundleType.COLLECTION); + filter.setIdEqual(Integer.valueOf(getProperty(DEFAULT_COLLECTION))); + + // get full list + List assets = executor.executeSync(list(filter) + .setKs(getAnonymousKs())) + .results + .getObjects(); + + Asset movie = null; + for (Asset asset : assets) { + if (asset.getType() == getMediaTypeId(MOVIE)) { + movie = asset; + break; + } + } + + if (movie == null){ + fail("Please add movie asset into the channel related to the provided collection"); + } + + // get movies list + filter.setTypeIn(String.valueOf(getMediaTypeId(MOVIE))); + ListResponse assetListResponse = executor.executeSync(list(filter) + .setKs(getAnonymousKs())).results; + + // assert response + assertThat(assetListResponse.getTotalCount()).isEqualTo(1); + + assertThat(assetListResponse.getObjects()).extracting("id") + .containsExactly(movie.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - bundleFilter - subscription - idEqual and collection bundleType") + @Test + private void list_assets_with_bundleFilter_by_subscription_idEqual_and_collection_bundleType() { + // set bundleFilter + BundleFilter filter = new BundleFilter(); + filter.setBundleTypeEqual(BundleType.COLLECTION); + filter.setIdEqual(Integer.valueOf(subscription.getId())); + + // get list + ListResponse assetListResponse = executor.executeSync(list(filter) + .setKs(getAnonymousKs())).results; + + // assert response + assertThat(assetListResponse.getTotalCount()).isEqualTo(0); + } + + @AfterClass + private void asset_list_bundleFilter_after_class() { + // delete channels + executor.executeSync(ChannelService.delete(Math.toIntExact(channel1.getId())) + .setKs(getOperatorKs())); + + executor.executeSync(ChannelService.delete(Math.toIntExact(channel2.getId())) + .setKs(getOperatorKs())); + + // delete subscription + IngestMppUtils.deleteMpp(subscription.getName()); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetListTests/ChannelFilterTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetListTests/ChannelFilterTests.java new file mode 100644 index 000000000..f0a0248e5 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetListTests/ChannelFilterTests.java @@ -0,0 +1,140 @@ +package com.kaltura.client.test.tests.servicesTests.AssetTests.AssetListTests; + +import com.kaltura.client.services.ChannelService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.tests.enums.MediaType; +import com.kaltura.client.test.utils.KsqlBuilder; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import static com.kaltura.client.services.AssetService.list; +import static com.kaltura.client.test.tests.enums.KsqlKey.EPG_ID; +import static com.kaltura.client.test.tests.enums.KsqlKey.MEDIA_ID; +import static com.kaltura.client.test.utils.AssetUtils.getAssets; +import static com.kaltura.client.test.utils.AssetUtils.getPrograms; +import static com.kaltura.client.test.utils.BaseUtils.getEpoch; +import static com.kaltura.client.test.utils.dbUtils.DBUtils.getAPIExceptionFromList; +import static com.kaltura.client.test.utils.dbUtils.DBUtils.setTranslationToken; +import static org.assertj.core.api.Assertions.assertThat; + +public class ChannelFilterTests extends BaseTest { + + private MediaAsset asset1, asset2, asset3; + private ProgramAsset program1; + private DynamicChannel channel; + + + @BeforeClass + private void asset_list_channelFilter_before_class() { + // get movie + asset1 = getAssets(1, MediaType.MOVIE).get(0); + + // get series + asset2 = getAssets(1, MediaType.SERIES).get(0); + + // get episode + asset3 = getAssets(1, MediaType.EPISODE).get(0); + + // get epg + program1 = getPrograms(1).get(0); + + // add assets to channel query + String query = new KsqlBuilder() + .openOr() + .equal(MEDIA_ID.getValue(), String.valueOf(asset1.getId())) + .equal(MEDIA_ID.getValue(), String.valueOf(asset2.getId())) + .equal(MEDIA_ID.getValue(), String.valueOf(asset3.getId())) + .equal(EPG_ID.getValue(), String.valueOf(program1.getId())) + .closeOr() + .toString(); + + // add channel + channel = new DynamicChannel(); + channel.setMultilingualName(setTranslationToken("channel_" + getEpoch())); + channel.setMultilingualDescription(setTranslationToken("Description of " + channel.getName())); + channel.setSystemName(channel.getMultilingualName().get(0).getValue()); + channel.setIsActive(true); + channel.setKSql(query); // "Free='" + channel.getName() + "'" + + channel = (DynamicChannel) executor.executeSync(ChannelService.add(channel) + .setKs(getOperatorKs()) + .setLanguage("*")) + .results; + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - channelFilter - idEqual") + @Test + private void list_assets_with_channelFilter_by_channelId() { + // set channelFilter + ChannelFilter filter = new ChannelFilter(); + filter.setIdEqual(Math.toIntExact(channel.getId())); + + // get list + ListResponse assetListResponse = executor.executeSync(list(filter) + .setKs(getAnonymousKs())).results; + + // assert response + assertThat(assetListResponse.getTotalCount()).isEqualTo(4); + assertThat(assetListResponse.getObjects()).extracting("id") + .containsExactlyInAnyOrder(asset1.getId(), asset2.getId(), asset3.getId(), program1.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - channelFilter - idEqual and KSql") + @Test + private void list_assets_with_channelFilter_by_channelId_and_ksql() { + // build query + String query = new KsqlBuilder() + .openOr() + .equal(MEDIA_ID.getValue(), String.valueOf(asset1.getId())) + .equal(EPG_ID.getValue(), String.valueOf(program1.getId())) + .closeOr() + .toString(); + + // set channelFilter + ChannelFilter filter = new ChannelFilter(); + filter.setIdEqual(Math.toIntExact(channel.getId())); + filter.setKSql(query); + + // get list + ListResponse assetListResponse = executor.executeSync(list(filter) + .setKs(getAnonymousKs())).results; + + // assert response + assertThat(assetListResponse.getTotalCount()).isEqualTo(2); + assertThat(assetListResponse.getObjects()).extracting("id") + .containsExactlyInAnyOrder(asset1.getId(), program1.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - with invalid channelId") + @Test + private void list_vod_assets_with_channelFilter_by_channelId_and_ksql() { + // set channelFilter + int invalidChannelId = 1; + ChannelFilter filter = new ChannelFilter(); + filter.setIdEqual(invalidChannelId); + + // get list + Response> assetListResponse = executor.executeSync(list(filter) + .setKs(getAnonymousKs())); + + // assert response + assertThat(assetListResponse.results).isNull(); + assertThat(assetListResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(4018).getCode()); + } + + @AfterClass + private void asset_list_channelFilter_after_class() { + // delete channel + executor.executeSync(ChannelService.delete(Math.toIntExact(channel.getId())) + .setKs(getOperatorKs())); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetListTests/RelatedFilterTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetListTests/RelatedFilterTests.java new file mode 100644 index 000000000..5cb6a0c28 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetListTests/RelatedFilterTests.java @@ -0,0 +1,5 @@ +package com.kaltura.client.test.tests.servicesTests.AssetTests.AssetListTests; + +public class RelatedFilterTests { + // TODO: 7/9/2018 implement RelatedFilterTests +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetListTests/ScheduledRecordingProgramFilterTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetListTests/ScheduledRecordingProgramFilterTests.java new file mode 100644 index 000000000..3e5f549bc --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetListTests/ScheduledRecordingProgramFilterTests.java @@ -0,0 +1,200 @@ +package com.kaltura.client.test.tests.servicesTests.AssetTests.AssetListTests; + +import com.kaltura.client.enums.RecordingStatus; +import com.kaltura.client.services.AssetService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.tests.enums.PremiumService; +import com.kaltura.client.test.utils.HouseholdUtils; +import com.kaltura.client.test.utils.dbUtils.DBUtils; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.json.JSONArray; +import org.json.JSONObject; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.Calendar; +import java.util.List; +import java.util.Optional; + +import static com.kaltura.client.services.HouseholdService.delete; +import static com.kaltura.client.services.RecordingService.add; +import static com.kaltura.client.test.utils.BaseUtils.*; +import static com.kaltura.client.test.utils.HouseholdUtils.createHousehold; +import static com.kaltura.client.test.utils.PurchaseUtils.purchasePpv; +import static com.kaltura.client.test.utils.PurchaseUtils.purchaseSubscription; +import static com.kaltura.client.test.utils.dbUtils.DBUtils.getSubscriptionWithPremiumService; +import static com.kaltura.client.test.utils.ingestUtils.IngestEpgUtils.EpgData; +import static com.kaltura.client.test.utils.ingestUtils.IngestEpgUtils.insertEpg; +import static org.assertj.core.api.Assertions.assertThat; + +public class ScheduledRecordingProgramFilterTests extends BaseTest { + + private int linearAssetId1, linearAssetId2; + private JSONObject linearAssetJsonObject1, linearAssetJsonObject2; + private String masterUserKs; + private List programAssets1, programAssets2; + + + @BeforeClass + private void asset_list_scheduledRecordingProgramFilter_before_class() { + // create household + Household household = createHousehold(); + String udid = HouseholdUtils.getDevicesList(household).get(0).getUdid(); + masterUserKs = HouseholdUtils.getHouseholdMasterUserKs(household, udid); + + // purchase subscription with npvr premium service + Subscription subscription = getSubscriptionWithPremiumService(PremiumService.NPVR); + purchaseSubscription(masterUserKs, Integer.parseInt(subscription.getId()), Optional.empty()); + + // get linearAsset and epg channelId + JSONArray jsonArray = DBUtils.getLinearAssetIdAndEpgChannelNameJsonArray(); + linearAssetJsonObject1 = jsonArray.getJSONObject(0); + linearAssetJsonObject2 = jsonArray.getJSONObject(1); + + linearAssetId1 = linearAssetJsonObject1.getInt("media_id"); + linearAssetId2 = linearAssetJsonObject2.getInt("media_id"); + + // purchase linearAsset + purchasePpv(masterUserKs, Optional.of(linearAssetId1), Optional.empty(), Optional.empty()); + purchasePpv(masterUserKs, Optional.of(linearAssetId2), Optional.empty(), Optional.empty()); + + // ingest epg's + EpgData epgData1 = new EpgData(linearAssetJsonObject1.getString("name")) + .startDate(getEpoch(Calendar.MINUTE, 5)); + programAssets1 = insertEpg(epgData1); + +// String seriesId = String.valueOf(getEpochInLocalTime()); + EpgData epgData2 = new EpgData(linearAssetJsonObject2.getString("name")) + .startDate(getEpoch(Calendar.HOUR, 6)); +// .seriesId(seriesId) +// .seasonsNum(3); + programAssets2 = insertEpg(epgData2); + + // add recordings 1 + Recording recording1 = new Recording(); + recording1.setAssetId(programAssets1.get(0).getId()); + + Response recordingResponse = executor.executeSync(add(recording1).setKs(masterUserKs)); + assertThat(recordingResponse.results.getStatus()).isEqualTo(RecordingStatus.SCHEDULED); + + // add recordings 2 + Recording recording2 = new Recording(); + recording2.setAssetId(programAssets2.get(0).getId()); + + recordingResponse = executor.executeSync(add(recording2).setKs(masterUserKs)); + assertThat(recordingResponse.results.getStatus()).isEqualTo(RecordingStatus.SCHEDULED); + +// // add series recording +// SeriesRecording seriesRecording = new SeriesRecording(); +// seriesRecording.setChannelId(linearAssetJsonObject2.getLong("id")); +// seriesRecording.setSeasonNumber(1); +// seriesRecording.setType(RecordingType.SERIES); +// seriesRecording.setEpgId(); +// +// Response seriesRecordingResponse = executor.executeSync(SeriesRecordingService.add(seriesRecording) +// .setKs(masterUserKs)); +//// assertThat(seriesRecordingResponse.results.getStatus()).isEqualTo(RecordingStatus.SCHEDULED); + + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - scheduledRecordingProgramFilter - channelsIn") + @Test + private void list_assets_with_channelFilter_by_channelId() { + // set scheduledRecordingProgramFilter + ScheduledRecordingProgramFilter filter = new ScheduledRecordingProgramFilter(); + String channelsIn = getConcatenatedString(String.valueOf(linearAssetJsonObject1.getInt("id")), + String.valueOf(linearAssetJsonObject2.getInt("id"))); + filter.setChannelsIn(channelsIn); + + // get list + Response> assetListResponse = executor.executeSync(AssetService.list(filter) + .setKs(masterUserKs)); + + // assert response + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(2); + + assertThat(assetListResponse.results.getObjects()).extracting("id") + .containsExactlyInAnyOrder(programAssets1.get(0).getId(), programAssets2.get(0).getId()); + + assertThat(assetListResponse.results.getObjects()).extracting("name") + .containsExactlyInAnyOrder(programAssets1.get(0).getName(), programAssets2.get(0).getName()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - scheduledRecordingProgramFilter - startDateGreaterThanOrNull") + @Test + private void list_assets_with_channelFilter_by_startDateGreaterThanOrNull() { + // set scheduledRecordingProgramFilter + String channelsIn = getConcatenatedString(String.valueOf(linearAssetJsonObject1.getInt("id")), + String.valueOf(linearAssetJsonObject2.getInt("id"))); + + ScheduledRecordingProgramFilter filter = new ScheduledRecordingProgramFilter(); + filter.setChannelsIn(channelsIn); + filter.setStartDateGreaterThanOrNull(getEpoch(Calendar.HOUR, 3)); + + // get list + Response> assetListResponse = executor.executeSync(AssetService.list(filter) + .setKs(masterUserKs)); + + // assert response + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(programAssets2.get(0).getId()); + assertThat(assetListResponse.results.getObjects().get(0).getName()).isEqualTo(programAssets2.get(0).getName()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - scheduledRecordingProgramFilter - setEndDateLessThanOrNull") + @Test(enabled = true) + private void list_assets_with_channelFilter_by_setEndDateLessThanOrNull() { + // set scheduledRecordingProgramFilter + String channelsIn = getConcatenatedString(String.valueOf(linearAssetJsonObject1.getInt("id")), + String.valueOf(linearAssetJsonObject2.getInt("id"))); + + ScheduledRecordingProgramFilter filter = new ScheduledRecordingProgramFilter(); + filter.setChannelsIn(channelsIn); + filter.setEndDateLessThanOrNull(getEpoch(Calendar.HOUR, 1)); + + // get list + Response> assetListResponse = executor.executeSync(AssetService.list(filter) + .setKs(masterUserKs)); + + // assert response + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(programAssets1.get(0).getId()); + assertThat(assetListResponse.results.getObjects().get(0).getName()).isEqualTo(programAssets1.get(0).getName()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - scheduledRecordingProgramFilter - setRecordingTypeEqual") + @Test(enabled = false) + private void list_assets_with_channelFilter_by_setRecordingTypeEqual() { +// // set scheduledRecordingProgramFilter +// String channelsIn = getConcatenatedString(String.valueOf(linearAssetJsonObject1.getInt("id")), +// String.valueOf(linearAssetJsonObject2.getInt("id"))); +// +// ScheduledRecordingProgramFilter filter = new ScheduledRecordingProgramFilter(); +// filter.setChannelsIn(channelsIn); +// filter.setRecordingTypeEqual(ScheduledRecordingAssetType.SERIES); +// +// // get list +// Response> assetListResponse = executor.executeSync(AssetService.list(filter) +// .setKs(masterUserKs)); +// +// // assert response +// assertThat(assetListResponse.results.getTotalCount()).isEqualTo(1); +// assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(programAssets1.get(0).getId()); +// assertThat(assetListResponse.results.getObjects().get(0).getName()).isEqualTo(programAssets1.get(0).getName()); + } + + @AfterClass + private void asset_list_scheduledRecordingProgramFilter_after_class() { + // cleanup + executor.executeSync(delete().setKs(masterUserKs)); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetListTests/SearchAssetFilterTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetListTests/SearchAssetFilterTests.java new file mode 100644 index 000000000..baed57634 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/AssetTests/AssetListTests/SearchAssetFilterTests.java @@ -0,0 +1,628 @@ +package com.kaltura.client.test.tests.servicesTests.AssetTests.AssetListTests; + +import com.kaltura.client.enums.AssetOrderBy; +import com.kaltura.client.enums.AssetType; +import com.kaltura.client.enums.MetaTagOrderBy; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.tests.enums.KsqlKey; +import com.kaltura.client.test.utils.HouseholdUtils; +import com.kaltura.client.test.utils.KsqlBuilder; +import com.kaltura.client.test.utils.PurchaseUtils; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Issue; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.json.JSONArray; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.*; +import java.util.concurrent.TimeUnit; + +import static com.kaltura.client.services.AssetService.ListAssetBuilder; +import static com.kaltura.client.services.AssetService.list; +import static com.kaltura.client.test.tests.BaseTest.SharedHousehold.getSharedMasterUserKs; +import static com.kaltura.client.test.tests.enums.KsqlKey.*; +import static com.kaltura.client.test.tests.enums.MediaType.EPISODE; +import static com.kaltura.client.test.tests.enums.MediaType.MOVIE; +import static com.kaltura.client.test.utils.AssetUtils.*; +import static com.kaltura.client.test.utils.BaseUtils.getRandomValue; +import static com.kaltura.client.test.utils.dbUtils.DBUtils.getLinearAssetIdAndEpgChannelNameJsonArray; +import static com.kaltura.client.test.utils.dbUtils.DBUtils.getMediaTypeId; +import static com.kaltura.client.test.utils.ingestUtils.IngestEpgUtils.EpgData; +import static com.kaltura.client.test.utils.ingestUtils.IngestEpgUtils.insertEpg; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.*; +import static java.util.TimeZone.getTimeZone; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public class SearchAssetFilterTests extends BaseTest { + + private final String tagName = "Genre"; + private final String metaName = "synopsis"; + private final String metaName2 = "Short title"; + private final String metaValue1 = "A" + getRandomValue("_"); + private final String metaValue2 = "B" + getRandomValue("_"); + + private MediaAsset asset, asset2, asset3; + private ProgramAsset program, program2; + private String tagValue, masterUserKs; + private AssetFilter assetFilter; + private String geoBlockRule = "Philippines Only"; + + + + @BeforeClass(alwaysRun = true) + private void asset_list_searchAssetFilter_before_class() { + // Get asset from shared asset method + tagValue = getRandomValue(tagName + "_"); + + ArrayList list = new ArrayList<>(); + list.add(tagValue); + + HashMap> tagMap = new HashMap<>(); + tagMap.put(tagName, list); + + HashMap stringMetaMap1 = new HashMap<>(); + stringMetaMap1.put(metaName, metaValue1); + stringMetaMap1.put(metaName2, metaValue1); + + HashMap stringMetaMap2 = new HashMap<>(); + stringMetaMap2.put(metaName, metaValue2); + + JSONArray ja = getLinearAssetIdAndEpgChannelNameJsonArray(); + String epgChannelName = ja.getJSONObject(0).getString("name"); + String epgChannelName2 = ja.getJSONObject(1).getString("name"); + + // ingest asset 1 + VodData vodData1 = new VodData() + .mediaType(MOVIE); + asset = insertVod(vodData1, true); + + // ingest asset 2 + VodData vodData2 = new VodData() + .mediaType(MOVIE) + .catalogStartDate(getFormattedTime(Calendar.MINUTE,-100, getTimeZone("UTC"))) + .tags(tagMap) + .stringsMeta(stringMetaMap1) + .geoBlockRule(geoBlockRule); + + asset2 = insertVod(vodData2, true); + + // ingest asset 3 + VodData vodData3 = new VodData() + .mediaType(EPISODE) + .catalogStartDate(getFormattedTime(Calendar.MINUTE,-10, getTimeZone("UTC"))) + .tags(tagMap) + .stringsMeta(stringMetaMap2); + asset3 = insertVod(vodData3, true); + + // ingest epg 1 + EpgData epgData1 = new EpgData(epgChannelName).episodesNum(1); + program = insertEpg(epgData1).get(0); + + // ingest epg 2 + EpgData epgData2 = new EpgData(epgChannelName2).episodesNum(1); + program2 = insertEpg(epgData2).get(0); + + Household household = HouseholdUtils.createHousehold(); + masterUserKs = HouseholdUtils.getHouseholdMasterUserKs(household); + + PurchaseUtils.purchasePpv(masterUserKs, Optional.of(asset.getId().intValue()), Optional.empty(), Optional.empty()); + } + + // Filter by KSQL + // ********************* + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - VOD - filter by geo blocked assets." + + "The filter return only asset that are not blocked for playback because of geo restriction") + @Test + private void listVodAssetsByGeoBlock() { + String query = new KsqlBuilder() + .openAnd() + .openOr() + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset.getId())) + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset2.getId())) + .closeOr() + .equal(GEO_BLOCK.getValue(), "true") + .closeAnd() + .toString(); + + assetFilter = getSearchAssetFilter(query); + + Response> assetListResponse = executor.executeSync(list(assetFilter) + .setKs(masterUserKs)); + + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(1); + // Only asset 1 returned (asset 2 has geo block rule) + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(asset.getId()); + } + + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - VOD - filter by entitled asset") + @Test + private void listVodAssetsByEntitled() { + String query = new KsqlBuilder() + .openAnd() + .openOr() + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset.getId())) + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset2.getId())) + .closeOr() + .equal(ENTITLED_ASSETS.getValue(), "entitled") + .closeAnd() + .toString(); + assetFilter = getSearchAssetFilter(query); + + Response> assetListResponse = executor.executeSync(list(assetFilter) + .setKs(masterUserKs)); + + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(asset.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - VOD - filter by asset name") + @Test + private void listVodAssetsByAssetName() { + String query = new KsqlBuilder().equal("name", asset.getName()).toString(); + assetFilter = getSearchAssetFilter(query); + + Response> assetListResponse = executor.executeSync(list(assetFilter) + .setKs(getSharedMasterUserKs())); + + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(asset.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("Reserved key: asset/action/list - VOD - filter by media_id") + @Test + private void listVodAssetsByMediaId() { + String query = new KsqlBuilder().equal(MEDIA_ID.getValue(), Math.toIntExact(asset.getId())).toString(); + assetFilter = getSearchAssetFilter(query); + + Response> assetListResponse = executor.executeSync(list(assetFilter) + .setKs(getSharedMasterUserKs())); + + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(asset.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - VOD - filter by meta") + @Test + private void listVodAssetsByMeta() { + String query = new KsqlBuilder().equal(metaName, metaValue1).toString(); + assetFilter = getSearchAssetFilter(query); + + Response> assetListResponse = executor.executeSync(list(assetFilter) + .setKs(getSharedMasterUserKs())); + + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(asset2.getId()); + } + + + @Severity(SeverityLevel.CRITICAL) + @Description("Logical conjunction: asset/action/list - VOD - OR query") + @Test + private void listVodAssetsWithOrQuery() { + String query = new KsqlBuilder() + .openOr() + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset.getId())) + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset2.getId())) + .closeOr() + .toString(); + assetFilter = getSearchAssetFilter(query); + + Response> assetListResponse = executor.executeSync(list(assetFilter) + .setKs(getSharedMasterUserKs())); + + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(2); + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(asset2.getId()); + assertThat(assetListResponse.results.getObjects().get(1).getId()).isEqualTo(asset.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("Logical conjunction: asset/action/list - VOD - AND query") + @Test + private void listVodAssetsWithAndQuery() { + String query = new KsqlBuilder() + .openAnd() + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset3.getId())) + .equal(tagName, tagValue) + .closeAnd() + .toString(); + assetFilter = getSearchAssetFilter(query); + + Response> assetListResponse = executor.executeSync(list(assetFilter) + .setKs(getSharedMasterUserKs())); + + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(asset3.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("Alpha numeric field: asset/action/list - VOD - not query") + @Test + private void listVodAssetsWithNotKsqlQuery() { + String query = new KsqlBuilder() + .openAnd() + .notEqual(MEDIA_ID.getValue(), Math.toIntExact(asset3.getId())) + .equal(tagName, tagValue) + .closeAnd() + .toString(); + assetFilter = getSearchAssetFilter(query); + + Response> assetListResponse = executor.executeSync(list(assetFilter) + .setKs(getSharedMasterUserKs())); + + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(asset2.getId()); + } + + + @Severity(SeverityLevel.CRITICAL) + @Description("Alpha numeric field: asset/action/list - VOD - with existing meta value (+)") + @Test + private void listVodAssetsWithExistingMetaValue() { + String query = new KsqlBuilder() + .openAnd() + .openOr() + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset.getId())) + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset2.getId())) + .closeOr() + .exists(metaName2) + .closeAnd() + .toString(); + assetFilter = getSearchAssetFilter(query); + + Response> assetListResponse = executor.executeSync(list(assetFilter) + .setKs(getSharedMasterUserKs())); + + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(asset2.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("Alpha numeric field: asset/action/list - VOD - like query") + @Test + private void listVodAssetsWithLikeKsqlQuery() { + String query = new KsqlBuilder().like(tagName, tagValue).toString(); + assetFilter = getSearchAssetFilter(query); + + List assets = executor.executeSync(list(assetFilter) + .setKs(getSharedMasterUserKs())) + .results + .getObjects(); + + assertThat(assets).isNotNull(); + assertThat(assets.size()).isEqualTo(2); + assertThat(assets).extracting("id").contains(asset3.getId(), asset2.getId()).doesNotContain(asset.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("Alpha numeric field: asset/action/list - VOD - start with query") + @Test + private void listVodAssetsWithStartWithKsqlQuery() { + String query = new KsqlBuilder().startsWith(tagName, tagValue).toString(); + assetFilter = getSearchAssetFilter(query); + + List assets = executor.executeSync(list(assetFilter) + .setKs(getSharedMasterUserKs())) + .results + .getObjects(); + + assertThat(assets).as("assets list").isNotNull(); + assertThat(assets.size()).isEqualTo(2); + assertThat(assets).extracting("id").contains(asset3.getId(), asset2.getId()).doesNotContain(asset.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - VOD - filtered by type (Movie)") + @Test + private void listVodAssetsFilteredByType() { + String query = new KsqlBuilder() + .openAnd() + .equal(tagName, tagValue) + .equal("asset_type", getMediaTypeId(MOVIE)) + .closeAnd() + .toString(); + assetFilter = getSearchAssetFilter(query); + + Response> assetListResponse = executor.executeSync(list(assetFilter) + .setKs(getSharedMasterUserKs())); + + assertThat(assetListResponse.results).isNotNull(); + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(asset2.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - VOD - order by VIEWS") + @Test(groups = "slowBefore") + private void orderVodAssetsByViews_before_wait() { + + int numOfActionsAsset = 3; + int numOfActionsAsset2 = 2; + int numOfActionsAsset3 = 1; + + // Add 3 views to asset + for (int i = 0; i < numOfActionsAsset; i++) { + addViewToAsset(asset, AssetType.MEDIA); + } + + // Add 2 views to asset2 + for (int i = 0; i < numOfActionsAsset2; i++) { + addViewToAsset(asset2, AssetType.MEDIA); + } + + // Add 1 view to asset3 + for (int i = 0; i < numOfActionsAsset3; i++) { + addViewToAsset(asset3, AssetType.MEDIA); + } + } + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - VOD - order by VIEWS") + @Test(groups = {"slowAfter"}, dependsOnGroups = {"slowBefore"}, alwaysRun = true) + private void orderVodAssetsByViews_after_wait() { + String query = new KsqlBuilder() + .openOr() + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset.getId())) + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset2.getId())) + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset3.getId())) + .closeOr() + .toString(); + assetFilter = getSearchAssetFilter(query, null, null, null, null, AssetOrderBy.VIEWS_DESC.getValue()); + + // prepare variables for await() functionality + int delayBetweenRetriesInSeconds = 15; + int maxTimeExpectingValidResponseInSeconds = 80; + // wait for pin to expire + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() -> { + List assetsList = executor.executeSync(list(assetFilter).setKs(getSharedMasterUserKs())).results.getObjects(); + return assetsList.get(0).getId().equals(asset.getId()) && + assetsList.get(1).getId().equals(asset2.getId()) && + assetsList.get(2).getId().equals(asset3.getId()); + }); + + Response> assetListResponse = executor.executeSync(list(assetFilter) + .setKs(getSharedMasterUserKs())); + + assertThat(assetListResponse.error).isNull(); + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(3); + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(asset.getId()); + assertThat(assetListResponse.results.getObjects().get(1).getId()).isEqualTo(asset2.getId()); + assertThat(assetListResponse.results.getObjects().get(2).getId()).isEqualTo(asset3.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - VOD - order by NAME (DESC/ASC") + @Test(enabled = true) + private void orderVodAssetsByName() { + VodData vodData = new VodData().name("AAA"); + updateVod(asset.getName(), vodData); + + vodData.name("BBB"); + updateVod(asset2.getName(), vodData); + + vodData.name("CCC"); + updateVod(asset3.getName(), vodData); + + String query = new KsqlBuilder() + .openOr() + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset.getId())) + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset2.getId())) + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset3.getId())) + .closeOr() + .toString(); + + assetFilter = getSearchAssetFilter(query,null, null, null, null, AssetOrderBy.NAME_ASC.getValue()); + + ListAssetBuilder listAssetBuilder = list(assetFilter) + .setKs(getSharedMasterUserKs()); + Response> assetListResponse = executor.executeSync(listAssetBuilder); + + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(asset.getId()); + assertThat(assetListResponse.results.getObjects().get(1).getId()).isEqualTo(asset2.getId()); + assertThat(assetListResponse.results.getObjects().get(2).getId()).isEqualTo(asset3.getId()); + + assetFilter = getSearchAssetFilter(query,null, null, null, null, AssetOrderBy.NAME_DESC.getValue()); + + listAssetBuilder = list(assetFilter).setKs(getSharedMasterUserKs()); + assetListResponse = executor.executeSync(listAssetBuilder); + + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(asset3.getId()); + assertThat(assetListResponse.results.getObjects().get(1).getId()).isEqualTo(asset2.getId()); + assertThat(assetListResponse.results.getObjects().get(2).getId()).isEqualTo(asset.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - VOD - order by LIKES") + @Test + private void orderVodAssetsByLikes() { + addLikesToAsset(asset3.getId(), 3, AssetType.MEDIA); + addLikesToAsset(asset2.getId(), 2, AssetType.MEDIA); + addLikesToAsset(asset.getId(), 1, AssetType.MEDIA); + + String query = new KsqlBuilder() + .openOr() + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset.getId())) + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset2.getId())) + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset3.getId())) + .closeOr() + .toString(); + assetFilter = getSearchAssetFilter(query,null, null, null, null, AssetOrderBy.LIKES_DESC.getValue()); + + Response> assetListResponse = executor.executeSync(list(assetFilter) + .setKs(getSharedMasterUserKs())); + + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(3); + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(asset3.getId()); + assertThat(assetListResponse.results.getObjects().get(1).getId()).isEqualTo(asset2.getId()); + assertThat(assetListResponse.results.getObjects().get(2).getId()).isEqualTo(asset.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - VOD - order by (num of) VOTES and RATING") + @Test + private void orderVodAssetsByVotesAndRating() { + addVotesToAsset(asset2.getId(), 2, AssetType.MEDIA, 1); + addVotesToAsset(asset3.getId(), 1, AssetType.MEDIA, 5); + + // Order by number of votes (highest to lowest) + String query = new KsqlBuilder() + .openOr() + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset.getId())) + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset2.getId())) + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset3.getId())) + .closeOr() + .toString(); + assetFilter = getSearchAssetFilter(query, null, null, null, null, AssetOrderBy.VOTES_DESC.getValue()); + + ListAssetBuilder listAssetBuilder = list(assetFilter) + .setKs(getSharedMasterUserKs()); + Response> assetListResponse = executor.executeSync(listAssetBuilder); + + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(3); + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(asset2.getId()); + assertThat(assetListResponse.results.getObjects().get(1).getId()).isEqualTo(asset3.getId()); + assertThat(assetListResponse.results.getObjects().get(2).getId()).isEqualTo(asset.getId()); + + // Order by Ratings (highest to lowest) + assetFilter = getSearchAssetFilter(query, null, null, null, null, AssetOrderBy.RATINGS_DESC.getValue()); + + listAssetBuilder = list(assetFilter).setKs(getSharedMasterUserKs()); + assetListResponse = executor.executeSync(listAssetBuilder); + + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(3); + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(asset3.getId()); + assertThat(assetListResponse.results.getObjects().get(1).getId()).isEqualTo(asset2.getId()); + assertThat(assetListResponse.results.getObjects().get(2).getId()).isEqualTo(asset.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - VOD - order by CATALOG START DATE") + @Test + private void orderVodAssetsByCatalogStartDate() { + String query = new KsqlBuilder() + .openOr() + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset.getId())) + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset2.getId())) + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset3.getId())) + .closeOr() + .toString(); + assetFilter = getSearchAssetFilter(query, null, null, null, null, AssetOrderBy.START_DATE_DESC.getValue()); + + ListAssetBuilder listAssetBuilder = list(assetFilter) + .setKs(getSharedMasterUserKs()); + Response> assetListResponse = executor.executeSync(listAssetBuilder); + + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(3); + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(asset3.getId()); + assertThat(assetListResponse.results.getObjects().get(1).getId()).isEqualTo(asset2.getId()); + assertThat(assetListResponse.results.getObjects().get(2).getId()).isEqualTo(asset.getId()); + + assetFilter = getSearchAssetFilter(query, null, null, null, null, AssetOrderBy.START_DATE_ASC.getValue()); + + listAssetBuilder = list(assetFilter).setKs(getSharedMasterUserKs()); + assetListResponse = executor.executeSync(listAssetBuilder); + + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(asset.getId()); + assertThat(assetListResponse.results.getObjects().get(1).getId()).isEqualTo(asset2.getId()); + assertThat(assetListResponse.results.getObjects().get(2).getId()).isEqualTo(asset3.getId()); + } + + @Issue("BEO-5254") + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - VOD - dynamicOrderBy meta (ASC/DESC") + @Test(enabled = false) + + private void dynamicOrderByMeta() { + String query = new KsqlBuilder() + .openAnd() + .openOr() + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset2.getId())) + .equal(MEDIA_ID.getValue(), Math.toIntExact(asset3.getId())) + .closeOr() + .equal("asset_type", getMediaTypeId(MOVIE)) + .closeAnd() + .toString(); + DynamicOrderBy dynamicOrderBy = new DynamicOrderBy(); + dynamicOrderBy.setName(metaName); + dynamicOrderBy.setOrderBy(MetaTagOrderBy.META_ASC); + assetFilter = getSearchAssetFilter(query, null, dynamicOrderBy, null, null, null); + + ListAssetBuilder listAssetBuilder = list(assetFilter) + .setKs(getSharedMasterUserKs()); + Response> assetListResponse = executor.executeSync(listAssetBuilder); + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(2); + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(asset2.getId()); + assertThat(assetListResponse.results.getObjects().get(1).getId()).isEqualTo(asset3.getId()); + } + + + //TODO - add test for KalturaPersistedFilter in searchHistory class + + // EPG + // *************************************************** + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - EPG - name equal query") + @Test + private void listEpgProgramByName() { + String query = new KsqlBuilder().equal("name", program.getName()).toString(); + assetFilter = getSearchAssetFilter(query, "0", null, null, null, null); + + Response> assetListResponse = executor.executeSync(list(assetFilter) + .setKs(getSharedMasterUserKs())); + + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(program.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - EPG - epg channel id equal query") + @Test + private void listEpgProgramByChannelId() { + String query = new KsqlBuilder().equal("epg_channel_id", Math.toIntExact(program.getEpgChannelId())).toString(); + assetFilter = getSearchAssetFilter(query); + + List epgPrograms = executor.executeSync(list(assetFilter) + .setKs(getSharedMasterUserKs())) + .results + .getObjects(); + + assertThat(epgPrograms.size()).isGreaterThan(1); + assertThat(epgPrograms).extracting("epgChannelId").contains(program.getEpgChannelId()); + } + + + @Severity(SeverityLevel.CRITICAL) + @Description("asset/action/list - EPG - filter by epg channel id") + @Test + private void listEpgProgramsFilteredByEpgChannel() { + String query = new KsqlBuilder() + .openAnd() + .openOr() + .equal("name", program.getName()) + .equal("name", program2.getName()) + .closeOr() + .equal(KsqlKey.EPG_CHANNEL_ID.getValue(), program2.getEpgChannelId().toString()) + .closeAnd() + .toString(); + assetFilter = getSearchAssetFilter(query, "0", null, null, null, null); + + Response> assetListResponse = executor.executeSync(list(assetFilter) + .setKs(getSharedMasterUserKs())); + + assertThat(assetListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetListResponse.results.getObjects().get(0).getId()).isEqualTo(program2.getId()); + } +} \ No newline at end of file diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/announcementTests/AnnouncementAddTest.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/announcementTests/AnnouncementAddTest.java new file mode 100644 index 000000000..ee53d5937 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/announcementTests/AnnouncementAddTest.java @@ -0,0 +1,100 @@ +package com.kaltura.client.test.tests.servicesTests.announcementTests; + +import com.kaltura.client.enums.AnnouncementRecipientsType; +import com.kaltura.client.enums.AnnouncementStatus; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.types.Announcement; +import com.kaltura.client.types.AnnouncementFilter; +import com.kaltura.client.types.FilterPager; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.Calendar; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; + +import static com.kaltura.client.services.AnnouncementService.*; +import static com.kaltura.client.services.OttUserService.login; +import static com.kaltura.client.test.utils.BaseUtils.getEpoch; +import static com.kaltura.client.test.utils.dbUtils.DBUtils.getAnnouncementResultMessageId; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public class AnnouncementAddTest extends BaseTest { + + @BeforeClass + private void announcement_add_tests_before_class() { + executor.executeSync(login(partnerId, "alon2986", "alon2986")); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("announcement/action/add") + @Test(enabled = true) + private void addAnnouncement() { + // set announcement + long epoch = getEpoch(Calendar.MINUTE, 1); + Announcement announcement = new Announcement(); + announcement.setName("Announcement_" + epoch); + announcement.setMailSubject(announcement.getName()); + announcement.setMessage(announcement.getName()); + announcement.setEnabled(true); + announcement.setStartTime(epoch); + announcement.setTimezone("UTC"); + announcement.setRecipients(AnnouncementRecipientsType.ALL); + + // add announcement + announcement = executor.executeSync(add(announcement) + .setKs(getOperatorKs())) + .results; + + // get list of announcements + AnnouncementFilter filter = new AnnouncementFilter(); + filter.setOrderBy("NONE"); + + FilterPager pager = new FilterPager(); + pager.setPageSize(10); + pager.setPageIndex(1); + + ListAnnouncementBuilder listAnnouncementBuilder = list(filter, pager).setKs(getOperatorKs()); + + // wait until announcement will be send + await() + .atMost(5, TimeUnit.MINUTES) + .pollInterval(30, TimeUnit.SECONDS) + .until(isAnnouncementSent(listAnnouncementBuilder, announcement.getId())); + + // assert confirmation from Amazon + List ids = getAnnouncementResultMessageId(announcement.getId()); + assertThat(ids).isNotNull(); + assertThat(ids.size()).isGreaterThan(0); + + // assert email sent +// assertThat(isEmailReceived(announcement.getMessage(), true)).isTrue(); + } + + + + // helper methods + private static Callable isAnnouncementSent(ListAnnouncementBuilder listAnnouncementBuilder, int announcementId) { + return () -> { + // get announcement list + List announcements = executor.executeSync(listAnnouncementBuilder) + .results + .getObjects(); + + // get created announcement from list + Announcement announcement = announcements.stream(). + filter(a -> a.getId().equals(announcementId)). + findFirst() + .orElse(null); + + // check if announcement sent + return announcement != null && + announcement.getStatus().equals(AnnouncementStatus.SENT); + }; + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/appTokenTests/AppTokenAddTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/appTokenTests/AppTokenAddTests.java index e66c4ba9a..15d7cbd1c 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/appTokenTests/AppTokenAddTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/appTokenTests/AppTokenAddTests.java @@ -4,36 +4,45 @@ import com.kaltura.client.services.AppTokenService; import com.kaltura.client.test.tests.BaseTest; import com.kaltura.client.test.utils.AppTokenUtils; -import com.kaltura.client.test.utils.BaseUtils; +import com.kaltura.client.types.APIException; import com.kaltura.client.types.AppToken; import com.kaltura.client.utils.response.base.Response; import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import java.util.Calendar; +import java.util.concurrent.TimeUnit; + import static com.kaltura.client.services.AppTokenService.AddAppTokenBuilder; import static com.kaltura.client.services.AppTokenService.GetAppTokenBuilder; import static com.kaltura.client.test.tests.BaseTest.SharedHousehold.*; import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; +import static com.kaltura.client.test.utils.BaseUtils.getEpoch; import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; public class AppTokenAddTests extends BaseTest { private String sessionUserId; private AppToken appToken; private String sessionPrivileges; + private Response addAppTokenResponseSlowTest; + private APIException apiException;; // TODO: 5/3/2018 Add comments! - @BeforeClass + @BeforeClass(alwaysRun = true) private void add_tests_before_class() { sessionUserId = getSharedUser().getUserId(); appToken = AppTokenUtils.addAppToken(sessionUserId, AppTokenHashType.SHA1, null, null); } + @Severity(SeverityLevel.CRITICAL) @Description("appToken/action/add") @Test private void addAppToken() { - AddAppTokenBuilder addAppTokenBuilder = AppTokenService.add(appToken) .setKs(getOperatorKs()); Response appTokenResponse = executor.executeSync(addAppTokenBuilder); @@ -50,11 +59,12 @@ private void addAppToken() { assertThat(appTokenResponse.results.getSessionUserId()).isEqualTo(String.valueOf(sessionUserId)); } + @Severity(SeverityLevel.CRITICAL) @Description("appToken/action/add - without hash type") @Test private void addAppTokenWithDefaultHashType() { appToken = AppTokenUtils.addAppToken(sessionUserId, null, null, null); - + // Invoke AppToken/action/add - with no hash type (will return the default hash type) AddAppTokenBuilder addAppTokenBuilder = AppTokenService.add(appToken) .setKs(getOperatorKs()); @@ -64,6 +74,7 @@ private void addAppTokenWithDefaultHashType() { assertThat(appTokenResponse.results.getHashType()).isEqualTo(AppTokenHashType.SHA256); } + @Severity(SeverityLevel.CRITICAL) @Description("appToken/action/add - with privileges") @Test private void addAppTokenWithPrivileges() { @@ -78,33 +89,44 @@ private void addAppTokenWithPrivileges() { } @Description("appToken/action/add - with expiry date") - @Test(groups = "slow") - private void addAppTokenWithExpiryDate() { - Long expiryDate = BaseUtils.getTimeInEpoch(1); + // priority needed, because at parralel execution both test threads launch setup method of this class and this cause to Error 1 at login with operator user. + @Test(groups = {"slowBefore"}, priority = 1) + private void addAppTokenWithExpiryDate_before_wait() { + // prepare token with expiration after 1 minute + Long expiryDate = getEpoch(Calendar.MINUTE, 1); appToken = AppTokenUtils.addAppToken(sessionUserId, null, sessionPrivileges, Math.toIntExact(expiryDate)); AddAppTokenBuilder addAppTokenBuilder = AppTokenService.add(appToken) .setKs(getOperatorKs()); - Response addAppTokenResponse = executor.executeSync(addAppTokenBuilder); + addAppTokenResponseSlowTest = executor.executeSync(addAppTokenBuilder); - assertThat(addAppTokenResponse.results.getExpiry()).isEqualTo(Math.toIntExact(expiryDate)); + assertThat(addAppTokenResponseSlowTest.results.getExpiry()).isEqualTo(Math.toIntExact(expiryDate)); // Wait until token is expired (according to expiry date) - System.out.println("Waiting 1 minute until token expiry date reached"); + System.out.println("Waiting until token expiry date reached"); + } - try { - Thread.sleep(72000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - GetAppTokenBuilder getAppTokenBuilder = AppTokenService.get(addAppTokenResponse.results.getId()) + @Test(groups = {"slowAfter"}, dependsOnGroups = {"slowBefore"}, alwaysRun = true) + private void addAppTokenWithExpiryDate_after_wait() { + // prepare builder and variables for await() functionality + GetAppTokenBuilder getAppTokenBuilder = AppTokenService.get(addAppTokenResponseSlowTest.results.getId()) .setKs(getOperatorKs()); - Response getAppTokenResponse = executor.executeSync(getAppTokenBuilder); - - assertThat(getAppTokenResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500055).getCode()); + int delayBetweenRetriesInSeconds = 10; + int maxTimeExpectingValidResponseInSeconds = 150; + // test that token expired + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() -> { + apiException = executor.executeSync(getAppTokenBuilder).error; + return (apiException != null); + }); + + assertThat(apiException.getCode()).isEqualTo(getAPIExceptionFromList(500055).getCode()); } + @Severity(SeverityLevel.CRITICAL) @Description("appToken/action/add - with no expiry date (return default expiry date -" + "According to app_token_max_expiry_seconds key value in group_203 CB document") @Test @@ -119,9 +141,10 @@ private void addAppTokenWithNoExpiryDate() { .setKs(getSharedMasterUserKs()); Response addAppTokenResponse = executor.executeSync(addAppTokenBuilder); - assertThat(addAppTokenResponse.results.getExpiry()).isGreaterThan(Math.toIntExact(BaseUtils.getTimeInEpoch(0))); + assertThat(addAppTokenResponse.results.getExpiry()).isGreaterThan(Math.toIntExact(getEpoch())); } + @Severity(SeverityLevel.CRITICAL) @Description("appToken/action/add - with no specific user id") @Test private void addAppTokenWithoutSpecificUserId() { diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/appTokenTests/AppTokenDeleteTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/appTokenTests/AppTokenDeleteTests.java index 7e32acfc8..df630a693 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/appTokenTests/AppTokenDeleteTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/appTokenTests/AppTokenDeleteTests.java @@ -1,61 +1,86 @@ package com.kaltura.client.test.tests.servicesTests.appTokenTests; import com.kaltura.client.enums.AppTokenHashType; -import com.kaltura.client.services.AppTokenService; import com.kaltura.client.test.tests.BaseTest; -import com.kaltura.client.test.utils.AppTokenUtils; import com.kaltura.client.types.AppToken; import com.kaltura.client.utils.response.base.Response; import io.qameta.allure.Description; -import org.testng.annotations.BeforeClass; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; import org.testng.annotations.Test; -import static com.kaltura.client.services.AppTokenService.*; +import static com.kaltura.client.services.AppTokenService.add; +import static com.kaltura.client.services.AppTokenService.delete; import static com.kaltura.client.test.tests.BaseTest.SharedHousehold.getSharedUser; import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; import static org.assertj.core.api.Assertions.assertThat; public class AppTokenDeleteTests extends BaseTest { - - private String sessionUserId; - private AppToken appToken; - - @BeforeClass - private void add_tests_before_class() { - sessionUserId = getSharedUser().getUserId(); - appToken = AppTokenUtils.addAppToken(sessionUserId, AppTokenHashType.SHA1, null, null); - } + @Severity(SeverityLevel.CRITICAL) @Description("appToken/action/delete") @Test - // TODO: 5/3/2018 not clear test name! - private void addAppToken() { + private void deleteAppToken() { // Add token - AddAppTokenBuilder addAppTokenBuilder = AppTokenService.add(appToken).setKs(getOperatorKs()); - Response appTokenResponse = executor.executeSync(addAppTokenBuilder); + String sessionUserId = getSharedUser().getUserId(); + + AppToken appToken = new AppToken(); + appToken.setSessionUserId(sessionUserId); + appToken.setHashType(AppTokenHashType.SHA1); + + Response appTokenResponse = executor.executeSync(add(appToken) + .setKs(getOperatorKs())); assertThat(appTokenResponse.error).isNull(); assertThat(appTokenResponse.results.getExpiry()).isNull(); // Delete token - DeleteAppTokenBuilder deleteAppTokenBuilder = AppTokenService.delete(appTokenResponse.results.getId()).setKs(getOperatorKs()); - Response deleteTokenResponse = executor.executeSync(deleteAppTokenBuilder); + Response booleanResponse = executor.executeSync(delete(appTokenResponse.results.getId()) + .setKs(getOperatorKs())); - assertThat(deleteTokenResponse.results).isTrue(); + assertThat(booleanResponse.results).isTrue(); + } + @Severity(SeverityLevel.MINOR) + @Description("appToken/action/delete - invalid token") + @Test + private void deleteInvalidAppToken() { // Try to delete token using invalid token id String invalidTokenId = "1234"; - deleteAppTokenBuilder = AppTokenService.delete(invalidTokenId).setKs(getOperatorKs()); - deleteTokenResponse = executor.executeSync(deleteAppTokenBuilder); + Response booleanResponse = executor.executeSync(delete(invalidTokenId) + .setKs(getOperatorKs())); + + assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500055).getCode()); + } + + @Severity(SeverityLevel.MINOR) + @Description("appToken/action/delete - same token twice") + @Test + private void deleteSameAppTokenTwice() { + // Add token + String sessionUserId = getSharedUser().getUserId(); + + AppToken appToken = new AppToken(); + appToken.setSessionUserId(sessionUserId); + appToken.setHashType(AppTokenHashType.SHA1); + + Response appTokenResponse = executor.executeSync(add(appToken) + .setKs(getOperatorKs())); + + assertThat(appTokenResponse.error).isNull(); + assertThat(appTokenResponse.results.getExpiry()).isNull(); + + // Delete token + Response booleanResponse = executor.executeSync(delete(appTokenResponse.results.getId()) + .setKs(getOperatorKs())); - // TODO: 5/3/2018 split two scenarios into separate tests - assertThat(deleteTokenResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500055).getCode()); + assertThat(booleanResponse.results).isTrue(); // Try to delete token again - exception returned - deleteAppTokenBuilder = AppTokenService.delete(appTokenResponse.results.getId()).setKs(getOperatorKs()); - deleteTokenResponse = executor.executeSync(deleteAppTokenBuilder); + booleanResponse = executor.executeSync(delete(appTokenResponse.results.getId()) + .setKs(getOperatorKs())); - assertThat(deleteTokenResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500055).getCode()); + assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500055).getCode()); } } \ No newline at end of file diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/appTokenTests/AppTokenGetTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/appTokenTests/AppTokenGetTests.java index 37256f284..f1b9249c8 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/appTokenTests/AppTokenGetTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/appTokenTests/AppTokenGetTests.java @@ -8,9 +8,13 @@ import com.kaltura.client.types.AppToken; import com.kaltura.client.utils.response.base.Response; import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import java.util.Calendar; + import static com.kaltura.client.test.tests.BaseTest.SharedHousehold.getSharedUser; import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; import static org.assertj.core.api.Assertions.assertThat; @@ -28,9 +32,10 @@ public class AppTokenGetTests extends BaseTest { @BeforeClass private void get_tests_before_class() { sessionUserId = getSharedUser().getUserId(); - expiryDate = BaseUtils.getTimeInEpoch(offSetInMinutes); + expiryDate = BaseUtils.getEpoch(Calendar.MINUTE, offSetInMinutes); } + @Severity(SeverityLevel.CRITICAL) @Description("AppToken/action/get") @Test private void getAppToken() { @@ -54,6 +59,7 @@ private void getAppToken() { assertThat(getAppTokenResponse.results.getSessionUserId()).isEqualTo(sessionUserId); } + @Severity(SeverityLevel.MINOR) @Description("AppToken/action/get") @Test // TODO: 5/3/2018 use underscore in test method names and edit the description diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/appTokenTests/AppTokenStartSessionTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/appTokenTests/AppTokenStartSessionTests.java index e732aed69..334dafbcc 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/appTokenTests/AppTokenStartSessionTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/appTokenTests/AppTokenStartSessionTests.java @@ -11,9 +11,13 @@ import com.kaltura.client.utils.response.base.Response; import io.qameta.allure.Description; import io.qameta.allure.Issue; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import java.util.Calendar; + import static com.kaltura.client.services.AppTokenService.StartSessionAppTokenBuilder; import static com.kaltura.client.services.OttUserService.AnonymousLoginOttUserBuilder; import static com.kaltura.client.services.OttUserService.anonymousLogin; @@ -39,9 +43,10 @@ private void add_tests_before_class() { AnonymousLoginOttUserBuilder anonymousLoginOttUserBuilder = anonymousLogin(partnerId, udid1); Response loginSessionResponse = executor.executeSync(anonymousLoginOttUserBuilder); anonymousKs = loginSessionResponse.results.getKs(); - expiryDate = BaseUtils.getTimeInEpoch(1); + expiryDate = BaseUtils.getEpoch(Calendar.MINUTE, 1); } + @Severity(SeverityLevel.CRITICAL) @Description("appToken/action/startSession - SHA1") @Test private void startSessionSha1() { @@ -85,6 +90,7 @@ private void startSessionSha1() { } + @Severity(SeverityLevel.CRITICAL) @Description("appToken/action/startSession - SHA256") @Test private void startSessionSha256() { @@ -125,9 +131,10 @@ private void startSessionSha256() { // TODO - Add session/action/get request with ks received from startSession API } + @Severity(SeverityLevel.CRITICAL) @Issue("BEO-4980") @Description("appToken/action/startSession - token id with default expiry date (according to the value in group_203 CB document") - @Test + @Test(enabled = false) private void startSessionDefaultExpiryDate() { // TODO: 5/3/2018 add comments! int expiryDate = 0; diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/assetCommentTests/AssetCommentAddTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/assetCommentTests/AssetCommentAddTests.java index d5171614f..6c09f5394 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/assetCommentTests/AssetCommentAddTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/assetCommentTests/AssetCommentAddTests.java @@ -6,19 +6,21 @@ import com.kaltura.client.test.tests.BaseTest; import com.kaltura.client.test.utils.AssetCommentUtils; import com.kaltura.client.test.utils.BaseUtils; -import com.kaltura.client.test.utils.IngestUtils; import com.kaltura.client.types.*; import com.kaltura.client.utils.response.base.Response; import io.qameta.allure.Description; +import org.assertj.core.data.Offset; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import java.util.Optional; +import java.util.List; import static com.kaltura.client.services.AssetCommentService.AddAssetCommentBuilder; import static com.kaltura.client.services.AssetCommentService.ListAssetCommentBuilder; import static com.kaltura.client.test.utils.HouseholdUtils.createHousehold; import static com.kaltura.client.test.utils.HouseholdUtils.getHouseholdMasterUserKs; +import static com.kaltura.client.test.utils.ingestUtils.IngestEpgUtils.EpgData; +import static com.kaltura.client.test.utils.ingestUtils.IngestEpgUtils.insertEpg; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; public class AssetCommentAddTests extends BaseTest { @@ -37,7 +39,7 @@ private void add_tests_before_class() { int numOfUsers = 1; int numOfDevices = 1; household = createHousehold(numOfUsers, numOfDevices, false); - householdMasterUserKs = getHouseholdMasterUserKs(household,null); + householdMasterUserKs = getHouseholdMasterUserKs(household); } @Description("AssetComment/action/add - vod asset") @@ -50,7 +52,7 @@ private void addCommentForVod() { // AssetComment/action/add AddAssetCommentBuilder addAssetCommentBuilder = AssetCommentService.add(assetComment) - .setKs(getHouseholdMasterUserKs(household,null)); + .setKs(getHouseholdMasterUserKs(household)); Response assetCommentResponse = executor.executeSync(addAssetCommentBuilder); //Assertions for AssetComment/action/add @@ -61,7 +63,7 @@ private void addCommentForVod() { assertThat(assetCommentResponse.results.getText()).isEqualTo(text); assertThat(assetCommentResponse.results.getSubHeader()).isEqualTo(subHeader); assertThat(assetCommentResponse.results.getHeader()).isEqualTo(header); - assertThat(assetCommentResponse.results.getCreateDate()).isLessThanOrEqualTo(BaseUtils.getTimeInEpoch(0)); + assertThat(assetCommentResponse.results.getCreateDate()).isCloseTo(BaseUtils.getEpoch(), Offset.offset ((long)10)); //Initialize assetCommentFilter object @@ -82,18 +84,16 @@ private void addCommentForVod() { assertThat(assetCommentObjectResponse.getHeader()).isEqualTo(assetCommentResponse.results.getHeader()); assertThat(assetCommentObjectResponse.getText()).isEqualTo(assetCommentResponse.results.getText()); assertThat(assetCommentObjectResponse.getWriter()).isEqualTo(assetCommentResponse.results.getWriter()); - assertThat(assetCommentObjectResponse.getCreateDate()).isLessThanOrEqualTo(BaseUtils.getTimeInEpoch(0)); + assertThat(assetCommentObjectResponse.getCreateDate()).isCloseTo(BaseUtils.getEpoch(), Offset.offset ((long)10)); } @Description("AssetComment/action/add - EPG program") @Test private void addCommentForEPGProgram() { - // Ingest EPG program - Response> epgProgram = IngestUtils.ingestEPG("Shmulik_Series_1", Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), - Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()); - Long epgProgramId = epgProgram.results.getObjects().get(0).getId(); + List epgPrograms = insertEpg(new EpgData("Shmulik_Series_1")); + Long epgProgramId = epgPrograms.get(0).getId(); // Initialize assetComment object AssetComment assetComment = AssetCommentUtils.assetComment(Math.toIntExact(epgProgramId), AssetType.EPG, writer, text, createDate, subHeader, header); diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/assetCommentTests/AssetCommentListTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/assetCommentTests/AssetCommentListTests.java index 434d103e0..67452fc9b 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/assetCommentTests/AssetCommentListTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/assetCommentTests/AssetCommentListTests.java @@ -4,8 +4,8 @@ import com.kaltura.client.enums.AssetType; import com.kaltura.client.services.AssetCommentService; import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.tests.enums.MediaType; import com.kaltura.client.test.utils.AssetCommentUtils; -import com.kaltura.client.test.utils.IngestUtils; import com.kaltura.client.types.AssetComment; import com.kaltura.client.types.AssetCommentFilter; import com.kaltura.client.types.Household; @@ -15,12 +15,11 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import java.util.Optional; - import static com.kaltura.client.services.AssetCommentService.ListAssetCommentBuilder; -import static com.kaltura.client.test.IngestConstants.MOVIE_MEDIA_TYPE; import static com.kaltura.client.test.utils.HouseholdUtils.createHousehold; import static com.kaltura.client.test.utils.HouseholdUtils.getHouseholdMasterUserKs; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.VodData; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.insertVod; import static org.assertj.core.api.Assertions.assertThat; public class AssetCommentListTests extends BaseTest { @@ -29,32 +28,30 @@ public class AssetCommentListTests extends BaseTest { private String householdMasterUserKs; @BeforeClass - // TODO: 5/3/2018 edit before method name - private void add_tests_before_class() { + private void asset_comment_listTests_before_class() { int numOfUsers = 1; int numOfDevices = 1; household = createHousehold(numOfUsers, numOfDevices, false); - householdMasterUserKs = getHouseholdMasterUserKs(household, null); + householdMasterUserKs = getHouseholdMasterUserKs(household); } @Description("AssetComment/action/list - check order by functionality") @Test private void checkCommentsOrder() { - String writer = "Shmulik"; Long createDate = 0L; String header = "header"; String subHeader = "subHeader"; String text = "A lot of text"; - Long assetId = IngestUtils.ingestVOD(Optional.empty(), Optional.empty(), true, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), - Optional.empty(), Optional.empty(), Optional.empty(), Optional.of(String.valueOf(MOVIE_MEDIA_TYPE)), Optional.empty(), Optional.empty()).getId(); + VodData vodData = new VodData() + .mediaType(MediaType.MOVIE); + Long assetId = insertVod(vodData, true).getId(); // Initialize assetComment object AssetComment assetComment = AssetCommentUtils.assetComment(Math.toIntExact(assetId), AssetType.MEDIA, writer, text, createDate, subHeader, header); // AssetComment/action/add - first comment - AssetCommentService.AddAssetCommentBuilder addAssetCommentBuilder = AssetCommentService.add(assetComment) .setKs(householdMasterUserKs); Response assetComment1Response = executor.executeSync(addAssetCommentBuilder); @@ -69,7 +66,6 @@ private void checkCommentsOrder() { AssetCommentOrderBy.CREATE_DATE_DESC); //AssetComment/action/list - return both comments - ListAssetCommentBuilder listAssetCommentBuilder = AssetCommentService.list(assetCommentFilter, null) .setKs(householdMasterUserKs); Response> assetCommentListResponse = executor.executeSync(listAssetCommentBuilder); diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/assetHistoryTests/AssetHistoryCleanTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/assetHistoryTests/AssetHistoryCleanTests.java new file mode 100644 index 000000000..0752bd9f7 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/assetHistoryTests/AssetHistoryCleanTests.java @@ -0,0 +1,412 @@ +package com.kaltura.client.test.tests.servicesTests.assetHistoryTests; + +import com.kaltura.client.enums.*; +import com.kaltura.client.services.HouseholdService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.AssetUtils; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.List; +import java.util.Optional; +import java.util.concurrent.TimeUnit; + +import static com.kaltura.client.services.AssetHistoryService.*; +import static com.kaltura.client.services.BookmarkService.AddBookmarkBuilder; +import static com.kaltura.client.services.BookmarkService.add; +import static com.kaltura.client.test.tests.enums.MediaType.EPISODE; +import static com.kaltura.client.test.tests.enums.MediaType.MOVIE; +import static com.kaltura.client.test.utils.AssetUtils.getAssets; +import static com.kaltura.client.test.utils.BookmarkUtils.addBookmark; +import static com.kaltura.client.test.utils.HouseholdUtils.*; +import static com.kaltura.client.test.utils.PurchaseUtils.purchasePpv; +import static com.kaltura.client.test.utils.dbUtils.DBUtils.getMediaTypeId; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public class AssetHistoryCleanTests extends BaseTest { + + + private final int position1 = 10; + private final int position2 = 20; + private final int numOfUsers = 1; + private final int numOfDevices = 2; + + private MediaAsset movie; + private int movieFileId; + + private MediaAsset movie2; + private int movie2FileId; + + private MediaAsset episode; + private int episodeFileId; + + String masterUserKsCleanHistory; + String masterUserKsCleanSpecifcAssetHistory; + String masterUserKsCleanSpecifcAssetTypeHistory; + String masterUserKsCleanAssetsAccordingToWatchStatusDone; + String masterUserKsCleanAssetsAccordingToWatchStatusProgress; + + @BeforeClass(alwaysRun = true) + private void assetHistory_clean_tests_before_class() { + List movies = getAssets(2, MOVIE); + + // get first movie asset + movie = movies.get(0); + movieFileId = AssetUtils.getAssetFileIds(String.valueOf(movie.getId())).get(0); + + // get second movie asset + movie2 = movies.get(1); + movie2FileId = AssetUtils.getAssetFileIds(String.valueOf(movie2.getId())).get(0); + + // Ingest episode asset + episode = getAssets(1, EPISODE).get(0); + episodeFileId = AssetUtils.getAssetFileIds(String.valueOf(episode.getId())).get(0); + } + + + @Description("assetHistory/action/clean - no filtering") + @Test(groups = {"slowBefore"}) + private void cleanHistory_before_wait() { + // create household + Household household = createHousehold(numOfUsers, numOfDevices, true); + String udid1 = getDevicesList(household).get(0).getUdid(); + String udid2 = getDevicesList(household).get(1).getUdid(); + masterUserKsCleanHistory = getHouseholdMasterUserKs(household, udid1); + + // purchase media and prepare media file for playback + purchasePpv(masterUserKsCleanHistory, Optional.of(movie.getId().intValue()), Optional.of(movieFileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsCleanHistory, String.valueOf(movie.getId()), + String.valueOf(movieFileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark first asset + Bookmark bookmark1 = addBookmark(position1, String.valueOf(movie.getId()), movieFileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); + AddBookmarkBuilder addBookmarkBuilder = add(bookmark1).setKs(masterUserKsCleanHistory); + executor.executeSync(addBookmarkBuilder); + + // purchase media2 and prepare media file for playback + masterUserKsCleanHistory = getHouseholdMasterUserKs(household, udid2); + purchasePpv(masterUserKsCleanHistory, Optional.of(movie2.getId().intValue()), Optional.of(movie2FileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsCleanHistory, String.valueOf(movie2.getId()), + String.valueOf(movie2FileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark second asset + Bookmark bookmark2 = addBookmark(position1, String.valueOf(movie2.getId()), movie2FileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); + addBookmarkBuilder = add(bookmark2).setKs(masterUserKsCleanHistory); + executor.executeSync(addBookmarkBuilder); + } + + @Description("assetHistory/action/clean - no filtering") + @Test(groups = {"slowAfter"}, dependsOnGroups = {"slowBefore"}, alwaysRun = true) + private void cleanHistory_after_wait() { + // assetHistory/action/list - both assets should returned + AssetHistoryFilter assetHistoryFilter = new AssetHistoryFilter(); + assetHistoryFilter.setStatusEqual(WatchStatus.ALL); + + // prepare variables for await() functionality + int delayBetweenRetriesInSeconds = 15; + int maxTimeExpectingValidResponseInSeconds = 80; + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() -> { + // wait for 2 assets at history response + return (executor.executeSync(list(assetHistoryFilter).setKs(masterUserKsCleanHistory)).results.getTotalCount() == 2); + }); + + Response> assetHistoryListResponse = executor.executeSync(list(assetHistoryFilter) + .setKs(masterUserKsCleanHistory)); + + assertThat(assetHistoryListResponse.error).isNull(); + assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(2); + + // assetHistory/action/clean + CleanAssetHistoryBuilder cleanAssetHistoryBuilder = clean(assetHistoryFilter); + cleanAssetHistoryBuilder.setKs(masterUserKsCleanHistory); + executor.executeSync(cleanAssetHistoryBuilder); + + // assetHistory/action/list - after clean - no object returned + assetHistoryListResponse = executor.executeSync(list(assetHistoryFilter) + .setKs(masterUserKsCleanHistory)); + + assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(0); + + // cleanup - delete household + executor.executeSync(HouseholdService.delete().setKs(masterUserKsCleanHistory)); + } + + @Description("assetHistory/action/clean - filtered by asset id") + @Test(groups = {"slowBefore"}) + private void cleanSpecifcAssetHistory_before_wait() { + // create household + Household household = createHousehold(numOfUsers, numOfDevices, true); + String udid1 = getDevicesList(household).get(0).getUdid(); + String udid2 = getDevicesList(household).get(1).getUdid(); + masterUserKsCleanSpecifcAssetHistory = getHouseholdMasterUserKs(household, udid1); + + // purchase media and prepare media file for playback + purchasePpv(masterUserKsCleanSpecifcAssetHistory, Optional.of(movie.getId().intValue()), Optional.of(movieFileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsCleanSpecifcAssetHistory, String.valueOf(movie.getId()), + String.valueOf(movieFileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark first asset + Bookmark bookmark1 = addBookmark(position1, String.valueOf(movie.getId()), movieFileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); + executor.executeSync(add(bookmark1) + .setKs(masterUserKsCleanSpecifcAssetHistory)); + + // purchase media2 and prepare media file for playback + masterUserKsCleanSpecifcAssetHistory = getHouseholdMasterUserKs(household, udid2); + purchasePpv(masterUserKsCleanSpecifcAssetHistory, Optional.of(movie2.getId().intValue()), Optional.of(movie2FileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsCleanSpecifcAssetHistory, String.valueOf(movie2.getId()), + String.valueOf(movie2FileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark second asset + Bookmark bookmark2 = addBookmark(position2, String.valueOf(movie2.getId()), movie2FileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); + executor.executeSync(add(bookmark2) + .setKs(masterUserKsCleanSpecifcAssetHistory)); + } + + @Description("assetHistory/action/clean - filtered by asset id") + @Test(groups = {"slowAfter"}, dependsOnGroups = {"slowBefore"}, alwaysRun = true) + private void cleanSpecifcAssetHistory_after_wait() { + // assetHistory/action/clean + AssetHistoryFilter assetHistoryFilter = new AssetHistoryFilter(); + assetHistoryFilter.setAssetIdIn(String.valueOf(movie.getId())); + assetHistoryFilter.setStatusEqual(WatchStatus.ALL); + + CleanAssetHistoryBuilder cleanAssetHistoryBuilder = clean(assetHistoryFilter); + cleanAssetHistoryBuilder.setKs(masterUserKsCleanSpecifcAssetHistory); + executor.executeSync(cleanAssetHistoryBuilder); + + // Update assetHistoryFilter object (assetIdIn = "") + assetHistoryFilter.setAssetIdIn(""); + + // prepare variables for await() functionality + int delayBetweenRetriesInSeconds = 15; + int maxTimeExpectingValidResponseInSeconds = 80; + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() -> { + // wait for 1 assets at history response + return (executor.executeSync(list(assetHistoryFilter).setKs(masterUserKsCleanSpecifcAssetHistory)).results.getTotalCount() == 1); + }); + + // assetHistory/action/list - after clean - only asset id 2 returned (was not cleaned) + Response> assetHistoryListResponse = executor.executeSync(list(assetHistoryFilter) + .setKs(masterUserKsCleanSpecifcAssetHistory)); + + assertThat(assetHistoryListResponse.error).isNull(); + assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetHistoryListResponse.results.getObjects().get(0).getAssetId()).isEqualTo(movie2.getId()); + + // cleanup - delete household + executor.executeSync(HouseholdService.delete().setKs(masterUserKsCleanSpecifcAssetHistory)); + } + + @Description("assetHistory/action/clean - filtered by asset type") + @Test(groups = {"slowBefore"}) + private void cleanSpecifcAssetTypeHistory_before_wait() { + // create household + Household household = createHousehold(numOfUsers, numOfDevices, true); + String udid1 = getDevicesList(household).get(0).getUdid(); + String udid2 = getDevicesList(household).get(1).getUdid(); + masterUserKsCleanSpecifcAssetTypeHistory = getHouseholdMasterUserKs(household, udid1); + + // purchase media and prepare media file for playback + purchasePpv(masterUserKsCleanSpecifcAssetTypeHistory, Optional.of(movie.getId().intValue()), Optional.of(movieFileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsCleanSpecifcAssetTypeHistory, String.valueOf(movie.getId()), + String.valueOf(movieFileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark first asset + Bookmark bookmark = addBookmark(position1, String.valueOf(movie.getId()), movieFileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); + executor.executeSync(add(bookmark) + .setKs(masterUserKsCleanSpecifcAssetTypeHistory)); + + // purchase media episode and prepare media file for playback + masterUserKsCleanSpecifcAssetTypeHistory = getHouseholdMasterUserKs(household, udid2); + purchasePpv(masterUserKsCleanSpecifcAssetTypeHistory, Optional.of(episode.getId().intValue()), Optional.of(episodeFileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsCleanSpecifcAssetTypeHistory, String.valueOf(episode.getId()), + String.valueOf(episodeFileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark second asset + bookmark = addBookmark(position2, String.valueOf(episode.getId()), episodeFileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); + executor.executeSync(add(bookmark) + .setKs(masterUserKsCleanSpecifcAssetTypeHistory)); + } + + @Description("assetHistory/action/clean - filtered by asset type") + @Test(groups = {"slowAfter"}, dependsOnGroups = {"slowBefore"}, alwaysRun = true) + private void cleanSpecifcAssetTypeHistory_after_wait() { + //assetHistory/action/clean - only episode type (episode) + AssetHistoryFilter assetHistoryFilter = new AssetHistoryFilter(); + assetHistoryFilter.setTypeIn(String.valueOf(getMediaTypeId(EPISODE))); + assetHistoryFilter.setStatusEqual(WatchStatus.ALL); + + CleanAssetHistoryBuilder cleanAssetHistoryBuilder = clean(assetHistoryFilter); + cleanAssetHistoryBuilder.setKs(masterUserKsCleanSpecifcAssetTypeHistory); + executor.executeSync(cleanAssetHistoryBuilder); + + // Update assetHistoryFilter object (assetIdIn = "") + assetHistoryFilter.setTypeIn(""); + + // prepare variables for await() functionality + int delayBetweenRetriesInSeconds = 15; + int maxTimeExpectingValidResponseInSeconds = 80; + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() -> { + // wait for 1 assets at history response + return (executor.executeSync(list(assetHistoryFilter).setKs(masterUserKsCleanSpecifcAssetTypeHistory)).results.getTotalCount() == 1); + }); + + // assetHistory/action/list - after clean - only movie returned (was not cleaned) + Response> assetHistoryListResponse = executor.executeSync(list(assetHistoryFilter) + .setKs(masterUserKsCleanSpecifcAssetTypeHistory)); + + assertThat(assetHistoryListResponse.error).isNull(); + assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetHistoryListResponse.results.getObjects().get(0).getAssetId()).isEqualTo(movie.getId()); + + // cleanup - delete household + executor.executeSync(HouseholdService.delete().setKs(masterUserKsCleanSpecifcAssetTypeHistory)); + } + + @Description("assetHistory/action/clean - filtered by asset finished") + @Test(groups = {"slowBefore"}) + private void cleanAssetsAccordingToWatchStatusDone_before_wait() { + // create household + Household household = createHousehold(numOfUsers, numOfDevices, true); + String udid1 = getDevicesList(household).get(0).getUdid(); + String udid2 = getDevicesList(household).get(1).getUdid(); + masterUserKsCleanAssetsAccordingToWatchStatusDone = getHouseholdMasterUserKs(household, udid1); + + // purchase media and prepare media file for playback + purchasePpv(masterUserKsCleanAssetsAccordingToWatchStatusDone, Optional.of(movie.getId().intValue()), Optional.of(movieFileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsCleanAssetsAccordingToWatchStatusDone, String.valueOf(movie.getId()), + String.valueOf(movieFileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark first asset + Bookmark bookmark = addBookmark(position1, String.valueOf(movie.getId()), movieFileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); + AddBookmarkBuilder addBookmarkBuilder = add(bookmark).setKs(masterUserKsCleanAssetsAccordingToWatchStatusDone); + executor.executeSync(addBookmarkBuilder); + + // purchase media episode and prepare media file for playback + masterUserKsCleanAssetsAccordingToWatchStatusDone = getHouseholdMasterUserKs(household, udid2); + purchasePpv(masterUserKsCleanAssetsAccordingToWatchStatusDone, Optional.of(episode.getId().intValue()), Optional.of(episodeFileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsCleanAssetsAccordingToWatchStatusDone, String.valueOf(episode.getId()), + String.valueOf(episodeFileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark second asset + bookmark = addBookmark(position2, String.valueOf(episode.getId()), episodeFileId, AssetType.MEDIA, BookmarkActionType.FINISH); + addBookmarkBuilder = add(bookmark).setKs(masterUserKsCleanAssetsAccordingToWatchStatusDone); + executor.executeSync(addBookmarkBuilder); + } + + @Description("assetHistory/action/clean - filtered by asset finished") + @Test(groups = {"slowAfter"}, dependsOnGroups = {"slowBefore"}, alwaysRun = true) + private void cleanAssetsAccordingToWatchStatusDone_after_wait() { + //assetHistory/action/clean - only asset that were finished (episode) + AssetHistoryFilter assetHistoryFilter = new AssetHistoryFilter(); + assetHistoryFilter.setStatusEqual(WatchStatus.DONE); + + CleanAssetHistoryBuilder cleanAssetHistoryBuilder = clean(assetHistoryFilter); + cleanAssetHistoryBuilder.setKs(masterUserKsCleanAssetsAccordingToWatchStatusDone); + executor.executeSync(cleanAssetHistoryBuilder); + + // assetHistory/action/list - after clean - only movie returned (was not cleaned) + assetHistoryFilter.setStatusEqual(WatchStatus.ALL); + + // prepare variables for await() functionality + int delayBetweenRetriesInSeconds = 15; + int maxTimeExpectingValidResponseInSeconds = 80; + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() -> { + // wait for 1 assets at history response + return (executor.executeSync(list(assetHistoryFilter).setKs(masterUserKsCleanAssetsAccordingToWatchStatusDone)).results.getTotalCount() == 1); + }); + + Response> assetHistoryListResponse = executor.executeSync(list(assetHistoryFilter) + .setKs(masterUserKsCleanAssetsAccordingToWatchStatusDone)); + + assertThat(assetHistoryListResponse.error).isNull(); + assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetHistoryListResponse.results.getObjects().get(0).getAssetId()).isEqualTo(movie.getId()); + + // cleanup - delete household + executor.executeSync(HouseholdService.delete().setKs(masterUserKsCleanAssetsAccordingToWatchStatusDone)); + } + + @Description("assetHistory/action/clean - filtered by asset in progress") + @Test(groups = {"slowBefore"}) + private void cleanAssetsAccordingToWatchStatusProgress_before_wait() { + // create household + Household household = createHousehold(numOfUsers, numOfDevices, true); + String udid1 = getDevicesList(household).get(0).getUdid(); + String udid2 = getDevicesList(household).get(1).getUdid(); + masterUserKsCleanAssetsAccordingToWatchStatusProgress = getHouseholdMasterUserKs(household, udid1); + + // purchase media and prepare media file for playback + purchasePpv(masterUserKsCleanAssetsAccordingToWatchStatusProgress, Optional.of(movie.getId().intValue()), Optional.of(movieFileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsCleanAssetsAccordingToWatchStatusProgress, String.valueOf(movie.getId()), + String.valueOf(movieFileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark first asset + Bookmark bookmark = addBookmark(position1, String.valueOf(movie.getId()), movieFileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); + AddBookmarkBuilder addBookmarkBuilder = add(bookmark).setKs(masterUserKsCleanAssetsAccordingToWatchStatusProgress); + executor.executeSync(addBookmarkBuilder); + + // purchase media2 and prepare media file for playback + masterUserKsCleanAssetsAccordingToWatchStatusProgress = getHouseholdMasterUserKs(household, udid2); + purchasePpv(masterUserKsCleanAssetsAccordingToWatchStatusProgress, Optional.of(episode.getId().intValue()), Optional.of(episodeFileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsCleanAssetsAccordingToWatchStatusProgress, String.valueOf(episode.getId()), + String.valueOf(episodeFileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark second asset + bookmark = addBookmark(position2, String.valueOf(episode.getId()), episodeFileId, AssetType.MEDIA, BookmarkActionType.FINISH); + addBookmarkBuilder = add(bookmark).setKs(masterUserKsCleanAssetsAccordingToWatchStatusProgress); + executor.executeSync(addBookmarkBuilder); + } + + @Description("assetHistory/action/clean - filtered by asset in progress") + @Test(groups = {"slowAfter"}, dependsOnGroups = {"slowBefore"}, alwaysRun = true) + private void cleanAssetsAccordingToWatchStatusProgress_after_wait() { + // assetHistory/action/clean - only asset that in progress (movie) + AssetHistoryFilter assetHistoryFilter = new AssetHistoryFilter(); + assetHistoryFilter.setStatusEqual(WatchStatus.PROGRESS); + + CleanAssetHistoryBuilder cleanAssetHistoryBuilder = clean(assetHistoryFilter); + cleanAssetHistoryBuilder.setKs(masterUserKsCleanAssetsAccordingToWatchStatusProgress); + executor.executeSync(cleanAssetHistoryBuilder); + + // assetHistory/action/list - after clean - only episode returned (was not cleaned) + assetHistoryFilter.setStatusEqual(WatchStatus.ALL); + + // prepare variables for await() functionality + int delayBetweenRetriesInSeconds = 15; + int maxTimeExpectingValidResponseInSeconds = 80; + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() -> { + // wait for 1 assets at history response + return (executor.executeSync(list(assetHistoryFilter).setKs(masterUserKsCleanAssetsAccordingToWatchStatusProgress)).results.getTotalCount() == 1); + }); + + Response> assetHistoryListResponse = executor.executeSync(list(assetHistoryFilter) + .setKs(masterUserKsCleanAssetsAccordingToWatchStatusProgress)); + + assertThat(assetHistoryListResponse.error).isNull(); + assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetHistoryListResponse.results.getObjects().get(0).getAssetId()).isEqualTo(episode.getId()); + + // cleanup - delete household + executor.executeSync(HouseholdService.delete().setKs(masterUserKsCleanAssetsAccordingToWatchStatusProgress)); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/assetHistoryTests/AssetHistoryListTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/assetHistoryTests/AssetHistoryListTests.java new file mode 100644 index 000000000..6be9373b0 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/assetHistoryTests/AssetHistoryListTests.java @@ -0,0 +1,437 @@ +package com.kaltura.client.test.tests.servicesTests.assetHistoryTests; + +import com.kaltura.client.enums.*; +import com.kaltura.client.services.HouseholdService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.tests.enums.MediaType; +import com.kaltura.client.test.utils.AssetUtils; +import com.kaltura.client.test.utils.BaseUtils; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.List; +import java.util.Optional; +import java.util.concurrent.TimeUnit; + +import static com.kaltura.client.services.AssetHistoryService.list; +import static com.kaltura.client.services.BookmarkService.AddBookmarkBuilder; +import static com.kaltura.client.services.BookmarkService.add; +import static com.kaltura.client.test.tests.enums.MediaType.EPISODE; +import static com.kaltura.client.test.tests.enums.MediaType.MOVIE; +import static com.kaltura.client.test.utils.AssetUtils.getAssets; +import static com.kaltura.client.test.utils.BaseUtils.getConcatenatedString; +import static com.kaltura.client.test.utils.BookmarkUtils.addBookmark; +import static com.kaltura.client.test.utils.HouseholdUtils.*; +import static com.kaltura.client.test.utils.PurchaseUtils.purchasePpv; +import static com.kaltura.client.test.utils.dbUtils.DBUtils.getMediaTypeId; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public class AssetHistoryListTests extends BaseTest { + private final int position1 = 10; + private final int position2 = 20; + private final int numOfUsers = 1; + private final int numOfDevices = 2; + + private MediaAsset movie; + private int movieFileId; + + private MediaAsset movie2; + private int movie2FileId; + + private MediaAsset episode; + private int episodeFileId; + + private String masterUserKsAssetHistoryTwoMedias; + private String masterUserKsAssetHistoryOneMedia; + private String masterUserKsVodAssetHistoryFilteredByAssetId; + private String masterUserKsVodAssetHistoryFilteredByAssetType; + private String masterUserKsVodAssetHistoryFilteredByAssetProgress; + + + @BeforeClass(alwaysRun = true) + private void list_tests_before_class() { + List movies = getAssets(2, MOVIE); + + // get first movie asset + movie = movies.get(0); + movieFileId = AssetUtils.getAssetFileIds(String.valueOf(movie.getId())).get(0); + + // get second movie asset + movie2 = movies.get(1); + movie2FileId = AssetUtils.getAssetFileIds(String.valueOf(movie2.getId())).get(0); + + // Ingest episode asset + episode = getAssets(1, EPISODE).get(0); + episodeFileId = AssetUtils.getAssetFileIds(String.valueOf(episode.getId())).get(0); + } + + @Description("assetHistory/action/list - with no filter and one device and two media") + @Test(groups = {"slowBefore"}, priority = -1) + private void assetHistory_vod_with_one_device_and_two_media_before_wait() { + // create household + Household household = createHousehold(numOfUsers, numOfDevices, true); + String udid1 = getDevicesList(household).get(0).getUdid(); + masterUserKsAssetHistoryTwoMedias = getHouseholdMasterUserKs(household, udid1); + + // purchase media and prepare media file for playback + purchasePpv(masterUserKsAssetHistoryTwoMedias, Optional.of(movie.getId().intValue()), Optional.of(movieFileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsAssetHistoryTwoMedias, String.valueOf(movie.getId()), + String.valueOf(movieFileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark first asset - first play + Bookmark bookmark = addBookmark(position1, String.valueOf(movie.getId()), movieFileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); + executor.executeSync(add(bookmark).setKs(masterUserKsAssetHistoryTwoMedias)); + + // Bookmark first asset - stop + bookmark = addBookmark(position1, String.valueOf(movie.getId()), movieFileId, AssetType.MEDIA, BookmarkActionType.STOP); + executor.executeSync(add(bookmark).setKs(masterUserKsAssetHistoryTwoMedias)); + + // purchase media2 and prepare media file for playback + purchasePpv(masterUserKsAssetHistoryTwoMedias, Optional.of(movie2.getId().intValue()), Optional.of(movie2FileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsAssetHistoryTwoMedias, String.valueOf(movie2.getId()), + String.valueOf(movie2FileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark second asset - first play + bookmark = addBookmark(position2, String.valueOf(movie2.getId()), movie2FileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); + executor.executeSync(add(bookmark).setKs(masterUserKsAssetHistoryTwoMedias)); + } + + @Description("assetHistory/action/list - with no filter and one device and two media") + @Test(groups = {"slowAfter"}, dependsOnGroups = {"slowBefore"}, alwaysRun = true) + private void assetHistory_vod_with_one_device_and_two_media_after_wait() { + // assetHistory/action/list - both assets should returned + AssetHistoryFilter assetHistoryFilter = new AssetHistoryFilter(); + assetHistoryFilter.setStatusEqual(WatchStatus.ALL); + + // prepare variables for await() functionality + int delayBetweenRetriesInSeconds = 15; + int maxTimeExpectingValidResponseInSeconds = 80; + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() -> { + // wait for 1 assets at history response + return (executor.executeSync(list(assetHistoryFilter).setKs(masterUserKsAssetHistoryTwoMedias)).results.getTotalCount() == 2); + }); + + Response> assetHistoryListResponse = executor.executeSync(list(assetHistoryFilter) + .setKs(masterUserKsAssetHistoryTwoMedias)); + + assertThat(assetHistoryListResponse.error).isNull(); + assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(2); + + // objects can be returned in any order + AssetHistory assetHistoryObject1, assetHistoryObject2; + if (assetHistoryListResponse.results.getObjects().get(0).getAssetId().equals(movie2.getId())) { + assetHistoryObject1 = assetHistoryListResponse.results.getObjects().get(0); + assetHistoryObject2 = assetHistoryListResponse.results.getObjects().get(1); + } else { + assetHistoryObject1 = assetHistoryListResponse.results.getObjects().get(1); + assetHistoryObject2 = assetHistoryListResponse.results.getObjects().get(0); + } + + // Assertions for first object returned + assertThat(assetHistoryObject1.getAssetType()).isEqualTo(AssetType.MEDIA); + assertThat(assetHistoryObject1.getDuration()).isGreaterThan(0); + assertThat(assetHistoryObject1.getPosition()).isEqualTo(position2); + assertThat(assetHistoryObject1.getAssetId()).isEqualTo(movie2.getId()); + + // Verify that flag is set to false (user hasn't finish watching the asset) + assertThat(assetHistoryObject1.getFinishedWatching()).isFalse(); + assertThat(assetHistoryObject1.getWatchedDate()).isLessThanOrEqualTo(BaseUtils.getEpoch()); + + // Assertions for second object returned + assertThat(assetHistoryObject2.getAssetId()).isEqualTo(movie.getId()); + assertThat(assetHistoryObject2.getAssetType()).isEqualTo(AssetType.MEDIA); + assertThat(assetHistoryObject2.getPosition()).isEqualTo(position1); + + // Assert total count = 2 (two bookmarks) + assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(2); + + // cleanup - delete household + executor.executeSync(HouseholdService.delete().setKs(masterUserKsAssetHistoryTwoMedias)); + } + + @Description("assetHistory/action/list - with no filter and two devices and one media") + @Test(groups = {"slowBefore"}) + private void assetHistory_vod_with_two_devices_and_one_media_before_wait() { + // create household + Household household = createHousehold(numOfUsers, numOfDevices, true); + String udid1 = getDevicesList(household).get(0).getUdid(); + String udid2 = getDevicesList(household).get(1).getUdid(); + masterUserKsAssetHistoryOneMedia = getHouseholdMasterUserKs(household, udid1); + + // purchase media and prepare media file for playback on first device + purchasePpv(masterUserKsAssetHistoryOneMedia, Optional.of(movie.getId().intValue()), Optional.of(movieFileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsAssetHistoryOneMedia, String.valueOf(movie.getId()), + String.valueOf(movieFileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark first device - first play + Bookmark bookmark = addBookmark(position1, String.valueOf(movie.getId()), movieFileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); + executor.executeSync(add(bookmark).setKs(masterUserKsAssetHistoryOneMedia)); + + // prepare media file for playback on second device + masterUserKsAssetHistoryOneMedia = getHouseholdMasterUserKs(household, udid2); + AssetUtils.playbackAssetFilePreparation(masterUserKsAssetHistoryOneMedia, String.valueOf(movie.getId()), + String.valueOf(movieFileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark second device - first play + bookmark = addBookmark(position2, String.valueOf(movie.getId()), movieFileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); + executor.executeSync(add(bookmark).setKs(masterUserKsAssetHistoryOneMedia)); + } + + @Description("assetHistory/action/list - with no filter and two devices and one media") + @Test(groups = {"slowAfter"}, dependsOnGroups = {"slowBefore"}, alwaysRun = true) + private void assetHistory_vod_with_two_devices_and_one_media_after_wait() { + // assetHistory/action/list - both assets should returned + AssetHistoryFilter assetHistoryFilter = new AssetHistoryFilter(); + assetHistoryFilter.setStatusEqual(WatchStatus.ALL); + + // prepare variables for await() functionality + int delayBetweenRetriesInSeconds = 15; + int maxTimeExpectingValidResponseInSeconds = 80; + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() -> { + // wait for 1 assets at history response + return (executor.executeSync(list(assetHistoryFilter).setKs(masterUserKsAssetHistoryOneMedia)).results.getTotalCount() == 1); + }); + + Response> assetHistoryListResponse = executor.executeSync(list(assetHistoryFilter) + .setKs(masterUserKsAssetHistoryOneMedia)); + + assertThat(assetHistoryListResponse.error).isNull(); + assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(1); + + AssetHistory assetHistoryObject1 = assetHistoryListResponse.results.getObjects().get(0); + assertThat(assetHistoryObject1.getAssetType()).isEqualTo(AssetType.MEDIA); + assertThat(assetHistoryObject1.getDuration()).isGreaterThan(0); + assertThat(assetHistoryObject1.getPosition()).isEqualTo(position2); + assertThat(assetHistoryObject1.getAssetId()).isEqualTo(movie.getId()); + assertThat(assetHistoryObject1.getFinishedWatching()).isFalse(); + assertThat(assetHistoryObject1.getWatchedDate()).isLessThanOrEqualTo(BaseUtils.getEpoch()); + + // cleanup - delete household + executor.executeSync(HouseholdService.delete().setKs(masterUserKsAssetHistoryOneMedia)); + } + + @Description("assetHistory/action/list - filtered by movie asset id") + @Test(groups = {"slowBefore"}) + private void vodAssetHistoryFilteredByAssetId_before_wait() { + // create household + int numOfDevices = 3; + Household household = createHousehold(numOfUsers, numOfDevices, true); + String udid1 = getDevicesList(household).get(0).getUdid(); + String udid2 = getDevicesList(household).get(1).getUdid(); + String udid3 = getDevicesList(household).get(2).getUdid(); + masterUserKsVodAssetHistoryFilteredByAssetId = getHouseholdMasterUserKs(household, udid1); + + // purchase media and prepare media file for playback + purchasePpv(masterUserKsVodAssetHistoryFilteredByAssetId, Optional.of(movie.getId().intValue()), Optional.of(movieFileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsVodAssetHistoryFilteredByAssetId, String.valueOf(movie.getId()), + String.valueOf(movieFileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark first asset + Bookmark bookmark = addBookmark(position1, String.valueOf(movie.getId()), movieFileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); + AddBookmarkBuilder addBookmarkBuilder = add(bookmark).setKs(masterUserKsVodAssetHistoryFilteredByAssetId); + executor.executeSync(addBookmarkBuilder); + + // purchase media2 and prepare media file for playback + masterUserKsVodAssetHistoryFilteredByAssetId = getHouseholdMasterUserKs(household, udid2); + purchasePpv(masterUserKsVodAssetHistoryFilteredByAssetId, Optional.of(movie2.getId().intValue()), Optional.of(movie2FileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsVodAssetHistoryFilteredByAssetId, String.valueOf(movie2.getId()), + String.valueOf(movie2FileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark Second asset + bookmark = addBookmark(position2, String.valueOf(movie2.getId()), movie2FileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); + addBookmarkBuilder = add(bookmark).setKs(masterUserKsVodAssetHistoryFilteredByAssetId); + executor.executeSync(addBookmarkBuilder); + + // purchase media2 and prepare media file for playback + masterUserKsVodAssetHistoryFilteredByAssetId = getHouseholdMasterUserKs(household, udid3); + purchasePpv(masterUserKsVodAssetHistoryFilteredByAssetId, Optional.of(episode.getId().intValue()), Optional.of(episodeFileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsVodAssetHistoryFilteredByAssetId, String.valueOf(episode.getId()), + String.valueOf(episodeFileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark third asset + bookmark = addBookmark(position1, String.valueOf(episode.getId()), episodeFileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); + addBookmarkBuilder = add(bookmark).setKs(masterUserKsVodAssetHistoryFilteredByAssetId); + executor.executeSync(addBookmarkBuilder); + } + + @Description("assetHistory/action/list - filtered by movie asset id") + @Test(groups = {"slowAfter"}, dependsOnGroups = {"slowBefore"}, alwaysRun = true) + private void vodAssetHistoryFilteredByAssetId_after_wait() { + //assetHistory/action/list - filter by asset 2 id + AssetHistoryFilter assetHistoryFilter = new AssetHistoryFilter(); + assetHistoryFilter.setAssetIdIn(String.valueOf(movie2.getId())); + assetHistoryFilter.setStatusEqual(WatchStatus.ALL); + + // prepare variables for await() functionality + int delayBetweenRetriesInSeconds = 15; + int maxTimeExpectingValidResponseInSeconds = 80; + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() -> { + // wait for 1 assets at history response + return (executor.executeSync(list(assetHistoryFilter).setKs(masterUserKsVodAssetHistoryFilteredByAssetId)).results.getTotalCount() == 1); + }); + + Response> assetHistoryListResponse = executor.executeSync(list(assetHistoryFilter) + .setKs(masterUserKsVodAssetHistoryFilteredByAssetId)); + + assertThat(assetHistoryListResponse.error).isNull(); + assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetHistoryListResponse.results.getObjects().get(0).getAssetId()).isEqualTo(movie2.getId()); + + //assetHistory/action/list - filter by asset 2 and asset 3 ids + String concatenatedString = getConcatenatedString(String.valueOf(movie2.getId()), String.valueOf(episode.getId())); + assetHistoryFilter.setAssetIdIn(concatenatedString); + + List assetHistoryList = executor.executeSync(list(assetHistoryFilter) + .setKs(masterUserKsVodAssetHistoryFilteredByAssetId)).results.getObjects(); + + assertThat(assetHistoryList).extracting("assetId") + .containsExactlyInAnyOrder(movie2.getId(), episode.getId()); + + // cleanup - delete household + executor.executeSync(HouseholdService.delete().setKs(masterUserKsVodAssetHistoryFilteredByAssetId)); + } + + @Description("assetHistory/action/list - filtered by movie type id") + @Test(groups = {"slowBefore"}) + private void vodAssetHistoryFilteredByAssetType_before_wait() { + // create household + Household household = createHousehold(numOfUsers, numOfDevices, true); + String udid1 = getDevicesList(household).get(0).getUdid(); + String udid2 = getDevicesList(household).get(1).getUdid(); + masterUserKsVodAssetHistoryFilteredByAssetType = getHouseholdMasterUserKs(household, udid1); + + // purchase media and prepare media file for playback + purchasePpv(masterUserKsVodAssetHistoryFilteredByAssetType, Optional.of(movie.getId().intValue()), Optional.of(movieFileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsVodAssetHistoryFilteredByAssetType, String.valueOf(movie.getId()), + String.valueOf(movieFileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark first asset + Bookmark bookmark = addBookmark(position1, String.valueOf(movie.getId()), movieFileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); + AddBookmarkBuilder addBookmarkBuilder = add(bookmark).setKs(masterUserKsVodAssetHistoryFilteredByAssetType); + executor.executeSync(addBookmarkBuilder); + + // purchase media episode and prepare media file for playback + masterUserKsVodAssetHistoryFilteredByAssetType = getHouseholdMasterUserKs(household, udid2); + purchasePpv(masterUserKsVodAssetHistoryFilteredByAssetType, Optional.of(episode.getId().intValue()), Optional.of(episodeFileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsVodAssetHistoryFilteredByAssetType, String.valueOf(episode.getId()), + String.valueOf(episodeFileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark Second asset + bookmark = addBookmark(position2, String.valueOf(episode.getId()), episodeFileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); + addBookmarkBuilder = add(bookmark).setKs(masterUserKsVodAssetHistoryFilteredByAssetType); + executor.executeSync(addBookmarkBuilder); + } + + @Description("assetHistory/action/list - filtered by movie type id") + @Test(groups = {"slowAfter"}, dependsOnGroups = {"slowBefore"}, alwaysRun = true) + private void vodAssetHistoryFilteredByAssetType_after_wait() { + //assetHistory/action/list - filter by in progress assets only + AssetHistoryFilter assetHistoryFilter = new AssetHistoryFilter(); + assetHistoryFilter.setStatusEqual(WatchStatus.ALL); + assetHistoryFilter.setTypeIn(String.valueOf(getMediaTypeId(MediaType.MOVIE))); + + // prepare variables for await() functionality + int delayBetweenRetriesInSeconds = 15; + int maxTimeExpectingValidResponseInSeconds = 80; + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() -> { + // wait for 1 assets at history response + return (executor.executeSync(list(assetHistoryFilter).setKs(masterUserKsVodAssetHistoryFilteredByAssetType)).results.getTotalCount() == 1); + }); + + Response> assetHistoryListResponse = executor.executeSync(list(assetHistoryFilter) + .setKs(masterUserKsVodAssetHistoryFilteredByAssetType)); + + assertThat(assetHistoryListResponse.error).isNull(); + assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetHistoryListResponse.results.getObjects().get(0).getAssetId()).isEqualTo(movie.getId()); + + // cleanup - delete household + executor.executeSync(HouseholdService.delete().setKs(masterUserKsVodAssetHistoryFilteredByAssetType)); + } + + @Description("assetHistory/action/list - filtered by assets progress") + @Test(groups = {"slowBefore"}) + private void vodAssetHistoryFilteredByAssetProgress_before_wait() { + // create household + Household household = createHousehold(numOfUsers, numOfDevices, true); + String udid1 = getDevicesList(household).get(0).getUdid(); + String udid2 = getDevicesList(household).get(1).getUdid(); + masterUserKsVodAssetHistoryFilteredByAssetProgress = getHouseholdMasterUserKs(household, udid1); + + // purchase media and prepare media file for playback + purchasePpv(masterUserKsVodAssetHistoryFilteredByAssetProgress, Optional.of(movie.getId().intValue()), Optional.of(movieFileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsVodAssetHistoryFilteredByAssetProgress, String.valueOf(movie.getId()), + String.valueOf(movieFileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark first asset + Bookmark bookmark = addBookmark(position1, String.valueOf(movie.getId()), movieFileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); + AddBookmarkBuilder addBookmarkBuilder = add(bookmark).setKs(masterUserKsVodAssetHistoryFilteredByAssetProgress); + executor.executeSync(addBookmarkBuilder); + + // purchase media episode and prepare media file for playback + masterUserKsVodAssetHistoryFilteredByAssetProgress = getHouseholdMasterUserKs(household, udid2); + purchasePpv(masterUserKsVodAssetHistoryFilteredByAssetProgress, Optional.of(episode.getId().intValue()), Optional.of(episodeFileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKsVodAssetHistoryFilteredByAssetProgress, String.valueOf(episode.getId()), + String.valueOf(episodeFileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + + // Bookmark Second asset + bookmark = addBookmark(position2, String.valueOf(episode.getId()), episodeFileId, AssetType.MEDIA, BookmarkActionType.FINISH); + addBookmarkBuilder = add(bookmark).setKs(masterUserKsVodAssetHistoryFilteredByAssetProgress); + executor.executeSync(addBookmarkBuilder); + } + + @Description("assetHistory/action/list - filtered by assets progress") + @Test(groups = {"slowAfter"}, dependsOnGroups = {"slowBefore"}, alwaysRun = true) + private void vodAssetHistoryFilteredByAssetProgress_after_wait() { + //assetHistory/action/list - filter by in progress assets only + AssetHistoryFilter assetHistoryFilter = new AssetHistoryFilter(); + assetHistoryFilter.setStatusEqual(WatchStatus.PROGRESS); + + // prepare variables for await() functionality + int delayBetweenRetriesInSeconds = 15; + int maxTimeExpectingValidResponseInSeconds = 80; + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() -> { + // wait for 1 assets at history response + return (executor.executeSync(list(assetHistoryFilter).setKs(masterUserKsVodAssetHistoryFilteredByAssetProgress)).results.getTotalCount() == 1); + }); + + Response> assetHistoryListResponse = executor.executeSync(list(assetHistoryFilter) + .setKs(masterUserKsVodAssetHistoryFilteredByAssetProgress)); + + assertThat(assetHistoryListResponse.error).isNull(); + assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetHistoryListResponse.results.getObjects().get(0).getAssetId()).isEqualTo(movie.getId()); + + //assetHistory/action/list - filter by finished assets only + assetHistoryFilter.setStatusEqual(WatchStatus.DONE); + + assetHistoryListResponse = executor.executeSync(list(assetHistoryFilter) + .setKs(masterUserKsVodAssetHistoryFilteredByAssetProgress)); + + assertThat(assetHistoryListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(assetHistoryListResponse.results.getObjects().get(0).getAssetId()).isEqualTo(episode.getId()); + + // cleanup - delete household + executor.executeSync(HouseholdService.delete().setKs(masterUserKsVodAssetHistoryFilteredByAssetProgress)); + } + //todo - Currently EPG program not returned in response (Ticket was opened to Omer - BEO-4594] +} \ No newline at end of file diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/assetRuleTests/AssetRuleDeleteTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/assetRuleTests/AssetRuleDeleteTests.java new file mode 100644 index 000000000..aff6e656e --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/assetRuleTests/AssetRuleDeleteTests.java @@ -0,0 +1,17 @@ +package com.kaltura.client.test.tests.servicesTests.assetRuleTests; + +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.AssetRuleUtils; +import io.qameta.allure.Description; +import org.testng.annotations.Test; + +public class AssetRuleDeleteTests extends BaseTest { + + + @Description("/assetrule/action/delete - currently used to run util only") + @Test(enabled = false) // as test is not implemented yet + private void deleteAllGeoAssetRules() { + AssetRuleUtils.deleteAllGeoAssetRules(); + } + +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/assetStatisticsTests/AssetStatisticsQueryTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/assetStatisticsTests/AssetStatisticsQueryTests.java new file mode 100644 index 000000000..b629c5783 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/assetStatisticsTests/AssetStatisticsQueryTests.java @@ -0,0 +1,48 @@ +package com.kaltura.client.test.tests.servicesTests.assetStatisticsTests; + +import com.kaltura.client.enums.AssetType; +import com.kaltura.client.services.AssetStatisticsService.QueryAssetStatisticsBuilder; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.tests.enums.MediaType; +import com.kaltura.client.test.utils.AssetUtils; +import com.kaltura.client.types.AssetStatistics; +import com.kaltura.client.types.AssetStatisticsQuery; +import com.kaltura.client.types.ListResponse; +import com.kaltura.client.types.MediaAsset; +import com.kaltura.client.utils.response.base.Response; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.List; + +import static com.kaltura.client.services.AssetStatisticsService.query; + +public class AssetStatisticsQueryTests extends BaseTest{ + + private MediaAsset media1; + private MediaAsset media2; + private MediaAsset media3; + + @BeforeClass(enabled = false) + private void assetStatistics_before_class(){ + List medias = AssetUtils.getAssets(3, MediaType.MOVIE); + media1 = medias.get(0); + media2 = medias.get(1); + media3 = medias.get(2); + } + + @Test(enabled = false) + public void asset(){ + + AssetStatisticsQuery assetStatisticsQuery = new AssetStatisticsQuery(); + assetStatisticsQuery.setAssetIdIn(String.valueOf(media1.getId())); + assetStatisticsQuery.setAssetTypeEqual(AssetType.MEDIA); + + QueryAssetStatisticsBuilder queryAssetStatisticsBuilder = query(assetStatisticsQuery); + Response> assetStatistics = executor.executeSync(queryAssetStatisticsBuilder); + + + } + + +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/bookmarkTests/BookmarkAddTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/bookmarkTests/BookmarkAddTests.java index 294466672..cda95feb2 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/bookmarkTests/BookmarkAddTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/bookmarkTests/BookmarkAddTests.java @@ -1,11 +1,14 @@ package com.kaltura.client.test.tests.servicesTests.bookmarkTests; import com.kaltura.client.enums.*; -import com.kaltura.client.services.BookmarkService; +import com.kaltura.client.services.HouseholdService; import com.kaltura.client.test.tests.BaseTest; import com.kaltura.client.test.utils.AssetUtils; import com.kaltura.client.test.utils.BookmarkUtils; -import com.kaltura.client.types.*; +import com.kaltura.client.types.Bookmark; +import com.kaltura.client.types.BookmarkFilter; +import com.kaltura.client.types.Household; +import com.kaltura.client.types.ListResponse; import com.kaltura.client.utils.response.base.Response; import io.qameta.allure.Description; import org.testng.annotations.BeforeClass; @@ -13,29 +16,30 @@ import java.util.ArrayList; import java.util.List; +import java.util.Optional; +import java.util.concurrent.TimeUnit; import static com.kaltura.client.services.BookmarkService.*; -import static com.kaltura.client.test.tests.BaseTest.SharedHousehold.*; +import static com.kaltura.client.test.tests.BaseTest.SharedHousehold.getSharedMasterUserKs; import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; +import static com.kaltura.client.test.utils.HouseholdUtils.*; +import static com.kaltura.client.test.utils.PurchaseUtils.purchasePpv; import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; public class BookmarkAddTests extends BaseTest { private long assetId; private int fileId; - private BookmarkActionType actionType; + private List assetList; + private Bookmark bookmark; + private BookmarkFilter bookmarkFilter; private int position; - private List assetList = new ArrayList<>(); - // instantiate Bookmark object - private Bookmark bookmark = new Bookmark(); - // instantiate BookmarkFilter object - private BookmarkFilter bookmarkFilter = new BookmarkFilter(); - @BeforeClass - private void add_tests_before_class() { - - getSharedHousehold(); + @BeforeClass(alwaysRun = true) + private void bookmark_addTests_before_class() { + assetList = new ArrayList<>(); assetId = BaseTest.getSharedMediaAsset().getId(); fileId = AssetUtils.getAssetFileIds(String.valueOf(assetId)).get(0); @@ -46,27 +50,37 @@ private void add_tests_before_class() { } @Description("bookmark/action/add - first play") - @Test - private void firstPlayback() { - actionType = BookmarkActionType.FIRST_PLAY; + @Test(groups = {"slowBefore"}) + private void firstPlayback_before_wait() { position = 0; - bookmark = BookmarkUtils.addBookmark(position, String.valueOf(assetId), fileId, AssetType.MEDIA, actionType); + + bookmark = BookmarkUtils.addBookmark(position, String.valueOf(assetId), fileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); // Invoke bookmark/action/add request - AddBookmarkBuilder addBookmarkBuilder = BookmarkService.add(bookmark); - addBookmarkBuilder.setKs(getSharedMasterUserKs()); + AddBookmarkBuilder addBookmarkBuilder = add(bookmark).setKs(getSharedMasterUserKs()); Response booleanResponse = executor.executeSync(addBookmarkBuilder); - // Verify response return true assertThat(booleanResponse.results.booleanValue()).isTrue(); - // Verify no error returned assertThat(booleanResponse.error).isNull(); - + } + @Description("bookmark/action/add - first play") + @Test(groups = {"slowAfter"}, dependsOnGroups = {"slowBefore"}, alwaysRun = true) + private void firstPlayback_after_wait() { + // prepare variables for await() functionality + int delayBetweenRetriesInSeconds = 15; + int maxTimeExpectingValidResponseInSeconds = 80; // Invoke bookmark/action/list to verify insertion of bookmark position - ListBookmarkBuilder listBookmarkBuilder = BookmarkService.list(bookmarkFilter); - listBookmarkBuilder.setKs(getSharedMasterUserKs()); + ListBookmarkBuilder listBookmarkBuilder = list(bookmarkFilter).setKs(getSharedMasterUserKs()); + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() ->{ + return (executor.executeSync(listBookmarkBuilder).results.getTotalCount() != 0); + }); + Response> bookmarkListResponse = executor.executeSync(listBookmarkBuilder); + assertThat(bookmarkListResponse.error).isNull(); Bookmark bookmark1 = bookmarkListResponse.results.getObjects().get(0); @@ -74,7 +88,7 @@ private void firstPlayback() { assertThat(bookmark1.getId()).isEqualTo(String.valueOf(assetId)); // Match content of asset position - assertThat(bookmark1.getPosition()).isEqualTo(this.position); + assertThat(bookmark1.getPosition()).isEqualTo(position); // verify finishedWatching = false assertThat(bookmark1.getFinishedWatching()).isFalse(); @@ -87,125 +101,184 @@ private void firstPlayback() { // Verify total count = 1 assertThat(bookmarkListResponse.results.getTotalCount()).isEqualTo(1); - } @Description("bookmark/action/add - pause") - @Test - private void pausePlayback() { - // Set action type to "PAUSE" - actionType = BookmarkActionType.PAUSE; + @Test(groups = {"slowAfter"}, dependsOnMethods = {"firstPlayback_after_wait"}, alwaysRun=true) + private void pausePlayback_before_wait() { position = 30; - bookmark = BookmarkUtils.addBookmark(position, String.valueOf(assetId), fileId, AssetType.MEDIA, actionType); + bookmark = BookmarkUtils.addBookmark(position, String.valueOf(assetId), fileId, AssetType.MEDIA, BookmarkActionType.PAUSE); // Invoke bookmark/action/add request - AddBookmarkBuilder addBookmarkBuilder = BookmarkService.add(bookmark); - addBookmarkBuilder.setKs(getSharedMasterUserKs()); + AddBookmarkBuilder addBookmarkBuilder = add(bookmark).setKs(getSharedMasterUserKs()); Response booleanResponse = executor.executeSync(addBookmarkBuilder); - // Verify response return true assertThat(booleanResponse.results.booleanValue()).isTrue(); - // Verify no error returned assertThat(booleanResponse.error).isNull(); + } + + @Description("bookmark/action/add - pause") + @Test(groups = {"slowAfter"}, dependsOnMethods = {"pausePlayback_before_wait"}, alwaysRun = true) + private void pausePlayback_after_wait() { + // prepare variables for await() functionality + int delayBetweenRetriesInSeconds = 15; + int maxTimeExpectingValidResponseInSeconds = 80; // Invoke bookmark/action/list to verify insertion of bookmark position - ListBookmarkBuilder listBookmarkBuilder = BookmarkService.list(bookmarkFilter); - listBookmarkBuilder.setKs(getSharedMasterUserKs()); + ListBookmarkBuilder listBookmarkBuilder = list(bookmarkFilter).setKs(getSharedMasterUserKs()); + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() ->{ + return (executor.executeSync(listBookmarkBuilder).results.getObjects().get(0).getPosition() == position); + }); + Response> bookmarkListResponse = executor.executeSync(listBookmarkBuilder); + assertThat(bookmarkListResponse.error).isNull(); Bookmark bookmark = bookmarkListResponse.results.getObjects().get(0); // Match content of asset position - assertThat(bookmark.getPosition()).isEqualTo(this.position); + assertThat(bookmark.getPosition()).isEqualTo(position); } @Description("bookmark/action/add - 95% watching == finish watching") - @Test - private void watchingNinetyFive() { - actionType = BookmarkActionType.PLAY; + @Test(groups = {"slowAfter"}, dependsOnMethods = {"pausePlayback_after_wait"}, alwaysRun=true) + private void watchingNinetyFive_before_wait() { position = 999; - bookmark = BookmarkUtils.addBookmark(position, String.valueOf(assetId), fileId, AssetType.MEDIA, actionType); + bookmark = BookmarkUtils.addBookmark(position, String.valueOf(assetId), fileId, AssetType.MEDIA, BookmarkActionType.PLAY); // Invoke bookmark/action/add request - AddBookmarkBuilder addBookmarkBuilder = BookmarkService.add(bookmark); - addBookmarkBuilder.setKs(getSharedMasterUserKs()); + AddBookmarkBuilder addBookmarkBuilder = add(bookmark).setKs(getSharedMasterUserKs()); Response booleanResponse = executor.executeSync(addBookmarkBuilder); - // Verify response return true + assertThat(booleanResponse.results.booleanValue()).isTrue(); - // Verify no error returned assertThat(booleanResponse.error).isNull(); + } + + @Description("bookmark/action/add - 95% watching == finish watching") + @Test(groups = {"slowAfter"}, dependsOnMethods = {"watchingNinetyFive_before_wait"}, alwaysRun = true) + private void watchingNinetyFive_after_wait() { + // prepare variables for await() functionality + int delayBetweenRetriesInSeconds = 15; + int maxTimeExpectingValidResponseInSeconds = 80; // Invoke bookmark/action/list to verify insertion of bookmark position - ListBookmarkBuilder listBookmarkBuilder = BookmarkService.list(bookmarkFilter); - listBookmarkBuilder.setKs(getSharedMasterUserKs()); + ListBookmarkBuilder listBookmarkBuilder = list(bookmarkFilter).setKs(getSharedMasterUserKs()); + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() ->{ + return (executor.executeSync(listBookmarkBuilder).results.getObjects().get(0).getPosition() == position); + }); + Response> bookmarkListResponse = executor.executeSync(listBookmarkBuilder); + assertThat(bookmarkListResponse.error).isNull(); Bookmark bookmark3 = bookmarkListResponse.results.getObjects().get(0); // Verify finishedWatching = true assertThat(bookmark3.getFinishedWatching()).isTrue(); - } @Description("bookmark/action/add - back to start - position:0") - @Test - private void backToStart() { - actionType = BookmarkActionType.STOP; + @Test(groups = {"slowAfter"}, dependsOnMethods = {"watchingNinetyFive_after_wait"}, alwaysRun=true) + private void backToStart_before_wait() { position = 0; - bookmark = BookmarkUtils.addBookmark(position, String.valueOf(assetId), fileId, AssetType.MEDIA, actionType); + bookmark = BookmarkUtils.addBookmark(position, String.valueOf(assetId), fileId, AssetType.MEDIA, BookmarkActionType.STOP); - AddBookmarkBuilder addBookmarkBuilder = BookmarkService.add(bookmark); - addBookmarkBuilder.setKs(getSharedMasterUserKs()); + AddBookmarkBuilder addBookmarkBuilder = add(bookmark).setKs(getSharedMasterUserKs()); Response booleanResponse = executor.executeSync(addBookmarkBuilder); assertThat(booleanResponse.results.booleanValue()).isTrue(); - ListBookmarkBuilder listBookmarkBuilder = BookmarkService.list(bookmarkFilter); - listBookmarkBuilder.setKs(getSharedMasterUserKs()); + assertThat(booleanResponse.error).isNull(); + } + + @Description("bookmark/action/add - back to start - position:0") + @Test(groups = {"slowAfter"}, dependsOnMethods = {"backToStart_before_wait"}, alwaysRun = true) + private void backToStart_after_wait() { + // prepare variables for await() functionality + int delayBetweenRetriesInSeconds = 15; + int maxTimeExpectingValidResponseInSeconds = 80; + + // Invoke bookmark/action/list to verify insertion of bookmark position + ListBookmarkBuilder listBookmarkBuilder = list(bookmarkFilter).setKs(getSharedMasterUserKs()); + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() ->{ + return (executor.executeSync(listBookmarkBuilder).results.getObjects().get(0).getPosition() == position); + }); + Response> bookmarkListResponse = executor.executeSync(listBookmarkBuilder); + assertThat(bookmarkListResponse.error).isNull(); Bookmark bookmark = bookmarkListResponse.results.getObjects().get(0); + // Verify finishedWatching = false assertThat(bookmark.getFinishedWatching()).isFalse(); } @Description("bookmark/action/add - finish watching") - @Test - private void finishWatching() { - // Set action type to "FINISH" - actionType = BookmarkActionType.FINISH; + @Test(groups = {"slowAfter"}, dependsOnMethods = {"backToStart_after_wait"}, alwaysRun=true) + private void finishWatching_before_wait() { position = 60; - bookmark = BookmarkUtils.addBookmark(position, String.valueOf(assetId), fileId, AssetType.MEDIA, actionType); + bookmark = BookmarkUtils.addBookmark(position, String.valueOf(assetId), fileId, AssetType.MEDIA, BookmarkActionType.FINISH); // Invoke bookmark/action/add request - AddBookmarkBuilder addBookmarkBuilder = BookmarkService.add(bookmark); - addBookmarkBuilder.setKs(getSharedMasterUserKs()); - Response booleanResponse = executor.executeSync(addBookmarkBuilder); - // Verify response return true + Response booleanResponse = executor.executeSync(add(bookmark) + .setKs(getSharedMasterUserKs())); + assertThat(booleanResponse.results.booleanValue()).isTrue(); - // Verify no error returned assertThat(booleanResponse.error).isNull(); + } + + @Description("bookmark/action/add - finish watching") + @Test(groups = {"slowAfter"}, dependsOnMethods = {"finishWatching_before_wait"}, alwaysRun = true) + private void finishWatching_after_wait() { + // prepare variables for await() functionality + int delayBetweenRetriesInSeconds = 15; + int maxTimeExpectingValidResponseInSeconds = 80; // Invoke bookmark/action/list to verify insertion of bookmark position - ListBookmarkBuilder listBookmarkBuilder = BookmarkService.list(bookmarkFilter); - listBookmarkBuilder.setKs(getSharedMasterUserKs()); + ListBookmarkBuilder listBookmarkBuilder = list(bookmarkFilter).setKs(getSharedMasterUserKs()); + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() ->{ + return (executor.executeSync(listBookmarkBuilder).results.getObjects().get(0).getFinishedWatching().equals(true)); + }); + Response> bookmarkListResponse = executor.executeSync(listBookmarkBuilder); + assertThat(bookmarkListResponse.error).isNull(); Bookmark bookmark = bookmarkListResponse.results.getObjects().get(0); - // Verify finishedWatching = true - assertThat(bookmark.getFinishedWatching()).isTrue(); - + // Verify postion = 0 + assertThat(bookmark.getPosition()).isEqualTo(0); } - // Error validations - @Description("bookmark/action/add - empty asset id") - @Test + @Test(enabled = false) private void emptyAssetId() { + // create household + int numberOfUsersInHousehold = 1; + int numberOfDevicesInHousehold = 1; + Household household = createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, true); + String udid1 = getDevicesList(household).get(0).getUdid(); + String masterUserKs = getHouseholdMasterUserKs(household, udid1); + + // purchase media and prepare media file for playback + purchasePpv(masterUserKs, Optional.of((int)assetId), Optional.of(fileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKs, String.valueOf(assetId), + String.valueOf(fileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + bookmark = BookmarkUtils.addBookmark(0, null, fileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); - AddBookmarkBuilder addBookmarkBuilder = BookmarkService.add(bookmark); - addBookmarkBuilder.setKs(getSharedMasterUserKs()); + AddBookmarkBuilder addBookmarkBuilder = add(bookmark).setKs(masterUserKs); Response booleanResponse = executor.executeSync(addBookmarkBuilder); + assertThat(booleanResponse.results).isNull(); // Verify exception returned - code: 500003 ("Invalid Asset id") assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500003).getCode()); - } + // cleanup - delete household + executor.executeSync(HouseholdService.delete().setKs(masterUserKs)); + } // TODO - Add test for EPG bookmark // TODO - Add test for recording bookmark diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/bookmarkTests/BookmarkListTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/bookmarkTests/BookmarkListTests.java index ba818af51..8001675cd 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/bookmarkTests/BookmarkListTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/bookmarkTests/BookmarkListTests.java @@ -1,14 +1,13 @@ package com.kaltura.client.test.tests.servicesTests.bookmarkTests; -import com.kaltura.client.enums.AssetType; -import com.kaltura.client.enums.BookmarkActionType; -import com.kaltura.client.enums.BookmarkOrderBy; +import com.kaltura.client.enums.*; import com.kaltura.client.services.BookmarkService; import com.kaltura.client.test.tests.BaseTest; import com.kaltura.client.test.utils.AssetUtils; import com.kaltura.client.test.utils.BookmarkUtils; import com.kaltura.client.types.Bookmark; import com.kaltura.client.types.BookmarkFilter; +import com.kaltura.client.types.Household; import com.kaltura.client.types.ListResponse; import com.kaltura.client.utils.response.base.Response; import io.qameta.allure.Description; @@ -17,24 +16,27 @@ import java.util.ArrayList; import java.util.List; +import java.util.Optional; +import java.util.concurrent.TimeUnit; import static com.kaltura.client.services.BookmarkService.*; import static com.kaltura.client.test.tests.BaseTest.SharedHousehold.getSharedMasterUserKs; +import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; +import static com.kaltura.client.test.utils.HouseholdUtils.*; +import static com.kaltura.client.test.utils.PurchaseUtils.purchasePpv; import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; public class BookmarkListTests extends BaseTest { - private Long assetId; - private int fileId; + private long assetId, assetId2; + private int fileId, fileId2; + private List assetList; + private String masterUserKs; - - private Long assetId2; - private int fileId2; - - private List assetList = new ArrayList<>(); - - @BeforeClass - private void list_tests_before_class() { + @BeforeClass(alwaysRun = true) + private void bookmark_listTests_before_class() { + assetList = new ArrayList<>(); assetId = BaseTest.getSharedMediaAsset().getId(); List assetFileIds = AssetUtils.getAssetFileIds(String.valueOf(assetId)); @@ -48,31 +50,66 @@ private void list_tests_before_class() { } @Description("bookmark/action/list - order by") - @Test - - private void BookmarkOrderBy() { + @Test(groups = {"slowBefore"}) + private void BookmarkOrderBy_before_wait() { + // create household + int numberOfUsersInHousehold = 1; + int numberOfDevicesInHousehold = 1; + Household household = createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, true); + String udid1 = getDevicesList(household).get(0).getUdid(); + masterUserKs = getHouseholdMasterUserKs(household, udid1); + + // purchase media and prepare media file for playback + purchasePpv(masterUserKs, Optional.of((int)assetId), Optional.of(fileId), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKs, String.valueOf(assetId), + String.valueOf(fileId), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); // Bookmark asset1 Bookmark bookmark = BookmarkUtils.addBookmark(0, String.valueOf(assetId), fileId, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); - BookmarkService.AddBookmarkBuilder addBookmarkBuilder = BookmarkService.add(bookmark); - addBookmarkBuilder.setKs(getSharedMasterUserKs()); + BookmarkService.AddBookmarkBuilder addBookmarkBuilder = BookmarkService.add(bookmark).setKs(masterUserKs); Response booleanResponse = executor.executeSync(addBookmarkBuilder); + assertThat(booleanResponse.error).isNull(); assertThat(booleanResponse.results.booleanValue()).isTrue(); + // purchase media2 and prepare media file for playback + purchasePpv(masterUserKs, Optional.of((int)assetId2), Optional.of(fileId2), Optional.empty()); + AssetUtils.playbackAssetFilePreparation(masterUserKs, String.valueOf(assetId2), + String.valueOf(fileId2), AssetType.MEDIA, PlaybackContextType.PLAYBACK, UrlType.PLAYMANIFEST); + // Bookmark asset2 Bookmark bookmark2 = BookmarkUtils.addBookmark(10, String.valueOf(assetId2), fileId2, AssetType.MEDIA, BookmarkActionType.FIRST_PLAY); - AddBookmarkBuilder addBookmarkBuilder2 = BookmarkService.add(bookmark2); - addBookmarkBuilder2.setKs(getSharedMasterUserKs()); + AddBookmarkBuilder addBookmarkBuilder2 = BookmarkService.add(bookmark2).setKs(masterUserKs); Response booleanResponse2 = executor.executeSync(addBookmarkBuilder2); + + assertThat(booleanResponse.error).isNull(); assertThat(booleanResponse2.results.booleanValue()).isTrue(); + } + @Description("bookmark/action/list - order by") + @Test(groups = {"slowAfter"}, dependsOnGroups = {"slowBefore"}, alwaysRun = true) + private void BookmarkOrderBy_after_wait() { + // set filter BookmarkFilter bookmarkFilter = BookmarkUtils.listBookmark(BookmarkOrderBy.POSITION_DESC,AssetType.MEDIA, assetList); - ListBookmarkBuilder listBookmarkBuilder = BookmarkService.list(bookmarkFilter); - listBookmarkBuilder.setKs(getSharedMasterUserKs()); + + // prepare variables for await() functionality + int delayBetweenRetriesInSeconds = 15; + int maxTimeExpectingValidResponseInSeconds = 80; + + // Invoke bookmark/action/list to verify insertion of assets bookmarks + ListBookmarkBuilder listBookmarkBuilderAwait = list(bookmarkFilter).setKs(masterUserKs); + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() ->{ + return (executor.executeSync(listBookmarkBuilderAwait).results.getTotalCount() == 2); + }); + + ListBookmarkBuilder listBookmarkBuilder = listBookmarkBuilderAwait; Response> bookmarkListResponse = executor.executeSync(listBookmarkBuilder); + assertThat(bookmarkListResponse.error).isNull(); Bookmark bookmarkObject = bookmarkListResponse.results.getObjects().get(0); Bookmark bookmarkObject2 = bookmarkListResponse.results.getObjects().get(1); @@ -81,10 +118,10 @@ private void BookmarkOrderBy() { assertThat( bookmarkObject2.getId()).isEqualTo(String.valueOf(assetId)); bookmarkFilter = BookmarkUtils.listBookmark(BookmarkOrderBy.POSITION_ASC,AssetType.MEDIA, assetList); - listBookmarkBuilder = BookmarkService.list(bookmarkFilter); - listBookmarkBuilder.setKs(getSharedMasterUserKs()); + listBookmarkBuilder = BookmarkService.list(bookmarkFilter).setKs(masterUserKs); bookmarkListResponse = executor.executeSync(listBookmarkBuilder); + assertThat(bookmarkListResponse.error).isNull(); bookmarkObject = bookmarkListResponse.results.getObjects().get(0); bookmarkObject2 = bookmarkListResponse.results.getObjects().get(1); @@ -92,4 +129,19 @@ private void BookmarkOrderBy() { assertThat( bookmarkObject.getId()).isEqualTo(String.valueOf(assetId)); assertThat( bookmarkObject2.getId()).isEqualTo(String.valueOf(assetId2)); } + + @Description("bookmark/action/list - empty asset id") + @Test + private void emptyAssetId() { + // creating bookmark filter with empty asset id + BookmarkFilter bookmarkFilter = new BookmarkFilter(); + bookmarkFilter.setAssetIdIn(""); + bookmarkFilter.setAssetTypeEqual(AssetType.MEDIA); + + ListBookmarkBuilder listBookmarkBuilder = list(bookmarkFilter).setKs(getSharedMasterUserKs()); + Response> bookmarkListResponse = executor.executeSync(listBookmarkBuilder); + + assertThat(bookmarkListResponse.results).isNull(); + assertThat(bookmarkListResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(50027).getCode()); + } } diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/channelTests/ChannelAddTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/channelTests/ChannelAddTests.java index d14d5cb9d..a69c6d27f 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/channelTests/ChannelAddTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/channelTests/ChannelAddTests.java @@ -1,16 +1,19 @@ package com.kaltura.client.test.tests.servicesTests.channelTests; -import com.kaltura.client.enums.AssetOrderBy; +import com.kaltura.client.enums.ChannelOrderBy; import com.kaltura.client.services.AssetService; import com.kaltura.client.services.ChannelService; import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.tests.enums.MediaType; import com.kaltura.client.test.utils.AssetUtils; import com.kaltura.client.test.utils.BaseUtils; import com.kaltura.client.test.utils.ChannelUtils; -import com.kaltura.client.test.utils.IngestUtils; import com.kaltura.client.types.*; import com.kaltura.client.utils.response.base.Response; import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -18,133 +21,235 @@ import java.util.List; import java.util.Optional; -import static com.kaltura.client.services.AssetService.*; -import static com.kaltura.client.services.ChannelService.*; -import static com.kaltura.client.test.IngestConstants.MOVIE_MEDIA_TYPE; +import static com.kaltura.client.services.ChannelService.add; import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; +import static com.kaltura.client.test.utils.BaseUtils.getEpoch; +import static com.kaltura.client.test.utils.dbUtils.DBUtils.getMediaTypeId; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.VodData; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.insertVod; import static org.assertj.core.api.Assertions.assertThat; public class ChannelAddTests extends BaseTest { - private Channel channel = new Channel(); - private String channelName; - private String Description; + private DynamicChannel channel; +// private String channelName; +// private String description; private Boolean isActive = true; - private String filterExpression; private IntegerValue integerValue = new IntegerValue(); - private List assetTypes = new ArrayList<>(); @BeforeClass - private void get_tests_before_class() { - channelName = "Channel_12345"; - Description = "description of channel"; + private void channel_addTests_before_class() { + String channelName = "Channel_" + getEpoch(); + String description = "description of " + channelName; } + @Severity(SeverityLevel.CRITICAL) @Description("channel/action/add - with all asset types") @Test private void addChannel() { - filterExpression = "name ~ 'movie'"; - channel = ChannelUtils.addChannel(channelName, Description, isActive, filterExpression, AssetOrderBy.LIKES_DESC, null, null); + String ksqlExpression = "name ~ 'movie'"; + ChannelOrder channelOrder = new ChannelOrder(); + channelOrder.setOrderBy(ChannelOrderBy.LIKES_DESC); - //channel/action/add - AddChannelBuilder addChannelBuilder = ChannelService.add(channel); - addChannelBuilder.setKs(getManagerKs()); - Response channelResponse = executor.executeSync(addChannelBuilder); + String channelName = "Channel_" + getEpoch(); + String description = "description of " + channelName; + channel = ChannelUtils.addDynamicChannel(channelName, description, isActive, ksqlExpression, channelOrder, null); + + // channel/action/add + Response channelResponse = executor.executeSync(add(channel) + .setKs(getManagerKs()) + .setLanguage("*")); assertThat(channelResponse.results.getName()).isEqualTo(channelName); + + // cleanup - delete channel + executor.executeSync(ChannelService.delete(Math.toIntExact(channelResponse.results.getId())) + .setKs(getManagerKs())); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("channel/action/add - with specific asset type") + @Test + private void addChannelWithAssetType() { + String ksqlExpression = "name ~ 'movie'"; + + int mediaTypeId = getMediaTypeId(MediaType.MOVIE); + integerValue.setValue(mediaTypeId); + List assetTypes = new ArrayList<>(); + assetTypes.add(integerValue); + + ChannelOrder channelOrder = new ChannelOrder(); + channelOrder.setOrderBy(ChannelOrderBy.LIKES_DESC); + + String channelName = "Channel_" + getEpoch(); + String description = "description of " + channelName; + channel = ChannelUtils.addDynamicChannel(channelName, description, isActive, ksqlExpression, channelOrder, assetTypes); + + // channel/action/add + Response channelResponse = executor.executeSync(add(channel) + .setKs(getManagerKs()) + .setLanguage("*")); + + assertThat(channelResponse.results.getName()).isEqualTo(channelName); + + // cleanup - delete channel + executor.executeSync(ChannelService.delete(Math.toIntExact(channelResponse.results.getId())) + .setKs(getManagerKs())); + } + + @Severity(SeverityLevel.MINOR) + @Description("channel/action/add - with not supported opc partner id") + @Test(enabled = false) // no validation in channel/action/add for account 203 + private void addDynamicChannelWithNotSupportedOpcPartnerId() { + String ksqlExpression = "name ~ 'movie'"; + + int mediaTypeId = getMediaTypeId(MediaType.MOVIE); + integerValue.setValue(mediaTypeId); + List assetTypes = new ArrayList<>(); + assetTypes.add(integerValue); + + ChannelOrder channelOrder = new ChannelOrder(); + channelOrder.setOrderBy(ChannelOrderBy.LIKES_DESC); + + String channelName = "Channel_" + getEpoch(); + String description = "description of " + channelName; + channel = ChannelUtils.addDynamicChannel(channelName, description, isActive, ksqlExpression, channelOrder, assetTypes); + + // channel/action/add + Response channelResponse = executor.executeSync(add(channel) + .setKs(getManagerKs()) + .setLanguage("*")); + + assertThat(channelResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(4074).getCode()); } - // TODO + @Severity(SeverityLevel.CRITICAL) @Description("channel/action/add - order by NAME_DESC") @Test private void checkOrderOfAssetsInChannel() { - - String asset1Name = "Movie_" + BaseUtils.getCurrentDataInFormat("yyMMddHHmmss"); - String asset2Name = "Episode_" + BaseUtils.getCurrentDataInFormat("yyMMddHHmmss"); + String asset1Name = "Movie_" + BaseUtils.getCurrentDateInFormat("yyMMddHHmmss"); + String asset2Name = "Episode_" + BaseUtils.getCurrentDateInFormat("yyMMddHHmmss"); // Ingest first asset - MediaAsset movieAsset = IngestUtils.ingestBasicVOD(Optional.of(asset1Name), MOVIE_MEDIA_TYPE); + VodData vodData = new VodData() + .name(asset1Name) + .mediaType(MediaType.MOVIE); + MediaAsset movieAsset = insertVod(vodData, true); // Ingest second asset - MediaAsset episodeAsset = IngestUtils.ingestBasicVOD(Optional.of(asset2Name), MOVIE_MEDIA_TYPE); + VodData vodData1 = new VodData() + .name(asset2Name) + .mediaType(MediaType.EPISODE); + MediaAsset episodeAsset = insertVod(vodData1, true); - filterExpression = "(or name = '" + movieAsset.getName() + "' name = '" + episodeAsset.getName() + "')"; - channel = ChannelUtils.addChannel(channelName, Description, isActive, filterExpression, AssetOrderBy.NAME_DESC, null, null); + String ksqlExpression = "(or name = '" + movieAsset.getName() + "' name = '" + episodeAsset.getName() + "')"; + ChannelOrder channelOrder = new ChannelOrder(); + channelOrder.setOrderBy(ChannelOrderBy.NAME_DESC); - //channel/action/add - AddChannelBuilder addChannelBuilder = ChannelService.add(channel); - addChannelBuilder.setKs(getManagerKs()); - Response channelResponse = executor.executeSync(addChannelBuilder); + String channelName = "Channel_" + getEpoch(); + String description = "description of " + channelName; + channel = ChannelUtils.addDynamicChannel(channelName, description, isActive, ksqlExpression, channelOrder, null); - assertThat(channelResponse.results.getName()).isEqualTo(channelName); + // channel/action/add + Response channelResponse = executor.executeSync(add(channel) + .setKs(getManagerKs()) + .setLanguage("*")); + assertThat(channelResponse.results.getMultilingualName().get(0).getValue()).isEqualTo(channelName); int channelId = Math.toIntExact(channelResponse.results.getId()); - ChannelFilter channelFilter = AssetUtils.getChannelFilter(channelId, null, null, null); - //asset/action/list - ListAssetBuilder listAssetBuilder = AssetService.list(channelFilter); - listAssetBuilder.setKs(getManagerKs()); - Response> listResponse = executor.executeSync(listAssetBuilder); + // asset/action/list + ChannelFilter channelFilter = AssetUtils.getChannelFilter(channelId, Optional.empty(), Optional.empty(), Optional.empty()); + + Response> listResponse = executor.executeSync(AssetService.list(channelFilter) + .setKs(getManagerKs())); assertThat(listResponse.results.getTotalCount()).isEqualTo(2); // Verify movie asset id returned first (because order is by name_desc) assertThat(listResponse.results.getObjects().get(0).getId()).isEqualTo(movieAsset.getId()); - // Cleanup - channel/action/delete - DeleteChannelBuilder deleteChannelBuilder = ChannelService.delete(channelId); - deleteChannelBuilder.setKs(getManagerKs()); - executor.executeSync(deleteChannelBuilder); - + // cleanup - delete channel + executor.executeSync(ChannelService.delete(channelId) + .setKs(getManagerKs())); } - - @Description("channel/action/add - with invalid asset type") - @Test + @Severity(SeverityLevel.NORMAL) + @Description("channel/action/add - with invalid asset type - error 4028") + @Test(enabled = false) // no validation in channel/action/add for account 203 private void addChannelWithInvalidAssetType() { - integerValue.setValue(666); + String ksqlExpression = "name ~ 'movie'"; + + int invalidAssetType = 1; + integerValue.setValue(invalidAssetType); + List assetTypes = new ArrayList<>(); assetTypes.add(integerValue); - channel = ChannelUtils.addChannel(channelName, Description, isActive, null, AssetOrderBy.LIKES_DESC, assetTypes, null); - //channel/action/add + ChannelOrder channelOrder = new ChannelOrder(); + channelOrder.setOrderBy(ChannelOrderBy.LIKES_DESC); + + String channelName = "Channel_" + getEpoch(); + String description = "description of " + channelName; + channel = ChannelUtils.addDynamicChannel(channelName, description, isActive, ksqlExpression, channelOrder, assetTypes); - AddChannelBuilder addChannelBuilder = ChannelService.add(channel); - addChannelBuilder.setKs(getManagerKs()); - Response channelResponse = executor.executeSync(addChannelBuilder); + // channel/action/add + Response channelResponse = executor.executeSync(add(channel) + .setKs(getManagerKs()) + .setLanguage("*")); - // KalturaAPIException","code":"4020","message":"KSQL Channel media type 666 does not belong to group" - assertThat(channelResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(4020).getCode()); + // KalturaAPIException","code":"4028" + assertThat(channelResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(4028).getCode()); } - @Description("channel/action/add - mandatory channel name not provided") + @Severity(SeverityLevel.NORMAL) + @Description("channel/action/add - mandatory channel multilingualName not provided") @Test - private void addChannelWithNoName() { - channel = ChannelUtils.addChannel(null, Description, isActive, null, AssetOrderBy.LIKES_DESC, null, null); + private void addChannelWithoutMultilingualName() { + String ksqlExpression = "name ~ 'movie'"; - //channel/action/add + ChannelOrder channelOrder = new ChannelOrder(); + channelOrder.setOrderBy(ChannelOrderBy.LIKES_DESC); + + DynamicChannel channel = new DynamicChannel(); + channel.setIsActive(true); + channel.setOrderBy(channelOrder); + channel.setSystemName("systemName " + getEpoch()); - AddChannelBuilder addChannelBuilder = ChannelService.add(channel); - addChannelBuilder.setKs(getManagerKs()); - Response channelResponse = executor.executeSync(addChannelBuilder); + //channel/action/add + Response channelResponse = executor.executeSync(add(channel) + .setKs(getManagerKs()) + .setLanguage("*")); - // KalturaAPIException","code":"5005","message":"KSQL Channel must have a name" - assertThat(channelResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(5005).getCode()); + // KalturaAPIException","code":"50027","message":"Argument [name] cannot be empty" + assertThat(channelResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(50027).getCode()); } + @Severity(SeverityLevel.NORMAL) @Description("channel/action/add - syntax error in filter expression") @Test private void addChannelWithSyntaxErrorInFilterExpression() { - filterExpression = "name = 'syntax error"; - channel = ChannelUtils.addChannel(channelName, Description, isActive, filterExpression, AssetOrderBy.LIKES_DESC, null, null); + String ksqlExpression = "name = 'syntax error"; - //channel/action/add + ChannelOrder channelOrder = new ChannelOrder(); + channelOrder.setOrderBy(ChannelOrderBy.LIKES_DESC); + + String channelName = "Channel_" + getEpoch(); + String description = "description of " + channelName; + channel = ChannelUtils.addDynamicChannel(channelName, description, isActive, ksqlExpression, channelOrder, null); - AddChannelBuilder addChannelBuilder = ChannelService.add(channel); - addChannelBuilder.setKs(getManagerKs()); - Response channelResponse = executor.executeSync(addChannelBuilder); + //channel/action/add + Response channelResponse = executor.executeSync(add(channel) + .setKs(getManagerKs()) + .setLanguage("*")); // KalturaAPIException","code":"4004","message":"Invalid expression structure" assertThat(channelResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(4004).getCode()); } + + @AfterClass + private void channel_addTests_after_class() { + + } + } diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/channelTests/ChannelDeleteTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/channelTests/ChannelDeleteTests.java index 12543b98e..66bf4cf3c 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/channelTests/ChannelDeleteTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/channelTests/ChannelDeleteTests.java @@ -1,66 +1,54 @@ package com.kaltura.client.test.tests.servicesTests.channelTests; -import com.kaltura.client.Client; -import com.kaltura.client.enums.AssetOrderBy; -import com.kaltura.client.services.ChannelService; +import com.kaltura.client.enums.ChannelOrderBy; import com.kaltura.client.test.tests.BaseTest; import com.kaltura.client.test.utils.ChannelUtils; import com.kaltura.client.types.Channel; +import com.kaltura.client.types.ChannelOrder; import com.kaltura.client.utils.response.base.Response; import io.qameta.allure.Description; -import org.testng.annotations.BeforeClass; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; import org.testng.annotations.Test; import static com.kaltura.client.services.ChannelService.*; import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; +import static com.kaltura.client.test.utils.BaseUtils.getEpoch; import static org.assertj.core.api.Assertions.assertThat; public class ChannelDeleteTests extends BaseTest { - private Channel channel = new Channel(); - private String channelName; - private String Description; - private Boolean isActive; - private String filterExpression; + private Channel channel; private int channelId; - - @BeforeClass - private void get_tests_before_class() { - channelName = "Channel_12345"; - Description = "description of channel"; - isActive = true; - filterExpression = "name ~ 'movie'"; - } - + @Severity(SeverityLevel.CRITICAL) @Description("channel/action/delete") @Test private void DeleteChannel() { + String channelName = "Channel_" + getEpoch(); + String description = "description of " + channelName; + String ksqlExpression = "name ~ 'movie'"; - channel = ChannelUtils.addChannel(channelName, Description, isActive, filterExpression, AssetOrderBy.LIKES_DESC, null, null); + ChannelOrder channelOrder = new ChannelOrder(); + channelOrder.setOrderBy(ChannelOrderBy.LIKES_DESC); + channel = ChannelUtils.addDynamicChannel(channelName, description, true, ksqlExpression, channelOrder, null); // channel/action/add - // channel/action/add - - ChannelService.AddChannelBuilder addChannelBuilder = ChannelService.add(channel); - addChannelBuilder.setKs(getManagerKs()); - Response channelResponse = executor.executeSync(addChannelBuilder); + Response channelResponse = executor.executeSync(add(channel) + .setKs(getManagerKs()) + .setLanguage("*")); channelId = Math.toIntExact(channelResponse.results.getId()); // channel/action/delete - - ChannelService.DeleteChannelBuilder deleteChannelBuilder = ChannelService.delete(channelId); - deleteChannelBuilder.setKs(getManagerKs()); - Response deleteResponse = executor.executeSync(deleteChannelBuilder); + Response deleteResponse = executor.executeSync(delete(channelId) + .setKs(getManagerKs())); assertThat(deleteResponse.results.booleanValue()).isTrue(); // channel/action/get - verify channel wasn't found - - GetChannelBuilder getChannelBuilder = ChannelService.get(channelId); - getChannelBuilder.setKs(getManagerKs()); - Response getResponse = executor.executeSync(getChannelBuilder); + Response getResponse = executor.executeSync(get(channelId) + .setKs(getManagerKs())); assertThat(getResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500007).getCode()); } diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/channelTests/ChannelGetTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/channelTests/ChannelGetTests.java index f8cbc9d3c..715a5155e 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/channelTests/ChannelGetTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/channelTests/ChannelGetTests.java @@ -2,29 +2,15 @@ import com.kaltura.client.test.tests.BaseTest; import com.kaltura.client.types.Channel; -import io.qameta.allure.Description; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; public class ChannelGetTests extends BaseTest { - private Channel channel = new Channel(); - private String channelName = "Channel_12345"; - private String Description = "description of channel"; - private Boolean isActive = true; + private Channel channel; private String filterExpression; -public class ChannelActionGet extends BaseTest { + private final String channelName = "Channel_12345"; + private final String description = "description of channel"; - @BeforeClass - private void get_tests_before_class() { - } - - @Description - @Test - private void channelGetTests() { - - } -} + // TODO: 7/14/2018 implement tests } diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/countryTests/CountryListTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/countryTests/CountryListTests.java new file mode 100644 index 000000000..cd9b076cf --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/countryTests/CountryListTests.java @@ -0,0 +1,189 @@ +package com.kaltura.client.test.tests.servicesTests.countryTests; + +import com.kaltura.client.enums.CountryOrderBy; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.types.Country; +import com.kaltura.client.types.CountryFilter; +import com.kaltura.client.types.ListResponse; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.Test; +import java.util.*; + +import static com.kaltura.client.services.CountryService.*; +import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; +import static com.kaltura.client.test.utils.ingestUtils.BaseIngestUtils.DEFAULT_LANGUAGE; +import static org.assertj.core.api.Assertions.assertThat; + +public class CountryListTests extends BaseTest { + + private String countryId = "1"; + private String countryId2 = "2"; + + @Severity(SeverityLevel.CRITICAL) + @Description("country/action/list - empty filter - get all countries") + @Test + private void listCountry() { + CountryFilter countryFilter = new CountryFilter(); + ListCountryBuilder listCountryBuilder = new ListCountryBuilder(countryFilter) + .setKs(getOperatorKs()); + + // country/action/list + Response> countryResponse = executor.executeSync(listCountryBuilder); + assertThat(countryResponse.error).isNull(); + assertThat(countryResponse.results.getTotalCount()).isGreaterThan(200); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("country/action/list - verify results order (by name)") + @Test + private void listCountryOrder() { + + CountryFilter countryFilter = new CountryFilter(); + countryFilter.setOrderBy(CountryOrderBy.NAME_ASC.toString()); + ListCountryBuilder listCountryBuilder = new ListCountryBuilder(countryFilter) + .setKs(getOperatorKs()); + + // country/action/list - order by name ASC + Response> countryResponse = executor.executeSync(listCountryBuilder); + List newList = new ArrayList<>(); + for (Country country: countryResponse.results.getObjects()) { + newList.add(country.getName()); + } + ArrayList temp = new ArrayList<>(newList); + Collections.sort(temp); + assertThat(temp).isEqualTo(newList); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("country/action/list - filter by country id's") + @Test + private void listCountryByIds() { + + CountryFilter countryFilter = new CountryFilter(); + countryFilter.setIdIn(countryId + "," + countryId2); + ListCountryBuilder listCountryBuilder = new ListCountryBuilder(countryFilter) + .setKs(getOperatorKs()); + Response> countryResponse = executor.executeSync(listCountryBuilder); + + // Total count = 2 + assertThat(countryResponse.results.getTotalCount()).isEqualTo(2); + // object[0] country id = 1 + assertThat(countryResponse.results.getObjects().get(0).getId()).isEqualTo(countryId); + // object[0] country id = 2 + assertThat(countryResponse.results.getObjects().get(1).getId()).isEqualTo(countryId2); + } + + //TODO - Ask alon how to get country code dynamically (in order to assert). + @Severity(SeverityLevel.CRITICAL) + @Description("country/action/list - filter by current country") + @Test + private void listCountryByCurrentLocation() { + + CountryFilter countryFilter = new CountryFilter(); + countryFilter.setIpEqualCurrent(true); + ListCountryBuilder listCountryBuilder = new ListCountryBuilder(countryFilter) + .setKs(getOperatorKs()); + Response> countryResponse = executor.executeSync(listCountryBuilder); + assertThat(countryResponse.results.getTotalCount()).isEqualTo(1); + } + + // TODO - Remove hardcoded values + @Severity(SeverityLevel.CRITICAL) + @Description("country/action/list - filter by specific ip") + @Test + private void listCountryBySepcificIp() { + String usaIp = "74.240.65.157"; + String usaCountryCode = "US"; + String currency = "USD"; + String currencySign = "$"; + String langCode = DEFAULT_LANGUAGE; + + CountryFilter countryFilter = new CountryFilter(); + countryFilter.setIpEqual(usaIp); + ListCountryBuilder listCountryBuilder = new ListCountryBuilder(countryFilter) + .setKs(getOperatorKs()); + Response> countryResponse = executor.executeSync(listCountryBuilder); + + assertThat(countryResponse.results.getTotalCount()).isEqualTo(1); + assertThat(countryResponse.results.getObjects().get(0).getCode()).isEqualTo(usaCountryCode); + assertThat(countryResponse.results.getObjects().get(0).getCurrency()).isEqualTo(currency); + assertThat(countryResponse.results.getObjects().get(0).getMainLanguageCode()).isEqualTo(langCode); + assertThat(countryResponse.results.getObjects().get(0).getCurrencySign()).isEqualTo(currencySign); + } + + // Error validations + + @Severity(SeverityLevel.CRITICAL) + @Description("country/action/list - 4025 - CountryNotFound") + @Test + private void invalidCountryIp() { + + String invalidIp = "8.8"; + + CountryFilter countryFilter = new CountryFilter(); + countryFilter.setIpEqual(invalidIp); + ListCountryBuilder listCountryBuilder = new ListCountryBuilder(countryFilter) + .setKs(getOperatorKs()); + Response> countryResponse = executor.executeSync(listCountryBuilder); + + // Assert error code + assertThat(countryResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(4025).getCode()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("country/action/list - Invalid country id") + @Test + private void invalidCountryId() { + + String invalidCountryId = "88888"; + + CountryFilter countryFilter = new CountryFilter(); + countryFilter.setIdIn(invalidCountryId); + ListCountryBuilder listCountryBuilder = new ListCountryBuilder(countryFilter) + .setKs(getOperatorKs()); + Response> countryResponse = executor.executeSync(listCountryBuilder); + + // Assert error code + assertThat(countryResponse.results.getTotalCount()).isEqualTo(0); + } + + + @Severity(SeverityLevel.CRITICAL) + @Description("country/action/list - 500038 - Only one of IpEqual or IpEqualCurrent can be used, not both of them") + @Test + private void ipEqualandUpEqualCurrent() { + + String iranIp = "5.232.189.218"; + + CountryFilter countryFilter = new CountryFilter(); + countryFilter.setIpEqual(iranIp); + countryFilter.setIpEqualCurrent(true); + + ListCountryBuilder listCountryBuilder = new ListCountryBuilder(countryFilter) + .setKs(getOperatorKs()); + Response> countryResponse = executor.executeSync(listCountryBuilder); + + // Assert error code + assertThat(countryResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500038).getCode()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("country/action/list - 500038 - Only one of IdIn or IpEqualCurrent can be used, not both of them") + @Test + private void idInandUpEqualCurrent() { + + CountryFilter countryFilter = new CountryFilter(); + countryFilter.setIdIn(countryId + "" + countryId2); + countryFilter.setIpEqualCurrent(true); + + ListCountryBuilder listCountryBuilder = new ListCountryBuilder(countryFilter) + .setKs(getOperatorKs()); + Response> countryResponse = executor.executeSync(listCountryBuilder); + + // Assert error code + assertThat(countryResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500038).getCode()); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/entitlementTests/CancelTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/entitlementTests/CancelTests.java deleted file mode 100644 index 6b8bf4c0e..000000000 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/entitlementTests/CancelTests.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.kaltura.client.test.tests.servicesTests.entitlementTests; - -import com.kaltura.client.test.tests.BaseTest; -import org.testng.annotations.Test; - -public class CancelTests extends BaseTest { - - @Test(description = "entitlement/action/cancel") - private void cancel() { -// EntitlementServiceImpl - - } -} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/entitlementTests/EntitlementCancelTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/entitlementTests/EntitlementCancelTests.java new file mode 100644 index 000000000..78b31bbc1 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/entitlementTests/EntitlementCancelTests.java @@ -0,0 +1,253 @@ +package com.kaltura.client.test.tests.servicesTests.entitlementTests; + +import com.kaltura.client.enums.AssetType; +import com.kaltura.client.enums.BookmarkActionType; +import com.kaltura.client.enums.TransactionType; +import com.kaltura.client.services.BookmarkService; +import com.kaltura.client.services.BookmarkService.AddBookmarkBuilder; +import com.kaltura.client.services.ChannelService; +import com.kaltura.client.services.EntitlementService; +import com.kaltura.client.services.LicensedUrlService; +import com.kaltura.client.services.LicensedUrlService.GetLicensedUrlBuilder; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.HouseholdUtils; +import com.kaltura.client.test.utils.OttUserUtils; +import com.kaltura.client.test.utils.PurchaseUtils; +import com.kaltura.client.test.utils.dbUtils.DBUtils; +import com.kaltura.client.test.utils.ingestUtils.IngestVodUtils; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import java.util.List; +import java.util.Optional; +import static com.kaltura.client.services.ChannelService.add; +import static com.kaltura.client.services.EntitlementService.*; +import static com.kaltura.client.services.HouseholdService.delete; +import static com.kaltura.client.test.Properties.WEB_FILE_TYPE; +import static com.kaltura.client.test.Properties.getProperty; +import static com.kaltura.client.test.utils.BaseUtils.*; +import static com.kaltura.client.test.utils.ingestUtils.IngestMppUtils.*; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.deleteVod; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.insertVod; +import static org.assertj.core.api.Assertions.assertThat; + +public class EntitlementCancelTests extends BaseTest { + + private int subscriptionId; + + private Household testSharedHousehold; + private HouseholdUser testSharedMasterUser; + private BookmarkPlayerData playerData; + private Bookmark bookmark; + private DynamicChannel sharedChannel; + + private final int numberOfUsersInHousehold = 2; + private final int numberOfDevicesInHousehold = 1; + + @BeforeClass + public void cancelTestBeforeClass() { + subscriptionId = Integer.valueOf(getSharedCommonSubscription().getId()); + + // set household + testSharedHousehold = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, true); + testSharedMasterUser = HouseholdUtils.getMasterUser(testSharedHousehold); + + playerData = new BookmarkPlayerData(); + playerData.setAction(BookmarkActionType.FIRST_PLAY); + playerData.setAverageBitrate(0); + playerData.setTotalBitrate(0); + playerData.setCurrentBitrate(0); + + bookmark = new Bookmark(); + bookmark.setPosition(0); + bookmark.setType(AssetType.MEDIA); + + sharedChannel = new DynamicChannel(); + sharedChannel.setMultilingualName(setTranslationToken(getRandomValue("Channel_"))); + sharedChannel.setMultilingualDescription(setTranslationToken("Description of " + sharedChannel.getName())); + sharedChannel.setSystemName(sharedChannel.getMultilingualName().get(0).getValue()); + sharedChannel.setIsActive(true); + sharedChannel.setAssetTypes(null); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("entitlement/action/cancel - cancel subscription") + @Test + public void cancelSubscription() { + // set household + Household household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, false); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + String userKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId())); + + // grant subscription + GrantEntitlementBuilder grantEntitlementBuilder = grant(subscriptionId, TransactionType.SUBSCRIPTION, true, 0) + .setKs(getAdministratorKs()).setUserId(Integer.valueOf(masterUser.getUserId())); + executor.executeSync(grantEntitlementBuilder); + + // set entitlementFilter + EntitlementFilter filter = new EntitlementFilter(); + filter.setProductTypeEqual(TransactionType.SUBSCRIPTION); + + // assert entitlement list size == 1 + ListEntitlementBuilder listEntitlementBuilder = EntitlementService.list(filter).setKs(userKs); + List entitlementList = executor.executeSync(listEntitlementBuilder).results.getObjects(); + assertThat(entitlementList.size()).isEqualTo(1); + + // cancel subscription + CancelEntitlementBuilder cancelEntitlementBuilder = cancel(subscriptionId, TransactionType.SUBSCRIPTION).setKs(userKs); + Response booleanResponse = executor.executeSync(cancelEntitlementBuilder); + assertThat(booleanResponse.results.booleanValue()).isTrue(); + + // assert entitlement list size == 0 + listEntitlementBuilder = EntitlementService.list(filter).setKs(userKs); + entitlementList = executor.executeSync(listEntitlementBuilder).results.getObjects(); + assertThat(entitlementList.size()).isEqualTo(0); + + // delete household for cleanup + executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getAdministratorKs())); + } + + @Severity(SeverityLevel.NORMAL) + @Description("entitlement/action/cancel - cancel non-purchased subscription - error 3000") + @Test + public void cancelWithInvalidSubscription() { + // cancel subscription + int invalidSubscriptionId = 1; + String userKs = OttUserUtils.getKs(Integer.parseInt(testSharedMasterUser.getUserId())); + + CancelEntitlementBuilder cancelEntitlementBuilder = cancel(invalidSubscriptionId, TransactionType.SUBSCRIPTION); + Response booleanResponse = executor.executeSync(cancelEntitlementBuilder.setKs(userKs)); + assertThat(booleanResponse.results).isNull(); + assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(3000).getCode()); + } + + @Severity(SeverityLevel.NORMAL) + @Description("entitlement/action/cancel - cancel played subscription - error 3005") + @Test + public void cancelPlayedSubscription() { + // create mpp having at least 1 media on its channel + sharedChannel.setKSql("name='" + getSharedMediaAsset().getName() + "'"); + + Response channelResponse = executor.executeSync(add(sharedChannel) + .setKs(getManagerKs()) + .setLanguage("*")); + + assertThat(channelResponse.results).isNotNull(); + + Channel channel = channelResponse.results; + assertThat(channel.getName()).isNotNull(); + PricePlan pricePlan = DBUtils.loadPPWithWaiver(); + + MppData mppData = new MppData() + .isRenewable(true) + .pricePlanCode1(pricePlan.getName()) + .channel1(channel.getName()); + Subscription subscription = insertMpp(mppData); + + // set household + Household household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, true); + //HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + String masterKs = HouseholdUtils.getHouseholdMasterUserKs(household, HouseholdUtils.getDevicesList(household).get(0).getUdid()); + + PurchaseUtils.purchaseSubscription(masterKs, Integer.valueOf(subscription.getId()), Optional.empty()); + + // get CDN code for media + MediaFile mediaFile = getMediaFileByType(getSharedMediaAsset(), getProperty(WEB_FILE_TYPE)); + String cdnCode = mediaFile.getUrl(); + + // check license for play + LicensedUrlMediaRequest licensedUrlRequest = new LicensedUrlMediaRequest(); + licensedUrlRequest.setAssetId(String.valueOf(getSharedMediaAsset().getId())); + licensedUrlRequest.setContentId(mediaFile.getId()); + licensedUrlRequest.setBaseUrl(cdnCode); + GetLicensedUrlBuilder licensedUrlBuilder = LicensedUrlService.get(licensedUrlRequest); + Response urlResponse = executor.executeSync(licensedUrlBuilder.setKs(masterKs)); + assertThat(urlResponse.results).isNotNull(); + // play + playerData.setFileId(mediaFile.getId().longValue()); + bookmark.setPlayerData(playerData); + bookmark.setId(String.valueOf(getSharedMediaAsset().getId())); + AddBookmarkBuilder addBookmarkBuilder = BookmarkService.add(bookmark); + Response booleanResponse = executor.executeSync(addBookmarkBuilder.setKs(masterKs)); + assertThat(booleanResponse.results.booleanValue()).isTrue(); + + // try cancel + CancelEntitlementBuilder cancelEntitlementBuilder = cancel(Integer.valueOf(subscription.getId()), + TransactionType.SUBSCRIPTION); + booleanResponse = executor.executeSync(cancelEntitlementBuilder.setKs(masterKs)); + assertThat(booleanResponse.results).isNull(); + assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(3005).getCode()); + + // delete household for cleanup + executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getAdministratorKs())); + //delete subscription + deleteMpp(subscription.getName()); + // delete channel + executor.executeSync(ChannelService.delete(Math.toIntExact(channel.getId())).setKs(getManagerKs())); + } + + @Severity(SeverityLevel.NORMAL) + @Description("entitlement/action/cancel - cancel subscription in cancellation window - error 3001") + @Test + public void cancelSubscriptionInCancellationWindow() { + // create MPP with enabled cancellation window + PricePlan pricePlan = DBUtils.loadPPWithoutWaiver(); + MppData mppData = new MppData() + .pricePlanCode1(pricePlan.getName()) + .isRenewable(true); + Subscription subscription = insertMpp(mppData); + + // purchase ingested MPP using shared HH + String masterKs = OttUserUtils.getKs(Integer.parseInt(testSharedMasterUser.getUserId()), null); + PurchaseUtils.purchaseSubscription(masterKs, Integer.valueOf(subscription.getId()), Optional.empty()); + + // try cancel + CancelEntitlementBuilder cancelEntitlementBuilder = cancel(Integer.valueOf(subscription.getId()), + TransactionType.SUBSCRIPTION); + Response booleanResponse = executor.executeSync(cancelEntitlementBuilder.setKs(masterKs)); + assertThat(booleanResponse.results).isNull(); + assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(3001).getCode()); + + //delete subscription + deleteMpp(subscription.getName()); + } + + // TODO: 5/22/2018 add cancel ppv test with dynamic data + @Severity(SeverityLevel.NORMAL) + @Description("entitlement/action/cancel - cancel ppv in cancellation window - error 3001") + @Test + public void cancelPpvInCancellationWindow() { + // ingest VOD having PPV with price plan without waiver + Ppv ppv = DBUtils.loadPPVByPPWithoutWaiver(); + IngestVodUtils.VodData vodData = new IngestVodUtils.VodData() + .ppvWebName(ppv.getName()) + .ppvMobileName(ppv.getName()); + MediaAsset mediaAsset = insertVod(vodData, true); + + String masterKs = OttUserUtils.getKs(Integer.parseInt(testSharedMasterUser.getUserId()), null); + // purchase ppv + Integer mediaFileId = mediaAsset.getMediaFiles().get(0).getId(); + Response transactionResponse = PurchaseUtils.purchasePpv(masterKs, Optional.of(Math.toIntExact(mediaAsset.getId())), + Optional.of(mediaFileId), Optional.empty()); + + // try cancel + CancelEntitlementBuilder cancelEntitlementBuilder = cancel(mediaFileId, TransactionType.PPV); + Response booleanResponse = executor.executeSync(cancelEntitlementBuilder.setKs(masterKs)); + assertThat(booleanResponse.results).isNull(); + assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(3001).getCode()); + + //delete Vod + deleteVod(mediaAsset.getName()); + } + + @AfterClass + public void cancelTestAfterClass() { + // delete shared household for cleanup + executor.executeSync(delete(Math.toIntExact(testSharedHousehold.getId())).setKs(getAdministratorKs())); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/entitlementTests/GrantTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/entitlementTests/EntitlementGrantTests.java similarity index 73% rename from src/test/java/com/kaltura/client/test/tests/servicesTests/entitlementTests/GrantTests.java rename to src/test/java/com/kaltura/client/test/tests/servicesTests/entitlementTests/EntitlementGrantTests.java index a4a7047c7..82d37f16f 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/entitlementTests/GrantTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/entitlementTests/EntitlementGrantTests.java @@ -4,50 +4,61 @@ import com.kaltura.client.enums.PurchaseStatus; import com.kaltura.client.enums.TransactionHistoryOrderBy; import com.kaltura.client.enums.TransactionType; -import com.kaltura.client.services.*; -import com.kaltura.client.services.EntitlementService.*; -import com.kaltura.client.services.HouseholdService.DeleteHouseholdBuilder; -import com.kaltura.client.services.ProductPriceService.ListProductPriceBuilder; +import com.kaltura.client.services.EntitlementService; +import com.kaltura.client.services.EntitlementService.GrantEntitlementBuilder; +import com.kaltura.client.services.HouseholdService.*; +import com.kaltura.client.services.TransactionHistoryService; import com.kaltura.client.services.TransactionHistoryService.ListTransactionHistoryBuilder; import com.kaltura.client.test.tests.BaseTest; -import com.kaltura.client.test.utils.AssetUtils; import com.kaltura.client.test.utils.HouseholdUtils; import com.kaltura.client.test.utils.OttUserUtils; import com.kaltura.client.types.*; import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; import io.qameta.allure.Issue; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import static com.kaltura.client.services.HouseholdService.*; +import static com.kaltura.client.services.OttUserService.RegisterOttUserBuilder; +import static com.kaltura.client.services.OttUserService.register; +import static com.kaltura.client.services.ProductPriceService.ListProductPriceBuilder; +import static com.kaltura.client.services.ProductPriceService.list; import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; import static org.assertj.core.api.Assertions.assertThat; -public class GrantTests extends BaseTest { +public class EntitlementGrantTests extends BaseTest { - // TODO: 4/12/2018 remove hardcoded subscription Id - private final int subscriptionId = 327699; - private final int ppvId = 30297; - private final int assetId = 607368; + private int ppvId; + private int assetId; + private int subscriptionId; + private int contentId; private final int numberOfUsersInHousehold = 2; private final int numberOfDevicesInHousehold = 1; - private Response> billingTransactionListResponse; - private int contentId; private Household testSharedHousehold; + private Response> billingTransactionListResponse; @BeforeClass private void grant_test_before_class() { - contentId = AssetUtils.getAssetFileIds(String.valueOf(assetId)).get(0); + assetId = Math.toIntExact(getSharedMediaAsset().getId()); + contentId = getSharedWebMediaFile().getId(); testSharedHousehold = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, false); + subscriptionId = Integer.valueOf(getSharedCommonSubscription().getId()); + ppvId = Integer.valueOf(getSharedCommonPpv().getId()); } - @Test(description = "entitlement/action/grant - grant subscription with history = true") + @Severity(SeverityLevel.CRITICAL) + @Description("entitlement/action/grant - grant subscription with history = true") + @Test private void grant_subscription_with_history() { // set household Household household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, false); - HouseholdUser masterUser = HouseholdUtils.getMasterUserFromHousehold(household); - HouseholdUser user = HouseholdUtils.getRegularUsersListFromHouseHold(household).get(0); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + HouseholdUser user = HouseholdUtils.getRegularUsersList(household).get(0); // grant subscription - history = true @@ -55,21 +66,21 @@ private void grant_subscription_with_history() { .setUserId(Integer.valueOf(user.getUserId())) .setKs(getAdministratorKs()); Response booleanResponse = executor.executeSync(grantEntitlementBuilder); - assertThat(booleanResponse.results.booleanValue()).isEqualTo(true); // verify other user from the household entitled to granted subscription ProductPriceFilter productPriceFilter = new ProductPriceFilter(); productPriceFilter.subscriptionIdIn(String.valueOf(subscriptionId)); - ProductPriceService.ListProductPriceBuilder listProductPriceBuilder = ProductPriceService.list(productPriceFilter) + ListProductPriceBuilder listProductPriceBuilder = list(productPriceFilter) .setUserId(Integer.valueOf(masterUser.getUserId())) .setKs(getAdministratorKs()); Response> productPriceListResponse = executor.executeSync(listProductPriceBuilder); ProductPrice productPrice = productPriceListResponse.results.getObjects().get(0); assertThat(productPriceListResponse.results.getTotalCount()).isEqualTo(1); - assertThat(productPrice.getPrice().getAmount()).isEqualTo(0); + // due to double purchase price is not 0 + assertThat(productPrice.getPrice().getAmount()).isNotEqualTo(0); assertThat(productPrice.getPurchaseStatus().getValue()).isEqualTo(PurchaseStatus.SUBSCRIPTION_PURCHASED.getValue()); @@ -80,8 +91,7 @@ private void grant_subscription_with_history() { transactionHistoryfilter.entityReferenceEqual(EntityReferenceBy.USER.getValue()); TransactionHistoryService.ListTransactionHistoryBuilder listTransactionHistoryBuilder = TransactionHistoryService.list(transactionHistoryfilter, null) - .setKs(OttUserUtils.getKs(Integer.parseInt(user.getUserId()), null)) - .setUserId(null); + .setKs(OttUserUtils.getKs(Integer.parseInt(user.getUserId()))); billingTransactionListResponse = executor.executeSync(listTransactionHistoryBuilder); assertThat(billingTransactionListResponse.results.getTotalCount()).isEqualTo(1); @@ -93,8 +103,7 @@ private void grant_subscription_with_history() { transactionHistoryfilter.entityReferenceEqual(EntityReferenceBy.HOUSEHOLD.getValue()); listTransactionHistoryBuilder = TransactionHistoryService.list(transactionHistoryfilter, null) - .setKs(OttUserUtils.getKs(Integer.parseInt(user.getUserId()), null)) - .setUserId(null); + .setKs(OttUserUtils.getKs(Integer.parseInt(user.getUserId()))); billingTransactionListResponse = executor.executeSync(listTransactionHistoryBuilder); assertThat(billingTransactionListResponse.results.getTotalCount()).isEqualTo(1); @@ -104,16 +113,18 @@ private void grant_subscription_with_history() { //delete household for cleanup //HouseholdService.delete(getClient(getAdministratorKs()), Math.toIntExact(household.getId())); - DeleteHouseholdBuilder deleteHouseholdBuilder = HouseholdService.delete(Math.toIntExact(household.getId())) + DeleteHouseholdBuilder deleteHouseholdBuilder = delete(Math.toIntExact(household.getId())) .setKs(getAdministratorKs()); executor.executeSync(deleteHouseholdBuilder); } - @Test(description = "entitlement/action/grant - grant subscription with history = false") + @Severity(SeverityLevel.CRITICAL) + @Description("entitlement/action/grant - grant subscription with history = false") + @Test private void grant_subscription_without_history() { // set household Household household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, false); - HouseholdUser user = HouseholdUtils.getRegularUsersListFromHouseHold(household).get(0); + HouseholdUser user = HouseholdUtils.getRegularUsersList(household).get(0); // grant subscription - history = true @@ -130,8 +141,7 @@ private void grant_subscription_without_history() { transactionHistoryfilter.entityReferenceEqual(EntityReferenceBy.USER.getValue()); TransactionHistoryService.ListTransactionHistoryBuilder listTransactionHistoryBuilder = TransactionHistoryService.list(transactionHistoryfilter, null) - .setKs(OttUserUtils.getKs(Integer.parseInt(user.getUserId()), null)) - .setUserId(null); + .setKs(OttUserUtils.getKs(Integer.parseInt(user.getUserId()))); billingTransactionListResponse = executor.executeSync(listTransactionHistoryBuilder); assertThat(billingTransactionListResponse.results.getTotalCount()).isEqualTo(0); @@ -139,32 +149,32 @@ private void grant_subscription_without_history() { transactionHistoryfilter.entityReferenceEqual(EntityReferenceBy.HOUSEHOLD.getValue()); listTransactionHistoryBuilder = TransactionHistoryService.list(transactionHistoryfilter, null) - .setKs(OttUserUtils.getKs(Integer.parseInt(user.getUserId()), null)) - .setUserId(null); + .setKs(OttUserUtils.getKs(Integer.parseInt(user.getUserId()))); billingTransactionListResponse = executor.executeSync(listTransactionHistoryBuilder); assertThat(billingTransactionListResponse.results.getTotalCount()).isEqualTo(0); //delete household for cleanup - DeleteHouseholdBuilder deleteHouseholdBuilder = HouseholdService.delete(Math.toIntExact(household.getId())) + DeleteHouseholdBuilder deleteHouseholdBuilder = delete(Math.toIntExact(household.getId())) .setKs(getAdministratorKs()); executor.executeSync(deleteHouseholdBuilder); } - @Test(description = "entitlement/action/grant - grant ppv with history = true") + @Severity(SeverityLevel.CRITICAL) + @Description("entitlement/action/grant - grant ppv with history = true") + @Test private void grant_ppv_with_history() { // set household Household household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, false); - HouseholdUser masterUser = HouseholdUtils.getMasterUserFromHousehold(household); - HouseholdUser user = HouseholdUtils.getRegularUsersListFromHouseHold(household).get(0); - + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + HouseholdUser user = HouseholdUtils.getRegularUsersList(household).get(0); // grant subscription - history = true GrantEntitlementBuilder grantEntitlementBuilder = EntitlementService.grant(ppvId, TransactionType.PPV, true, contentId) .setUserId(Integer.valueOf(user.getUserId())) .setKs(getAdministratorKs()); Response booleanResponse = executor.executeSync(grantEntitlementBuilder); - + assertThat(booleanResponse).isNotNull(); assertThat(booleanResponse.results.booleanValue()).isEqualTo(true); @@ -172,7 +182,7 @@ private void grant_ppv_with_history() { ProductPriceFilter productPriceFilter = new ProductPriceFilter(); productPriceFilter.fileIdIn(String.valueOf(contentId)); - ListProductPriceBuilder listProductPriceBuilder = ProductPriceService.list(productPriceFilter) + ListProductPriceBuilder listProductPriceBuilder = list(productPriceFilter) .setUserId(Integer.valueOf(masterUser.getUserId())) .setKs(getAdministratorKs()); Response> productPriceListResponse = executor.executeSync(listProductPriceBuilder); @@ -190,8 +200,7 @@ private void grant_ppv_with_history() { transactionHistoryfilter.entityReferenceEqual(EntityReferenceBy.USER.getValue()); ListTransactionHistoryBuilder listTransactionHistoryBuilder = TransactionHistoryService.list(transactionHistoryfilter, null) - .setKs(OttUserUtils.getKs(Integer.parseInt(user.getUserId()), null)) - .setUserId(null); + .setKs(OttUserUtils.getKs(Integer.parseInt(user.getUserId()))); billingTransactionListResponse = executor.executeSync(listTransactionHistoryBuilder); assertThat(billingTransactionListResponse.results.getTotalCount()).isEqualTo(1); @@ -203,8 +212,7 @@ private void grant_ppv_with_history() { transactionHistoryfilter.entityReferenceEqual(EntityReferenceBy.HOUSEHOLD.getValue()); listTransactionHistoryBuilder = TransactionHistoryService.list(transactionHistoryfilter, null) - .setKs(OttUserUtils.getKs(Integer.parseInt(user.getUserId()), null)) - .setUserId(null); + .setKs(OttUserUtils.getKs(Integer.parseInt(user.getUserId()))); billingTransactionListResponse = executor.executeSync(listTransactionHistoryBuilder); assertThat(billingTransactionListResponse.results.getTotalCount()).isEqualTo(1); @@ -213,25 +221,26 @@ private void grant_ppv_with_history() { //delete household for cleanup - DeleteHouseholdBuilder deleteHouseholdBuilder = HouseholdService.delete(Math.toIntExact(household.getId())) + DeleteHouseholdBuilder deleteHouseholdBuilder = delete(Math.toIntExact(household.getId())) .setKs(getAdministratorKs()); executor.executeSync(deleteHouseholdBuilder); } - @Test(description = "entitlement/action/grant - grant ppv with history = false") + @Severity(SeverityLevel.CRITICAL) + @Description("entitlement/action/grant - grant ppv with history = false") + @Test private void grant_ppv_without_history() { // set household Household household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, false); - HouseholdUser masterUser = HouseholdUtils.getMasterUserFromHousehold(household); - HouseholdUser user = HouseholdUtils.getRegularUsersListFromHouseHold(household).get(0); - + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + HouseholdUser user = HouseholdUtils.getRegularUsersList(household).get(0); // grant subscription - history = true GrantEntitlementBuilder grantEntitlementBuilder = EntitlementService.grant(ppvId, TransactionType.PPV, true, contentId) .setUserId(Integer.valueOf(user.getUserId())) .setKs(getAdministratorKs()); Response booleanResponse = executor.executeSync(grantEntitlementBuilder); - + assertThat(booleanResponse).isNotNull(); assertThat(booleanResponse.results.booleanValue()).isEqualTo(true); @@ -242,8 +251,7 @@ private void grant_ppv_without_history() { transactionHistoryfilter.entityReferenceEqual(EntityReferenceBy.USER.getValue()); ListTransactionHistoryBuilder listTransactionHistoryBuilder = TransactionHistoryService.list(transactionHistoryfilter, null) - .setKs(OttUserUtils.getKs(Integer.parseInt(user.getUserId()), null)) - .setUserId(null); + .setKs(OttUserUtils.getKs(Integer.parseInt(user.getUserId()))); billingTransactionListResponse = executor.executeSync(listTransactionHistoryBuilder); assertThat(billingTransactionListResponse.results.getTotalCount()).isEqualTo(1); @@ -255,8 +263,7 @@ private void grant_ppv_without_history() { transactionHistoryfilter.entityReferenceEqual(EntityReferenceBy.HOUSEHOLD.getValue()); listTransactionHistoryBuilder = TransactionHistoryService.list(transactionHistoryfilter, null) - .setKs(OttUserUtils.getKs(Integer.parseInt(user.getUserId()), null)) - .setUserId(null); + .setKs(OttUserUtils.getKs(Integer.parseInt(user.getUserId()))); billingTransactionListResponse = executor.executeSync(listTransactionHistoryBuilder); assertThat(billingTransactionListResponse.results.getTotalCount()).isEqualTo(1); @@ -265,17 +272,18 @@ private void grant_ppv_without_history() { //delete household for cleanup - DeleteHouseholdBuilder deleteHouseholdBuilder = HouseholdService.delete(Math.toIntExact(household.getId())) + DeleteHouseholdBuilder deleteHouseholdBuilder = delete(Math.toIntExact(household.getId())) .setKs(getAdministratorKs()); executor.executeSync(deleteHouseholdBuilder); } - @Test(description = "entitlement/action/grant - grant ppv with wrong id - error 6001") + @Severity(SeverityLevel.NORMAL) + @Description("entitlement/action/grant - grant ppv with wrong id - error 6001") private void grant_ppv_with_wrong_id() { int productId = 1; // get user form test shared household - HouseholdUser user = HouseholdUtils.getRegularUsersListFromHouseHold(testSharedHousehold).get(0); + HouseholdUser user = HouseholdUtils.getRegularUsersList(testSharedHousehold).get(0); // grant ppv with wrong id GrantEntitlementBuilder grantEntitlementBuilder = EntitlementService.grant(productId, TransactionType.PPV, true, contentId) @@ -285,36 +293,41 @@ private void grant_ppv_with_wrong_id() { // assert error 6001 is return - assertThat(booleanResponse.results).isEqualTo(null); + assertThat(booleanResponse.results).isNull(); assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(6001).getCode()); } - @Test(description = "entitlement/action/grant - grant purchased ppv - error 3021") + @Severity(SeverityLevel.NORMAL) + @Description("entitlement/action/grant - grant purchased ppv - error 3021") + @Test private void grant_purchased_ppv() { // get user form test shared household - HouseholdUser user = HouseholdUtils.getRegularUsersListFromHouseHold(testSharedHousehold).get(0); + HouseholdUser user = HouseholdUtils.getRegularUsersList(testSharedHousehold).get(0); // grant ppv - first time GrantEntitlementBuilder grantEntitlementBuilder = EntitlementService.grant(ppvId, TransactionType.PPV, true, contentId) .setUserId(Integer.valueOf(user.getUserId())) .setKs(getAdministratorKs()); - executor.executeSync(grantEntitlementBuilder); + Response booleanResponse = executor.executeSync(grantEntitlementBuilder); + assertThat(booleanResponse.error).isNull(); // grant ppv - second time grantEntitlementBuilder = EntitlementService.grant(ppvId, TransactionType.PPV, true, contentId) .setUserId(Integer.valueOf(user.getUserId())) .setKs(getAdministratorKs()); - Response booleanResponse = executor.executeSync(grantEntitlementBuilder); + booleanResponse = executor.executeSync(grantEntitlementBuilder); // assert error 3021 is return - assertThat(booleanResponse.results).isEqualTo(null); + assertThat(booleanResponse.results).isNull(); assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(3021).getCode()); } - @Test(description = "entitlement/action/grant - grant purchased subscription - error 3024") + @Severity(SeverityLevel.NORMAL) + @Description("entitlement/action/grant - grant purchased subscription - error 3024") + @Test private void grant_purchased_subscription() { // get user form test shared household - HouseholdUser user = HouseholdUtils.getRegularUsersListFromHouseHold(testSharedHousehold).get(0); + HouseholdUser user = HouseholdUtils.getRegularUsersList(testSharedHousehold).get(0); // grant subscription - first time GrantEntitlementBuilder grantEntitlementBuilder = EntitlementService.grant(subscriptionId, TransactionType.SUBSCRIPTION, false, 0) @@ -329,26 +342,45 @@ private void grant_purchased_subscription() { Response booleanResponse = executor.executeSync(grantEntitlementBuilder); // assert error 3024 is return - assertThat(booleanResponse.results).isEqualTo(null); + assertThat(booleanResponse.results).isNull(); assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(3024).getCode()); } + @Severity(SeverityLevel.NORMAL) @Issue("BEO-5022") - @Test(description = "entitlement/action/grant - error 3023") + @Description("entitlement/action/grant - error 3023") + @Test(enabled = false) private void grant_3023() { // TODO: 4/30/2018 implement test } + @Severity(SeverityLevel.NORMAL) @Issue("BEO-5022") - @Test(description = "entitlement/action/grant - grant ppv with missing content id - error 3018") - private void grant_ppv_with_missing_contentId() { - // TODO: 4/30/2018 implement test + @Description("entitlement/action/grant - grant ppv with invalid content id - error 3018") + @Test(enabled = false) + private void grant_ppv_with_invalid_contentId() { + // get user form test shared household + HouseholdUser user = HouseholdUtils.getRegularUsersList(testSharedHousehold).get(0); + + // grant ppv with invalid content id + int invalidContentId = 1; + GrantEntitlementBuilder grantEntitlementBuilder = EntitlementService.grant(ppvId, TransactionType.PPV, true, invalidContentId) + .setKs(getAdministratorKs()) + .setUserId(Integer.valueOf(user.getUserId())); + Response booleanResponse = executor.executeSync(grantEntitlementBuilder); + assertThat(booleanResponse.error).isNull(); + + // assert error 3018 is return + assertThat(booleanResponse.results).isNull(); + assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(3018).getCode()); } - @Test(description = "entitlement/action/grant - user not in domain - error 1005") + @Severity(SeverityLevel.NORMAL) + @Description("entitlement/action/grant - user not in domain - error 1005") + @Test private void grant_ppv_user_not_in_domain() { // get user form test shared household - OttUserService.RegisterOttUserBuilder registerOttUserBuilder = OttUserService.register(partnerId, OttUserUtils.generateOttUser(), defaultUserPassword); + RegisterOttUserBuilder registerOttUserBuilder = register(partnerId, OttUserUtils.generateOttUser(), defaultUserPassword); Response ottUserResponse = executor.executeSync(registerOttUserBuilder); OTTUser user = ottUserResponse.results; @@ -360,30 +392,33 @@ private void grant_ppv_user_not_in_domain() { Response booleanResponse = executor.executeSync(grantEntitlementBuilder); // assert error 1005 is return - assertThat(booleanResponse.results).isEqualTo(null); + assertThat(booleanResponse.results).isNull(); assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(1005).getCode()); } - @Test(description = "entitlement/action/grant - user suspend - error 2001") + @Severity(SeverityLevel.NORMAL) + @Description("entitlement/action/grant - user suspend - error 2001") + @Test private void grant_ppv_user_suspend() { - // set household Household household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, false); - HouseholdUser masterUser = HouseholdUtils.getMasterUserFromHousehold(household); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); // suspend household - HouseholdService.suspend(0) + SuspendHouseholdBuilder suspendHouseholdBuilder = suspend(0) .setKs(getAdministratorKs()) .setUserId(Integer.valueOf(masterUser.getUserId())); + Response booleanResponse = executor.executeSync(suspendHouseholdBuilder); + assertThat(booleanResponse.results.booleanValue()).isTrue(); // grant subscription to suspend user GrantEntitlementBuilder grantEntitlementBuilder = EntitlementService.grant(subscriptionId, TransactionType.SUBSCRIPTION, false, 0) .setKs(getAdministratorKs()) .setUserId(Integer.valueOf(masterUser.getUserId())); - Response booleanResponse = executor.executeSync(grantEntitlementBuilder); + booleanResponse = executor.executeSync(grantEntitlementBuilder); // assert error 2001 is return - assertThat(booleanResponse.results).isEqualTo(null); + assertThat(booleanResponse.results).isNull(); assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(2001).getCode()); } diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/entitlementTests/EntitlementListTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/entitlementTests/EntitlementListTests.java new file mode 100644 index 000000000..410c1df14 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/entitlementTests/EntitlementListTests.java @@ -0,0 +1,286 @@ +package com.kaltura.client.test.tests.servicesTests.entitlementTests; + +import com.kaltura.client.enums.EntityReferenceBy; +import com.kaltura.client.enums.PaymentMethodType; +import com.kaltura.client.enums.TransactionType; +import com.kaltura.client.services.EntitlementService; +import com.kaltura.client.services.EntitlementService.ForceCancelEntitlementBuilder; +import com.kaltura.client.services.EntitlementService.ListEntitlementBuilder; +import com.kaltura.client.services.HouseholdService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.HouseholdUtils; +import com.kaltura.client.test.utils.PurchaseUtils; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.Optional; + +import static com.kaltura.client.enums.EntitlementOrderBy.PURCHASE_DATE_ASC; +import static com.kaltura.client.services.HouseholdService.delete; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.*; +import static org.assertj.core.api.Assertions.assertThat; + +public class EntitlementListTests extends BaseTest { + + private EntitlementFilter filter; + private Household household; + private String masterUserId; + private String masterUserKs; + private String regularUserId; + private String regularUserKs; + + private Response> entitlementResponse; + + private final int numberOfUsersInHousehold = 2; + private final int numberOfDevicesInHousehold = 1; + + @BeforeClass + public void setUp() { + filter = new EntitlementFilter(); + filter.setOrderBy(PURCHASE_DATE_ASC.getValue()); + filter.setEntityReferenceEqual(EntityReferenceBy.HOUSEHOLD); + + household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, true); + masterUserKs = HouseholdUtils.getHouseholdMasterUserKs(household, HouseholdUtils.getDevicesList(household).get(0).getUdid()); + regularUserKs = HouseholdUtils.getHouseholdUserKs(household, HouseholdUtils.getDevicesList(household).get(0).getUdid()); + masterUserId = HouseholdUtils.getMasterUser(household).getUserId(); + regularUserId = HouseholdUtils.getRegularUsersList(household).get(0).getUserId(); + } + + @Severity(SeverityLevel.NORMAL) + @Description("/entitlement/action/list before purchase") + @Test + public void entitlementListBeforePurchase() { + Household household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, false); + String masterUserKs = HouseholdUtils.getHouseholdUserKs(household, HouseholdUtils.getDevicesList(household).get(0).getUdid()); + + // subscription + filter.setProductTypeEqual(TransactionType.SUBSCRIPTION); + filter.setIsExpiredEqual(false); + ListEntitlementBuilder entitlementListBeforePurchase = EntitlementService.list(filter, null); + entitlementResponse = executor.executeSync(entitlementListBeforePurchase.setKs(masterUserKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(0); + + // ppv + filter.setProductTypeEqual(TransactionType.PPV); + entitlementListBeforePurchase = EntitlementService.list(filter, null); + entitlementResponse = executor.executeSync(entitlementListBeforePurchase.setKs(masterUserKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(0); + + //with is expiredEqual: true + filter.setIsExpiredEqual(true); + // ppv + filter.setProductTypeEqual(TransactionType.PPV); + entitlementListBeforePurchase = EntitlementService.list(filter, null); + entitlementResponse = executor.executeSync(entitlementListBeforePurchase.setKs(masterUserKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(0); + + // subscription + filter.setProductTypeEqual(TransactionType.SUBSCRIPTION); + EntitlementService.list(filter, null); + entitlementResponse = executor.executeSync(entitlementListBeforePurchase.setKs(masterUserKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(0); + + //delete household for cleanup + HouseholdService.DeleteHouseholdBuilder deleteHouseholdBuilder = delete(Math.toIntExact(household.getId())); + executor.executeSync(deleteHouseholdBuilder.setKs(getAdministratorKs())); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("/entitlement/action/list after purchase") + @Test + public void entitlementListAfterPurchase() { + PurchaseUtils.purchasePpv(masterUserKs, Optional.of(Math.toIntExact(getSharedMediaAsset().getId())), + Optional.of(getSharedWebMediaFile().getId()), Optional.empty()); + PurchaseUtils.purchaseSubscription(masterUserKs, Integer.valueOf(getSharedCommonSubscription().getId()), + Optional.empty()); + + // subscription + filter.setProductTypeEqual(TransactionType.SUBSCRIPTION); + filter.setIsExpiredEqual(false); + ListEntitlementBuilder entitlementListAfterPurchase = EntitlementService.list(filter, null); + entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(masterUserKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(1); // only sub + assertThat(entitlementResponse.results.getObjects().get(0).getProductId()).isEqualTo(getSharedCommonSubscription().getId()); + assertThat(entitlementResponse.results.getObjects().get(0).getEndDate()).isGreaterThan( + entitlementResponse.results.getObjects().get(0).getCurrentDate()); + assertThat(entitlementResponse.results.getObjects().get(0).getPaymentMethod()).isIn( + PaymentMethodType.OFFLINE, PaymentMethodType.UNKNOWN); + + // ppv + filter.setProductTypeEqual(TransactionType.PPV); + entitlementListAfterPurchase = EntitlementService.list(filter, null); + entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(masterUserKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(1); // only Ppv + assertThat(((PpvEntitlement)entitlementResponse.results.getObjects().get(0)).getMediaFileId()).isEqualTo(getSharedWebMediaFile().getId()); + assertThat(((PpvEntitlement)entitlementResponse.results.getObjects().get(0)).getMediaId()).isEqualTo(Math.toIntExact(getSharedMediaAsset().getId())); + assertThat(entitlementResponse.results.getObjects().get(0).getEndDate()).isGreaterThan( + entitlementResponse.results.getObjects().get(0).getCurrentDate()); + assertThat(entitlementResponse.results.getObjects().get(0).getPaymentMethod()).isIn( + PaymentMethodType.OFFLINE, PaymentMethodType.UNKNOWN); + + //cancel household purchases for cleanup + ForceCancelEntitlementBuilder forceCancelEntitlementBuilder = EntitlementService.forceCancel( + Integer.valueOf(getSharedCommonSubscription().getId()), TransactionType.SUBSCRIPTION); + executor.executeSync(forceCancelEntitlementBuilder.setKs(getOperatorKs()).setUserId(Integer.valueOf(masterUserId))); + forceCancelEntitlementBuilder = EntitlementService.forceCancel(getSharedWebMediaFile().getId(), TransactionType.PPV); + executor.executeSync(forceCancelEntitlementBuilder.setKs(getOperatorKs()).setUserId(Integer.valueOf(masterUserId))); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("/entitlement/action/list after forceCancel") + @Test + public void entitlementListAfterForceCancel() { + PurchaseUtils.purchasePpv(masterUserKs, Optional.of(Math.toIntExact(getSharedMediaAsset().getId())), + Optional.of(getSharedWebMediaFile().getId()), Optional.empty()); + PurchaseUtils.purchaseSubscription(masterUserKs, Integer.valueOf(getSharedCommonSubscription().getId()), + Optional.empty()); + + // after purchase + // ppv + filter.setProductTypeEqual(TransactionType.PPV); + filter.setIsExpiredEqual(true); + ListEntitlementBuilder entitlementListAfterPurchase = EntitlementService.list(filter, null); + entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(masterUserKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(0); + + // subscription + filter.setProductTypeEqual(TransactionType.SUBSCRIPTION); + entitlementListAfterPurchase = EntitlementService.list(filter, null); + entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(masterUserKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(0); + + // cancel purchases + ForceCancelEntitlementBuilder forceCancelEntitlementBuilder = EntitlementService.forceCancel( + Integer.valueOf(getSharedCommonSubscription().getId()), TransactionType.SUBSCRIPTION); + executor.executeSync(forceCancelEntitlementBuilder.setKs(getOperatorKs()).setUserId(Integer.valueOf(masterUserId))); + forceCancelEntitlementBuilder = EntitlementService.forceCancel(getSharedWebMediaFile().getId(), TransactionType.PPV); + executor.executeSync(forceCancelEntitlementBuilder.setKs(getOperatorKs()).setUserId(Integer.valueOf(masterUserId))); + + // after cancel purchase + // ppv + filter.setProductTypeEqual(TransactionType.PPV); + filter.setIsExpiredEqual(true); + entitlementListAfterPurchase = EntitlementService.list(filter, null); + entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(masterUserKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(1); // only Ppv + assertThat(((PpvEntitlement)entitlementResponse.results.getObjects().get(0)).getMediaFileId()).isEqualTo(getSharedWebMediaFile().getId()); + assertThat(((PpvEntitlement)entitlementResponse.results.getObjects().get(0)).getMediaId()).isEqualTo(Math.toIntExact(getSharedMediaAsset().getId())); + assertThat(entitlementResponse.results.getObjects().get(0).getEndDate()).isLessThanOrEqualTo( + entitlementResponse.results.getObjects().get(0).getCurrentDate()); + assertThat(entitlementResponse.results.getObjects().get(0).getPaymentMethod()).isIn( + PaymentMethodType.OFFLINE, PaymentMethodType.UNKNOWN); + + // subscription + filter.setProductTypeEqual(TransactionType.SUBSCRIPTION); + entitlementListAfterPurchase = EntitlementService.list(filter, null); + entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(masterUserKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(1); // only sub + assertThat(entitlementResponse.results.getObjects().get(0).getProductId()).isEqualTo(getSharedCommonSubscription().getId()); + assertThat(entitlementResponse.results.getObjects().get(0).getEndDate()).isLessThanOrEqualTo( + entitlementResponse.results.getObjects().get(0).getCurrentDate()); + assertThat(entitlementResponse.results.getObjects().get(0).getPaymentMethod()).isIn( + PaymentMethodType.OFFLINE, PaymentMethodType.UNKNOWN); + } + + @Severity(SeverityLevel.NORMAL) + @Description("/entitlement/action/list paging") + @Test + public void entitlementListWithPaging() { + PurchaseUtils.purchasePpv(masterUserKs, Optional.of(Math.toIntExact(getSharedMediaAsset().getId())), + Optional.of(getSharedWebMediaFile().getId()), Optional.empty()); + + VodData vodData = new VodData(); + MediaAsset mediaAsset = insertVod(vodData, true); + + int mediaFileId = mediaAsset.getMediaFiles().get(0).getId(); + PurchaseUtils.purchasePpv(masterUserKs, Optional.of(Math.toIntExact(mediaAsset.getId())), + Optional.of(mediaFileId), Optional.empty()); + + // after purchase + // without paging + filter.setProductTypeEqual(TransactionType.PPV); + filter.setIsExpiredEqual(false); + ListEntitlementBuilder entitlementListAfterPurchase = EntitlementService.list(filter, null); + entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(masterUserKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(2); // 2 files + assertThat(((PpvEntitlement)entitlementResponse.results.getObjects().get(0)).getMediaFileId()).isEqualTo(getSharedWebMediaFile().getId()); + assertThat(((PpvEntitlement)entitlementResponse.results.getObjects().get(1)).getMediaFileId()).isEqualTo(mediaFileId); + + // with paging on 1st page + FilterPager pager = new FilterPager(); + pager.setPageSize(1); + pager.setPageIndex(1); + entitlementListAfterPurchase = EntitlementService.list(filter, pager); + entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(masterUserKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(2); // purchased 2 files + assertThat(entitlementResponse.results.getObjects().size()).isEqualTo(1); // only 1st file + assertThat(((PpvEntitlement)entitlementResponse.results.getObjects().get(0)).getMediaFileId()).isEqualTo(getSharedWebMediaFile().getId()); + + // with paging on 2nd page + pager.setPageIndex(2); + entitlementListAfterPurchase = EntitlementService.list(filter, pager); + entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(masterUserKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(2); // purchased 2 files + assertThat(entitlementResponse.results.getObjects().size()).isEqualTo(1); // only 2nd file + assertThat(((PpvEntitlement)entitlementResponse.results.getObjects().get(0)).getMediaFileId()).isEqualTo(mediaFileId); + + //cancel household purchases for cleanup + ForceCancelEntitlementBuilder forceCancelEntitlementBuilder = EntitlementService.forceCancel(getSharedWebMediaFile().getId(), TransactionType.PPV); + executor.executeSync(forceCancelEntitlementBuilder.setKs(getOperatorKs()).setUserId(Integer.valueOf(masterUserId))); + forceCancelEntitlementBuilder = EntitlementService.forceCancel(mediaFileId, TransactionType.PPV); + executor.executeSync(forceCancelEntitlementBuilder.setKs(getOperatorKs()).setUserId(Integer.valueOf(masterUserId))); + + // delete media + deleteVod(mediaAsset.getName()); + } + + @Severity(SeverityLevel.NORMAL) + @Description("/entitlement/action/list paging") + @Test + public void entitlementListByUser() { + EntitlementFilter filter = new EntitlementFilter(); + filter.setEntityReferenceEqual(EntityReferenceBy.USER); + filter.setIsExpiredEqual(false); + PurchaseUtils.purchasePpv(masterUserKs, Optional.of(Math.toIntExact(getSharedMediaAsset().getId())), + Optional.of(getSharedWebMediaFile().getId()), Optional.empty()); + PurchaseUtils.purchaseSubscription(regularUserKs, Integer.valueOf(getSharedCommonSubscription().getId()), + Optional.empty()); + + // after purchase + // by 1st user + filter.setProductTypeEqual(TransactionType.PPV); + ListEntitlementBuilder entitlementListAfterPurchase = EntitlementService.list(filter, null); + entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(masterUserKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(1); + assertThat(((PpvEntitlement)entitlementResponse.results.getObjects().get(0)).getMediaFileId()).isEqualTo(getSharedWebMediaFile().getId()); + + // by 2nd user + filter.setProductTypeEqual(TransactionType.SUBSCRIPTION); + entitlementListAfterPurchase = EntitlementService.list(filter, null); + entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(regularUserKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(1); + assertThat(entitlementResponse.results.getObjects().get(0).getProductId()).isEqualTo(getSharedCommonSubscription().getId()); + + //cancel household purchases for cleanup + ForceCancelEntitlementBuilder forceCancelEntitlementBuilder = EntitlementService.forceCancel(getSharedWebMediaFile().getId(), TransactionType.PPV); + executor.executeSync(forceCancelEntitlementBuilder.setKs(getOperatorKs()).setUserId(Integer.valueOf(masterUserId))); + forceCancelEntitlementBuilder = EntitlementService.forceCancel(Integer.valueOf(getSharedCommonSubscription().getId()), TransactionType.SUBSCRIPTION); + executor.executeSync(forceCancelEntitlementBuilder.setKs(getOperatorKs()).setUserId(Integer.valueOf(regularUserId))); + } + + @AfterClass + public void tearDown() { + //delete household for cleanup + HouseholdService.DeleteHouseholdBuilder deleteHouseholdBuilder = delete(Math.toIntExact(household.getId())); + executor.executeSync(deleteHouseholdBuilder.setKs(getAdministratorKs())); + } +} + +// TODO: add tests for collections? A: Yes. Examples can be found in BaseTest.getSharedCommonCollection() \ No newline at end of file diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdAddTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdAddTests.java new file mode 100644 index 000000000..fc26c4e8d --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdAddTests.java @@ -0,0 +1,57 @@ +package com.kaltura.client.test.tests.servicesTests.householdTests; + +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.BaseUtils; +import com.kaltura.client.test.utils.HouseholdUtils; +import com.kaltura.client.test.utils.OttUserUtils; +import com.kaltura.client.types.Household; +import com.kaltura.client.types.HouseholdUser; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import static com.kaltura.client.services.HouseholdService.add; +import static com.kaltura.client.services.HouseholdService.delete; +import static org.assertj.core.api.Assertions.assertThat; + +public class HouseholdAddTests extends BaseTest { + + private Household household; + private HouseholdUser masterUser; + + @BeforeClass + private void household_addTests_beforeClass() { + // set household + int numberOfUsersInHousehold = 1; + int numberOfDevicesInHousehold = 1; + household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, false); + masterUser = HouseholdUtils.getMasterUser(household); + } + + @Severity(SeverityLevel.NORMAL) + @Description("household/action/add - master user exists in other household - error 1018") + @Test + private void add_with_exists_in_other_household_masterUser() { + // create household + Household household = new Household(); + household.setName(masterUser.getUserId() + " Domain"); + household.setDescription(masterUser.getUserId() + " Description"); + + // add household + String masterUserKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId())); + Response householdResponse = executor.executeSync(add(household).setKs(masterUserKs)); + + assertThat(householdResponse.results).isNull(); + assertThat(householdResponse.error.getCode()).isEqualTo(BaseUtils.getAPIExceptionFromList(1018).getCode()); + } + + @AfterClass + private void household_getTests_afterClass() { + // delete household + executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getAdministratorKs())); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdDeleteTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdDeleteTests.java new file mode 100644 index 000000000..f18d05a70 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdDeleteTests.java @@ -0,0 +1,63 @@ +package com.kaltura.client.test.tests.servicesTests.householdTests; + +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.BaseUtils; +import com.kaltura.client.test.utils.HouseholdUtils; +import com.kaltura.client.test.utils.OttUserUtils; +import com.kaltura.client.types.Household; +import com.kaltura.client.types.HouseholdUser; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.Test; + +import static com.kaltura.client.services.HouseholdService.delete; +import static com.kaltura.client.services.HouseholdService.get; +import static org.assertj.core.api.Assertions.assertThat; + +public class HouseholdDeleteTests extends BaseTest { + + private final int numberOfUsersInHousehold = 1; + private final int numberOfDevicesInHousehold = 1; + + + @Severity(SeverityLevel.CRITICAL) + @Description("household/action/delete - master user household delete") + @Test + private void delete_with_household_masterUser() { + // set household + Household household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, false); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + + // delete household + String masterUserKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId())); + Response booleanResponse = executor.executeSync(delete().setKs(masterUserKs)); + + assertThat(booleanResponse.results.booleanValue()).isTrue(); + + // get household + Response householdResponse = executor.executeSync(get(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + + assertThat(householdResponse.results).isNull(); + assertThat(householdResponse.error.getCode()).isEqualTo(BaseUtils.getAPIExceptionFromList(1006).getCode()); + } + + @Severity(SeverityLevel.MINOR) + @Description("household/action/delete - regular user household delete - error 500004") + @Test + private void delete_with_household_regularUser() { + // set household + Household household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, false); + HouseholdUser user = HouseholdUtils.getRegularUsersList(household).get(0); + + // delete household + String userKs = OttUserUtils.getKs(Integer.parseInt(user.getUserId())); + Response booleanResponse = executor.executeSync(delete().setKs(userKs)); + + assertThat(booleanResponse.results).isNull(); + assertThat(booleanResponse.error.getCode()).isEqualTo(BaseUtils.getAPIExceptionFromList(500004).getCode()); + } + + +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdGetTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdGetTests.java new file mode 100644 index 000000000..7a6262650 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdGetTests.java @@ -0,0 +1,99 @@ +package com.kaltura.client.test.tests.servicesTests.householdTests; + +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.BaseUtils; +import com.kaltura.client.test.utils.HouseholdUtils; +import com.kaltura.client.test.utils.OttUserUtils; +import com.kaltura.client.types.Household; +import com.kaltura.client.types.HouseholdUser; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import static com.kaltura.client.services.HouseholdService.*; +import static org.assertj.core.api.Assertions.assertThat; + +public class HouseholdGetTests extends BaseTest { + + private Household household; + + @BeforeClass + private void household_getTests_beforeClass() { + // set household + int numberOfUsersInHousehold = 2; + int numberOfDevicesInHousehold = 2; + household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, false); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("household/action/get - with master user ks") + @Test + private void get_with_masterUser_ks() { + // get master user ks + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + String masterUserKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId())); + + // get household + GetHouseholdBuilder getHouseholdBuilder = get() + .setKs(masterUserKs); + Response householdResponse = executor.executeSync(getHouseholdBuilder); + + assertThat(householdResponse.error).isNull(); + assertThat(householdResponse.results.getId()).isEqualTo(household.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("household/action/get - with regular user ks") + @Test + private void get_with_regularUser_ks() { + // get regular user ks + HouseholdUser user = HouseholdUtils.getRegularUsersList(household).get(0); + String userKs = OttUserUtils.getKs(Integer.parseInt(user.getUserId())); + + // get household + GetHouseholdBuilder getHouseholdBuilder = get() + .setKs(userKs); + Response householdResponse = executor.executeSync(getHouseholdBuilder); + + assertThat(householdResponse.error).isNull(); + assertThat(householdResponse.results.getId()).isEqualTo(household.getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("household/action/get - with operator user ks") + @Test + private void get_with_operatorUser_ks() { + // get household + GetHouseholdBuilder getHouseholdBuilder = get(Math.toIntExact(household.getId())) + .setKs(getOperatorKs()); + Response householdResponse = executor.executeSync(getHouseholdBuilder); + + assertThat(householdResponse.error).isNull(); + assertThat(householdResponse.results.getId()).isEqualTo(household.getId()); + } + + @Severity(SeverityLevel.MINOR) + @Description("household/action/get - with invalid household id - error 1006") + @Test + private void get_with_invalid_householdId() { + int invalidHouseholdId = 1; + + // get household + GetHouseholdBuilder getHouseholdBuilder = get(invalidHouseholdId) + .setKs(getOperatorKs()); + Response householdResponse = executor.executeSync(getHouseholdBuilder); + + assertThat(householdResponse.results).isNull(); + assertThat(householdResponse.error.getCode()).isEqualTo(BaseUtils.getAPIExceptionFromList(1006).getCode()); + } + + @AfterClass + private void household_getTests_afterClass() { + // delete household + executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getAdministratorKs())); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdPurgeTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdPurgeTests.java new file mode 100644 index 000000000..883011a26 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdPurgeTests.java @@ -0,0 +1,296 @@ +package com.kaltura.client.test.tests.servicesTests.householdTests; + +import com.kaltura.client.services.HouseholdService; +import com.kaltura.client.services.HouseholdUserService; +import com.kaltura.client.services.OttUserService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.HouseholdUtils; +import com.kaltura.client.test.utils.dbUtils.DBUtils; +import com.kaltura.client.types.Household; +import com.kaltura.client.types.HouseholdUser; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.json.JSONObject; +import org.testng.annotations.Test; + +import static com.kaltura.client.services.HouseholdService.delete; +import static com.kaltura.client.services.HouseholdService.purge; +import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; +import static org.assertj.core.api.Assertions.assertThat; + +public class HouseholdPurgeTests extends BaseTest { + + private final int numbOfUsers = 1; + private final int numbOfDevices = 1; + + + @Severity(SeverityLevel.CRITICAL) + @Description("household/action/purge - active household") + @Test() + private void purge_active_household() { + // set household + Household household = HouseholdUtils.createHousehold(numbOfUsers, numbOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + + // assert relevant statuses in db before purge + JSONObject householdJO = DBUtils.getHouseholdById(Math.toIntExact(household.getId())); + assertThat(householdJO.getInt("purge")).as("household purge status").isEqualTo(0); + assertThat(householdJO.getInt("status")).as("household delete status").isEqualTo(1); + + JSONObject userJO = DBUtils.getUserById(Integer.parseInt(masterUser.getUserId())); + assertThat(userJO.getInt("purge")).as("user purge status").isEqualTo(0); + assertThat(userJO.getInt("status")).as("user delete status").isEqualTo(1); + + // purge + Response booleanResponse = executor.executeSync(purge(Math.toIntExact(household.getId())) + .setKs(getOperatorKs())); + assertThat(booleanResponse.results.booleanValue()).isTrue(); + + // assert relevant statuses in db after purge + householdJO = DBUtils.getHouseholdById(Math.toIntExact(household.getId())); + assertThat(householdJO.getInt("purge")).as("household purge status").isEqualTo(1); + assertThat(householdJO.getInt("status")).as("household delete status").isEqualTo(2); + + userJO = DBUtils.getUserById(Integer.parseInt(masterUser.getUserId())); + assertThat(userJO.getInt("purge")).as("user purge status").isEqualTo(1); + assertThat(userJO.getInt("status")).as("user delete status").isEqualTo(2); + + // delete household after purge + booleanResponse = executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(1006).getCode()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("household/action/purge - deleted household") + @Test() + private void purge_deleted_household() { + // set household + Household household = HouseholdUtils.createHousehold(numbOfUsers, numbOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + + // delete household before purge + executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + + // assert relevant statuses in db before purge + JSONObject householdJO = DBUtils.getHouseholdById(Math.toIntExact(household.getId())); + assertThat(householdJO.getInt("purge")).as("household purge status").isEqualTo(0); + assertThat(householdJO.getInt("status")).as("household delete status").isEqualTo(2); + + JSONObject userJO = DBUtils.getUserById(Integer.parseInt(masterUser.getUserId())); + assertThat(userJO.getInt("purge")).as("user purge status").isEqualTo(0); + assertThat(userJO.getInt("status")).as("user delete status").isEqualTo(2); + + // purge + Response booleanResponse = executor.executeSync(purge(Math.toIntExact(household.getId())) + .setKs(getOperatorKs())); + assertThat(booleanResponse.results.booleanValue()).isTrue(); + + // assert relevant statuses in db after purge + householdJO = DBUtils.getHouseholdById(Math.toIntExact(household.getId())); + assertThat(householdJO.getInt("purge")).as("household purge status").isEqualTo(1); + assertThat(householdJO.getInt("status")).as("household delete status").isEqualTo(2); + + userJO = DBUtils.getUserById(Integer.parseInt(masterUser.getUserId())); + assertThat(userJO.getInt("purge")).as("user purge status").isEqualTo(1); + assertThat(userJO.getInt("status")).as("user delete status").isEqualTo(2); + + // delete household after purge + booleanResponse = executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(1006).getCode()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("household/action/purge - after deleting user") + @Test() + private void purge_after_delete_user() { + // set household + Household household = HouseholdUtils.createHousehold(numbOfUsers, numbOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + HouseholdUser user = HouseholdUtils.getRegularUsersList(household).get(0); + + // delete user before purge + executor.executeSync(OttUserService.delete() + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(user.getUserId()))); + + // assert relevant statuses in db before purge + JSONObject householdJO = DBUtils.getHouseholdById(Math.toIntExact(household.getId())); + assertThat(householdJO.getInt("purge")).as("household purge status").isEqualTo(0); + assertThat(householdJO.getInt("status")).as("household delete status").isEqualTo(1); + + JSONObject masterUserJO = DBUtils.getUserById(Integer.parseInt(masterUser.getUserId())); + assertThat(masterUserJO.getInt("purge")).as("master user purge status").isEqualTo(0); + assertThat(masterUserJO.getInt("status")).as("master user delete status").isEqualTo(1); + + JSONObject userJO = DBUtils.getUserById(Integer.parseInt(user.getUserId())); + assertThat(userJO.getInt("purge")).as("user purge status").isEqualTo(0); + assertThat(userJO.getInt("status")).as("user delete status").isEqualTo(2); + + // purge + Response booleanResponse = executor.executeSync(purge(Math.toIntExact(household.getId())) + .setKs(getOperatorKs())); + assertThat(booleanResponse.results.booleanValue()).isTrue(); + + // assert relevant statuses in db after purge + householdJO = DBUtils.getHouseholdById(Math.toIntExact(household.getId())); + assertThat(householdJO.getInt("purge")).as("household purge status").isEqualTo(1); + assertThat(householdJO.getInt("status")).as("household delete status").isEqualTo(2); + + masterUserJO = DBUtils.getUserById(Integer.parseInt(masterUser.getUserId())); + assertThat(masterUserJO.getInt("purge")).as("master user purge status").isEqualTo(1); + assertThat(masterUserJO.getInt("status")).as("master user delete status").isEqualTo(2); + + userJO = DBUtils.getUserById(Integer.parseInt(user.getUserId())); + assertThat(userJO.getInt("purge")).as("user purge status").isEqualTo(0); + assertThat(userJO.getInt("status")).as("user delete status").isEqualTo(2); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("household/action/purge - after removing user from household") + @Test() + private void purge_after_remove_user_from_household() { + // set household + Household household = HouseholdUtils.createHousehold(numbOfUsers, numbOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + HouseholdUser user = HouseholdUtils.getRegularUsersList(household).get(0); + + // remove user from household before purge + executor.executeSync(HouseholdUserService.delete(user.getUserId()) + .setKs(getOperatorKs())); + + // assert relevant statuses in db before purge + JSONObject householdJO = DBUtils.getHouseholdById(Math.toIntExact(household.getId())); + assertThat(householdJO.getInt("purge")).as("household purge status").isEqualTo(0); + assertThat(householdJO.getInt("status")).as("household delete status").isEqualTo(1); + + JSONObject masterUserJO = DBUtils.getUserById(Integer.parseInt(masterUser.getUserId())); + assertThat(masterUserJO.getInt("purge")).as("master user purge status").isEqualTo(0); + assertThat(masterUserJO.getInt("status")).as("master user delete status").isEqualTo(1); + + JSONObject userJO = DBUtils.getUserById(Integer.parseInt(user.getUserId())); + assertThat(userJO.getInt("purge")).as("user purge status").isEqualTo(0); + assertThat(userJO.getInt("status")).as("user delete status").isEqualTo(1); + + // purge + Response booleanResponse = executor.executeSync(purge(Math.toIntExact(household.getId())) + .setKs(getOperatorKs())); + assertThat(booleanResponse.results.booleanValue()).isTrue(); + + // assert relevant statuses in db after purge + householdJO = DBUtils.getHouseholdById(Math.toIntExact(household.getId())); + assertThat(householdJO.getInt("purge")).as("household purge status").isEqualTo(1); + assertThat(householdJO.getInt("status")).as("household delete status").isEqualTo(2); + + masterUserJO = DBUtils.getUserById(Integer.parseInt(masterUser.getUserId())); + assertThat(masterUserJO.getInt("purge")).as("master user purge status").isEqualTo(1); + assertThat(masterUserJO.getInt("status")).as("master user delete status").isEqualTo(2); + + userJO = DBUtils.getUserById(Integer.parseInt(user.getUserId())); + assertThat(userJO.getInt("purge")).as("user purge status").isEqualTo(1); + assertThat(userJO.getInt("status")).as("user delete status").isEqualTo(2); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("household/action/purge - on suspended household") + @Test() + private void purge_on_suspended_household() { + // set household + Household household = HouseholdUtils.createHousehold(numbOfUsers, numbOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + + // suspend household before purge + executor.executeSync(HouseholdService.suspend() + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(masterUser.getUserId()))); + + // assert relevant statuses in db before purge + JSONObject householdJO = DBUtils.getHouseholdById(Math.toIntExact(household.getId())); + assertThat(householdJO.getInt("purge")).as("household purge status").isEqualTo(0); + assertThat(householdJO.getInt("status")).as("household delete status").isEqualTo(1); + assertThat(householdJO.getInt("is_suspended")).as("household suspend status").isEqualTo(1); + + JSONObject masterUserJO = DBUtils.getUserById(Integer.parseInt(masterUser.getUserId())); + assertThat(masterUserJO.getInt("purge")).as("master user purge status").isEqualTo(0); + assertThat(masterUserJO.getInt("status")).as("master user delete status").isEqualTo(1); + + // purge + Response booleanResponse = executor.executeSync(purge(Math.toIntExact(household.getId())) + .setKs(getOperatorKs())); + assertThat(booleanResponse.results.booleanValue()).isTrue(); + + // assert relevant statuses in db after purge + householdJO = DBUtils.getHouseholdById(Math.toIntExact(household.getId())); + assertThat(householdJO.getInt("purge")).as("household purge status").isEqualTo(1); + assertThat(householdJO.getInt("status")).as("household delete status").isEqualTo(2); + assertThat(householdJO.getInt("is_suspended")).as("household suspend status").isEqualTo(1); + + masterUserJO = DBUtils.getUserById(Integer.parseInt(masterUser.getUserId())); + assertThat(masterUserJO.getInt("purge")).as("master user purge status").isEqualTo(1); + assertThat(masterUserJO.getInt("status")).as("master user delete status").isEqualTo(2); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("household/action/purge - after deleting user and household") + @Test() + private void purge_after_delete_user_and_household() { + // set household + Household household = HouseholdUtils.createHousehold(numbOfUsers, numbOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + HouseholdUser user = HouseholdUtils.getRegularUsersList(household).get(0); + + // delete user before purge + executor.executeSync(OttUserService.delete() + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(user.getUserId()))); + + // delete household before purge + executor.executeSync(HouseholdService.delete(Math.toIntExact(household.getId())) + .setKs(getOperatorKs())); + + // assert relevant statuses in db before purge + JSONObject householdJO = DBUtils.getHouseholdById(Math.toIntExact(household.getId())); + assertThat(householdJO.getInt("purge")).as("household purge status").isEqualTo(0); + assertThat(householdJO.getInt("status")).as("household delete status").isEqualTo(2); + + JSONObject masterUserJO = DBUtils.getUserById(Integer.parseInt(masterUser.getUserId())); + assertThat(masterUserJO.getInt("purge")).as("master user purge status").isEqualTo(0); + assertThat(masterUserJO.getInt("status")).as("master user delete status").isEqualTo(2); + + JSONObject userJO = DBUtils.getUserById(Integer.parseInt(user.getUserId())); + assertThat(userJO.getInt("purge")).as("user purge status").isEqualTo(0); + assertThat(userJO.getInt("status")).as("user delete status").isEqualTo(2); + + // purge + Response booleanResponse = executor.executeSync(purge(Math.toIntExact(household.getId())) + .setKs(getOperatorKs())); + assertThat(booleanResponse.results.booleanValue()).isTrue(); + + // assert relevant statuses in db after purge + householdJO = DBUtils.getHouseholdById(Math.toIntExact(household.getId())); + assertThat(householdJO.getInt("purge")).as("household purge status").isEqualTo(1); + assertThat(householdJO.getInt("status")).as("household delete status").isEqualTo(2); + + masterUserJO = DBUtils.getUserById(Integer.parseInt(masterUser.getUserId())); + assertThat(masterUserJO.getInt("purge")).as("master user purge status").isEqualTo(1); + assertThat(masterUserJO.getInt("status")).as("master user delete status").isEqualTo(2); + + userJO = DBUtils.getUserById(Integer.parseInt(user.getUserId())); + assertThat(userJO.getInt("purge")).as("user purge status").isEqualTo(1); + assertThat(userJO.getInt("status")).as("user delete status").isEqualTo(2); + } + + @Severity(SeverityLevel.MINOR) + @Description("household/action/purge - with not exists household") + @Test() + private void purge_with_not_exists_household() { + // purge + int invalidHouseholdId = -1; + Response booleanResponse = executor.executeSync(purge(invalidHouseholdId) + .setKs(getOperatorKs())); + + assertThat(booleanResponse.results).isNull(); + assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(1006).getCode()); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdResetFrequencyTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdResetFrequencyTests.java new file mode 100644 index 000000000..ab39878ab --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdResetFrequencyTests.java @@ -0,0 +1,105 @@ +package com.kaltura.client.test.tests.servicesTests.householdTests; + +import com.kaltura.client.enums.HouseholdFrequencyType; +import com.kaltura.client.services.HouseholdService; +import com.kaltura.client.services.HouseholdUserService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.BaseUtils; +import com.kaltura.client.test.utils.HouseholdUtils; +import com.kaltura.client.test.utils.OttUserUtils; +import com.kaltura.client.types.Household; +import com.kaltura.client.types.HouseholdDevice; +import com.kaltura.client.types.HouseholdUser; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.List; + +import static com.kaltura.client.services.HouseholdDeviceService.delete; +import static com.kaltura.client.services.HouseholdService.*; +import static org.assertj.core.api.Assertions.assertThat; + +public class HouseholdResetFrequencyTests extends BaseTest { + + private Household household; + private HouseholdUser masterUser; + private String masterUserKs; + + @BeforeClass + private void household_resetFrequencyTests_beforeClass() { + // set household + int numberOfUsersInHousehold = 3; + int numberOfDevicesInHousehold = 3; + household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, true); + masterUser = HouseholdUtils.getMasterUser(household); + + // set masterUserKs + String udid = HouseholdUtils.getDevicesList(household).get(0).getUdid(); + masterUserKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId()), udid); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("household/action/resetFrequency - household devices") + @Test + private void resetFrequency_household_devices() { + // delete devices until error 1014 return + List devices = HouseholdUtils.getDevicesList(household); + + executor.executeSync(delete(devices.get(1).getUdid()).setKs(masterUserKs)); + Response booleanResponse = executor.executeSync(delete(devices.get(2).getUdid()).setKs(masterUserKs)); + assertThat(booleanResponse.error.getCode()).isEqualTo(BaseUtils.getAPIExceptionFromList(1014).getCode()); + + // reset frequency for household devices + Response householdResponse = executor.executeSync(resetFrequency(HouseholdFrequencyType.DEVICES) + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(masterUser.getUserId()))); + assertThat(householdResponse.error).isNull(); + assertThat(householdResponse.results.getId()).isEqualTo(household.getId()); + + // delete additional device to verify frequency was reset + booleanResponse = executor.executeSync(delete(devices.get(2).getUdid()).setKs(masterUserKs)); + assertThat(booleanResponse.results.booleanValue()).isTrue(); + + // assert devices list size = 1 + devices = HouseholdUtils.getDevicesList(household); + assertThat(devices.size()).isEqualTo(1); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("household/action/resetFrequency - household users") + @Test + private void resetFrequency_household_users() { + // delete users until error 1014 return + List users = HouseholdUtils.getRegularUsersList(household); + + executor.executeSync(HouseholdUserService.delete(users.get(0).getUserId()).setKs(masterUserKs)); + Response booleanResponse = executor.executeSync(HouseholdUserService.delete(users.get(1).getUserId()).setKs(masterUserKs)); + assertThat(booleanResponse.error.getCode()).isEqualTo(BaseUtils.getAPIExceptionFromList(1014).getCode()); + + // reset frequency for household users + Response householdResponse = executor.executeSync(resetFrequency(HouseholdFrequencyType.USERS) + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(masterUser.getUserId()))); + assertThat(householdResponse.error).isNull(); + assertThat(householdResponse.results.getId()).isEqualTo(household.getId()); + + // delete additional user to verify frequency was reset + booleanResponse = executor.executeSync(HouseholdUserService.delete(users.get(1).getUserId()).setKs(masterUserKs)); + assertThat(booleanResponse.results.booleanValue()).isTrue(); + + // assert regular users list size = 1 + users = HouseholdUtils.getRegularUsersList(household); + assertThat(users.size()).isEqualTo(1); + } + + @AfterClass + private void household_resetFrequencyTests_afterClass() { + // delete household + executor.executeSync(HouseholdService.delete(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdResumeTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdResumeTests.java new file mode 100644 index 000000000..8687620f3 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdResumeTests.java @@ -0,0 +1,120 @@ +package com.kaltura.client.test.tests.servicesTests.householdTests; + +import com.kaltura.client.enums.HouseholdState; +import com.kaltura.client.services.UserRoleService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.HouseholdUtils; +import com.kaltura.client.test.utils.OttUserUtils; +import com.kaltura.client.test.utils.PurchaseUtils; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.Optional; + +import static com.kaltura.client.services.HouseholdService.*; +import static org.assertj.core.api.Assertions.assertThat; + +public class HouseholdResumeTests extends BaseTest { + + private Household household; + private HouseholdUser masterUser; + private String masterUserKs; + private Subscription subscription; + + @BeforeClass + private void household_resumeTests_beforeClass() { + // set household + int numberOfUsersInHousehold = 2; + int numberOfDevicesInHousehold = 1; + household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, true); + masterUser = HouseholdUtils.getMasterUser(household); + + // set masterUserKs + String udid = HouseholdUtils.getDevicesList(household).get(0).getUdid(); + masterUserKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId()), udid); + + // set subscription + subscription = BaseTest.getSharedCommonSubscription(); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("household/action/resume - suspended household") + @Test + private void resume_suspended_household() { + // suspend household + executor.executeSync(suspend() + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(masterUser.getUserId()))); + + // get household - verify status is suspended + Response householdResponse = executor.executeSync(get(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + assertThat(householdResponse.results.getState()).isEqualTo(HouseholdState.SUSPENDED); + + // resume household + Response booleanResponse = executor.executeSync(resume() + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(masterUser.getUserId()))); + assertThat(booleanResponse.results.booleanValue()).isTrue(); + + // get household - verify status is ok + householdResponse = executor.executeSync(get(Math.toIntExact(household.getId())) + .setKs(getOperatorKs())); + assertThat(householdResponse.results.getState()).isEqualTo(HouseholdState.OK); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("household/action/resume - suspended with purchase_subscription role household") + @Test + private void resume_suspended_with_purchase_subscription_role_household() { + // create role + UserRole role = new UserRole(); + role.setExcludedPermissionNames("PURCHASE_SUBSCRIPTION"); + role.setName("PURCHASE_SUBSCRIPTION"); + + // add role + Response userRoleResponse = executor.executeSync(UserRoleService.add(role).setKs(getOperatorKs())); + role = userRoleResponse.results; + + // suspend household + executor.executeSync(suspend(Math.toIntExact(role.getId())) + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(masterUser.getUserId()))); + + // get household - verify status is suspended + Response householdResponse = executor.executeSync(get(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + assertThat(householdResponse.results.getState()).isEqualTo(HouseholdState.SUSPENDED); + + // resume household + Response booleanResponse = executor.executeSync(resume() + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(masterUser.getUserId()))); + assertThat(booleanResponse.results.booleanValue()).isTrue(); + + // get household - verify status is ok + householdResponse = executor.executeSync(get(Math.toIntExact(household.getId())) + .setKs(getOperatorKs())); + assertThat(householdResponse.results.getState()).isEqualTo(HouseholdState.OK); + + // purchase subscription + Response transactionResponse = PurchaseUtils.purchaseSubscription(masterUserKs, Integer.parseInt(subscription.getId()), Optional.empty()); + assertThat(transactionResponse.error).isNull(); + assertThat(transactionResponse.results.getState()).isEqualTo("OK"); + + // cleanup - delete role + executor.executeSync(UserRoleService.delete(role.getId()).setKs(getOperatorKs())); + } + + @AfterClass + private void household_resumeTests_afterClass() { + // cleanup - delete household + executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + } + + +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdSuspendTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdSuspendTests.java new file mode 100644 index 000000000..f6f239ac6 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdSuspendTests.java @@ -0,0 +1,567 @@ +package com.kaltura.client.test.tests.servicesTests.householdTests; + +import com.kaltura.client.enums.*; +import com.kaltura.client.services.*; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.tests.enums.PremiumService; +import com.kaltura.client.test.utils.*; +import com.kaltura.client.test.utils.dbUtils.DBUtils; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Issue; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.List; +import java.util.Optional; +import java.util.concurrent.TimeUnit; + +import static com.kaltura.client.services.AssetService.GetPlaybackContextAssetBuilder; +import static com.kaltura.client.services.AssetService.getPlaybackContext; +import static com.kaltura.client.services.EntitlementService.CancelEntitlementBuilder; +import static com.kaltura.client.services.EntitlementService.cancel; +import static com.kaltura.client.services.HouseholdService.*; +import static com.kaltura.client.services.OttUserService.login; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public class HouseholdSuspendTests extends BaseTest { + + private final int numOfUsers = 2; + private final int numOfDevices = 1; + + private Subscription subscription; + private Asset asset; + private Household householdSlowTest; + private Response> productPriceListResponseSlowTest; + private String masterUserKsSlowTest; + private UserRole roleSlowTest; + private Subscription fiveMinRenewSubscriptionSlowTest; + + private enum Permissions { + PLAYBACK_SUBSCRIPTION, + PLAYBACK_PPV, + PURCHASE_SUBSCRIPTION, + PURCHASE_PPV, + RENEW_SUBSCRIPTION, + PURCHASE_SERVICE, + LOGIN, + CANCEL_SUBSCRIPTION, + DELETE_ALL_APP_TOKENS + } + + @BeforeClass(alwaysRun = true) + private void household_suspendTests_beforeClass() { + // set subscription + subscription = BaseTest.getSharedCommonSubscription(); + + // set subscription with 5 min renew + fiveMinRenewSubscriptionSlowTest = get5MinRenewableSubscription(); + + // set asset + List assets = SubscriptionUtils.getAssetsListBySubscription(Integer.parseInt(subscription.getId()), Optional.empty(), false); + asset = AssetUtils.getAssetByPurchaeStatus(assets, PurchaseStatus.FOR_PURCHASE); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("household/action/suspend") + @Test + private void suspend() { + // set household + Household household = HouseholdUtils.createHousehold(numOfUsers, numOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + + // suspend household + SuspendHouseholdBuilder suspendHouseholdBuilder = HouseholdService.suspend() + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(masterUser.getUserId())); + Response booleanResponse = executor.executeSync(suspendHouseholdBuilder); + + assertThat(booleanResponse.error).isNull(); + assertThat(booleanResponse.results.booleanValue()).isTrue(); + + // get household + Response householdResponse = executor.executeSync(get(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + assertThat(householdResponse.results.getState().getValue()).isEqualTo(HouseholdState.SUSPENDED.getValue()); + + // cleanup - delete household + executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + } + + @Severity(SeverityLevel.MINOR) + @Description("household/action/suspend - with master user ks - error 500004") + @Test + private void suspend_with_masterUser_ks() { + // set household + Household household = HouseholdUtils.createHousehold(numOfUsers, numOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + + // set masterUserKs + String udid = HouseholdUtils.getDevicesList(household).get(0).getUdid(); + String masterUserKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId()), udid); + + // suspend household + Response booleanResponse = executor.executeSync(HouseholdService.suspend().setKs(masterUserKs)); + + assertThat(booleanResponse.results).isNull(); + assertThat(booleanResponse.error.getCode()).isEqualTo(BaseUtils.getAPIExceptionFromList(500004).getCode()); + + // cleanup - delete household + executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + } + + @Severity(SeverityLevel.NORMAL) + @Description("household/action/suspend - with login role - error 7013") + @Test + private void suspend_with_login_role() { + // set household + Household household = HouseholdUtils.createHousehold(numOfUsers, numOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + + // create role + UserRole role = new UserRole(); +// role.setPermissionNames(""); + role.setExcludedPermissionNames(Permissions.LOGIN.name()); + role.setName(Permissions.LOGIN.name()); + + // add role + Response userRoleResponse = executor.executeSync(UserRoleService.add(role).setKs(getOperatorKs())); + role = userRoleResponse.results; + + // suspend with login role + SuspendHouseholdBuilder suspendHouseholdBuilder = HouseholdService.suspend(Math.toIntExact(role.getId())) + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(masterUser.getUserId())); + Response booleanResponse = executor.executeSync(suspendHouseholdBuilder); + assertThat(booleanResponse.results).isTrue(); + + // login + String username = OttUserUtils.getOttUserById(Integer.parseInt(masterUser.getUserId())).getUsername(); + Response loginResponse = executor.executeSync(login(partnerId, username, defaultUserPassword)); + + assertThat(loginResponse.results).isNull(); + assertThat(loginResponse.error.getCode()).isEqualTo(BaseUtils.getAPIExceptionFromList(7013).getCode()); + + // cleanup - delete role + executor.executeSync(UserRoleService.delete(role.getId()).setKs(getOperatorKs())); + + // cleanup - delete household + executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + } + + @Severity(SeverityLevel.NORMAL) + @Description("household/action/suspend - with purchase_subscription role - error 7013") + @Test + private void suspend_with_purchase_subscription_role() { + // set household + Household household = HouseholdUtils.createHousehold(numOfUsers, numOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + + // set masterUserKs + String udid = HouseholdUtils.getDevicesList(household).get(0).getUdid(); + String masterUserKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId()), udid); + + // create role + UserRole role = new UserRole(); +// role.setPermissionNames(""); + role.setExcludedPermissionNames(Permissions.PURCHASE_SUBSCRIPTION.name()); + role.setName(Permissions.PURCHASE_SUBSCRIPTION.name()); + + // add role + Response userRoleResponse = executor.executeSync(UserRoleService.add(role).setKs(getOperatorKs())); + role = userRoleResponse.results; + + // suspend with purchase_subscription role + SuspendHouseholdBuilder suspendHouseholdBuilder = HouseholdService.suspend(Math.toIntExact(role.getId())) + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(masterUser.getUserId())); + Response booleanResponse = executor.executeSync(suspendHouseholdBuilder); + assertThat(booleanResponse.results).isTrue(); + + // purchase subscription + Response transactionResponse = PurchaseUtils.purchaseSubscription(masterUserKs, Integer.parseInt(subscription.getId()), Optional.empty()); + + assertThat(transactionResponse.results).isNull(); + assertThat(transactionResponse.error.getCode()).isEqualTo(BaseUtils.getAPIExceptionFromList(7013).getCode()); + + // purchase ppv in order to verify suspend is specific to role + Integer mediaFileId = asset.getMediaFiles().get(0).getId(); + transactionResponse = PurchaseUtils.purchasePpv(masterUserKs, Optional.of(Math.toIntExact(asset.getId())), + Optional.of(mediaFileId), Optional.empty()); + + assertThat(transactionResponse.error).isNull(); + assertThat(transactionResponse.results.getState()).isEqualTo("OK"); + + // add device to household to verify suspend is specific to role + HouseholdDevice householdDevice = HouseholdUtils.generateHouseholdDevice(); + Response householdDeviceResponse = executor.executeSync(HouseholdDeviceService.add(householdDevice) + .setKs(masterUserKs)); + assertThat(householdDeviceResponse.error).isNull(); + + // cleanup - delete role + executor.executeSync(UserRoleService.delete(role.getId()).setKs(getOperatorKs())); + + // cleanup - delete household + executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + } + + @Severity(SeverityLevel.NORMAL) + @Description("household/action/suspend - with cancel_subscription role - error 1009") + @Test + private void suspend_with_cancel_subscription_role() { + // set household + Household household = HouseholdUtils.createHousehold(numOfUsers, numOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + + // set masterUserKs + String udid = HouseholdUtils.getDevicesList(household).get(0).getUdid(); + String masterUserKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId()), udid); + + // create role + UserRole role = new UserRole(); +// role.setPermissionNames(""); + role.setExcludedPermissionNames(Permissions.CANCEL_SUBSCRIPTION.name()); + role.setName(Permissions.CANCEL_SUBSCRIPTION.name()); + + // add role + Response userRoleResponse = executor.executeSync(UserRoleService.add(role).setKs(getOperatorKs())); + role = userRoleResponse.results; + + // suspend with cancel_subscription role + SuspendHouseholdBuilder suspendHouseholdBuilder = HouseholdService.suspend(Math.toIntExact(role.getId())) + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(masterUser.getUserId())); + Response booleanResponse = executor.executeSync(suspendHouseholdBuilder); + assertThat(booleanResponse.results).isTrue(); + + // purchase subscription + PurchaseUtils.purchaseSubscription(masterUserKs, Integer.parseInt(subscription.getId()), Optional.empty()); + + // cancel subscription + CancelEntitlementBuilder cancelEntitlementBuilder = cancel(Integer.parseInt(subscription.getId()), TransactionType.SUBSCRIPTION) + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(masterUser.getUserId())); + booleanResponse = executor.executeSync(cancelEntitlementBuilder); + + assertThat(booleanResponse.results).isNull(); + assertThat(booleanResponse.error.getCode()).isEqualTo(BaseUtils.getAPIExceptionFromList(1009).getCode()); + + // cleanup - delete role + executor.executeSync(UserRoleService.delete(role.getId()).setKs(getOperatorKs())); + + // cleanup - delete household + executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + } + + @Severity(SeverityLevel.NORMAL) + @Description("household/action/suspend - with playback_subscription role") + @Test + private void suspend_with_playback_subscription_role() { + // set household + Household household = HouseholdUtils.createHousehold(numOfUsers, numOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + + // set masterUserKs + String udid = HouseholdUtils.getDevicesList(household).get(0).getUdid(); + String masterUserKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId()), udid); + + // create role + UserRole role = new UserRole(); +// role.setPermissionNames(""); + role.setExcludedPermissionNames(Permissions.PLAYBACK_SUBSCRIPTION.name()); + role.setName(Permissions.PLAYBACK_SUBSCRIPTION.name()); + + // add role + Response userRoleResponse = executor.executeSync(UserRoleService.add(role).setKs(getOperatorKs())); + role = userRoleResponse.results; + + // suspend with playback_subscription role + SuspendHouseholdBuilder suspendHouseholdBuilder = HouseholdService.suspend(Math.toIntExact(role.getId())) + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(masterUser.getUserId())); + Response booleanResponse = executor.executeSync(suspendHouseholdBuilder); + assertThat(booleanResponse.results).isTrue(); + + // purchase subscription + PurchaseUtils.purchaseSubscription(masterUserKs, Integer.parseInt(subscription.getId()), Optional.empty()); + + // get platbackContext + PlaybackContextOptions playbackContextOptions = new PlaybackContextOptions(); + playbackContextOptions.setContext(PlaybackContextType.PLAYBACK); + playbackContextOptions.setStreamerType("applehttp"); + playbackContextOptions.setMediaProtocol("http"); + + GetPlaybackContextAssetBuilder getPlaybackContextAssetBuilder = getPlaybackContext(String.valueOf(asset.getId()), AssetType.MEDIA, playbackContextOptions) + .setKs(masterUserKs); + Response playbackContextResponse = executor.executeSync(getPlaybackContextAssetBuilder); + + assertThat(playbackContextResponse.results.getMessages().get(0).getMessage()).isEqualTo("Not entitled"); + assertThat(playbackContextResponse.results.getMessages().get(0).getCode()).isEqualTo("NotEntitled"); + assertThat(playbackContextResponse.results.getActions().get(0).getType()).isEqualTo(RuleActionType.BLOCK); + + // cleanup - delete role + executor.executeSync(UserRoleService.delete(role.getId()).setKs(getOperatorKs())); + + // cleanup - delete household + executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + } + + @Severity(SeverityLevel.NORMAL) + @Description("household/action/suspend - with purchase_ppv role") + @Test + private void suspend_with_purchase_ppv_role() { + // set household + Household household = HouseholdUtils.createHousehold(numOfUsers, numOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + + // set masterUserKs + String udid = HouseholdUtils.getDevicesList(household).get(0).getUdid(); + String masterUserKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId()), udid); + + // create role + UserRole role = new UserRole(); +// role.setPermissionNames(""); + role.setExcludedPermissionNames(Permissions.PURCHASE_PPV.name()); + role.setName(Permissions.PURCHASE_PPV.name()); + + // add role + Response userRoleResponse = executor.executeSync(UserRoleService.add(role).setKs(getOperatorKs())); + role = userRoleResponse.results; + + // suspend with purchase_ppv role + SuspendHouseholdBuilder suspendHouseholdBuilder = HouseholdService.suspend(Math.toIntExact(role.getId())) + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(masterUser.getUserId())); + Response booleanResponse = executor.executeSync(suspendHouseholdBuilder); + assertThat(booleanResponse.results).isTrue(); + + // purchase ppv + Integer mediaFileId = asset.getMediaFiles().get(0).getId(); + Response transactionResponse = PurchaseUtils.purchasePpv(masterUserKs, Optional.of(Math.toIntExact(asset.getId())), + Optional.of(mediaFileId), Optional.empty()); + + assertThat(transactionResponse.results).isNull(); + assertThat(transactionResponse.error.getCode()).isEqualTo(BaseUtils.getAPIExceptionFromList(7013).getCode()); + + // purchase subscription in order to verify suspend is specific to role + transactionResponse = PurchaseUtils.purchaseSubscription(masterUserKs, Integer.parseInt(subscription.getId()), Optional.empty()); + + assertThat(transactionResponse.error).isNull(); + assertThat(transactionResponse.results.getState()).isEqualTo("OK"); + + // cleanup - delete role + executor.executeSync(UserRoleService.delete(role.getId()).setKs(getOperatorKs())); + + // cleanup - delete household + executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + } + + @Severity(SeverityLevel.NORMAL) + @Issue("BEO-5166") + @Description("household/action/suspend - with playback_ppv role") + @Test + private void suspend_with_playback_ppv_role() { + // set household + Household household = HouseholdUtils.createHousehold(numOfUsers, numOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + + // set masterUserKs + String udid = HouseholdUtils.getDevicesList(household).get(0).getUdid(); + String masterUserKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId()), udid); + + // create role + UserRole role = new UserRole(); +// role.setPermissionNames(""); + role.setExcludedPermissionNames(Permissions.PLAYBACK_PPV.name()); + role.setName(Permissions.PLAYBACK_PPV.name()); + + // add role + Response userRoleResponse = executor.executeSync(UserRoleService.add(role).setKs(getOperatorKs())); + role = userRoleResponse.results; + + // purchase ppv + Integer mediaFileId = asset.getMediaFiles().get(0).getId(); + PurchaseUtils.purchasePpv(masterUserKs, Optional.of(Math.toIntExact(asset.getId())), Optional.of(mediaFileId), Optional.empty()); + + // suspend with playback_ppv role + SuspendHouseholdBuilder suspendHouseholdBuilder = HouseholdService.suspend(Math.toIntExact(role.getId())) + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(masterUser.getUserId())); + Response booleanResponse = executor.executeSync(suspendHouseholdBuilder); + assertThat(booleanResponse.results).isTrue(); + + // get platbackContext + PlaybackContextOptions playbackContextOptions = new PlaybackContextOptions(); + playbackContextOptions.setContext(PlaybackContextType.PLAYBACK); + playbackContextOptions.setStreamerType("applehttp"); + playbackContextOptions.setMediaProtocol("http"); + + GetPlaybackContextAssetBuilder getPlaybackContextAssetBuilder = getPlaybackContext(String.valueOf(asset.getId()), AssetType.MEDIA, playbackContextOptions) + .setKs(masterUserKs); + Response playbackContextResponse = executor.executeSync(getPlaybackContextAssetBuilder); + + assertThat(playbackContextResponse.results.getMessages().get(0).getMessage()).isEqualTo("Not entitled"); + assertThat(playbackContextResponse.results.getMessages().get(0).getCode()).isEqualTo("NotEntitled"); + assertThat(playbackContextResponse.results.getActions().get(0).getType()).isEqualTo(RuleActionType.BLOCK); + + // purchase subscription in order to verify suspend is specific to role + Response transactionResponse = PurchaseUtils.purchaseSubscription(masterUserKs, Integer.parseInt(subscription.getId()), Optional.empty()); + assertThat(transactionResponse.error).isNull(); + assertThat(transactionResponse.results.getState()).isEqualTo("OK"); + + // cleanup - delete role + executor.executeSync(UserRoleService.delete(role.getId()).setKs(getOperatorKs())); + + // cleanup - delete household + executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + } + + @Severity(SeverityLevel.NORMAL) + @Description("household/action/suspend - with renew_subscription role") + @Test(groups = {"slowBefore"}) + private void suspend_with_renew_subscription_role_before_wait() { + // set household + householdSlowTest = HouseholdUtils.createHousehold(numOfUsers, numOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(householdSlowTest); + + // set masterUserKs + String udid = HouseholdUtils.getDevicesList(householdSlowTest).get(0).getUdid(); + masterUserKsSlowTest = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId()), udid); + + // create role + roleSlowTest = new UserRole(); + roleSlowTest.setPermissionNames(""); + roleSlowTest.setExcludedPermissionNames(Permissions.RENEW_SUBSCRIPTION.name()); + roleSlowTest.setName(Permissions.RENEW_SUBSCRIPTION.name()); + + // add role + Response userRoleResponse = executor.executeSync(UserRoleService.add(roleSlowTest).setKs(getOperatorKs())); + roleSlowTest = userRoleResponse.results; + + // purchase subscription + int fiveMinRenewSubscriptionId = Integer.parseInt(fiveMinRenewSubscriptionSlowTest.getId().trim()); + PurchaseUtils.purchaseSubscription(masterUserKsSlowTest, fiveMinRenewSubscriptionId, Optional.empty()); + + //get productprice list - before renew + ProductPriceFilter subscriptionFilter = new ProductPriceFilter(); + subscriptionFilter.setSubscriptionIdIn(fiveMinRenewSubscriptionSlowTest.getId()); + productPriceListResponseSlowTest = executor.executeSync(ProductPriceService.list(subscriptionFilter) + .setKs(masterUserKsSlowTest)); + + assertThat(productPriceListResponseSlowTest.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceListResponseSlowTest.results.getObjects().get(0).getProductId()).isEqualTo(fiveMinRenewSubscriptionSlowTest.getId().trim()); + assertThat(productPriceListResponseSlowTest.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.SUBSCRIPTION_PURCHASED); + + // suspend with renew_subscription role + SuspendHouseholdBuilder suspendHouseholdBuilder = HouseholdService.suspend(Math.toIntExact(roleSlowTest.getId())) + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(masterUser.getUserId())); + Response booleanResponse = executor.executeSync(suspendHouseholdBuilder); + assertThat(booleanResponse.results).isTrue(); + } + + @Test(groups = {"slowAfter"}, dependsOnGroups = {"slowBefore"}, alwaysRun = true) + private void suspend_with_renew_subscription_role_after_wait() { + // get productprice list for asset in subscription - after renew + Asset asset = SubscriptionUtils.getAssetsListBySubscription(Integer.parseInt(fiveMinRenewSubscriptionSlowTest.getId()), Optional.empty(), false).get(0); + ProductPriceFilter assetFilter = new ProductPriceFilter(); + assetFilter.setFileIdIn(String.valueOf(asset.getMediaFiles().get(0).getId())); + + // prepare variables for await() functionality + int delayBetweenRetriesInSeconds = 20; + int maxTimeExpectingValidResponseInSeconds = 360; + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() -> (executor.executeSync(ProductPriceService.list(assetFilter) + .setKs(masterUserKsSlowTest)).results.getObjects().get(0).getPurchaseStatus()) + .equals(PurchaseStatus.FOR_PURCHASE)); + + productPriceListResponseSlowTest = executor.executeSync(ProductPriceService.list(assetFilter) + .setKs(masterUserKsSlowTest)); + assertThat(productPriceListResponseSlowTest.results.getTotalCount()).isEqualTo(1); +// assertThat(productPriceListResponseSlowTest.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + + // transactionHistory list - verify media file related to subscription billing status = purchase + Response> billingTransactionListResponse = executor.executeSync(TransactionHistoryService.list() + .setKs(masterUserKsSlowTest)); + assertThat(billingTransactionListResponse.results.getTotalCount()).isEqualTo(1); + assertThat(billingTransactionListResponse.results.getObjects().get(0).getBillingAction()).isEqualTo(BillingAction.PURCHASE); + + // entitlement list - verify subscription isSuspend = true + EntitlementFilter entitlementFilter = new EntitlementFilter(); + entitlementFilter.setProductTypeEqual(TransactionType.SUBSCRIPTION); + entitlementFilter.setEntityReferenceEqual(EntityReferenceBy.HOUSEHOLD); + entitlementFilter.setIsExpiredEqual(false); + + Response> entitlementListResponse = executor.executeSync(EntitlementService.list(entitlementFilter) + .setKs(masterUserKsSlowTest)); + assertThat(entitlementListResponse.results.getTotalCount()).isEqualTo(1); + SubscriptionEntitlement subscriptionEntitlement = (SubscriptionEntitlement) entitlementListResponse.results.getObjects().get(0); + assertThat(subscriptionEntitlement.getProductId()).isEqualTo(fiveMinRenewSubscriptionSlowTest.getId().trim()); + assertThat(subscriptionEntitlement.getIsSuspended()).isTrue(); + + // cleanup - delete role + executor.executeSync(UserRoleService.delete(roleSlowTest.getId()).setKs(getOperatorKs())); + + // cleanup - delete household + executor.executeSync(delete(Math.toIntExact(householdSlowTest.getId())).setKs(getOperatorKs())); + System.out.println("after finished"); + } + + @Severity(SeverityLevel.NORMAL) + @Description("household/action/suspend - with purchase_service role") + @Test(enabled = true) + private void suspend_with_purchase_service_role() { + // set household + Household household = HouseholdUtils.createHousehold(numOfUsers, numOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + + // set masterUserKs + String udid = HouseholdUtils.getDevicesList(household).get(0).getUdid(); + String masterUserKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId()), udid); + + // create role + UserRole role = new UserRole(); +// role.setPermissionNames(""); + role.setExcludedPermissionNames(Permissions.PURCHASE_SERVICE.name()); + role.setName(Permissions.PURCHASE_SERVICE.name()); + + // add role + Response userRoleResponse = executor.executeSync(UserRoleService.add(role).setKs(getOperatorKs())); + role = userRoleResponse.results; + + // suspend with purchase_service role + SuspendHouseholdBuilder suspendHouseholdBuilder = HouseholdService.suspend(Math.toIntExact(role.getId())) + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(masterUser.getUserId())); + Response booleanResponse = executor.executeSync(suspendHouseholdBuilder); + + assertThat(booleanResponse.results).isTrue(); + + // purchase subscription with premium service + Subscription subscription = DBUtils.getSubscriptionWithPremiumService(PremiumService.NPVR); + Response transactionResponse = PurchaseUtils + .purchaseSubscription(masterUserKs, Integer.parseInt(subscription.getId()), Optional.empty()); + + assertThat(transactionResponse.results).isNull(); + assertThat(transactionResponse.error.getCode()).isEqualTo(BaseUtils.getAPIExceptionFromList(7013).getCode()); + + // purchase ppv in order to verify suspend is specific to role + Integer mediaFileId = asset.getMediaFiles().get(0).getId(); + transactionResponse = PurchaseUtils.purchasePpv(masterUserKs, Optional.of(Math.toIntExact(asset.getId())), + Optional.of(mediaFileId), Optional.empty()); + + assertThat(transactionResponse.error).isNull(); + assertThat(transactionResponse.results.getState()).isEqualTo("OK"); + + // cleanup - delete role + executor.executeSync(UserRoleService.delete(role.getId()).setKs(getOperatorKs())); + + // cleanup - delete household + executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdUpdateTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdUpdateTests.java new file mode 100644 index 000000000..61b47cba6 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/householdTests/HouseholdUpdateTests.java @@ -0,0 +1,128 @@ +package com.kaltura.client.test.tests.servicesTests.householdTests; + +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.HouseholdUtils; +import com.kaltura.client.test.utils.OttUserUtils; +import com.kaltura.client.types.Household; +import com.kaltura.client.types.HouseholdUser; +import io.qameta.allure.Description; +import io.qameta.allure.Issue; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import static com.kaltura.client.services.HouseholdService.delete; +import static com.kaltura.client.services.HouseholdService.update; +import static org.assertj.core.api.Assertions.assertThat; + +public class HouseholdUpdateTests extends BaseTest { + + private Household household; + private HouseholdUser masterUser; + private String masterUserKs; + + @BeforeClass + private void household_updateTests_beforeClass() { + // set household + int numberOfUsersInHousehold = 2; + int numberOfDevicesInHousehold = 1; + household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, true); + masterUser = HouseholdUtils.getMasterUser(household); + + // set masterUserKs + String udid = HouseholdUtils.getDevicesList(household).get(0).getUdid(); + masterUserKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId()), udid); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("household/action/update - with masterUserKs") + @Test + private void update_with_masterUserKs() { + // update household + String householdUpdatedDetails = "updated details with masterUserKs"; + Household updatedHousehold = new Household(); + updatedHousehold.setName(householdUpdatedDetails); + updatedHousehold.setDescription(householdUpdatedDetails); + + updatedHousehold = executor.executeSync(update(updatedHousehold) + .setKs(masterUserKs)) + .results; + + assertThat(updatedHousehold.getName()).isEqualTo(householdUpdatedDetails); + assertThat(updatedHousehold.getDescription()).isEqualTo(householdUpdatedDetails); + assertThat(updatedHousehold).isEqualToIgnoringGivenFields(household, "name", "description", + "frequencyNextDeviceAction", "frequencyNextUserAction", "restriction"); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("household/action/update - with operatorKs") + @Test + private void update_with_operatorKs() { + // update household + String householdUpdatedDetails = "updated details with operatorKs"; + Household updatedHousehold = new Household(); + updatedHousehold.setName(householdUpdatedDetails); + updatedHousehold.setDescription(householdUpdatedDetails); + + updatedHousehold = executor.executeSync(update(updatedHousehold) + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(masterUser.getUserId()))) + .results; + + assertThat(updatedHousehold.getName()).isEqualTo(householdUpdatedDetails); + assertThat(updatedHousehold.getDescription()).isEqualTo(householdUpdatedDetails); + assertThat(updatedHousehold).isEqualToIgnoringGivenFields(household, "name", "description", + "frequencyNextDeviceAction", "frequencyNextUserAction", "restriction"); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("household/action/update - with regular userKs") + @Test + private void update_with_regular_userKs() { + // update household + String householdUpdatedDetails = "updated details with regular userKs"; + Household updatedHousehold = new Household(); + updatedHousehold.setName(householdUpdatedDetails); + updatedHousehold.setDescription(householdUpdatedDetails); + + HouseholdUser user = HouseholdUtils.getRegularUsersList(household).get(0); + String userKs = OttUserUtils.getKs(Integer.parseInt(user.getUserId())); + + updatedHousehold = executor.executeSync(update(updatedHousehold) + .setKs(userKs)) + .results; + + assertThat(updatedHousehold.getName()).isEqualTo(householdUpdatedDetails); + assertThat(updatedHousehold.getDescription()).isEqualTo(householdUpdatedDetails); + assertThat(updatedHousehold).isEqualToIgnoringGivenFields(household, "name", "description", + "frequencyNextDeviceAction", "frequencyNextUserAction", "restriction"); + } + + @Severity(SeverityLevel.MINOR) + @Description("household/action/update - with empty household object") + @Issue("BEO-5169") + @Test(enabled = false) + private void update_with_empty_household() { + // update household + String householdUpdatedDetails = "updated details with empty household"; + Household updatedHousehold = new Household(); + + HouseholdUser user = HouseholdUtils.getRegularUsersList(household).get(0); + String userKs = OttUserUtils.getKs(Integer.parseInt(user.getUserId())); + + updatedHousehold = executor.executeSync(update(updatedHousehold) + .setKs(userKs)) + .results; + + assertThat(updatedHousehold).isEqualToIgnoringGivenFields(household, "frequencyNextDeviceAction", + "frequencyNextUserAction", "restriction"); + } + + @AfterClass + private void household_updateTests_afterClass() { + // cleanup - delete household + executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getAdministratorKs())); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/licensedUrlTests/LicensedUrlGetTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/licensedUrlTests/LicensedUrlGetTests.java new file mode 100644 index 000000000..b6f02f8ea --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/licensedUrlTests/LicensedUrlGetTests.java @@ -0,0 +1,4 @@ +package com.kaltura.client.test.tests.servicesTests.licensedUrlTests; + +public class LicensedUrlGetTests { +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/ActivateTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/ActivateTests.java deleted file mode 100644 index ae67cb9de..000000000 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/ActivateTests.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.kaltura.client.test.tests.servicesTests.ottUserTests; - -import com.kaltura.client.enums.UserState; -import com.kaltura.client.services.OttUserService; -import com.kaltura.client.test.tests.BaseTest; -import com.kaltura.client.test.utils.DBUtils; -import com.kaltura.client.types.OTTUser; -import com.kaltura.client.utils.response.base.Response; -import io.qameta.allure.Description; -import io.qameta.allure.Severity; -import io.qameta.allure.SeverityLevel; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import static com.kaltura.client.services.OttUserService.login; -import static com.kaltura.client.services.OttUserService.register; -import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; -import static org.assertj.core.api.Assertions.assertThat; - -public class ActivateTests extends BaseTest { - - private OTTUser user; - private Response ottUserResponse; - - @BeforeClass - private void ottUser_activate_tests_setup() { - // register user - user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; - - // login user - user = executor.executeSync(login(partnerId, user.getUsername(), defaultUserPassword)).results.getUser(); - - // assert user is not activated - assertThat(user.getUserState()).isEqualTo(UserState.USER_NOT_ACTIVATED); - } - - @Severity(SeverityLevel.CRITICAL) - @Description("ottUser/action/activate - activate") - @Test - private void activate() { - // get activation token - String activationToken = DBUtils.getActivationToken(user.getUsername()); - - // activate user - ottUserResponse = executor.executeSync(OttUserService.activate(partnerId, user.getUsername(), activationToken)); - - // assert user activated - assertThat(ottUserResponse.error).isNull(); - assertThat(ottUserResponse.results.getUserState()).isEqualTo(UserState.OK); - } - - @Severity(SeverityLevel.MINOR) - @Description("ottUser/action/activate - activate twice with the same token") - @Test - private void activate_with_sa() { - // TODO: 5/2/2018 implement test - } -} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/AddRoleTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/AddRoleTests.java deleted file mode 100644 index 35b08a0ae..000000000 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/AddRoleTests.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.kaltura.client.test.tests.servicesTests.ottUserTests; - -import com.kaltura.client.test.tests.BaseTest; -import com.kaltura.client.types.OTTUser; -import com.kaltura.client.utils.response.base.Response; -import io.qameta.allure.Description; -import io.qameta.allure.Severity; -import io.qameta.allure.SeverityLevel; -import org.assertj.core.api.Assertions; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import static com.kaltura.client.services.OttUserService.*; -import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; - -public class AddRoleTests extends BaseTest { - - private OTTUser user; - - @BeforeClass - private void ottUser_addRole_tests_setup() { - // register user - user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; - } - - @Severity(SeverityLevel.CRITICAL) - @Description("ottUser/action/addRole - addRole") - @Test(enabled = false) - // TODO: 3/27/2018 finish and fix test - private void addRoleTest() { - int roleId = 3; - - // add role - AddRoleOttUserBuilder addRoleOttUserBuilder = addRole(roleId) - .setKs(getAdministratorKs()) - .setUserId(Integer.valueOf(user.getId())); - Response booleanResponse = executor.executeSync(addRoleOttUserBuilder); - Assertions.assertThat(booleanResponse.results.booleanValue()).isEqualTo(true); - - // TODO: 3/27/2018 finish and fix test - } -} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/GetTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/GetTests.java deleted file mode 100644 index db59a7a36..000000000 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/GetTests.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.kaltura.client.test.tests.servicesTests.ottUserTests; - -import com.kaltura.client.test.tests.BaseTest; -import com.kaltura.client.types.LoginResponse; -import com.kaltura.client.types.OTTUser; -import com.kaltura.client.utils.response.base.Response; -import io.qameta.allure.Description; -import io.qameta.allure.Severity; -import io.qameta.allure.SeverityLevel; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import static com.kaltura.client.services.OttUserService.*; -import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; -import static org.assertj.core.api.Assertions.assertThat; - -public class GetTests extends BaseTest { - - private OTTUser user; - private Response loginResponse; - - @BeforeClass - private void ottUser_get_tests_setup() { - // register user - user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; - - // login user - loginResponse = executor.executeSync(login(partnerId, user.getUsername(), defaultUserPassword)); - user = loginResponse.results.getUser(); - } - - @Severity(SeverityLevel.CRITICAL) - @Description("ottUser/action/get - get") - @Test - private void getTest() { - // get user - GetOttUserBuilder getOttUserBuilder = get() - .setKs(loginResponse.results.getLoginSession().getKs()); - Response ottUserResponse = executor.executeSync(getOttUserBuilder); - - assertThat(loginResponse.error).isNull(); - assertThat(ottUserResponse.results).isEqualToIgnoringGivenFields(user, "userState", "userType"); - } -} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/LoginTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/LoginTests.java deleted file mode 100644 index 32a4e36ab..000000000 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/LoginTests.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.kaltura.client.test.tests.servicesTests.ottUserTests; - - -import com.kaltura.client.test.tests.BaseTest; -import com.kaltura.client.types.LoginResponse; -import com.kaltura.client.types.OTTUser; -import com.kaltura.client.utils.response.base.Response; -import io.qameta.allure.Description; -import io.qameta.allure.Severity; -import io.qameta.allure.SeverityLevel; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import static com.kaltura.client.services.OttUserService.login; -import static com.kaltura.client.services.OttUserService.register; -import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; -import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; -import static org.assertj.core.api.Assertions.assertThat; - -public class LoginTests extends BaseTest { - - private OTTUser user; - private Response loginResponse; - - @BeforeClass - private void ottUser_login_tests_setup() { - // register user - user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; - } - - @Severity(SeverityLevel.CRITICAL) - @Test(description = "ottUser/action/login - login") - private void loginTest() { - // login user - loginResponse = executor.executeSync(login(partnerId, user.getUsername(), defaultUserPassword)); - - // assertions - assertThat(loginResponse.error).isNull(); - assertThat(loginResponse.results.getLoginSession()).isNotNull(); - assertThat(loginResponse.results.getUser().getUsername()).isEqualTo(user.getUsername()); - } - - @Severity(SeverityLevel.NORMAL) - @Description("ottUser/action/login - login with wrong password - error 1011") - @Test - private void login_with_wrong_password() { - String fakePassword = "fake"; - - // login user - loginResponse = executor.executeSync(login(partnerId, user.getUsername(), fakePassword)); - - // assertions - assertThat(loginResponse.results).isNull(); - assertThat(loginResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(1011).getCode()); - } - - @Severity(SeverityLevel.NORMAL) - @Description("ottUser/action/login - login with wrong username - error 1011") - @Test - private void login_with_wrong_username() { - String fakeUsername = user.getUsername() + "1"; - - // login user - loginResponse = executor.executeSync(login(partnerId, fakeUsername, defaultUserPassword)); - - // assertions - assertThat(loginResponse.results).isNull(); - assertThat(loginResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(1011).getCode()); - } - - @Severity(SeverityLevel.NORMAL) - @Description("ottUser/action/login - login with wrong partnerId - error 500006") - @Test() - private void login_with_wrong_partnerId() { - int fakePartnerId = partnerId + 1; - - // login user - loginResponse = executor.executeSync(login( fakePartnerId, user.getUsername(), defaultUserPassword)); - - // assertions - assertThat(loginResponse.results).isNull(); - assertThat(loginResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500006).getCode()); - } -} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/LogoutTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/LogoutTests.java deleted file mode 100644 index 3c66f3062..000000000 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/LogoutTests.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.kaltura.client.test.tests.servicesTests.ottUserTests; - -import com.kaltura.client.services.OttUserService; -import com.kaltura.client.test.tests.BaseTest; -import com.kaltura.client.test.utils.BaseUtils; -import com.kaltura.client.types.LoginResponse; -import com.kaltura.client.types.OTTUser; -import com.kaltura.client.utils.response.base.Response; -import io.qameta.allure.Description; -import io.qameta.allure.Severity; -import io.qameta.allure.SeverityLevel; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import static com.kaltura.client.services.OttUserService.*; -import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; -import static org.assertj.core.api.Assertions.assertThat; - -public class LogoutTests extends BaseTest { - - private OTTUser user; - - private Response loginResponse; - private Response booleanResponse; - - - @BeforeClass - private void ottUser_logout_tests_setup() { - // register user - Response ottUserResponse = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)); - user = ottUserResponse.results; - } - - @Severity(SeverityLevel.CRITICAL) - @Description("ottUser/action/logout - logout") - @Test - private void logout() { - // login user - loginResponse = executor.executeSync(login(partnerId, user.getUsername(), defaultUserPassword)); - String userKs = loginResponse.results.getLoginSession().getKs(); - - // logout user - LogoutOttUserBuilder logoutOttUserBuilder = OttUserService.logout().setKs(userKs); - booleanResponse = executor.executeSync(logoutOttUserBuilder); - - assertThat(booleanResponse.error).isNull(); - assertThat(booleanResponse.results.booleanValue()).isTrue(); - - // assert can't get user after logout - GetOttUserBuilder getOttUserBuilder = OttUserService.get().setKs(userKs); - Response ottUserResponse = executor.executeSync(getOttUserBuilder); - assertThat(ottUserResponse.results).isNull(); - assertThat(ottUserResponse.error.getCode()).isEqualTo(BaseUtils.getAPIExceptionFromList(500016).getCode()); - } - -} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserActivateTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserActivateTests.java new file mode 100644 index 000000000..02dfa31d9 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserActivateTests.java @@ -0,0 +1,149 @@ +package com.kaltura.client.test.tests.servicesTests.ottUserTests; + +import com.kaltura.client.enums.UserState; +import com.kaltura.client.services.OttUserService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.dbUtils.DBUtils; +import com.kaltura.client.types.OTTUser; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import static com.kaltura.client.services.OttUserService.delete; +import static com.kaltura.client.services.OttUserService.login; +import static com.kaltura.client.services.OttUserService.register; +import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; +import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; +import static org.assertj.core.api.Assertions.assertThat; + +public class OttUserActivateTests extends BaseTest { + + private OTTUser user; + private Response ottUserResponse; + + @BeforeClass + private void ottUser_activate_tests_setup() { + // register user + user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; + + // login user + user = executor.executeSync(login(partnerId, user.getUsername(), defaultUserPassword)).results.getUser(); + + // assert user is not activated + assertThat(user.getUserState()).isEqualTo(UserState.USER_NOT_ACTIVATED); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/activate - activate") + @Test + private void activate() { + // register user + user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; + + // login user + user = executor.executeSync(login(partnerId, user.getUsername(), defaultUserPassword)).results.getUser(); + + // assert user is not activated + assertThat(user.getUserState()).isEqualTo(UserState.USER_NOT_ACTIVATED); + + // get activation token + String activationToken = DBUtils.getActivationToken(user.getUsername()); + + // activate user + ottUserResponse = executor.executeSync(OttUserService.activate(partnerId, user.getUsername(), activationToken)); + + // assert user activated + assertThat(ottUserResponse.error).isNull(); + assertThat(ottUserResponse.results.getUserState()).isEqualTo(UserState.OK); + } + + @Severity(SeverityLevel.MINOR) + @Description("ottUser/action/activate - activate twice with the same token - error 2000") + @Test + private void activate_twice_with_same_token() { + // register user + user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; + + // login user + user = executor.executeSync(login(partnerId, user.getUsername(), defaultUserPassword)).results.getUser(); + + // assert user is not activated + assertThat(user.getUserState()).isEqualTo(UserState.USER_NOT_ACTIVATED); + + // get activation token + String activationToken = DBUtils.getActivationToken(user.getUsername()); + + // activate user - first time + ottUserResponse = executor.executeSync(OttUserService.activate(partnerId, user.getUsername(), activationToken)); + + // assert user activated + assertThat(ottUserResponse.error).isNull(); + assertThat(ottUserResponse.results.getUserState()).isEqualTo(UserState.OK); + + // activate user - second time + ottUserResponse = executor.executeSync(OttUserService.activate(partnerId, user.getUsername(), activationToken)); + + // assert error return + assertThat(ottUserResponse.results).isNull(); + assertThat(ottUserResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(2000).getCode()); + } + + @Severity(SeverityLevel.MINOR) + @Description("ottUser/action/activate - invalid user name - error 2000") + @Test + private void activate_with_invalid_username() { + // register user + user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; + + // login user + user = executor.executeSync(login(partnerId, user.getUsername(), defaultUserPassword)).results.getUser(); + + // assert user is not activated + assertThat(user.getUserState()).isEqualTo(UserState.USER_NOT_ACTIVATED); + + // get activation token + String activationToken = DBUtils.getActivationToken(user.getUsername()); + + // activate user - with invalid user name + String invalidUserName = user.getUsername() + 1; + ottUserResponse = executor.executeSync(OttUserService.activate(partnerId, invalidUserName, activationToken)); + + // assert error return + assertThat(ottUserResponse.results).isNull(); + assertThat(ottUserResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(2000).getCode()); + } + + @Severity(SeverityLevel.MINOR) + @Description("ottUser/action/activate - invalid activationToken - error 2000") + @Test + private void activate_with_invalid_activationToken() { + // register user + user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; + + // login user + user = executor.executeSync(login(partnerId, user.getUsername(), defaultUserPassword)).results.getUser(); + + // assert user is not activated + assertThat(user.getUserState()).isEqualTo(UserState.USER_NOT_ACTIVATED); + + // get activation token + String invalidActivationToken = "1"; + + // activate user - with invalid activationToken + ottUserResponse = executor.executeSync(OttUserService.activate(partnerId, user.getUsername(), invalidActivationToken)); + + // assert error return + assertThat(ottUserResponse.results).isNull(); + assertThat(ottUserResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(2000).getCode()); + } + + @AfterClass + private void activate_afterClass() { + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserAddRoleTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserAddRoleTests.java new file mode 100644 index 000000000..dc7b058ca --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserAddRoleTests.java @@ -0,0 +1,101 @@ +package com.kaltura.client.test.tests.servicesTests.ottUserTests; + +import com.kaltura.client.services.OttUserService; +import com.kaltura.client.services.UserRoleService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.UserRoleUtils; +import com.kaltura.client.types.OTTUser; +import com.kaltura.client.types.UserRole; +import com.kaltura.client.types.UserRoleFilter; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Issue; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.List; + +import static com.kaltura.client.services.OttUserService.*; +import static com.kaltura.client.services.UserRoleService.*; +import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; +import static com.kaltura.client.test.utils.OttUserUtils.getKs; +import static org.assertj.core.api.Assertions.assertThat; + +public class OttUserAddRoleTests extends BaseTest { + + + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/addRole - addRole") + @Issue("BEO-5081") + @Test(enabled = false) + private void addRole() { + // register user + OTTUser user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; + + // generate new role + UserRole userRole = UserRoleUtils.generateUserRole(); + + // add role + AddUserRoleBuilder addUserRoleBuilder = add(userRole) + .setKs(getAdministratorKs()); + Response userRoleResponse = executor.executeSync(addUserRoleBuilder); + assertThat(userRoleResponse.results).isNotNull(); + UserRole userRoleResult = userRoleResponse.results; + + // add role to user + AddRoleOttUserBuilder addRoleOttUserBuilder = OttUserService.addRole(userRoleResult.getId()) + .setKs(getAdministratorKs()) + .setUserId(Integer.valueOf(user.getId())); + Response booleanResponse = executor.executeSync(addRoleOttUserBuilder); + assertThat(booleanResponse.results.booleanValue()).isEqualTo(true); + + // get user roles + UserRoleFilter filter = new UserRoleFilter(); + filter.setCurrentUserRoleIdsContains(true); + + int userId = Integer.parseInt(user.getId()); + ListUserRoleBuilder listUserRoleBuilder = UserRoleService.list(filter) + .setKs(getKs(userId)); + List userRoles = executor.executeSync(listUserRoleBuilder).results.getObjects(); + + // assert new added role is return + List userRolesIds = new ArrayList<>(); + for (UserRole ur : userRoles) { + userRolesIds.add(ur.getId()); + } + + assertThat(userRolesIds).contains(userRoleResult.getId()); + + // cleanup - delete role + // TODO: 5/14/2018 finish test after when reletead bug will be fixed + + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); + } + + @Severity(SeverityLevel.NORMAL) + @Description("ottUser/action/addRole - addRole with invalid roleId - error ") + @Issue("BEO-5083") + @Test(enabled = false) + private void addRole_with_invalid_roleId() { + // register user + OTTUser user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; + + // add not existing role to user + int invalidRoleId = -2; + AddRoleOttUserBuilder addRoleOttUserBuilder = OttUserService.addRole(invalidRoleId) + .setKs(getAdministratorKs()) + .setUserId(Integer.valueOf(user.getId())); + Response booleanResponse = executor.executeSync(addRoleOttUserBuilder); + + assertThat(booleanResponse.results.booleanValue()).isEqualTo(true); + + // cleanup - delete role + // TODO: 5/14/2018 finish test after when reletead bug will be fixed + + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/AnonymousLoginTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserAnonymousLoginTests.java similarity index 70% rename from src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/AnonymousLoginTests.java rename to src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserAnonymousLoginTests.java index f5577338d..dc02b0f3e 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/AnonymousLoginTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserAnonymousLoginTests.java @@ -1,5 +1,6 @@ package com.kaltura.client.test.tests.servicesTests.ottUserTests; +import com.kaltura.client.services.OttUserService; import com.kaltura.client.test.tests.BaseTest; import com.kaltura.client.types.LoginSession; import com.kaltura.client.utils.response.base.Response; @@ -8,20 +9,21 @@ import io.qameta.allure.SeverityLevel; import org.testng.annotations.Test; -import static com.kaltura.client.services.OttUserService.anonymousLogin; import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; import static org.assertj.core.api.Assertions.assertThat; -public class AnonymousLoginTests extends BaseTest { + +public class OttUserAnonymousLoginTests extends BaseTest { private Response loginSessionResponse; @Severity(SeverityLevel.CRITICAL) @Description("ottUser/action/anonymousLogin - anonymousLogin") @Test() - private void anonymousLoginTest() { - loginSessionResponse = executor.executeSync(anonymousLogin(partnerId)); + private void anonymousLogin() { + String udid = "1234"; + loginSessionResponse = executor.executeSync(OttUserService.anonymousLogin(partnerId, udid)); assertThat(loginSessionResponse.error).isNull(); assertThat(loginSessionResponse.results.getKs()).isNotNull(); @@ -30,9 +32,9 @@ private void anonymousLoginTest() { @Severity(SeverityLevel.MINOR) @Description("ottUser/action/anonymousLogin - anonymousLogin with wrong partnerId - error 500006") @Test() - private void anonymousLogin_with_wrong_partnerId() { - int fakePartnerId = 1; - loginSessionResponse = executor.executeSync(anonymousLogin(fakePartnerId)); + private void anonymousLogin_with_invalod_partnerId() { + int invalidPartnerId = 1; + loginSessionResponse = executor.executeSync(OttUserService.anonymousLogin(invalidPartnerId)); assertThat(loginSessionResponse.results).isNull(); assertThat(loginSessionResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500006).getCode()); diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/DeleteTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserDeleteTests.java similarity index 63% rename from src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/DeleteTests.java rename to src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserDeleteTests.java index f03405ecd..f909911d6 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/DeleteTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserDeleteTests.java @@ -15,25 +15,26 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import static com.kaltura.client.services.HouseholdService.*; import static com.kaltura.client.services.HouseholdService.DeleteHouseholdBuilder; import static com.kaltura.client.services.OttUserService.*; import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; -import static com.kaltura.client.test.utils.HouseholdUtils.getDefaultUserFromHousehold; -import static com.kaltura.client.test.utils.HouseholdUtils.getMasterUserFromHousehold; +import static com.kaltura.client.test.utils.HouseholdUtils.getDefaultUser; +import static com.kaltura.client.test.utils.HouseholdUtils.getMasterUser; import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; import static org.assertj.core.api.Assertions.assertThat; -public class DeleteTests extends BaseTest { +public class OttUserDeleteTests extends BaseTest { private Household household; - private Response booleanResponse; private DeleteOttUserBuilder deleteOttUserBuilder; + private final int numberOfDevicesInHousehold = 0; + private final int numberOfUsersInHousehold = 2; + @BeforeClass private void ottUser_delete_tests_setup() { - int numberOfDevicesInHousehold = 0; - int numberOfUsersInHousehold = 2; household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, false); } @@ -42,9 +43,7 @@ private void ottUser_delete_tests_setup() { @Test private void delete() { // register user - RegisterOttUserBuilder registerOttUserBuilder = register(partnerId, generateOttUser(), defaultUserPassword) - .setKs(getAdministratorKs()); - OTTUser user = executor.executeSync(registerOttUserBuilder).results; + OTTUser user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; // delete user and assert success deleteOttUserBuilder = OttUserService.delete() @@ -66,10 +65,10 @@ private void delete() { @Severity(SeverityLevel.NORMAL) @Description("ottUser/action/delete - delete master user: error 2031") - @Test(enabled = true) + @Test() private void delete_master_user() { // get household master user - HouseholdUser masterUser = getMasterUserFromHousehold(household); + HouseholdUser masterUser = getMasterUser(household); // try to delete master user and assert error deleteOttUserBuilder = OttUserService.delete() @@ -83,10 +82,10 @@ private void delete_master_user() { @Severity(SeverityLevel.NORMAL) @Description("ottUser/action/delete - delete default user: error 2030") - @Test(enabled = true) + @Test() private void delete_default_user() { // get household default user - HouseholdUser defaultUser = getDefaultUserFromHousehold(household); + HouseholdUser defaultUser = getDefaultUser(household); // try to delete default user and assert error deleteOttUserBuilder = OttUserService.delete() @@ -98,6 +97,48 @@ private void delete_default_user() { assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(2030).getCode()); } + @Severity(SeverityLevel.MINOR) + @Description("ottUser/action/delete - delete not exist user: error 500004") + @Test() + private void delete_not_exist_user() { + // delete not exist user and assert error + int invalidUserId = 1; + deleteOttUserBuilder = OttUserService.delete() + .setKs(getAdministratorKs()) + .setUserId(invalidUserId); + booleanResponse = executor.executeSync(deleteOttUserBuilder); + + assertThat(booleanResponse.results).isNull(); + assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500004).getCode()); + } + + @Severity(SeverityLevel.MINOR) + @Description("ottUser/action/delete - delete user with suspended household: error 1009") + @Test() + private void delete_user_with_suspended_household() { + // set household + Household household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, false); + + // get regular user + HouseholdUser user = HouseholdUtils.getRegularUsersList(household).get(0); + + // suspend household + SuspendHouseholdBuilder suspendHouseholdBuilder = suspend() + .setKs(getAdministratorKs()) + .setUserId(Integer.valueOf(user.getUserId())); + booleanResponse = executor.executeSync(suspendHouseholdBuilder); + + // delete suspended user + deleteOttUserBuilder = OttUserService.delete() + .setKs(getAdministratorKs()) + .setUserId(Integer.valueOf(user.getUserId())); + booleanResponse = executor.executeSync(deleteOttUserBuilder); + + // assert error + assertThat(booleanResponse.results).isNull(); + assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(1009).getCode()); + } + @AfterClass private void ottUser_delete_tests_tearDown() { DeleteHouseholdBuilder deleteHouseholdBuilder = HouseholdService.delete(Math.toIntExact(household.getId())) diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/GetEncryptedUserIdTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserGetEncryptedUserIdTests.java similarity index 50% rename from src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/GetEncryptedUserIdTests.java rename to src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserGetEncryptedUserIdTests.java index c7d637403..16f9ef146 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/GetEncryptedUserIdTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserGetEncryptedUserIdTests.java @@ -1,5 +1,6 @@ package com.kaltura.client.test.tests.servicesTests.ottUserTests; +import com.kaltura.client.services.OttUserService; import com.kaltura.client.test.tests.BaseTest; import com.kaltura.client.types.OTTUser; import com.kaltura.client.types.StringValue; @@ -7,14 +8,16 @@ import io.qameta.allure.Description; import io.qameta.allure.Severity; import io.qameta.allure.SeverityLevel; +import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static com.kaltura.client.services.OttUserService.*; import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; +import static com.kaltura.client.test.utils.OttUserUtils.getKs; import static org.assertj.core.api.Assertions.assertThat; -public class GetEncryptedUserIdTests extends BaseTest { +public class OttUserGetEncryptedUserIdTests extends BaseTest { private OTTUser user; @@ -25,15 +28,34 @@ private void ottUser_getEncryptedUserId_tests_setup() { } @Severity(SeverityLevel.CRITICAL) - @Description("ottUser/action/getEncryptedUserId - getEncryptedUserId") + @Description("ottUser/action/getEncryptedUserId - getEncryptedUserId with super user ks") @Test - private void getEncryptedUserIdTest() { - GetEncryptedUserIdOttUserBuilder getEncryptedUserIdOttUserBuilder = getEncryptedUserId(); - getEncryptedUserIdOttUserBuilder.setKs(getAdministratorKs()); - getEncryptedUserIdOttUserBuilder.setUserId(Integer.valueOf(user.getId())); + private void getEncryptedUserId_with_superUserKs () { + GetEncryptedUserIdOttUserBuilder getEncryptedUserIdOttUserBuilder = OttUserService.getEncryptedUserId() + .setKs(getAdministratorKs()) + .setUserId(Integer.valueOf(user.getId())); Response stringValueResponse = executor.executeSync(getEncryptedUserIdOttUserBuilder); assertThat(stringValueResponse.error).isNull(); assertThat(stringValueResponse.results.getValue()).isNotNull(); } + + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/getEncryptedUserId") + @Test + private void getEncryptedUserId() { + String userKs = getKs(Integer.parseInt(user.getId())); + GetEncryptedUserIdOttUserBuilder getEncryptedUserIdOttUserBuilder = OttUserService.getEncryptedUserId() + .setKs(userKs); + Response stringValueResponse = executor.executeSync(getEncryptedUserIdOttUserBuilder); + + assertThat(stringValueResponse.error).isNull(); + assertThat(stringValueResponse.results.getValue()).isNotNull(); + } + + @AfterClass + private void getEncryptedUserId_afterClass() { + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); + } } diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserGetTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserGetTests.java new file mode 100644 index 000000000..8120158c3 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserGetTests.java @@ -0,0 +1,83 @@ +package com.kaltura.client.test.tests.servicesTests.ottUserTests; + +import com.kaltura.client.services.OttUserService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.types.LoginResponse; +import com.kaltura.client.types.OTTUser; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import static com.kaltura.client.services.OttUserService.*; +import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; +import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; +import static org.assertj.core.api.Assertions.assertThat; + +public class OttUserGetTests extends BaseTest { + + private OTTUser user; + private Response loginResponse; + + @BeforeClass + private void ottUser_get_tests_setup() { + // register user + user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; + + // login user + loginResponse = executor.executeSync(login(partnerId, user.getUsername(), defaultUserPassword)); + user = loginResponse.results.getUser(); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/get - get") + @Test + private void get() { + // get user + GetOttUserBuilder getOttUserBuilder = OttUserService.get() + .setKs(loginResponse.results.getLoginSession().getKs()); + Response ottUserResponse = executor.executeSync(getOttUserBuilder); + + assertThat(loginResponse.error).isNull(); + assertThat(ottUserResponse.results).isEqualToIgnoringGivenFields(user, "userState", "userType"); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/get - get with super user ks") + @Test + private void get_with_superUserKs() { + // get user + GetOttUserBuilder getOttUserBuilder = OttUserService.get() + .setKs(getAdministratorKs()) + .setUserId(Integer.valueOf(user.getId())); + Response ottUserResponse = executor.executeSync(getOttUserBuilder); + + assertThat(loginResponse.error).isNull(); + assertThat(ottUserResponse.results).isEqualToIgnoringGivenFields(user, "userState", "userType"); + } + + @Severity(SeverityLevel.MINOR) + @Description("ottUser/action/get - get with invalid userId - error 500004") + @Test + private void get_with_invalid_userId() { + // get user + int invalidUserId = 1; + GetOttUserBuilder getOttUserBuilder = OttUserService.get() + .setKs(getAdministratorKs()) + .setUserId(invalidUserId); + Response ottUserResponse = executor.executeSync(getOttUserBuilder); + + assertThat(ottUserResponse.results).isNull(); + assertThat(ottUserResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500004).getCode()); + } + + @AfterClass + private void get_afterClass() { + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); + } + +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/ListTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserListTests.java similarity index 51% rename from src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/ListTests.java rename to src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserListTests.java index 1c6861ed1..3ae5e639a 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/ListTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserListTests.java @@ -1,5 +1,6 @@ package com.kaltura.client.test.tests.servicesTests.ottUserTests; +import com.kaltura.client.services.HouseholdService; import com.kaltura.client.test.tests.BaseTest; import com.kaltura.client.test.utils.HouseholdUtils; import com.kaltura.client.types.*; @@ -7,6 +8,7 @@ import io.qameta.allure.Description; import io.qameta.allure.Severity; import io.qameta.allure.SeverityLevel; +import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -15,17 +17,18 @@ import static com.kaltura.client.services.OttUserService.*; import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; import static com.kaltura.client.test.utils.BaseUtils.getConcatenatedString; -import static com.kaltura.client.test.utils.HouseholdUtils.getMasterUserFromHousehold; -import static com.kaltura.client.test.utils.HouseholdUtils.getUsersListFromHouseHold; -import static com.kaltura.client.test.utils.OttUserUtils.getUserById; +import static com.kaltura.client.test.utils.HouseholdUtils.*; +import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; +import static com.kaltura.client.test.utils.OttUserUtils.getOttUserById; import static org.assertj.core.api.Assertions.assertThat; -public class ListTests extends BaseTest { +public class OttUserListTests extends BaseTest { private Household household; private Response> householdUserListResponse; - private int numberOfUsersInHousehold = 4; - private int numberOfDevicesInHousehold = 1; + + private final int numberOfUsersInHousehold = 4; + private final int numberOfDevicesInHousehold = 1; @BeforeClass @@ -34,14 +37,37 @@ private void ottUser_list_tests_setup() { } @Severity(SeverityLevel.CRITICAL) - @Description("ottUser/action/list - list from master ks") + @Description("ottUser/action/list - list with master user ks") @Test - private void list_from_master_ks() { + private void list_with_masterUserKs() { // get master user from household - HouseholdUser masterUser = getMasterUserFromHousehold(household); + HouseholdUser masterUser = getMasterUser(household); // login master user - String username = getUserById(Integer.parseInt(masterUser.getUserId())).getUsername(); + String username = getOttUserById(Integer.parseInt(masterUser.getUserId())).getUsername(); + LoginOttUserBuilder loginOttUserBuilder = login(partnerId, username, defaultUserPassword); + Response loginResponse = executor.executeSync(loginOttUserBuilder); + + // list household users + ListOttUserBuilder listOttUserBuilder = list() + .setKs(loginResponse.results.getLoginSession().getKs()); + householdUserListResponse = executor.executeSync(listOttUserBuilder); + List users = householdUserListResponse.results.getObjects(); + + // assert users list size + assertThat(householdUserListResponse.error).isNull(); + assertThat(users.size()).isEqualTo(numberOfUsersInHousehold + 2); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/list - list with regular user ks") + @Test + private void list_with_regularUserKs() { + // get master user from household + HouseholdUser user = getRegularUsersList(household).get(0); + + // login regular user + String username = getOttUserById(Integer.parseInt(user.getUserId())).getUsername(); LoginOttUserBuilder loginOttUserBuilder = login(partnerId, username, defaultUserPassword); Response loginResponse = executor.executeSync(loginOttUserBuilder); @@ -59,9 +85,9 @@ private void list_from_master_ks() { @Severity(SeverityLevel.CRITICAL) @Description("ottUser/action/list - get list with filter using idIn") @Test - private void list_with_filter_idIn() { + private void list_with_id_filter() { // get users from household - List householdUsers = getUsersListFromHouseHold(household); + List householdUsers = getUsersList(household); // set user filter OTTUserFilter ottUserFilter = new OTTUserFilter(); @@ -70,7 +96,7 @@ private void list_with_filter_idIn() { // list household users ListOttUserBuilder listOttUserBuilder = list(ottUserFilter) - .setKs(getAdministratorKs()); + .setKs(getOperatorKs()); householdUserListResponse = executor.executeSync(listOttUserBuilder); List users = householdUserListResponse.results.getObjects(); @@ -82,18 +108,18 @@ private void list_with_filter_idIn() { @Severity(SeverityLevel.CRITICAL) @Description("ottUser/action/list - get list with filter using usernameEqual") @Test - private void list_withd_filter_usernameEqual() { + private void list_with_username_filter() { // get users from household - List householdUsers = getUsersListFromHouseHold(household); + List householdUsers = getUsersList(household); // set user filter OTTUserFilter ottUserFilter = new OTTUserFilter(); - String usernameEqual = getUserById(Integer.valueOf(householdUsers.get(0).getUserId())).getUsername(); + String usernameEqual = getOttUserById(Integer.valueOf(householdUsers.get(0).getUserId())).getUsername(); ottUserFilter.setUsernameEqual(usernameEqual); // list household users ListOttUserBuilder listOttUserBuilder = list(ottUserFilter) - .setKs(getAdministratorKs()); + .setKs(getOperatorKs()); householdUserListResponse = executor.executeSync(listOttUserBuilder); List users = householdUserListResponse.results.getObjects(); @@ -103,24 +129,53 @@ private void list_withd_filter_usernameEqual() { } @Severity(SeverityLevel.NORMAL) - @Description("ottUser/action/list - get list with not valid filter") + @Description("ottUser/action/list - get list with invalid filter") @Test - private void list_with_not_valid_filter() { + private void list_with_invalid_filter() { // get users from household - List householdUsers = getUsersListFromHouseHold(household); + List householdUsers = getUsersList(household); - // set user filter + // set invalid user filter OTTUserFilter ottUserFilter = new OTTUserFilter(); ottUserFilter.setIdIn(householdUsers.get(0).getUserId()); - ottUserFilter.setUsernameEqual(getUserById(Integer.valueOf(householdUsers.get(1).getUserId())).getUsername()); + ottUserFilter.setUsernameEqual(getOttUserById(Integer.valueOf(householdUsers.get(1).getUserId())).getUsername()); // list household users ListOttUserBuilder listOttUserBuilder = list(ottUserFilter) - .setKs(getAdministratorKs()); + .setKs(getOperatorKs()); householdUserListResponse = executor.executeSync(listOttUserBuilder); // assert error 500038 is return assertThat(householdUserListResponse.results).isNull(); assertThat(householdUserListResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500038).getCode()); } + + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/list - get list with filter using usernameEqual") + @Test + private void list_with_externalId_filter() { + // register user + OTTUser user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; + + // set user filter + OTTUserFilter ottUserFilter = new OTTUserFilter(); + ottUserFilter.setExternalIdEqual(user.getExternalId()); + + // list household users + ListOttUserBuilder listOttUserBuilder = list(ottUserFilter) + .setKs(getOperatorKs()); + householdUserListResponse = executor.executeSync(listOttUserBuilder); + List users = householdUserListResponse.results.getObjects(); + + // assert users list size + assertThat(householdUserListResponse.error).isNull(); + assertThat(users.size()).isEqualTo(1); + } + + @AfterClass + private void list_AfterClass() { + HouseholdService.DeleteHouseholdBuilder deleteHouseholdBuilder = HouseholdService.delete(Math.toIntExact(household.getId())) + .setKs(getAdministratorKs()); + executor.executeSync(deleteHouseholdBuilder); + } } diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserLoginTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserLoginTests.java new file mode 100644 index 000000000..defe0fafa --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserLoginTests.java @@ -0,0 +1,173 @@ +package com.kaltura.client.test.tests.servicesTests.ottUserTests; + + +import com.kaltura.client.enums.UserState; +import com.kaltura.client.services.OttUserService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.HouseholdUtils; +import com.kaltura.client.types.Household; +import com.kaltura.client.types.HouseholdUser; +import com.kaltura.client.types.LoginResponse; +import com.kaltura.client.types.OTTUser; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import static com.kaltura.client.services.HouseholdService.SuspendHouseholdBuilder; +import static com.kaltura.client.services.HouseholdService.suspend; +import static com.kaltura.client.services.OttUserService.delete; +import static com.kaltura.client.services.OttUserService.register; +import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; +import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; +import static com.kaltura.client.test.utils.OttUserUtils.getOttUserById; +import static org.assertj.core.api.Assertions.assertThat; + +public class OttUserLoginTests extends BaseTest { + + private OTTUser user; + private Response loginResponse; + + @BeforeClass + private void ottUser_login_tests_setup() { + // register user + user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; + } + + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/login - login") + @Test + private void login() { + // login user + loginResponse = executor.executeSync(OttUserService.login(partnerId, user.getUsername(), defaultUserPassword)); + + // assertions + assertThat(loginResponse.error).isNull(); + assertThat(loginResponse.results.getLoginSession()).isNotNull(); + assertThat(loginResponse.results.getUser().getUsername()).isEqualTo(user.getUsername()); + } + + @Severity(SeverityLevel.NORMAL) + @Description("ottUser/action/login - login with invalid password - error 1011") + @Test + private void login_with_invalid_password() { + String invalidPassword = "invalid"; + + // login user + loginResponse = executor.executeSync(OttUserService.login(partnerId, user.getUsername(), invalidPassword)); + + // assertions + assertThat(loginResponse.results).isNull(); + assertThat(loginResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(1011).getCode()); + } + + @Severity(SeverityLevel.NORMAL) + @Description("ottUser/action/login - login with invalid username - error 2000") + @Test + private void login_with_invalid_username() { + String invalidUsername = user.getUsername() + "1"; + + // login user + loginResponse = executor.executeSync(OttUserService.login(partnerId, invalidUsername, defaultUserPassword)); + + // assertions + assertThat(loginResponse.results).isNull(); + assertThat(loginResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(2000).getCode()); + } + + @Severity(SeverityLevel.NORMAL) + @Description("ottUser/action/login - login with invalid partnerId - error 500006") + @Test() + private void login_with_invalid_partnerId() { + int invalidPartnerId = partnerId + 1; + + // login user + loginResponse = executor.executeSync(OttUserService.login(invalidPartnerId, user.getUsername(), defaultUserPassword)); + + // assertions + assertThat(loginResponse.results).isNull(); + assertThat(loginResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500006).getCode()); + } + + @Severity(SeverityLevel.NORMAL) + @Description("ottUser/action/login - login with suspended user - error ") + @Test() + private void login_with_suspended_user() { + // set household + int numberOfUsersInHousehold = 2; + int numberOfDevicesInHousehold = 1; + Household household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, false); + + // get regular user + HouseholdUser user = HouseholdUtils.getRegularUsersList(household).get(0); + + // suspend household + SuspendHouseholdBuilder suspendHouseholdBuilder = suspend() + .setKs(getAdministratorKs()) + .setUserId(Integer.valueOf(user.getUserId())); + executor.executeSync(suspendHouseholdBuilder); + + // login user + String username = getOttUserById(Integer.parseInt(user.getUserId())).getUsername(); + loginResponse = executor.executeSync(OttUserService.login(partnerId, username, defaultUserPassword)); + + // assertions + assertThat(loginResponse.error).isNull(); + assertThat(loginResponse.results.getUser().getUserState().getValue()).isEqualTo(UserState.USER_NOT_ACTIVATED.getValue()); + } + + // TODO: 5/14/2018 ask Ira how to reproduce the below errors +// @Severity(SeverityLevel.NORMAL) +// @Description("ottUser/action/login - login with user twice - error ") +// @Test() +// private void login_with_user_twice() { +// // register user +// OTTUser user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; +// +// // login user - first time +// executor.executeSync(OttUserService.login(partnerId, user.getUsername(), defaultUserPassword)); +// +// // login user - second time +// loginResponse = executor.executeSync(OttUserService.login(partnerId, user.getUsername(), defaultUserPassword)); +// +// // assertions +// assertThat(loginResponse.results).isNull(); +//// assertThat(loginResponse.error.getCode()).isEqualTo(UserState.USER_NOT_ACTIVATED.getValue()); +// } +// +// @Severity(SeverityLevel.NORMAL) +// @Description("ottUser/action/login - login with not registered device - error ") +// @Test() +// private void login_with_not_registered_devcie() { +// // set household +// int numberOfUsersInHousehold = 2; +// int numberOfDevicesInHousehold = 1; +// Household household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold, false); +// +// // get regular user +// HouseholdUser user = HouseholdUtils.getRegularUsersList(household).get(0); +// +// // login user with invalid udid +// String username = getOttUserById(Integer.parseInt(user.getUserId())).getUsername(); +// String invalidDeviceId = "invalid_device_id"; +// loginResponse = executor.executeSync(OttUserService.login(partnerId, username, defaultUserPassword, null, invalidDeviceId)); +// +// // assertions +// assertThat(loginResponse.results).isNull(); +// } + + // UserAllreadyLoggedIn + // UserDoubleLogIn + // InsideLockTime + // DeviceNotRegistered - login with invalid registered + // UserNotMasterApproved - user in pending status + + @AfterClass + private void login_afterClass() { + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/LoginWithPinTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserLoginWithPinTests.java similarity index 56% rename from src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/LoginWithPinTests.java rename to src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserLoginWithPinTests.java index bf2f0baf2..0beb4c3bf 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/LoginWithPinTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserLoginWithPinTests.java @@ -1,6 +1,7 @@ package com.kaltura.client.test.tests.servicesTests.ottUserTests; import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.BaseUtils; import com.kaltura.client.types.LoginResponse; import com.kaltura.client.types.OTTUser; import com.kaltura.client.types.UserLoginPin; @@ -8,17 +9,21 @@ import io.qameta.allure.Description; import io.qameta.allure.Severity; import io.qameta.allure.SeverityLevel; +import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import java.util.concurrent.TimeUnit; + import static com.kaltura.client.services.OttUserService.*; import static com.kaltura.client.services.UserLoginPinService.AddUserLoginPinBuilder; import static com.kaltura.client.services.UserLoginPinService.add; import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; -public class LoginWithPinTests extends BaseTest { +public class OttUserLoginWithPinTests extends BaseTest { private OTTUser user; @@ -27,17 +32,16 @@ public class LoginWithPinTests extends BaseTest { private final String SECRET = "secret"; - @BeforeClass + @BeforeClass(alwaysRun = true) private void ottUser_login_tests_setup() { // register user - Response ottUserResponse = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)); - user = ottUserResponse.results; + user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; } @Severity(SeverityLevel.CRITICAL) @Description("ottUser/action/loginWithPin - loginWithPin with secret") @Test - private void loginWithPin_with_secret() throws InterruptedException { + private void loginWithPin_with_secret() { // add pin AddUserLoginPinBuilder addUserLoginPinBuilder = add(SECRET) .setKs(getAdministratorKs()) @@ -56,9 +60,9 @@ private void loginWithPin_with_secret() throws InterruptedException { } @Severity(SeverityLevel.NORMAL) - @Description("ottUser/action/loginWithPin - loginWithPin with wrong secret - error 2008") + @Description("ottUser/action/loginWithPin - loginWithPin with invalid secret - error 2008") @Test - private void loginWithPin_with_wrong_secret() { + private void loginWithPin_with_invalid_secret() { // add pin AddUserLoginPinBuilder addUserLoginPinBuilder = add(SECRET) .setKs(getAdministratorKs()) @@ -66,9 +70,9 @@ private void loginWithPin_with_wrong_secret() { userLoginPinResponse = executor.executeSync(addUserLoginPinBuilder); // login with pin and wrong secret - String wrongSecret = SECRET + 1; + String invalidSecret = SECRET + 1; String pin = userLoginPinResponse.results.getPinCode(); - LoginWithPinOttUserBuilder loginWithPinOttUserBuilder = loginWithPin(partnerId, pin, null, wrongSecret); + LoginWithPinOttUserBuilder loginWithPinOttUserBuilder = loginWithPin(partnerId, pin, null, invalidSecret); loginResponse = executor.executeSync(loginWithPinOttUserBuilder); // assert error 2008 is return @@ -78,22 +82,68 @@ private void loginWithPin_with_wrong_secret() { @Severity(SeverityLevel.NORMAL) @Description("ottUser/action/loginWithPin - loginWithPin with expired pinCode - error 2004") - @Test(groups = "slow") - private void loginWithPin_with_expired_pinCode() { + @Test(groups = {"slowBefore"}) + private void loginWithPin_with_expired_pinCode_before_wait() { // add pin AddUserLoginPinBuilder addUserLoginPinBuilder = add(SECRET) .setKs(getAdministratorKs()) .setUserId(Integer.valueOf(user.getId())); userLoginPinResponse = executor.executeSync(addUserLoginPinBuilder); + } - // login with expired pin - String pin = userLoginPinResponse.results.getPinCode(); - // sleep for 1.5 minutes - try { Thread.sleep(120000); } catch (InterruptedException e) { e.printStackTrace(); } - LoginWithPinOttUserBuilder loginWithPinOttUserBuilder = loginWithPin(partnerId, pin, null, SECRET); + @Test(groups = {"slowAfter"}, dependsOnGroups = {"slowBefore"}, alwaysRun = true) + private void loginWithPin_with_expired_pinCode_after_wait() { + // prepare variables for await() functionality + int delayBetweenRetriesInSeconds = 10; + int maxTimeExpectingValidResponseInSeconds = 200; + // wait for pin to expire + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() -> { + long expire = userLoginPinResponse.results.getExpirationTime() + 120; + long now = BaseUtils.getEpoch(); + return now > expire; + }); + + LoginWithPinOttUserBuilder loginWithPinOttUserBuilder = loginWithPin(partnerId, userLoginPinResponse.results.getPinCode(), null, SECRET); loginResponse = executor.executeSync(loginWithPinOttUserBuilder); assertThat(loginResponse.results).isNull(); assertThat(loginResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(2004).getCode()); + + } + + @Severity(SeverityLevel.NORMAL) + @Description("ottUser/action/loginWithPin - loginWithPin with invalid pin") + @Test() + private void loginWithPin_with_invalid_pin() { + // login with invalid pin + String invalidPin = "invalidPin"; + LoginWithPinOttUserBuilder loginWithPinOttUserBuilder = loginWithPin(partnerId, invalidPin, null, SECRET); + loginResponse = executor.executeSync(loginWithPinOttUserBuilder); + + assertThat(loginResponse.results).isNull(); + assertThat(loginResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(2003).getCode()); + } + +// +// +// +// +// +// +// +// +// +// +// +// +// + + @AfterClass + private void loginWithPin_afterClass() { + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); } } diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserLogoutTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserLogoutTests.java new file mode 100644 index 000000000..dee67882a --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserLogoutTests.java @@ -0,0 +1,97 @@ +package com.kaltura.client.test.tests.servicesTests.ottUserTests; + +import com.kaltura.client.services.OttUserService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.BaseUtils; +import com.kaltura.client.types.LoginResponse; +import com.kaltura.client.types.OTTUser; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.Test; + +import static com.kaltura.client.services.OttUserService.*; +import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; +import static org.assertj.core.api.Assertions.assertThat; + +public class OttUserLogoutTests extends BaseTest { + + private Response loginResponse; + private Response booleanResponse; + private Response ottUserResponse; + + + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/logout - logout") + @Test + private void logout() { + // register user + OTTUser user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; + + // login user + loginResponse = executor.executeSync(login(partnerId, user.getUsername(), defaultUserPassword)); + String userKs = loginResponse.results.getLoginSession().getKs(); + + // logout user + LogoutOttUserBuilder logoutOttUserBuilder = OttUserService.logout().setKs(userKs); + booleanResponse = executor.executeSync(logoutOttUserBuilder); + + assertThat(booleanResponse.error).isNull(); + assertThat(booleanResponse.results.booleanValue()).isTrue(); + + // assert can't get user after logout + GetOttUserBuilder getOttUserBuilder = OttUserService.get().setKs(userKs); + ottUserResponse = executor.executeSync(getOttUserBuilder); + assertThat(ottUserResponse.results).isNull(); + assertThat(ottUserResponse.error.getCode()).isEqualTo(BaseUtils.getAPIExceptionFromList(500016).getCode()); + + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/logout - logout") + @Test + private void logout_from_specific_platform() { + // register user + OTTUser user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; + + // login user without device + loginResponse = executor.executeSync(login(partnerId, user.getUsername(), defaultUserPassword)); + String userWithoutDeviceKs = loginResponse.results.getLoginSession().getKs(); + + // login user with device + String udid = "123456"; + loginResponse = executor.executeSync(login(partnerId, user.getUsername(), defaultUserPassword, null, udid)); + String userWithDeviceKs = loginResponse.results.getLoginSession().getKs(); + + user = loginResponse.results.getUser(); + + // logout user using device ks + LogoutOttUserBuilder logoutOttUserBuilder = OttUserService.logout().setKs(userWithDeviceKs); + booleanResponse = executor.executeSync(logoutOttUserBuilder); + + assertThat(booleanResponse.error).isNull(); + assertThat(booleanResponse.results.booleanValue()).isTrue(); + + // assert can't 'get' user using device ks + GetOttUserBuilder getOttUserBuilder = OttUserService.get().setKs(userWithDeviceKs); + ottUserResponse = executor.executeSync(getOttUserBuilder); + + assertThat(ottUserResponse.results).isNull(); + assertThat(ottUserResponse.error.getCode()).isEqualTo(BaseUtils.getAPIExceptionFromList(500016).getCode()); + + // assert can 'get' user using no-device ks + getOttUserBuilder = OttUserService.get().setKs(userWithoutDeviceKs); + ottUserResponse = executor.executeSync(getOttUserBuilder); + + assertThat(ottUserResponse.error).isNull(); + assertThat(ottUserResponse.results).isEqualToIgnoringGivenFields(user, "userState", "userType"); + + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); + } + + +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserRegisterTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserRegisterTests.java new file mode 100644 index 000000000..6a5632bec --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserRegisterTests.java @@ -0,0 +1,68 @@ +package com.kaltura.client.test.tests.servicesTests.ottUserTests; + +import com.kaltura.client.services.OttUserService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.types.OTTUser; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.Test; + +import static com.kaltura.client.services.OttUserService.delete; +import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; +import static com.kaltura.client.test.utils.OttUserUtils.dynamicDataMapBuilder; +import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; +import static org.assertj.core.api.Assertions.assertThat; + +public class OttUserRegisterTests extends BaseTest { + + private Response ottUserResponse; + + + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/register - register") + @Test + private void register() { + // generate user + OTTUser user = generateOttUser(); + + // set dynamic date + user.setDynamicData(dynamicDataMapBuilder("key", "value")); + + // register + ottUserResponse = executor.executeSync(OttUserService.register(partnerId, user, defaultUserPassword)); + user = ottUserResponse.results; + + assertThat(ottUserResponse.error).isNull(); + assertThat(ottUserResponse.results).isEqualToIgnoringGivenFields(user, "userState", "userType", + "householdId", "dynamicData", "isHouseholdMaster", "suspensionState", "id", "params"); + + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); + } + + @Severity(SeverityLevel.NORMAL) + @Description("ottUser/action/register - user exists - error 2014") + @Test + private void register_exists_user() { + // generate user + OTTUser user = generateOttUser(); + + // register - first time + ottUserResponse = executor.executeSync(OttUserService.register(partnerId, user, defaultUserPassword)); + String userId = ottUserResponse.results.getId(); + + // register - second time + ottUserResponse = executor.executeSync(OttUserService.register(partnerId, user, defaultUserPassword)); + + assertThat(ottUserResponse.results).isNull(); + assertThat(ottUserResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(2014).getCode()); + + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(userId))); + } + + // + // +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/ResendActivationTokenTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserResendActivationTokenTests.java similarity index 69% rename from src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/ResendActivationTokenTests.java rename to src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserResendActivationTokenTests.java index f5159135d..a46985df8 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/ResendActivationTokenTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserResendActivationTokenTests.java @@ -1,40 +1,39 @@ package com.kaltura.client.test.tests.servicesTests.ottUserTests; +import com.kaltura.client.services.OttUserService; import com.kaltura.client.test.tests.BaseTest; import com.kaltura.client.types.OTTUser; import com.kaltura.client.utils.response.base.Response; import io.qameta.allure.Description; import io.qameta.allure.Severity; import io.qameta.allure.SeverityLevel; -import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static com.kaltura.client.services.OttUserService.*; import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; import static org.assertj.core.api.Assertions.assertThat; -public class ResendActivationTokenTests extends BaseTest { +public class OttUserResendActivationTokenTests extends BaseTest { - private OTTUser user; - - @BeforeClass - private void ottUser_resendActivationToken_tests_setup() { + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/resendActivationToken - resendActivationToken") + @Test(enabled = false) + private void resendActivationToken() { // register user - user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; + OTTUser user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; // login user user = executor.executeSync(login(partnerId, user.getUsername(), defaultUserPassword)).results.getUser(); - } - @Severity(SeverityLevel.CRITICAL) - @Description("ottUser/action/resendActivationToken - resendActivationToken") - @Test(enabled = false) - private void resendActivationTokenTest() { - Response booleanResponse = executor.executeSync(resendActivationToken(partnerId, user.getUsername())); + // resendActivationToken + Response booleanResponse = executor.executeSync(OttUserService.resendActivationToken(partnerId, user.getUsername())); assertThat(booleanResponse.error).isNull(); assertThat(booleanResponse.results.booleanValue()).isTrue(); + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); + // TODO: 4/1/2018 can't be completely tested until we verify emails } } diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserResetPasswordTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserResetPasswordTests.java new file mode 100644 index 000000000..e01eac159 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserResetPasswordTests.java @@ -0,0 +1,64 @@ +package com.kaltura.client.test.tests.servicesTests.ottUserTests; + +import com.kaltura.client.services.OttUserService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.dbUtils.DBUtils; +import com.kaltura.client.types.OTTUser; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.Test; +import org.testng.util.Strings; + +import static com.kaltura.client.services.OttUserService.ResetPasswordOttUserBuilder; +import static com.kaltura.client.services.OttUserService.delete; +import static com.kaltura.client.services.OttUserService.register; +import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; +import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; +import static org.assertj.core.api.Assertions.assertThat; + +public class OttUserResetPasswordTests extends BaseTest { + + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/resetPassword - resetPassword") + @Test() + private void resetPassword() { + // register user + OTTUser user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; + + // assert resetPassword token is null + String resetPasswordToken = DBUtils.getResetPasswordToken(user.getUsername()); + assertThat(resetPasswordToken).isNull(); + + // reset user password + ResetPasswordOttUserBuilder resetPasswordOttUserBuilder = OttUserService.resetPassword(partnerId, user.getUsername()); + Response booleanResponse = executor.executeSync(resetPasswordOttUserBuilder); + + assertThat(booleanResponse.error).isNull(); + assertThat(booleanResponse.results.booleanValue()).isTrue(); + + // assert resetPassword token is not null or empty + resetPasswordToken = DBUtils.getResetPasswordToken(user.getUsername()); + assertThat(Strings.isNotNullAndNotEmpty(resetPasswordToken)).isTrue(); + + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/resetPassword - resetPassword with invalid user - error 2000") + @Test() + private void resetPassword_with_invalid_user() { + // register user + String invalidUsername = "invalidUsername"; + + // reset user password with invalid user + ResetPasswordOttUserBuilder resetPasswordOttUserBuilder = OttUserService.resetPassword(partnerId, invalidUsername); + Response booleanResponse = executor.executeSync(resetPasswordOttUserBuilder); + + assertThat(booleanResponse.results).isNull(); + assertThat(booleanResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(2000).getCode()); + + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserSetInitialPasswordTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserSetInitialPasswordTests.java new file mode 100644 index 000000000..baecf6906 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserSetInitialPasswordTests.java @@ -0,0 +1,104 @@ +package com.kaltura.client.test.tests.servicesTests.ottUserTests; + +import com.kaltura.client.services.OttUserService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.dbUtils.DBUtils; +import com.kaltura.client.types.LoginSession; +import com.kaltura.client.types.OTTUser; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.Test; + +import static com.kaltura.client.services.OttUserService.*; +import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; +import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; +import static org.assertj.core.api.Assertions.assertThat; + +public class OttUserSetInitialPasswordTests extends BaseTest { + + + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/setInitialPassword") + @Test() + private void setInitialPassword() { + // register user + OTTUser user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; + + // reset user password + executor.executeSync(resetPassword(partnerId, user.getUsername())); + + // get resetPassword token + String resetPasswordToken = DBUtils.getResetPasswordToken(user.getUsername()); + + // set initial password + String newPassword = "newPassword"; + SetInitialPasswordOttUserBuilder setInitialPasswordOttUserBuilder = OttUserService.setInitialPassword(partnerId, resetPasswordToken, newPassword); + Response ottUserResponse = executor.executeSync(setInitialPasswordOttUserBuilder); + + assertThat(ottUserResponse.results).isEqualToComparingOnlyGivenFields(user, "username", "email", + "address", "firstName", "lastName", "city", "externalId", "countryId"); + + // login with new password + LoginSession loginSession = executor.executeSync(login(partnerId, user.getUsername(), newPassword)).results.getLoginSession(); + assertThat(loginSession.getKs()).isNotNull(); + + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); + } + + @Severity(SeverityLevel.MINOR) + @Description("ottUser/action/setInitialPassword - invalid resetPassword token") + @Test() + private void setInitialPassword_with_invalid_resetPassword_token() { + // register user + OTTUser user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; + + // reset user password + executor.executeSync(resetPassword(partnerId, user.getUsername())); + + // set initial password with invalid token + String newPassword = "newPassword"; + String invalidToken = "invalidToken"; + + SetInitialPasswordOttUserBuilder setInitialPasswordOttUserBuilder = OttUserService.setInitialPassword(partnerId, invalidToken, newPassword); + Response ottUserResponse = executor.executeSync(setInitialPasswordOttUserBuilder); + + assertThat(ottUserResponse.results).isNull(); + assertThat(ottUserResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(2000).getCode()); + + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); + } + + @Severity(SeverityLevel.NORMAL) + @Description("ottUser/action/setInitialPassword - expired resetPassword token") + @Test() + private void setInitialPassword_with_expired_resetPassword_token() { + // register user + OTTUser user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; + + // reset user password + executor.executeSync(resetPassword(partnerId, user.getUsername())); + + // get resetPassword token + String resetPasswordToken = DBUtils.getResetPasswordToken(user.getUsername()); + + // set initial password - first time + String newPassword = "newPassword"; + + SetInitialPasswordOttUserBuilder setInitialPasswordOttUserBuilder = OttUserService.setInitialPassword(partnerId, resetPasswordToken, newPassword); + executor.executeSync(setInitialPasswordOttUserBuilder); + + // set initial password - second time + Response ottUserResponse = executor.executeSync(setInitialPasswordOttUserBuilder); + + assertThat(ottUserResponse.results).isNull(); + assertThat(ottUserResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(2000).getCode()); + + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); + } + +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserUpdateDynamicDataTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserUpdateDynamicDataTests.java new file mode 100644 index 000000000..5dfbffd50 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserUpdateDynamicDataTests.java @@ -0,0 +1,140 @@ +package com.kaltura.client.test.tests.servicesTests.ottUserTests; + +import com.kaltura.client.services.HouseholdService; +import com.kaltura.client.services.OttUserService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.BaseUtils; +import com.kaltura.client.test.utils.HouseholdUtils; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.Test; + +import static com.kaltura.client.services.OttUserService.*; +import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; +import static org.assertj.core.api.Assertions.assertThat; + +public class OttUserUpdateDynamicDataTests extends BaseTest { + + + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/updateDynamicData - updateDynamicData") + @Test + private void updateDynamicData() { + // register user + OTTUser user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; + + // set dynamic data + String keyString = BaseUtils.getRandomString(); + String valueString = BaseUtils.getRandomString(); + + StringValue value = new StringValue(); + value.setValue(valueString); + + // update user dynamic data + UpdateDynamicDataOttUserBuilder updateDynamicDataOttUserBuilder = OttUserService.updateDynamicData(keyString, value) + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(user.getId())); + Response ottUserDynamicDataResponse = executor.executeSync(updateDynamicDataOttUserBuilder); + + // assert new dynamic data + assertThat(ottUserDynamicDataResponse.error).isNull(); + assertThat(ottUserDynamicDataResponse.results.getKey()).isEqualTo(keyString); + assertThat(ottUserDynamicDataResponse.results.getValue().getValue()).isEqualTo(valueString); + + // get user + Response ottUserResponse = executor.executeSync(OttUserService.get() + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(user.getId()))); + + // assert get user data + assertThat(ottUserResponse.error).isNull(); + assertThat(ottUserResponse.results.getDynamicData()).isNotNull(); + assertThat(ottUserResponse.results.getDynamicData().get(keyString).getValue()).isEqualTo(valueString); + + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/updateDynamicData - with masterUser ks") + @Test + private void updateDynamicData_with_masterUser_ks() { + // set household + int numOfUsers = 1; + int numOfDevices = 1; + Household household = HouseholdUtils.createHousehold(numOfUsers, numOfDevices, false); + String masterUserKs = HouseholdUtils.getHouseholdMasterUserKs(household); + + // set dynamic data + String keyString = BaseUtils.getRandomString(); + String valueString = BaseUtils.getRandomString(); + + StringValue value = new StringValue(); + value.setValue(valueString); + + // update user dynamic data + Response ottUserDynamicDataResponse = + executor.executeSync(OttUserService.updateDynamicData(keyString, value) + .setKs(masterUserKs)); + + // assert new dynamic data + assertThat(ottUserDynamicDataResponse.error).isNull(); + assertThat(ottUserDynamicDataResponse.results.getKey()).isEqualTo(keyString); + assertThat(ottUserDynamicDataResponse.results.getValue().getValue()).isEqualTo(valueString); + + // get user + Response ottUserResponse = executor.executeSync(OttUserService.get() + .setKs(masterUserKs)); + + // assert get user data + assertThat(ottUserResponse.error).isNull(); + assertThat(ottUserResponse.results.getDynamicData()).isNotNull(); + assertThat(ottUserResponse.results.getDynamicData().get(keyString).getValue()).isEqualTo(valueString); + + // cleanup + executor.executeSync(HouseholdService.delete().setKs(masterUserKs)); + } + + @Severity(SeverityLevel.NORMAL) + @Description("ottUser/action/updateDynamicData - with user ks") + @Test + private void updateDynamicData_with_user_ks() { + // set household + int numOfUsers = 1; + int numOfDevices = 1; + Household household = HouseholdUtils.createHousehold(numOfUsers, numOfDevices, false); + String userKs = HouseholdUtils.getHouseholdUserKs(household); + + // set dynamic data + String keyString = BaseUtils.getRandomString(); + String valueString = BaseUtils.getRandomString(); + + StringValue value = new StringValue(); + value.setValue(valueString); + + // update user dynamic data + Response ottUserDynamicDataResponse = + executor.executeSync(OttUserService.updateDynamicData(keyString, value) + .setKs(userKs)); + + // assert new dynamic data + assertThat(ottUserDynamicDataResponse.error).isNull(); + assertThat(ottUserDynamicDataResponse.results.getKey()).isEqualTo(keyString); + assertThat(ottUserDynamicDataResponse.results.getValue().getValue()).isEqualTo(valueString); + + // get user + Response ottUserResponse = executor.executeSync(OttUserService.get() + .setKs(userKs)); + + // assert get user data + assertThat(ottUserResponse.error).isNull(); + assertThat(ottUserResponse.results.getDynamicData()).isNotNull(); + assertThat(ottUserResponse.results.getDynamicData().get(keyString).getValue()).isEqualTo(valueString); + + // cleanup + executor.executeSync(HouseholdService.delete().setKs(userKs)); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/UpdateLoginDataTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserUpdateLoginDataTests.java similarity index 85% rename from src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/UpdateLoginDataTests.java rename to src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserUpdateLoginDataTests.java index 518071c90..4b0a1d356 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/UpdateLoginDataTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserUpdateLoginDataTests.java @@ -1,5 +1,6 @@ package com.kaltura.client.test.tests.servicesTests.ottUserTests; +import com.kaltura.client.services.OttUserService; import com.kaltura.client.test.tests.BaseTest; import com.kaltura.client.types.LoginResponse; import com.kaltura.client.types.OTTUser; @@ -14,14 +15,14 @@ import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; import static org.assertj.core.api.Assertions.assertThat; -public class UpdateLoginDataTests extends BaseTest { +public class OttUserUpdateLoginDataTests extends BaseTest { private Response loginResponse; @Severity(SeverityLevel.CRITICAL) @Description("ottUser/action/updateLoginData - updateLoginData") @Test - private void updateLoginDataTest() { + private void updateLoginData() { // register user OTTUser user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; @@ -31,8 +32,8 @@ private void updateLoginDataTest() { // update user login data String userNewPassword = defaultUserPassword + 1; - UpdateLoginDataOttUserBuilder updateLoginDataOttUserBuilder = updateLoginData(user.getUsername(), defaultUserPassword, userNewPassword) - .setKs(userKs); + UpdateLoginDataOttUserBuilder updateLoginDataOttUserBuilder = OttUserService.updateLoginData(user.getUsername(), defaultUserPassword, userNewPassword) + .setKs(userKs); Response booleanResponse = executor.executeSync(updateLoginDataOttUserBuilder); assertThat(booleanResponse.error).isNull(); @@ -49,6 +50,9 @@ private void updateLoginDataTest() { assertThat(loginResponse.error).isNull(); assertThat(loginResponse.results.getLoginSession().getKs()).isNotNull(); + + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); } @Severity(SeverityLevel.CRITICAL) @@ -63,7 +67,7 @@ private void updateLoginData_with_administratorKs() { // update usser login data String userNewPassword = defaultUserPassword + 2; - UpdateLoginDataOttUserBuilder updateLoginDataOttUserBuilder = updateLoginData(user.getUsername(), defaultUserPassword, userNewPassword) + UpdateLoginDataOttUserBuilder updateLoginDataOttUserBuilder = OttUserService.updateLoginData(user.getUsername(), defaultUserPassword, userNewPassword) .setKs(getAdministratorKs()); Response booleanResponse = executor.executeSync(updateLoginDataOttUserBuilder); @@ -81,5 +85,8 @@ private void updateLoginData_with_administratorKs() { assertThat(loginResponse.error).isNull(); assertThat(loginResponse.results.getLoginSession().getKs()).isNotNull(); + + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); } } diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserUpdatePasswordTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserUpdatePasswordTests.java new file mode 100644 index 000000000..895988708 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserUpdatePasswordTests.java @@ -0,0 +1,46 @@ +package com.kaltura.client.test.tests.servicesTests.ottUserTests; + +import com.kaltura.client.services.OttUserService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.types.LoginResponse; +import com.kaltura.client.types.OTTUser; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.Test; + +import static com.kaltura.client.services.OttUserService.*; +import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; +import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; +import static org.assertj.core.api.Assertions.assertThat; + +public class OttUserUpdatePasswordTests extends BaseTest { + + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/updateLoginData - updateLoginData") + @Test + private void updatePassword() { + // register user + OTTUser user = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)).results; + + // update password + String newPassword = "newPassword"; + UpdatePasswordOttUserBuilder updatePasswordOttUserBuilder = OttUserService.updatePassword(Integer.parseInt(user.getId()), newPassword); + updatePasswordOttUserBuilder.setKs(getAdministratorKs()); + executor.executeSync(updatePasswordOttUserBuilder); + + // login with old password + Response loginResponse = executor.executeSync(login(partnerId, user.getUsername(), defaultUserPassword)); + assertThat(loginResponse.results).isNull(); + assertThat(loginResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(1011).getCode()); + + // login with new password + loginResponse = executor.executeSync(login(partnerId, user.getUsername(), newPassword)); + assertThat(loginResponse.error).isNull(); + assertThat(loginResponse.results.getLoginSession().getKs()).isNotNull(); + + // cleanup + executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserUpdateTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserUpdateTests.java new file mode 100644 index 000000000..f7f2696df --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/OttUserUpdateTests.java @@ -0,0 +1,111 @@ +package com.kaltura.client.test.tests.servicesTests.ottUserTests; + +import com.kaltura.client.services.HouseholdService; +import com.kaltura.client.services.OttUserService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.HouseholdUtils; +import com.kaltura.client.test.utils.OttUserUtils; +import com.kaltura.client.types.Household; +import com.kaltura.client.types.HouseholdUser; +import com.kaltura.client.types.OTTUser; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Issue; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import static com.kaltura.client.services.OttUserService.get; +import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; +import static org.assertj.core.api.Assertions.assertThat; + + +public class OttUserUpdateTests extends BaseTest { + + private OTTUser user; + private String userKs; + + @BeforeClass + private void ottUser_updateTests_beforeClass() { + // set household + int numOfUsersInHousehold = 2; + int numOfDevicesInHousehold = 1; + Household household = HouseholdUtils.createHousehold(numOfUsersInHousehold, numOfDevicesInHousehold, true); + HouseholdUser householdUser = HouseholdUtils.getMasterUser(household); + userKs = OttUserUtils.getKs(Integer.parseInt(householdUser.getUserId())); + + // get ottUser + user = executor.executeSync(get().setKs(userKs)).results; + } + + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/update - update") + @Issue("BEO-5168") + @Issue("BEO-5169") + @Test(enabled = false) + private void update() { + // update user info + String newUserInfo = "newUserInfo"; + OTTUser updatedUser = new OTTUser(); + updatedUser.setFirstName(newUserInfo); + updatedUser.setLastName(newUserInfo); + updatedUser.setAddress(newUserInfo); + + updatedUser = executor.executeSync(OttUserService.update(updatedUser) + .setKs(userKs)) + .results; + + // assert user new info + assertThat(updatedUser.getFirstName()).isEqualTo(newUserInfo); + assertThat(updatedUser.getLastName()).isEqualTo(newUserInfo); + assertThat(updatedUser.getAddress()).isEqualTo(newUserInfo); + assertThat(updatedUser).isEqualToIgnoringGivenFields(user, "firstName", "lastName", "address"); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("ottUser/action/update - with administratorKs") + @Issue("BEO-5168") + @Issue("BEO-5169") + @Test(enabled = false) + private void update_with_administratorKs() { + // update user info + String newUserInfo = "newUserInfo"; + OTTUser updatedUser = new OTTUser(); + updatedUser.setFirstName(newUserInfo); + updatedUser.setLastName(newUserInfo); + updatedUser.setAddress(newUserInfo); + + updatedUser = executor.executeSync(OttUserService.update(updatedUser) + .setKs(getAdministratorKs()) + .setUserId(Integer.valueOf(user.getId()))) + .results; + + // assert user new info + assertThat(updatedUser.getFirstName()).isEqualTo(newUserInfo); + assertThat(updatedUser.getLastName()).isEqualTo(newUserInfo); + assertThat(updatedUser.getAddress()).isEqualTo(newUserInfo); + assertThat(updatedUser).isEqualToIgnoringGivenFields(user, "firstName", "lastName", "address"); + } + + @Severity(SeverityLevel.NORMAL) + @Description("ottUser/action/update - update user externalId - error 500051") + @Test(enabled = true) + private void update_user_externalId() { + // update user externalId + String newExternalId = "newExternalId"; + OTTUser updatedUser = new OTTUser(); + updatedUser.setExternalId(newExternalId); + + Response ottUserResponse = executor.executeSync(OttUserService.update(updatedUser).setKs(userKs)); + assertThat(ottUserResponse.results).isNull(); + assertThat(ottUserResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500051).getCode()); + } + + @AfterClass + private void ottUser_updateTests_afterClass() { + // cleanup - delete household + executor.executeSync(HouseholdService.delete().setKs(userKs)); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/RegisterTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/RegisterTests.java deleted file mode 100644 index 6c5f4fb37..000000000 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/RegisterTests.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.kaltura.client.test.tests.servicesTests.ottUserTests; - -import com.kaltura.client.test.tests.BaseTest; -import com.kaltura.client.types.OTTUser; -import com.kaltura.client.utils.response.base.Response; -import io.qameta.allure.Description; -import io.qameta.allure.Severity; -import io.qameta.allure.SeverityLevel; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import static com.kaltura.client.services.OttUserService.register; -import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; -import static org.assertj.core.api.Assertions.assertThat; - -public class RegisterTests extends BaseTest { - - private OTTUser user; - private Response ottUserResponse; - - @BeforeClass - private void ottUser_login_tests_setup() { - user = generateOttUser(); - } - - @Severity(SeverityLevel.CRITICAL) - @Description("ottUser/action/register - register") - @Test - private void registerTest() { - ottUserResponse = executor.executeSync(register(partnerId, user, defaultUserPassword)); - - assertThat(ottUserResponse.error).isNull(); - assertThat(ottUserResponse.results.getUsername()).isEqualTo(user.getUsername()); - // TODO: 3/28/2018 add relevant assertions - } - - // TODO: 3/29/2018 add relevant scenarios -} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/ResetPasswordTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/ResetPasswordTests.java deleted file mode 100644 index 8a23ae50a..000000000 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/ResetPasswordTests.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.kaltura.client.test.tests.servicesTests.ottUserTests; - -import com.kaltura.client.test.tests.BaseTest; -import com.kaltura.client.types.OTTUser; -import com.kaltura.client.utils.response.base.Response; -import io.qameta.allure.Description; -import io.qameta.allure.Severity; -import io.qameta.allure.SeverityLevel; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import static com.kaltura.client.services.OttUserService.*; -import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; -import static org.assertj.core.api.Assertions.assertThat; - -public class ResetPasswordTests extends BaseTest { - - private OTTUser user; - - @BeforeClass - private void ottUser_resetPassword_tests_setup() { - // register user - Response ottUserResponse = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)); - user = ottUserResponse.results; - } - - @Severity(SeverityLevel.CRITICAL) - @Description("ottUser/action/resetPassword - resetPassword") - @Test(enabled = false) - private void resetPasswordTest() { - // reset user password - ResetPasswordOttUserBuilder resetPasswordOttUserBuilder = resetPassword(partnerId, user.getUsername()) - .setKs(getAdministratorKs()); - Response booleanResponse = executor.executeSync(resetPasswordOttUserBuilder); - - // assert success - assertThat(booleanResponse.error).isNull(); - assertThat(booleanResponse.results.booleanValue()).isTrue(); - - // TODO: 4/1/2018 finsih the test after bug BEO-4884 will be fixed - } -} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/SetInitialPasswordTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/SetInitialPasswordTests.java deleted file mode 100644 index 82c075a04..000000000 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/SetInitialPasswordTests.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.kaltura.client.test.tests.servicesTests.ottUserTests; - -import com.kaltura.client.test.tests.BaseTest; - -public class SetInitialPasswordTests extends BaseTest { - - // TODO: 4/1/2018 implemente tests -} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/UpdateDynamicDataTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/UpdateDynamicDataTests.java deleted file mode 100644 index 67063a3aa..000000000 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/UpdateDynamicDataTests.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.kaltura.client.test.tests.servicesTests.ottUserTests; - -import com.kaltura.client.test.tests.BaseTest; -import com.kaltura.client.types.OTTUser; -import com.kaltura.client.types.OTTUserDynamicData; -import com.kaltura.client.types.StringValue; -import com.kaltura.client.utils.response.base.Response; -import io.qameta.allure.Description; -import io.qameta.allure.Severity; -import io.qameta.allure.SeverityLevel; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import static com.kaltura.client.services.OttUserService.*; -import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; -import static org.assertj.core.api.Assertions.assertThat; - -public class UpdateDynamicDataTests extends BaseTest { - - private OTTUser user; - - @BeforeClass - private void ottUser_updateDynamicData_tests_setup() { - // register user - Response ottUserResponse = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)); - user = ottUserResponse.results; - } - - @Severity(SeverityLevel.CRITICAL) - @Description("ottUser/action/updateDynamicData - updateDynamicData") - @Test - private void updateDynamicDataTest() { - // set dynamic data - String keyString = "key1"; - String valueString = "value1"; - - StringValue value = new StringValue(); - value.setValue(valueString); - - // update user dynamic data - UpdateDynamicDataOttUserBuilder updateDynamicDataOttUserBuilder = updateDynamicData(keyString, value) - .setKs(getAdministratorKs()) - .setUserId(Integer.valueOf(user.getId())); - Response ottUserDynamicDataResponse = executor.executeSync(updateDynamicDataOttUserBuilder); - - // assert new dynamic data - assertThat(ottUserDynamicDataResponse.error).isNull(); - assertThat(ottUserDynamicDataResponse.results.getKey()).isEqualTo(keyString); - assertThat(ottUserDynamicDataResponse.results.getValue().getValue()).isEqualTo(valueString); - } -} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/UpdatePasswordTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/UpdatePasswordTests.java deleted file mode 100644 index a3ade05e3..000000000 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/UpdatePasswordTests.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.kaltura.client.test.tests.servicesTests.ottUserTests; - -import com.kaltura.client.test.tests.BaseTest; - -public class UpdatePasswordTests extends BaseTest { - // TODO: 4/1/2018 implement tests -} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/UpdateTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/UpdateTests.java deleted file mode 100644 index 2c87ab74f..000000000 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/ottUserTests/UpdateTests.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.kaltura.client.test.tests.servicesTests.ottUserTests; - -import com.kaltura.client.test.tests.BaseTest; -import com.kaltura.client.types.LoginResponse; -import com.kaltura.client.types.OTTUser; -import com.kaltura.client.utils.response.base.Response; -import io.qameta.allure.Description; -import io.qameta.allure.Issue; -import io.qameta.allure.Severity; -import io.qameta.allure.SeverityLevel; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import static com.kaltura.client.services.OttUserService.*; -import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; -import static org.assertj.core.api.Assertions.assertThat; - - -public class UpdateTests extends BaseTest { - - private OTTUser user; - private String originalUserEmail; - - private Response ottUserResponse; - - @BeforeClass - private void ottUser_update_tests_setup() { - // register user - ottUserResponse = executor.executeSync(register(partnerId, generateOttUser(), defaultUserPassword)); - user = ottUserResponse.results; - originalUserEmail = user.getEmail(); - } - - @Severity(SeverityLevel.CRITICAL) - @Description("ottUser/action/update - update") - @Test - private void updateTest() { - // login user - Response loginResponse = executor.executeSync(login(partnerId, user.getUsername(), defaultUserPassword)); - String userKs = loginResponse.results.getLoginSession().getKs(); - - // update user info - String newUserInfo = "abc"; - user.setFirstName(newUserInfo); - user.setLastName(newUserInfo); - - ottUserResponse = executor.executeSync(update(user).setKs(userKs)); - assertThat(ottUserResponse.error).isNull(); - - // get user after update - ottUserResponse = executor.executeSync(get().setKs(userKs)); - user = ottUserResponse.results; - - // assert user new info - assertThat(ottUserResponse.error).isNull(); - assertThat(user.getFirstName()).isEqualTo(newUserInfo); - assertThat(user.getLastName()).isEqualTo(newUserInfo); - assertThat(user.getEmail()).isEqualTo(originalUserEmail); - } - - @Severity(SeverityLevel.CRITICAL) - @Description("ottUser/action/update - update with administratorKs") - @Issue("BEO-4919") - @Test(enabled = true) - private void update_with_administratorKs() { - - // update user info - String newUserInfo = "def"; - user.setFirstName(newUserInfo); - user.setLastName(newUserInfo); -// user.setAffiliateCode(null); - - ottUserResponse = executor.executeSync(update(user).setKs(getAdministratorKs())); - assertThat(ottUserResponse.error).isNull(); - - // get user after update - ottUserResponse = executor.executeSync(get().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); - user = ottUserResponse.results; - - // assert user new info - assertThat(ottUserResponse.error).isNull(); - assertThat(user.getFirstName()).isEqualTo(newUserInfo); - assertThat(user.getLastName()).isEqualTo(newUserInfo); - assertThat(user.getEmail()).isEqualTo(originalUserEmail); - } - - @AfterClass - private void ottUser_update_tests_tearDown() { - executor.executeSync(delete().setKs(getAdministratorKs()).setUserId(Integer.valueOf(user.getId()))); - } -} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/productPriceTests/ListTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/productPriceTests/ListTests.java deleted file mode 100644 index d2637e77e..000000000 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/productPriceTests/ListTests.java +++ /dev/null @@ -1,239 +0,0 @@ -package com.kaltura.client.test.tests.servicesTests.productPriceTests; - -import com.kaltura.client.enums.*; -import com.kaltura.client.services.EntitlementService; -import com.kaltura.client.services.EntitlementService.ListEntitlementBuilder; -import com.kaltura.client.services.ProductPriceService; -import com.kaltura.client.services.ProductPriceService.ListProductPriceBuilder; -import com.kaltura.client.test.tests.BaseTest; -import com.kaltura.client.test.utils.HouseholdUtils; -import com.kaltura.client.test.utils.OttUserUtils; -import com.kaltura.client.test.utils.PurchaseUtils; -import com.kaltura.client.types.*; -import com.kaltura.client.utils.response.base.Response; -import io.qameta.allure.Description; -import io.qameta.allure.Severity; -import io.qameta.allure.SeverityLevel; -import org.hamcrest.MatcherAssert; -import org.hamcrest.Matchers; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import java.util.Optional; -import static com.kaltura.client.test.IngestConstants.CURRENCY_EUR; -import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; -import static org.assertj.core.api.Assertions.assertThat; - -public class ListTests extends BaseTest { - - private EntitlementFilter entitlementPpvsFilter; - private EntitlementFilter entitlementSubsFilter; - private Household household; - private String classMasterUserKs; - - private Response> productPriceResponse; - private Response> entitlementResponse; - - @BeforeClass - public void beforeClass() { - - entitlementPpvsFilter = new EntitlementFilter(); - entitlementPpvsFilter.setOrderBy(EntitlementOrderBy.PURCHASE_DATE_ASC.getValue()); - entitlementPpvsFilter.setProductTypeEqual(TransactionType.PPV); - entitlementPpvsFilter.setEntityReferenceEqual(EntityReferenceBy.HOUSEHOLD); - entitlementPpvsFilter.setIsExpiredEqual(false); - - entitlementSubsFilter = new EntitlementFilter(); - entitlementSubsFilter.setOrderBy(EntitlementOrderBy.PURCHASE_DATE_ASC.getValue()); - entitlementSubsFilter.setProductTypeEqual(TransactionType.SUBSCRIPTION); - entitlementSubsFilter.setEntityReferenceEqual(EntityReferenceBy.HOUSEHOLD); - entitlementSubsFilter.setIsExpiredEqual(false); - - /*Ppv ppv = IngestUtils.ingestPPV(INGEST_ACTION_INSERT, true, "My ingest PPV", getProperty(FIFTY_PERCENTS_ILS_DISCOUNT_NAME), - Double.valueOf(getProperty(PRICE_CODE_AMOUNT_4_99)), CURRENCY_EUR, getProperty(DEFAULT_USAGE_MODULE_4_INGEST_PPV), false, false, - getProperty(DEFAULT_PRODUCT_CODE), getProperty(WEB_FILE_TYPE), getProperty(MOBILE_FILE_TYPE));*/ - - /*Response> ingestedProgrammes = IngestUtils.ingestEPG("Shmulik_Series_1", Optional.of(2), Optional.empty(), Optional.of(30), - Optional.of("minutes"), Optional.empty(), Optional.of(1), Optional.empty(), Optional.empty(), Optional.empty()); - System.out.println("ID:" + ingestedProgrammes.results.getObjects().get(0).getId());*/ - - int numberOfUsers = 2; - int numberOfDevices = 1; - household = HouseholdUtils.createHousehold(numberOfUsers, numberOfDevices, true); - classMasterUserKs = HouseholdUtils.getHouseholdUserKs(household, HouseholdUtils.getDevicesListFromHouseHold(household).get(0).getUdid()); - - } - - @Severity(SeverityLevel.NORMAL) - @Description("productPrice/action/list - subscription test by Operator without currency") - @Test(enabled = false) // as used in feature tests - public void listSubscription() { - ProductPriceFilter filter = new ProductPriceFilter(); - filter.setSubscriptionIdIn(get5MinRenewableSubscription().getId()); - - ListProductPriceBuilder productPriceList = ProductPriceService.list(filter); - productPriceResponse = executor.executeSync(productPriceList); - assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualToIgnoringCase(get5MinRenewableSubscription().getId().trim()); - assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); - assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()).isGreaterThan(0); - } - - @Severity(SeverityLevel.NORMAL) - @Description("productPrice/action/list - subscription test with currency by Operator") - @Test() - public void listSubscriptionWithCurrencyTest() { - ProductPriceFilter filter = new ProductPriceFilter(); - filter.setSubscriptionIdIn(get5MinRenewableSubscription().getId()); - productPriceResponse = executor.executeSync(ProductPriceService.list(filter).setCurrency(CURRENCY_EUR).setKs(getOperatorKs())); - // TODO: should we create ENUMs for currencies? A: Yes if library doesn't contain them - assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualToIgnoringCase(get5MinRenewableSubscription().getId().trim()); - assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); - assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()).isGreaterThan(0); - assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()).isEqualTo(CURRENCY_EUR); - } - - @Severity(SeverityLevel.MINOR) - @Description("productPrice/action/list - without required fields (subscriptionIdIn, collectionIdIn and fileIdIn are empty)") - @Test() - public void listWithoutRequiredFields() { - ProductPriceFilter filter = new ProductPriceFilter(); - ListProductPriceBuilder productPriceList = ProductPriceService.list(filter); - productPriceResponse = executor.executeSync(productPriceList.setKs(getOperatorKs())); - - int errorCode = 500056; - assertThat(productPriceResponse.results).isNull(); - assertThat(productPriceResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(errorCode).getCode()); - assertThat(productPriceResponse.error.getMessage()).isEqualToIgnoringCase( - "One of the arguments [KalturaProductPriceFilter.subscriptionIdIn, KalturaProductPriceFilter.fileIdIn, KalturaProductPriceFilter.collectionIdIn] must have a value"); - } - - @Severity(SeverityLevel.CRITICAL) - @Description("productPrice/action/list - ppv test") - @Test() - public void ppvTest() { - // TODO: after fix of BEO-4967 change HouseholdDevice.json to have only 1 enum value in objectType - - ListEntitlementBuilder entitlementListBeforePurchase = EntitlementService.list(entitlementPpvsFilter, null); - entitlementResponse = executor.executeSync(entitlementListBeforePurchase.setKs(classMasterUserKs)); - assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(0); - - ProductPriceFilter ppFilter = new ProductPriceFilter(); - int webMediaFileId = getSharedMediaAsset().getMediaFiles().get(0).getId(); - int mobileMediaFileId = getSharedMediaAsset().getMediaFiles().get(1).getId(); - ppFilter.setFileIdIn(String.valueOf(webMediaFileId)); - ppFilter.setIsLowest(false); - ListProductPriceBuilder productPriceListBeforePurchase = ProductPriceService.list(ppFilter); - productPriceResponse = executor.executeSync(productPriceListBeforePurchase.setKs(classMasterUserKs)); - // TODO: 4/8/2018 talk with Max about the assertions (currently it not asserting nothing as only actual was implemented) - assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); - assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); - assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.PPV); - assertThat(((PpvPrice)productPriceResponse.results.getObjects().get(0)).getFileId()).isEqualTo(webMediaFileId); - - PurchaseUtils.purchasePpv(classMasterUserKs, Optional.empty(), Optional.of(webMediaFileId), null); - - ListEntitlementBuilder entitlementListAfterPurchase = EntitlementService.list(entitlementPpvsFilter, null); - entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(classMasterUserKs)); - assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(1); - assertThat(((PpvEntitlement) entitlementResponse.results.getObjects().get(0)).getMediaFileId()).isEqualTo(webMediaFileId); - assertThat(((PpvEntitlement) entitlementResponse.results.getObjects().get(0)).getMediaId()).isEqualTo(getSharedMediaAsset().getId().intValue()); - assertThat(entitlementResponse.results.getObjects().get(0).getEndDate()) - .isGreaterThan(entitlementResponse.results.getObjects().get(0).getCurrentDate()); - assertThat(entitlementResponse.results.getObjects().get(0).getPaymentMethod()).isIn(PaymentMethodType.OFFLINE, PaymentMethodType.UNKNOWN); - - ListProductPriceBuilder productPriceListAfterPurchase = ProductPriceService.list(ppFilter); - productPriceResponse = executor.executeSync(productPriceListAfterPurchase.setKs(classMasterUserKs)); - // only 1 item mention in filter - assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); - assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.PPV_PURCHASED); - assertThat(((PpvPrice) productPriceResponse.results.getObjects().get(0)).getFileId()).isEqualTo(webMediaFileId); - - ppFilter.setFileIdIn(String.valueOf(mobileMediaFileId)); - ListProductPriceBuilder productPriceListAfterPurchaseForAnotherFileFromTheSameMedia = ProductPriceService.list(ppFilter); - productPriceResponse = executor.executeSync(productPriceListAfterPurchaseForAnotherFileFromTheSameMedia.setKs(classMasterUserKs)); - assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); - assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.PPV_PURCHASED); - assertThat(((PpvPrice) productPriceResponse.results.getObjects().get(0)).getFileId()).isEqualTo(mobileMediaFileId); - } - - @Severity(SeverityLevel.NORMAL) - @Description("productPrice/action/list - common test for PPV and subscription to check before purchase") - @Test() - public void productPriceSubscriptionAndPpvBeforePurchaseTest() { - int numberOfUsers = 1; - int numberOfDevices = 1; - Household household = HouseholdUtils.createHousehold(numberOfUsers, numberOfDevices, true); - HouseholdUser masterUser = HouseholdUtils.getMasterUserFromHousehold(household); - - ProductPriceFilter filter = new ProductPriceFilter(); - filter.setSubscriptionIdIn(get5MinRenewableSubscription().getId()); - filter.setFileIdIn(String.valueOf(getSharedWebMediaFile().getId())); - filter.setIsLowest(false); - ListProductPriceBuilder productPriceListBeforePurchase = ProductPriceService.list(filter) - .setKs(OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId()), null)); - productPriceResponse = executor.executeSync(productPriceListBeforePurchase); - // should be 2 ss one item is subscription an another is media file - assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(2); - assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); - assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.SUBSCRIPTION); - assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualToIgnoringCase(get5MinRenewableSubscription().getId().trim()); - assertThat(productPriceResponse.results.getObjects().get(1).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); - assertThat(productPriceResponse.results.getObjects().get(1).getProductType()).isEqualTo(TransactionType.PPV); - assertThat(((PpvPrice) productPriceResponse.results.getObjects().get(1)).getFileId()).isEqualTo(getSharedWebMediaFile().getId()); - } - - @Severity(SeverityLevel.CRITICAL) - @Description("productPrice/action/list - subscription test") - @Test(enabled = false) // as not completed - public void subscriptionTest() { - String sharedWebMediaFileId = String.valueOf(getSharedWebMediaFile().getId()); - - // TODO: 3/7/2018 add remarks when possible such as below - show to Shmulik / Michael and see if test is clear - ListEntitlementBuilder entitlementListBeforePurchase = EntitlementService.list(entitlementSubsFilter, null); - entitlementResponse = executor.executeSync(entitlementListBeforePurchase); - assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(0); - - ProductPriceFilter ppFilter = new ProductPriceFilter(); - ppFilter.setSubscriptionIdIn(get5MinRenewableSubscription().getId().trim()); - ppFilter.setIsLowest(false); - ListProductPriceBuilder productPriceListBeforePurchase = ProductPriceService.list(ppFilter); - productPriceResponse = executor.executeSync(productPriceListBeforePurchase); - assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); - assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); - assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.SUBSCRIPTION); - assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualTo(get5MinRenewableSubscription().getId().trim()); - - ListProductPriceBuilder productPriceListBeforePurchase4Anonymous = ProductPriceService.list(ppFilter); - productPriceResponse = executor.executeSync(productPriceListBeforePurchase4Anonymous); - assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); - assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); - assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.SUBSCRIPTION); - assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualTo(get5MinRenewableSubscription().getId().trim()); - - //PurchaseUtils.purchaseSubscription(client, Integer.valueOf(get5MinRenewableSubscription().getId().trim())); - - ListEntitlementBuilder entitlementListAfterPurchase = EntitlementService.list(entitlementSubsFilter, null); - entitlementResponse = executor.executeSync(entitlementListAfterPurchase); - assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(1); - assertThat(entitlementResponse.results.getObjects().get(0).getProductId()).isEqualToIgnoringCase(get5MinRenewableSubscription().getId().trim()); - assertThat(entitlementResponse.results.getObjects().get(0).getEndDate()).isGreaterThan( - entitlementResponse.results.getObjects().get(0).getCurrentDate()); - MatcherAssert.assertThat(entitlementResponse.results.getObjects().get(0).getPaymentMethod(), - Matchers.anyOf(Matchers.is(PaymentMethodType.OFFLINE), Matchers.is(PaymentMethodType.UNKNOWN))); - - ppFilter.setFileIdIn(sharedWebMediaFileId); - ListProductPriceBuilder productPriceListAfterPurchase = ProductPriceService.list(ppFilter); - productPriceResponse = executor.executeSync(productPriceListAfterPurchase); - - assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(2); - assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.SUBSCRIPTION_PURCHASED); - assertThat(productPriceResponse.results.getObjects().get(1).getPurchaseStatus()).isEqualTo(PurchaseStatus.SUBSCRIPTION_PURCHASED); - // TODO: should we use ENUM containing subs of KalturaProductPrice class such as: KalturaCollectionPrice, KalturaPpvPrice, KalturaSubscriptionPrice??? - // that logic can't be checked by schema as schema can't check that exactly 1st item is Subscription and 2nd one is PPV - assertThat(productPriceResponse.results.getObjects().get(0).getClass().getSimpleName()).isEqualToIgnoringCase("SubscriptionPrice"); - assertThat(productPriceResponse.results.getObjects().get(1).getClass().getSimpleName()).isEqualToIgnoringCase("PpvPrice"); - assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.SUBSCRIPTION); - assertThat(productPriceResponse.results.getObjects().get(1).getProductType()).isEqualTo(TransactionType.PPV); - assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualToIgnoringCase(get5MinRenewableSubscription().getId().trim()); - assertThat(((PpvPrice) productPriceResponse.results.getObjects().get(1)).getFileId()).isEqualTo(sharedWebMediaFileId); - } -} \ No newline at end of file diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/productPriceTests/ProductPriceListTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/productPriceTests/ProductPriceListTests.java new file mode 100644 index 000000000..01bb52b2f --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/productPriceTests/ProductPriceListTests.java @@ -0,0 +1,780 @@ +package com.kaltura.client.test.tests.servicesTests.productPriceTests; + +import com.kaltura.client.enums.*; +import com.kaltura.client.services.*; +import com.kaltura.client.services.AssetService.ListAssetBuilder; +import com.kaltura.client.services.ChannelService.DeleteChannelBuilder; +import com.kaltura.client.services.EntitlementService.ListEntitlementBuilder; +import com.kaltura.client.services.ProductPriceService.ListProductPriceBuilder; +import com.kaltura.client.services.TransactionHistoryService.ListTransactionHistoryBuilder; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.HouseholdUtils; +import com.kaltura.client.test.utils.OttUserUtils; +import com.kaltura.client.test.utils.PurchaseUtils; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.hamcrest.MatcherAssert; +import org.hamcrest.Matchers; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.Optional; + +import static com.kaltura.client.services.ChannelService.add; +import static com.kaltura.client.services.HouseholdService.delete; +import static com.kaltura.client.test.Properties.*; +import static com.kaltura.client.test.tests.enums.Currency.*; +import static com.kaltura.client.test.utils.BaseUtils.*; +import static com.kaltura.client.test.utils.ingestUtils.IngestMppUtils.*; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.*; +import static org.assertj.core.api.Assertions.assertThat; + +public class ProductPriceListTests extends BaseTest { + + private EntitlementFilter entitlementPpvsFilter; + private EntitlementFilter entitlementSubsFilter; + private TransactionHistoryFilter transactionHistoryFilter; + private Household household; + private String classMasterUserKs; + private String classMasterUserId; + private DynamicChannel sharedChannel; + private Subscription subscriptionWithMultiCurrenciesAndDiscountPercentage; + + private Response> productPriceResponse; + private Response> entitlementResponse; + private Response> listBillingTransactionResponse; + + @BeforeClass + public void beforeClass() { + entitlementPpvsFilter = new EntitlementFilter(); + entitlementPpvsFilter.setOrderBy(EntitlementOrderBy.PURCHASE_DATE_ASC.getValue()); + entitlementPpvsFilter.setProductTypeEqual(TransactionType.PPV); + entitlementPpvsFilter.setEntityReferenceEqual(EntityReferenceBy.HOUSEHOLD); + entitlementPpvsFilter.setIsExpiredEqual(false); + + entitlementSubsFilter = new EntitlementFilter(); + entitlementSubsFilter.setOrderBy(EntitlementOrderBy.PURCHASE_DATE_ASC.getValue()); + entitlementSubsFilter.setProductTypeEqual(TransactionType.SUBSCRIPTION); + entitlementSubsFilter.setEntityReferenceEqual(EntityReferenceBy.HOUSEHOLD); + entitlementSubsFilter.setIsExpiredEqual(false); + + transactionHistoryFilter = new TransactionHistoryFilter(); + transactionHistoryFilter.setEntityReferenceEqual(EntityReferenceBy.HOUSEHOLD); + transactionHistoryFilter.setStartDateGreaterThanOrEqual(0); + + int numberOfUsers = 2; + int numberOfDevices = 1; + household = HouseholdUtils.createHousehold(numberOfUsers, numberOfDevices, true); + classMasterUserKs = HouseholdUtils.getHouseholdUserKs(household, HouseholdUtils.getDevicesList(household).get(0).getUdid()); + classMasterUserId = HouseholdUtils.getMasterUser(household).getUserId(); + + sharedChannel = new DynamicChannel(); + sharedChannel.setMultilingualName(setTranslationToken(getRandomValue("Channel_"))); + sharedChannel.setMultilingualDescription(setTranslationToken("Description of " + sharedChannel.getName())); + sharedChannel.setIsActive(true); + sharedChannel.setAssetTypes(null); + sharedChannel.setSystemName(sharedChannel.getMultilingualName().get(0).getValue() + "_" + getEpoch()); + + MppData mppData = new MppData() + .isRenewable(true) + .pricePlanCode1(PRICE_PLAN_WITH_MULTI_CURRENCIES_AND_DISCOUNT_PERCENTS); + subscriptionWithMultiCurrenciesAndDiscountPercentage = insertMpp(mppData); + } + + @Severity(SeverityLevel.NORMAL) + @Description("productPrice/action/list - subscription test by Operator without currency") + @Test(enabled = false) // as used in feature tests + public void listSubscriptionTest() { + ProductPriceFilter filter = new ProductPriceFilter(); + filter.setSubscriptionIdIn(get5MinRenewableSubscription().getId()); + + ListProductPriceBuilder productPriceList = ProductPriceService.list(filter); + productPriceResponse = executor.executeSync(productPriceList.setKs(getOperatorKs())); + assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualToIgnoringCase(get5MinRenewableSubscription().getId().trim()); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()).isGreaterThan(0); + } + + @Severity(SeverityLevel.NORMAL) + @Description("productPrice/action/list - subscription test with currency by Operator") + @Test() + public void listSubscriptionWithCurrencyTest() { + ProductPriceFilter filter = new ProductPriceFilter(); + filter.setSubscriptionIdIn(get5MinRenewableSubscription().getId()); + productPriceResponse = executor.executeSync(ProductPriceService.list(filter).setCurrency(EUR.getValue()).setKs(getOperatorKs())); + assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualToIgnoringCase(get5MinRenewableSubscription().getId().trim()); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()).isGreaterThan(0); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()).isEqualTo(EUR.getValue()); + } + + @Severity(SeverityLevel.MINOR) + @Description("productPrice/action/list - without required fields (subscriptionIdIn, collectionIdIn and fileIdIn are empty)") + @Test() + public void listWithoutRequiredFieldsTest() { + ProductPriceFilter filter = new ProductPriceFilter(); + ListProductPriceBuilder productPriceList = ProductPriceService.list(filter); + productPriceResponse = executor.executeSync(productPriceList.setKs(getOperatorKs())); + + int errorCode = 500056; + assertThat(productPriceResponse.results).isNull(); + assertThat(productPriceResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(errorCode).getCode()); + assertThat(productPriceResponse.error.getMessage()).isEqualToIgnoringCase( + "One of the arguments [KalturaProductPriceFilter.subscriptionIdIn, KalturaProductPriceFilter.fileIdIn, KalturaProductPriceFilter.collectionIdIn] must have a value"); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("productPrice/action/list - ppv test") + @Test + public void ppvTest() { + // TODO: after fix of BEO-4967 change HouseholdDevice.json to have only 1 enum value in objectType + ListEntitlementBuilder entitlementListBeforePurchase = EntitlementService.list(entitlementPpvsFilter, null); + entitlementResponse = executor.executeSync(entitlementListBeforePurchase.setKs(classMasterUserKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(0); + + ProductPriceFilter ppFilter = new ProductPriceFilter(); + int webMediaFileId = getSharedMediaAsset().getMediaFiles().get(0).getId(); + int mobileMediaFileId = getSharedMediaAsset().getMediaFiles().get(1).getId(); + ppFilter.setFileIdIn(String.valueOf(webMediaFileId)); + ppFilter.setIsLowest(false); + ListProductPriceBuilder productPriceListBeforePurchase = ProductPriceService.list(ppFilter); + productPriceResponse = executor.executeSync(productPriceListBeforePurchase.setKs(classMasterUserKs)); + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.PPV); + assertThat(((PpvPrice)productPriceResponse.results.getObjects().get(0)).getFileId()).isEqualTo(webMediaFileId); + + PurchaseUtils.purchasePpv(classMasterUserKs, Optional.empty(), Optional.of(webMediaFileId), Optional.empty()); + + ListEntitlementBuilder entitlementListAfterPurchase = EntitlementService.list(entitlementPpvsFilter, null); + entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(classMasterUserKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(1); + assertThat(((PpvEntitlement) entitlementResponse.results.getObjects().get(0)).getMediaFileId()).isEqualTo(webMediaFileId); + assertThat(((PpvEntitlement) entitlementResponse.results.getObjects().get(0)).getMediaId()).isEqualTo(Math.toIntExact(getSharedMediaAsset().getId())); + assertThat(entitlementResponse.results.getObjects().get(0).getEndDate()) + .isGreaterThan(entitlementResponse.results.getObjects().get(0).getCurrentDate()); + assertThat(entitlementResponse.results.getObjects().get(0).getPaymentMethod()).isIn(PaymentMethodType.OFFLINE, PaymentMethodType.UNKNOWN); + + ListProductPriceBuilder productPriceListAfterPurchase = ProductPriceService.list(ppFilter); + productPriceResponse = executor.executeSync(productPriceListAfterPurchase.setKs(classMasterUserKs)); + // only 1 item mention in filter + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.PPV_PURCHASED); + assertThat(((PpvPrice) productPriceResponse.results.getObjects().get(0)).getFileId()).isEqualTo(webMediaFileId); + + ppFilter.setFileIdIn(String.valueOf(mobileMediaFileId)); + ListProductPriceBuilder productPriceListAfterPurchaseForAnotherFileFromTheSameMedia = ProductPriceService.list(ppFilter); + productPriceResponse = executor.executeSync(productPriceListAfterPurchaseForAnotherFileFromTheSameMedia.setKs(classMasterUserKs)); + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isIn(PurchaseStatus.FOR_PURCHASE, PurchaseStatus.FOR_PURCHASE_SUBSCRIPTION_ONLY); + assertThat(((PpvPrice) productPriceResponse.results.getObjects().get(0)).getFileId()).isEqualTo(mobileMediaFileId); + } + + @Severity(SeverityLevel.NORMAL) + @Description("productPrice/action/list - common test for PPV and subscription to check before purchase") + @Test() + public void productPriceSubscriptionAndPpvBeforePurchaseTest() { + int numberOfUsers = 1; + int numberOfDevices = 1; + Household household = HouseholdUtils.createHousehold(numberOfUsers, numberOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + + ProductPriceFilter filter = new ProductPriceFilter(); + filter.setSubscriptionIdIn(get5MinRenewableSubscription().getId()); + filter.setFileIdIn(String.valueOf(getSharedWebMediaFile().getId())); + filter.setIsLowest(false); + ListProductPriceBuilder productPriceListBeforePurchase = ProductPriceService.list(filter); + productPriceResponse = executor.executeSync(productPriceListBeforePurchase + .setKs(OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId())))); + // should be 2 ss one item is subscription an another is media file + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(2); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.SUBSCRIPTION); + assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualToIgnoringCase(get5MinRenewableSubscription().getId().trim()); + assertThat(productPriceResponse.results.getObjects().get(1).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPriceResponse.results.getObjects().get(1).getProductType()).isEqualTo(TransactionType.PPV); + assertThat(((PpvPrice) productPriceResponse.results.getObjects().get(1)).getFileId()).isEqualTo(getSharedWebMediaFile().getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("productPrice/action/list - subscription test") + @Test + public void subscriptionTest() { + // TODO: 3/7/2018 add remarks when possible such as below - show to Shmulik / Michael and see if test is clear + int numberOfUsers = 1; + int numberOfDevices = 1; + Household household = HouseholdUtils.createHousehold(numberOfUsers, numberOfDevices, true); + String classMasterUserKs = HouseholdUtils.getHouseholdUserKs(household, HouseholdUtils.getDevicesList(household).get(0).getUdid()); + + // create mpp with supporting of 1 type only and having at least 1 media on its channel + sharedChannel.setKSql("name='" + getSharedMediaAsset().getName() + "'"); + + Response channelResponse = executor.executeSync(add(sharedChannel) + .setKs(getManagerKs()) + .setLanguage("*")); + + assertThat(channelResponse.results).isNotNull(); + + Channel channel = channelResponse.results; + assertThat(channel.getName()).isNotNull(); + + MppData mppData = new MppData() + .isRenewable(true) + .channel1(channel.getName()) + .fileType1(getProperty(WEB_FILE_TYPE)); + Subscription subscription = insertMpp(mppData); + + ListEntitlementBuilder entitlementListBeforePurchase = EntitlementService.list(entitlementSubsFilter, null); + entitlementResponse = executor.executeSync(entitlementListBeforePurchase.setKs(classMasterUserKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(0); + + ProductPriceFilter ppFilter = new ProductPriceFilter(); + ppFilter.setSubscriptionIdIn(subscription.getId()); + ppFilter.setIsLowest(false); + ListProductPriceBuilder productPriceListBeforePurchase = ProductPriceService.list(ppFilter); + productPriceResponse = executor.executeSync(productPriceListBeforePurchase.setKs(classMasterUserKs)); + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.SUBSCRIPTION); + assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualTo(subscription.getId()); + + ListProductPriceBuilder productPriceListBeforePurchase4Anonymous = ProductPriceService.list(ppFilter); + productPriceResponse = executor.executeSync(productPriceListBeforePurchase4Anonymous.setKs(getAnonymousKs())); + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.SUBSCRIPTION); + assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualTo(subscription.getId()); + + PurchaseUtils.purchaseSubscription(classMasterUserKs, Integer.valueOf(subscription.getId()), Optional.empty()); + + ListEntitlementBuilder entitlementListAfterPurchase = EntitlementService.list(entitlementSubsFilter, null); + entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(classMasterUserKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(1); + assertThat(entitlementResponse.results.getObjects().get(0).getProductId()).isEqualToIgnoringCase(subscription.getId()); + assertThat(entitlementResponse.results.getObjects().get(0).getEndDate()).isGreaterThan( + entitlementResponse.results.getObjects().get(0).getCurrentDate()); + MatcherAssert.assertThat(entitlementResponse.results.getObjects().get(0).getPaymentMethod(), + Matchers.anyOf(Matchers.is(PaymentMethodType.OFFLINE), Matchers.is(PaymentMethodType.UNKNOWN))); + + // get data about assets inside subscription to get file + BundleFilter bundleFilter = new BundleFilter(); + bundleFilter.setBundleTypeEqual(BundleType.SUBSCRIPTION); + bundleFilter.setIdEqual(Integer.valueOf(subscription.getId())); + ListAssetBuilder listAssetBuilder = AssetService.list(bundleFilter); + Response> listResponseAssets = executor.executeSync(listAssetBuilder.setKs(classMasterUserKs)); + assertThat(listResponseAssets.results.getTotalCount()).isGreaterThan(0); + String sharedWebMediaFileId = String.valueOf(listResponseAssets.results.getObjects().get(0).getMediaFiles().get(0).getId()).trim(); + + ppFilter.setFileIdIn(sharedWebMediaFileId); + ListProductPriceBuilder productPriceListAfterPurchase = ProductPriceService.list(ppFilter); + productPriceResponse = executor.executeSync(productPriceListAfterPurchase.setKs(classMasterUserKs)); + + // as we have file and subscription in filter + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(2); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.SUBSCRIPTION_PURCHASED); + assertThat(productPriceResponse.results.getObjects().get(1).getPurchaseStatus()).isEqualTo(PurchaseStatus.SUBSCRIPTION_PURCHASED); + // TODO: should we use ENUM containing subs of KalturaProductPrice class such as: KalturaCollectionPrice, KalturaPpvPrice, KalturaSubscriptionPrice??? + // that logic can't be checked by schema as schema can't check that exactly 1st item is Subscription and 2nd one is PPV + assertThat(productPriceResponse.results.getObjects().get(0).getClass().getSimpleName()).isEqualToIgnoringCase("SubscriptionPrice"); + assertThat(productPriceResponse.results.getObjects().get(1).getClass().getSimpleName()).isEqualToIgnoringCase("PpvPrice"); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.SUBSCRIPTION); + assertThat(productPriceResponse.results.getObjects().get(1).getProductType()).isEqualTo(TransactionType.PPV); + assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualToIgnoringCase(subscription.getId()); + assertThat(((PpvPrice) productPriceResponse.results.getObjects().get(1)).getFileId()).isEqualTo(Integer.valueOf(sharedWebMediaFileId)); + + //delete HH for cleanup + HouseholdService.DeleteHouseholdBuilder deleteHouseholdBuilder = delete(Math.toIntExact(household.getId())); + executor.executeSync(deleteHouseholdBuilder.setKs(getAdministratorKs())); + + //delete subscription + deleteMpp(subscription.getName()); + } + + @Severity(SeverityLevel.NORMAL) + @Description("/productprice/action/list - subscription - Web_HD_File_only") + @Test() + public void productPriceSubscriptionWebHDFileTypeOnlyTest() { + // create mpp with supporting of 1 type only and having at least 1 media on its channel + sharedChannel.setKSql("name='" + getSharedMediaAsset().getName() + "'"); + + Response channelResponse = executor.executeSync(add(sharedChannel) + .setKs(getManagerKs()) + .setLanguage("*")); + + assertThat(channelResponse.results).isNotNull(); + + Channel channel = channelResponse.results; + assertThat(channel.getName()).isNotNull(); + + MppData mppData = new MppData() + .isRenewable(true) + .channel1(channel.getName()) + .fileType1(getProperty(WEB_FILE_TYPE)); + Subscription subscription = insertMpp(mppData); + + int webHDFileOnlySubId = Integer.valueOf(subscription.getId()); + + int numberOfUsers = 1; + int numberOfDevices = 1; + Household household = HouseholdUtils.createHousehold(numberOfUsers, numberOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + String masterKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId())); + + ProductPriceFilter ppFilter = new ProductPriceFilter(); + ppFilter.setSubscriptionIdIn(String.valueOf(webHDFileOnlySubId)); + ppFilter.setFileIdIn(String.valueOf(getSharedWebMediaFile().getId()) + "," + String.valueOf(getSharedMobileMediaFile().getId())); + ppFilter.setIsLowest(false); + ListProductPriceBuilder productPriceListBeforePurchase = ProductPriceService.list(ppFilter); + productPriceResponse = executor.executeSync(productPriceListBeforePurchase.setKs(masterKs)); + // should be 3 as we have 2 files and 1 subscriptions + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(3); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.SUBSCRIPTION); + assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualTo(String.valueOf(webHDFileOnlySubId)); + assertThat(productPriceResponse.results.getObjects().get(1).getPurchaseStatus()).isIn(PurchaseStatus.FOR_PURCHASE, PurchaseStatus.FOR_PURCHASE_SUBSCRIPTION_ONLY); + assertThat(productPriceResponse.results.getObjects().get(1).getProductType()).isEqualTo(TransactionType.PPV); + assertThat(((PpvPrice) productPriceResponse.results.getObjects().get(1)).getFileId()).isEqualTo(getSharedWebMediaFile().getId()); + assertThat(productPriceResponse.results.getObjects().get(2).getPurchaseStatus()).isIn(PurchaseStatus.FOR_PURCHASE, PurchaseStatus.FOR_PURCHASE_SUBSCRIPTION_ONLY); + assertThat(productPriceResponse.results.getObjects().get(2).getProductType()).isEqualTo(TransactionType.PPV); + assertThat(((PpvPrice) productPriceResponse.results.getObjects().get(2)).getFileId()).isEqualTo(getSharedMobileMediaFile().getId()); + + PurchaseUtils.purchaseSubscription(masterKs, webHDFileOnlySubId, Optional.empty()); + + productPriceResponse = executor.executeSync(productPriceListBeforePurchase.setKs(masterKs)); + // should be 3 as we have 2 files and 1 subscriptions + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(3); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.SUBSCRIPTION_PURCHASED); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.SUBSCRIPTION); + assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualTo(String.valueOf(webHDFileOnlySubId)); + assertThat(productPriceResponse.results.getObjects().get(1).getPurchaseStatus()).isEqualTo(PurchaseStatus.SUBSCRIPTION_PURCHASED); + assertThat(productPriceResponse.results.getObjects().get(1).getProductType()).isEqualTo(TransactionType.PPV); + assertThat(productPriceResponse.results.getObjects().get(1).getPrice().getAmount()).isEqualTo(0); + assertThat(((PpvPrice) productPriceResponse.results.getObjects().get(1)).getFileId()).isEqualTo(getSharedWebMediaFile().getId()); + assertThat(productPriceResponse.results.getObjects().get(2).getPurchaseStatus()).isIn(PurchaseStatus.FOR_PURCHASE, PurchaseStatus.FOR_PURCHASE_SUBSCRIPTION_ONLY); + assertThat(productPriceResponse.results.getObjects().get(2).getProductType()).isEqualTo(TransactionType.PPV); + assertThat(productPriceResponse.results.getObjects().get(2).getPrice().getAmount()).isGreaterThan(0); + assertThat(((PpvPrice) productPriceResponse.results.getObjects().get(2)).getFileId()).isEqualTo(getSharedMobileMediaFile().getId()); + + //delete household for cleanup + HouseholdService.DeleteHouseholdBuilder deleteHouseholdBuilder = delete(Math.toIntExact(household.getId())); + executor.executeSync(deleteHouseholdBuilder.setKs(getAdministratorKs())); + + // delete channel + DeleteChannelBuilder deleteChannelBuilder = ChannelService.delete(Math.toIntExact(channel.getId())); + executor.executeSync(deleteChannelBuilder.setKs(getManagerKs())); + + //delete subscription + deleteMpp(subscription.getName()); + } + + @Severity(SeverityLevel.NORMAL) + @Description("productPrice/action/list - subscription - no specifed currency") + @Test() + public void productPriceSubscriptionNoSpecifiedCurrencyTest() { + MppData mppData = new MppData() + .isRenewable(true) + .pricePlanCode1(PRICE_PLAN_WITH_MULTI_CURRENCIES); + Subscription subscription = insertMpp(mppData); + + int subWithMultiCurrencyId = Integer.valueOf(subscription.getId()); + + int numberOfUsers = 1; + int numberOfDevices = 1; + Household household = HouseholdUtils.createHousehold(numberOfUsers, numberOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + String masterKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId())); + + ProductPriceFilter ppFilter = new ProductPriceFilter(); + ppFilter.setSubscriptionIdIn(String.valueOf(subWithMultiCurrencyId)); + ListProductPriceBuilder productPriceListBeforePurchase = ProductPriceService.list(ppFilter); + productPriceResponse = executor.executeSync(productPriceListBeforePurchase.setKs(masterKs)); + // should be 1 subscription + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.SUBSCRIPTION); + assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualTo(String.valueOf(subWithMultiCurrencyId)); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()).isGreaterThan(0); + // as default group currency is EURO + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()).isEqualTo(EUR.getValue()); + + PurchaseUtils.purchaseSubscription(masterKs, subWithMultiCurrencyId, Optional.empty()); + // to check purchase + ListEntitlementBuilder entitlementListAfterPurchase = EntitlementService.list(entitlementSubsFilter, null); + entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(masterKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(1); + assertThat(entitlementResponse.results.getObjects().get(0).getProductId()).isEqualTo(String.valueOf(subWithMultiCurrencyId)); + // to check purchase + ListTransactionHistoryBuilder listTransactionHistoryBuilder = TransactionHistoryService.list(transactionHistoryFilter); + listBillingTransactionResponse = executor.executeSync(listTransactionHistoryBuilder.setKs(masterKs)); + assertThat(listBillingTransactionResponse.results.getTotalCount()).isEqualTo(1); + assertThat(listBillingTransactionResponse.results.getObjects().get(0).getPurchasedItemCode()).isEqualTo(String.valueOf(subWithMultiCurrencyId)); + + productPriceResponse = executor.executeSync(productPriceListBeforePurchase.setKs(masterKs)); + // should be 1 subscription + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.SUBSCRIPTION_PURCHASED); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.SUBSCRIPTION); + assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualTo(String.valueOf(subWithMultiCurrencyId)); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()).isEqualTo(0); + // as default group currency is EURO + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()).isEqualTo(EUR.getValue()); + + //delete household for cleanup + HouseholdService.DeleteHouseholdBuilder deleteHouseholdBuilder = delete(Math.toIntExact(household.getId())); + executor.executeSync(deleteHouseholdBuilder.setKs(getAdministratorKs())); + + //delete subscription + deleteMpp(subscription.getName()); + } + + @Severity(SeverityLevel.NORMAL) + @Description("productPrice/action/list - subscription with discount (percentage) - specified currency") + @Test() + public void productPriceSubscriptionWithPercentageDiscountAndSpecifiedCurrencyTest() { + // TODO: should we save it in Properties? + double subPriceAfterDiscount = 7.5; // as price 15 and discount is 50% + int subWithDiscountAndCurrencyId = Integer.valueOf(subscriptionWithMultiCurrenciesAndDiscountPercentage.getId()); + + int numberOfUsers = 1; + int numberOfDevices = 1; + Household household = HouseholdUtils.createHousehold(numberOfUsers, numberOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + String masterKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId())); + + ProductPriceFilter ppFilter = new ProductPriceFilter(); + ppFilter.setSubscriptionIdIn(String.valueOf(subWithDiscountAndCurrencyId)); + ListProductPriceBuilder productPriceListBeforePurchase = ProductPriceService.list(ppFilter).setCurrency(USD.getValue()); + productPriceResponse = executor.executeSync(productPriceListBeforePurchase.setKs(masterKs)); + // should be 1 subscription + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.SUBSCRIPTION); + assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualTo(String.valueOf(subWithDiscountAndCurrencyId)); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()).isEqualTo(subPriceAfterDiscount); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()).isEqualTo(USD.getValue()); + + PurchaseUtils.purchaseSubscription(masterKs, subWithDiscountAndCurrencyId, Optional.of(USD.getValue())); + // to check purchase + ListEntitlementBuilder entitlementListAfterPurchase = EntitlementService.list(entitlementSubsFilter, null); + entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(masterKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(1); + assertThat(entitlementResponse.results.getObjects().get(0).getProductId()).isEqualTo(String.valueOf(subWithDiscountAndCurrencyId)); + // to check purchase + ListTransactionHistoryBuilder listTransactionHistoryBuilder = TransactionHistoryService.list(transactionHistoryFilter); + listBillingTransactionResponse = executor.executeSync(listTransactionHistoryBuilder.setKs(masterKs)); + assertThat(listBillingTransactionResponse.results.getTotalCount()).isEqualTo(1); + assertThat(listBillingTransactionResponse.results.getObjects().get(0).getPurchasedItemCode()).isEqualTo(String.valueOf(subWithDiscountAndCurrencyId)); + assertThat(listBillingTransactionResponse.results.getObjects().get(0).getPrice().getAmount()).isEqualTo(subPriceAfterDiscount); + + productPriceResponse = executor.executeSync(productPriceListBeforePurchase.setKs(masterKs)); + // should be 1 subscription + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.SUBSCRIPTION_PURCHASED); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.SUBSCRIPTION); + assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualTo(String.valueOf(subWithDiscountAndCurrencyId)); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()).isEqualTo(0); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()).isEqualTo(USD.getValue()); + + //delete household for cleanup + HouseholdService.DeleteHouseholdBuilder deleteHouseholdBuilder = delete(Math.toIntExact(household.getId())); + executor.executeSync(deleteHouseholdBuilder.setKs(getAdministratorKs())); + } + + @Severity(SeverityLevel.NORMAL) + @Description("productPrice/action/list - subscription with discount (fixed amount) - specified currency - not in locale") + @Test() + public void productPriceSubscriptionWithFixedDiscountAndSpecifiedCurrencyNotInLocaleTest() { + // TODO: should we save it in Properties? + double subPriceAfterDiscount = 4; // as price 5 and discount is 1 + + MppData mppData = new MppData() + .isRenewable(true) + .pricePlanCode1(PRICE_PLAN_WITH_MULTI_CURRENCIES_AND_DISCOUNT_FIXED); + Subscription subscription = insertMpp(mppData); + + int subWithDiscountAndCurrencyId = Integer.valueOf(subscription.getId()); + + int numberOfUsers = 1; + int numberOfDevices = 1; + Household household = HouseholdUtils.createHousehold(numberOfUsers, numberOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + String masterKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId())); + + ProductPriceFilter ppFilter = new ProductPriceFilter(); + ppFilter.setSubscriptionIdIn(String.valueOf(subWithDiscountAndCurrencyId)); + ListProductPriceBuilder productPriceListBeforePurchase = ProductPriceService.list(ppFilter).setCurrency(CLP.getValue()); + productPriceResponse = executor.executeSync(productPriceListBeforePurchase.setKs(masterKs)); + // should be 1 subscription + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.SUBSCRIPTION); + assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualTo(String.valueOf(subWithDiscountAndCurrencyId)); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()).isEqualTo(subPriceAfterDiscount); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()).isEqualTo(CLP.getValue()); + + PurchaseUtils.purchaseSubscription(masterKs, subWithDiscountAndCurrencyId, Optional.of(CLP.getValue())); + // to check purchase + ListEntitlementBuilder entitlementListAfterPurchase = EntitlementService.list(entitlementSubsFilter, null); + entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(masterKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(1); + assertThat(entitlementResponse.results.getObjects().get(0).getProductId()).isEqualTo(String.valueOf(subWithDiscountAndCurrencyId)); + // to check purchase + ListTransactionHistoryBuilder listTransactionHistoryBuilder = TransactionHistoryService.list(transactionHistoryFilter); + listBillingTransactionResponse = executor.executeSync(listTransactionHistoryBuilder.setKs(masterKs)); + assertThat(listBillingTransactionResponse.results.getTotalCount()).isEqualTo(1); + assertThat(listBillingTransactionResponse.results.getObjects().get(0).getPurchasedItemCode()).isEqualTo(String.valueOf(subWithDiscountAndCurrencyId)); + assertThat(listBillingTransactionResponse.results.getObjects().get(0).getPrice().getAmount()).isEqualTo(subPriceAfterDiscount); + + productPriceResponse = executor.executeSync(productPriceListBeforePurchase.setKs(masterKs)); + // should be 1 subscription + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.SUBSCRIPTION_PURCHASED); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.SUBSCRIPTION); + assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualTo(String.valueOf(subWithDiscountAndCurrencyId)); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()).isEqualTo(0); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()).isEqualTo(CLP.getValue()); + + //delete household for cleanup + HouseholdService.DeleteHouseholdBuilder deleteHouseholdBuilder = delete(Math.toIntExact(household.getId())); + executor.executeSync(deleteHouseholdBuilder.setKs(getAdministratorKs())); + + //delete subscription + deleteMpp(subscription.getName()); + } + + @Severity(SeverityLevel.NORMAL) + @Description("productPrice/action/list - subscription with discount (percentage) - no specified currency") + @Test() + public void productPriceSubscriptionWithPercentageDiscountAndNoSpecifiedCurrencyTest() { + // TODO: should we save it in Properties? + double subPriceAfterDiscount = 9.6; // as price 12 in default locale and discount is 20% in default locale + int subWithDiscountAndCurrencyId = Integer.valueOf(subscriptionWithMultiCurrenciesAndDiscountPercentage.getId()); + + int numberOfUsers = 1; + int numberOfDevices = 1; + Household household = HouseholdUtils.createHousehold(numberOfUsers, numberOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + String masterKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId())); + + ProductPriceFilter ppFilter = new ProductPriceFilter(); + ppFilter.setSubscriptionIdIn(String.valueOf(subWithDiscountAndCurrencyId)); + ListProductPriceBuilder productPriceListBeforePurchase = ProductPriceService.list(ppFilter); + productPriceResponse = executor.executeSync(productPriceListBeforePurchase.setKs(masterKs)); + // should be 1 subscription + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.SUBSCRIPTION); + assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualTo(String.valueOf(subWithDiscountAndCurrencyId)); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()).isEqualTo(subPriceAfterDiscount); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()).isEqualTo(EUR.getValue()); + + PurchaseUtils.purchaseSubscription(masterKs, subWithDiscountAndCurrencyId, Optional.empty()); + // to check purchase + ListEntitlementBuilder entitlementListAfterPurchase = EntitlementService.list(entitlementSubsFilter, null); + entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(masterKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(1); + assertThat(entitlementResponse.results.getObjects().get(0).getProductId()).isEqualTo(String.valueOf(subWithDiscountAndCurrencyId)); + // to check purchase + ListTransactionHistoryBuilder listTransactionHistoryBuilder = TransactionHistoryService.list(transactionHistoryFilter); + listBillingTransactionResponse = executor.executeSync(listTransactionHistoryBuilder.setKs(masterKs)); + assertThat(listBillingTransactionResponse.results.getTotalCount()).isEqualTo(1); + assertThat(listBillingTransactionResponse.results.getObjects().get(0).getPurchasedItemCode()).isEqualTo(String.valueOf(subWithDiscountAndCurrencyId)); + assertThat(listBillingTransactionResponse.results.getObjects().get(0).getPrice().getAmount()).isEqualTo(subPriceAfterDiscount); + + productPriceResponse = executor.executeSync(productPriceListBeforePurchase.setKs(masterKs)); + // should be 1 subscription + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.SUBSCRIPTION_PURCHASED); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.SUBSCRIPTION); + assertThat(productPriceResponse.results.getObjects().get(0).getProductId()).isEqualTo(String.valueOf(subWithDiscountAndCurrencyId)); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()).isEqualTo(0); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()).isEqualTo(EUR.getValue()); + + //delete household for cleanup + HouseholdService.DeleteHouseholdBuilder deleteHouseholdBuilder = delete(Math.toIntExact(household.getId())) + .setKs(getAdministratorKs()); + executor.executeSync(deleteHouseholdBuilder); + } + + @Severity(SeverityLevel.NORMAL) + @Description("productPrice/action/list - PPV - with discount (percentage) - specified currency") + @Test() + public void productPricePpvWithPercentageDiscountAndSpecifiedCurrencyTest() { + int numberOfUsers = 1; + int numberOfDevices = 1; + Household household = HouseholdUtils.createHousehold(numberOfUsers, numberOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + String masterKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId())); + + // TODO: should we save it in Properties? + double ppvPriceAfterDiscount = 33.3; // as price 37 ILS and discount is 10% + + VodData vodData = new VodData() + .ppvWebName(PPV_WITH_MULTI_CURRENCIES_AND_DISCOUNT_PERCENTS) + .ppvMobileName(PPV_WITH_MULTI_CURRENCIES_AND_DISCOUNT_PERCENTS); + MediaAsset mediaAsset = insertVod(vodData, true); + + int mediaFileId = mediaAsset.getMediaFiles().get(0).getId(); + int assetWithMultiCurrencyId = Math.toIntExact(mediaAsset.getId()); + + ProductPriceFilter ppFilter = new ProductPriceFilter(); + ppFilter.setFileIdIn(String.valueOf(mediaFileId)); + ListProductPriceBuilder productPriceListBeforePurchase = ProductPriceService.list(ppFilter); + productPriceResponse = executor.executeSync(productPriceListBeforePurchase.setKs(masterKs).setCurrency(ILS.getValue())); + // should be 1 file + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.PPV); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()).isEqualTo(ppvPriceAfterDiscount); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()).isEqualTo(ILS.getValue()); + + PurchaseUtils.purchasePpv(masterKs, Optional.of(assetWithMultiCurrencyId), Optional.of(mediaFileId), Optional.of(ILS.getValue())); + // to check purchase + ListEntitlementBuilder entitlementListAfterPurchase = EntitlementService.list(entitlementPpvsFilter, null); + entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(masterKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(1); + assertThat(((PpvEntitlement) entitlementResponse.results.getObjects().get(0)).getMediaId()).isEqualTo(assetWithMultiCurrencyId); + assertThat(((PpvEntitlement) entitlementResponse.results.getObjects().get(0)).getMediaFileId()).isEqualTo(mediaFileId); + // to check purchase + ListTransactionHistoryBuilder listTransactionHistoryBuilder = TransactionHistoryService.list(transactionHistoryFilter); + listBillingTransactionResponse = executor.executeSync(listTransactionHistoryBuilder.setKs(masterKs)); + assertThat(listBillingTransactionResponse.results.getTotalCount()).isEqualTo(1); + assertThat(listBillingTransactionResponse.results.getObjects().get(0).getPurchasedItemCode()).isEqualTo(String.valueOf(assetWithMultiCurrencyId)); + assertThat(listBillingTransactionResponse.results.getObjects().get(0).getPrice().getAmount()).isEqualTo(ppvPriceAfterDiscount); + + productPriceResponse = executor.executeSync(productPriceListBeforePurchase.setKs(masterKs)); + // should be 1 ppv + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.PPV_PURCHASED); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.PPV); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()).isEqualTo(0); + assertThat(((PpvPrice)productPriceResponse.results.getObjects().get(0)).getFileId()).isEqualTo(mediaFileId); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()).isEqualTo(ILS.getValue()); + + //delete household for cleanup + HouseholdService.DeleteHouseholdBuilder deleteHouseholdBuilder = delete(Math.toIntExact(household.getId())); + executor.executeSync(deleteHouseholdBuilder.setKs(getAdministratorKs())); + + // delete media + deleteVod(mediaAsset.getName()); + } + + @Severity(SeverityLevel.NORMAL) + @Description("productPrice/action/list - PPV - with discount (fixed amount) - specified currency") + @Test() + public void productPricePpvWithFixedDiscountAndSpecifiedCurrencyTest() { + int numberOfUsers = 1; + int numberOfDevices = 1; + Household household = HouseholdUtils.createHousehold(numberOfUsers, numberOfDevices, true); + HouseholdUser masterUser = HouseholdUtils.getMasterUser(household); + String masterKs = OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId())); + + VodData vodData = new VodData() + .ppvWebName(PPV_WITH_MULTI_CURRENCIES_AND_FIXED_DISCOUNT) + .ppvMobileName(PPV_WITH_MULTI_CURRENCIES_AND_FIXED_DISCOUNT); + MediaAsset mediaAsset = insertVod(vodData, true); + + int mediaFileId = mediaAsset.getMediaFiles().get(0).getId(); + int assetWithMultiCurrencyId = Math.toIntExact(mediaAsset.getId()); + double ppvPriceAfterDiscount = 2; // as price 5 ILS and discount is 3 + + ProductPriceFilter ppFilter = new ProductPriceFilter(); + ppFilter.setFileIdIn(String.valueOf(mediaFileId)); + ListProductPriceBuilder productPriceListBeforePurchase = ProductPriceService.list(ppFilter); + productPriceResponse = executor.executeSync(productPriceListBeforePurchase.setKs(masterKs).setCurrency(ILS.getValue())); + // should be 1 file + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.PPV); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()).isEqualTo(ppvPriceAfterDiscount); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()).isEqualTo(ILS.getValue()); + + PurchaseUtils.purchasePpv(masterKs, Optional.of(assetWithMultiCurrencyId), Optional.of(mediaFileId), Optional.of(ILS.getValue())); + // to check purchase + ListEntitlementBuilder entitlementListAfterPurchase = EntitlementService.list(entitlementPpvsFilter, null); + entitlementResponse = executor.executeSync(entitlementListAfterPurchase.setKs(masterKs)); + assertThat(entitlementResponse.results.getTotalCount()).isEqualTo(1); + assertThat(((PpvEntitlement) entitlementResponse.results.getObjects().get(0)).getMediaId()).isEqualTo(assetWithMultiCurrencyId); + assertThat(((PpvEntitlement) entitlementResponse.results.getObjects().get(0)).getMediaFileId()).isEqualTo(mediaFileId); + // to check purchase + ListTransactionHistoryBuilder listTransactionHistoryBuilder = TransactionHistoryService.list(transactionHistoryFilter); + listBillingTransactionResponse = executor.executeSync(listTransactionHistoryBuilder.setKs(masterKs)); + assertThat(listBillingTransactionResponse.results.getTotalCount()).isEqualTo(1); + assertThat(listBillingTransactionResponse.results.getObjects().get(0).getPurchasedItemCode()).isEqualTo(String.valueOf(assetWithMultiCurrencyId)); + assertThat(listBillingTransactionResponse.results.getObjects().get(0).getPrice().getAmount()).isEqualTo(ppvPriceAfterDiscount); + + productPriceResponse = executor.executeSync(productPriceListBeforePurchase.setKs(masterKs)); + // should be 1 ppv + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.PPV_PURCHASED); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.PPV); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()).isEqualTo(0); + assertThat(((PpvPrice)productPriceResponse.results.getObjects().get(0)).getFileId()).isEqualTo(mediaFileId); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()).isEqualTo(ILS.getValue()); + + //delete household for cleanup + HouseholdService.DeleteHouseholdBuilder deleteHouseholdBuilder = delete(Math.toIntExact(household.getId())); + executor.executeSync(deleteHouseholdBuilder.setKs(getAdministratorKs())); + + // delete media + deleteVod(mediaAsset.getName()); + } + + @Severity(SeverityLevel.NORMAL) + @Description("/productPrice/action/list - with passed PPV") + @Test() + public void productPriceWithPassedPpvTest() { + String ppvWithExpiredDate = ";;01/01/2017 00:00:00"; + String ppvMobileModule = getSharedCommonPpv().getName() + ppvWithExpiredDate + PPV_WITH_MULTI_CURRENCIES_AND_DISCOUNT_PERCENTS + ";;"; + + VodData vodData = new VodData() + .ppvMobileName(ppvMobileModule); + MediaAsset mediaAssetWith2Ppv1Expired = insertVod(vodData, true); + + ProductPriceFilter ppFilter = new ProductPriceFilter(); + ppFilter.setFileIdIn(String.valueOf(mediaAssetWith2Ppv1Expired.getMediaFiles().get(1).getId())); + ListProductPriceBuilder productPriceListBeforePurchase = ProductPriceService.list(ppFilter); + productPriceResponse = executor.executeSync(productPriceListBeforePurchase.setKs(classMasterUserKs)); + // should be 1 file with non passed PPV price only + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.PPV); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()).isGreaterThan(0); + assertThat(((PpvPrice) productPriceResponse.results.getObjects().get(0)).getFileId()).isEqualTo( + mediaAssetWith2Ppv1Expired.getMediaFiles().get(1).getId()); + + ppvMobileModule = getSharedCommonPpv().getName() + ppvWithExpiredDate; + VodData vodData1 = new VodData() + .ppvMobileName(ppvMobileModule); + mediaAssetWith2Ppv1Expired = insertVod(vodData1, true); + + ppFilter = new ProductPriceFilter(); + ppFilter.setFileIdIn(String.valueOf(mediaAssetWith2Ppv1Expired.getMediaFiles().get(1).getId())); + productPriceListBeforePurchase = ProductPriceService.list(ppFilter); + productPriceResponse = executor.executeSync(productPriceListBeforePurchase.setKs(classMasterUserKs)); + // should be 1 file and free + assertThat(productPriceResponse.results.getTotalCount()).isEqualTo(1); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FREE); + assertThat(productPriceResponse.results.getObjects().get(0).getProductType()).isEqualTo(TransactionType.PPV); + assertThat(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()).isEqualTo(0); + assertThat(((PpvPrice) productPriceResponse.results.getObjects().get(0)).getFileId()).isEqualTo( + mediaAssetWith2Ppv1Expired.getMediaFiles().get(1).getId()); + + // delete media + deleteVod(mediaAssetWith2Ppv1Expired.getName()); + } + + @AfterClass + public void afterClass() { + //delete household for cleanup + HouseholdService.DeleteHouseholdBuilder deleteHouseholdBuilder = delete(Math.toIntExact(household.getId())); + executor.executeSync(deleteHouseholdBuilder.setKs(getAdministratorKs())); + + // delete subscription + deleteMpp(subscriptionWithMultiCurrenciesAndDiscountPercentage.getName()); + } +} \ No newline at end of file diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/sessionTests/SessionGetTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/sessionTests/SessionGetTests.java index bbe983a3d..5d301bb58 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/sessionTests/SessionGetTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/sessionTests/SessionGetTests.java @@ -1,6 +1,5 @@ package com.kaltura.client.test.tests.servicesTests.sessionTests; -import com.kaltura.client.Client; import com.kaltura.client.services.SessionService; import com.kaltura.client.test.tests.BaseTest; import com.kaltura.client.test.utils.HouseholdUtils; @@ -11,32 +10,23 @@ import com.kaltura.client.types.Session; import com.kaltura.client.utils.response.base.Response; import io.qameta.allure.Description; -import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import static com.kaltura.client.services.SessionService.*; +import static com.kaltura.client.services.SessionService.GetSessionBuilder; import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; import static org.assertj.core.api.Assertions.assertThat; public class SessionGetTests extends BaseTest { - private Client client; - - @BeforeClass - private void get_tests_before_class() { - - } - @Description("session/action/get - master user") @Test private void getMasterUserSession() { Household household = HouseholdUtils.createHousehold(2, 1, false); - HouseholdUser user = HouseholdUtils.getMasterUserFromHousehold(household); - String udid = HouseholdUtils.getDevicesListFromHouseHold(household).get(0).getUdid(); + HouseholdUser user = HouseholdUtils.getMasterUser(household); + String udid = HouseholdUtils.getDevicesList(household).get(0).getUdid(); String session = OttUserUtils.getKs(Integer.parseInt(user.getUserId()), udid); - GetSessionBuilder getSessionBuilder = SessionService.get(session); - getSessionBuilder.setKs(getAdministratorKs()); + GetSessionBuilder getSessionBuilder = SessionService.get(session).setKs(getAdministratorKs()); Response getSessionResponse = executor.executeSync(getSessionBuilder); assertThat(getSessionResponse.results.getKs()).isEqualTo(session); @@ -52,8 +42,7 @@ private void getMasterUserSession() { private void getAnonymousUserSession() { String session = BaseTest.getAnonymousKs(); - GetSessionBuilder getSessionBuilder = SessionService.get(session); - getSessionBuilder.setKs(getAdministratorKs()); + GetSessionBuilder getSessionBuilder = SessionService.get(session).setKs(getAdministratorKs()); Response getSessionResponse = executor.executeSync(getSessionBuilder); assertThat(getSessionResponse.results.getKs()).isEqualTo(session); @@ -66,8 +55,7 @@ private void getAnonymousUserSession() { private void getOperatorUserSession() { String session = getOperatorKs(); - GetSessionBuilder getSessionBuilder = SessionService.get(session); - getSessionBuilder.setKs(getAdministratorKs()); + GetSessionBuilder getSessionBuilder = SessionService.get(session).setKs(getAdministratorKs()); Response getSessionResponse = executor.executeSync(getSessionBuilder); assertThat(getSessionResponse.results.getKs()).isEqualTo(session); @@ -80,8 +68,7 @@ private void getOperatorUserSession() { private void getSessionWithInvalidSessionKs() { String session = getOperatorKs() + 1; - GetSessionBuilder getSessionBuilder = SessionService.get(session); - getSessionBuilder.setKs(getAdministratorKs()); + GetSessionBuilder getSessionBuilder = SessionService.get(session).setKs(getAdministratorKs()); Response getSessionResponse = executor.executeSync(getSessionBuilder); assertThat(getSessionResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500015).getCode()); diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/sessionTests/SessionRevokeTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/sessionTests/SessionRevokeTests.java index 81f400ed7..b583baeba 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/sessionTests/SessionRevokeTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/sessionTests/SessionRevokeTests.java @@ -1,38 +1,28 @@ package com.kaltura.client.test.tests.servicesTests.sessionTests; -import com.kaltura.client.Client; import com.kaltura.client.services.OttUserService; import com.kaltura.client.services.SessionService; import com.kaltura.client.test.tests.BaseTest; import com.kaltura.client.test.utils.HouseholdUtils; - import com.kaltura.client.types.Household; import com.kaltura.client.types.OTTUser; import com.kaltura.client.utils.response.base.Response; import io.qameta.allure.Description; -import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import static com.kaltura.client.services.OttUserService.GetOttUserBuilder; +import static com.kaltura.client.services.SessionService.RevokeSessionBuilder; import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; import static org.assertj.core.api.Assertions.assertThat; -import static com.kaltura.client.services.SessionService.*; -import static com.kaltura.client.services.OttUserService.*; public class SessionRevokeTests extends BaseTest { - public static Client client; - - @BeforeClass - private void revoke_tests_before_class() { - } - - @Description("/session/action/revoke - 2 different kss") @Test private void RevokeKs() { Household household = HouseholdUtils.createHousehold(2, 2, false); - String udid = HouseholdUtils.getDevicesListFromHouseHold(household).get(0).getUdid(); - String masterUserKs = HouseholdUtils.getHouseholdMasterUserKs(household, null); + String udid = HouseholdUtils.getDevicesList(household).get(0).getUdid(); + String masterUserKs = HouseholdUtils.getHouseholdMasterUserKs(household); String masterUserKs2 = HouseholdUtils.getHouseholdMasterUserKs(household, udid); try { @@ -42,9 +32,7 @@ private void RevokeKs() { } // Revoke all sessions for specific user - - RevokeSessionBuilder revokeSessionBuilder = SessionService.revoke(); - revokeSessionBuilder.setKs(masterUserKs); + RevokeSessionBuilder revokeSessionBuilder = SessionService.revoke().setKs(masterUserKs); Response booleanResponse = executor.executeSync(revokeSessionBuilder); assertThat(booleanResponse.results).isTrue(); @@ -56,17 +44,15 @@ private void RevokeKs() { } // Verify ks is expired - - GetOttUserBuilder getOttUserBuilder = OttUserService.get(); - getOttUserBuilder.setKs(masterUserKs); + GetOttUserBuilder getOttUserBuilder = OttUserService.get().setKs(masterUserKs); Response ottUserResponse = executor.executeSync(getOttUserBuilder); + assertThat(ottUserResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500016).getCode()); // Verify ks2 is expired - - GetOttUserBuilder getOttUserBuilder2 = OttUserService.get(); - getOttUserBuilder2.setKs(masterUserKs2); + GetOttUserBuilder getOttUserBuilder2 = OttUserService.get().setKs(masterUserKs2); Response ottUserResponse2 = executor.executeSync(getOttUserBuilder); + assertThat(ottUserResponse2.error.getCode()).isEqualTo(getAPIExceptionFromList(500016).getCode()); } diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/sessionTests/SessionSwitchUserTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/sessionTests/SessionSwitchUserTests.java index ca2894cf4..824aadaf6 100644 --- a/src/test/java/com/kaltura/client/test/tests/servicesTests/sessionTests/SessionSwitchUserTests.java +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/sessionTests/SessionSwitchUserTests.java @@ -1,146 +1,144 @@ package com.kaltura.client.test.tests.servicesTests.sessionTests; -import com.kaltura.client.Client; import com.kaltura.client.enums.UserState; +import com.kaltura.client.services.HouseholdService; import com.kaltura.client.services.OttUserService; import com.kaltura.client.services.SessionService; import com.kaltura.client.test.tests.BaseTest; -import com.kaltura.client.test.utils.HouseholdUtils; import com.kaltura.client.test.utils.OttUserUtils; -import com.kaltura.client.types.*; +import com.kaltura.client.types.Household; +import com.kaltura.client.types.LoginSession; +import com.kaltura.client.types.OTTUser; +import com.kaltura.client.types.Session; import com.kaltura.client.utils.response.base.Response; import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static com.kaltura.client.test.utils.BaseUtils.getAPIExceptionFromList; +import static com.kaltura.client.test.utils.HouseholdUtils.*; import static org.assertj.core.api.Assertions.assertThat; -import static com.kaltura.client.services.SessionService.*; -import static com.kaltura.client.services.OttUserService.*; public class SessionSwitchUserTests extends BaseTest { - //TODO - replace hardcoded user id - private String UserId = "1543798"; + private final int numOfUsers = 2; + private final int numOfDevices = 1; + + private String userId; private String userKs; - public static Client client; @BeforeClass private void switchUser_tests_before_class() { - userKs = OttUserUtils.getKs(Integer.valueOf(UserId), null); + userId = executor.executeSync(OttUserService.register(partnerId, OttUserUtils.generateOttUser(), defaultUserPassword)) + .results.getId(); + userKs = OttUserUtils.getKs(Integer.valueOf(userId)); } - @Description("/session/action/switchUser") + @Severity(SeverityLevel.CRITICAL) + @Description("session/action/switchUser") @Test - private void SwitchUser() { - - Household household = HouseholdUtils.createHousehold(2, 1, false); - String udid = HouseholdUtils.getDevicesListFromHouseHold(household).get(0).getUdid(); - String masterUserKs = HouseholdUtils.getHouseholdMasterUserKs(household, udid); - String secondUserId = HouseholdUtils.getRegularUsersListFromHouseHold(household).get(0).getUserId(); + private void switchUser() { + Household household = createHousehold(numOfUsers, numOfDevices, false); + String udid = getDevicesList(household).get(0).getUdid(); + String masterUserId = getMasterUser(household).getUserId(); + String secondUserId = getRegularUsersList(household).get(0).getUserId(); + String masterUserKs = OttUserUtils.getKs(Integer.parseInt(masterUserId), udid); // Invoke session/action/switchUser - second user replace master user in the session - - SwitchUserSessionBuilder switchUserSessionBuilder = SessionService.switchUser(secondUserId); - switchUserSessionBuilder.setKs(masterUserKs); - Response loginSessionResponse = executor.executeSync(switchUserSessionBuilder); + Response loginSessionResponse = executor.executeSync(SessionService.switchUser(secondUserId) + .setKs(masterUserKs)); // Verify new session ks returned - assertThat(loginSessionResponse.results.getKs()).isNotEmpty(); + assertThat(loginSessionResponse.results).isNotNull(); String secondUserKs = loginSessionResponse.results.getKs(); + assertThat(secondUserKs).isNotEmpty(); ///----- After User was switched ------ - // Invoke OttUser/action/get - with master user (expired) ks - - OttUserService.GetOttUserBuilder getOttUserBuilder = OttUserService.get(); - getOttUserBuilder.setKs(masterUserKs); - Response ottUserResponse = executor.executeSync(getOttUserBuilder); + Response ottUserResponse = executor.executeSync(OttUserService.get() + .setKs(masterUserKs)); // Verify master user ks is now expired (after the switch) assertThat(ottUserResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500016).getCode()); // Invoke OttUser/action/get with second user new ks - - GetOttUserBuilder getOttUserBuilder2 = OttUserService.get(); - getOttUserBuilder2.setKs(secondUserKs); - Response ottUserResponse2 = executor.executeSync(getOttUserBuilder); + ottUserResponse = executor.executeSync(OttUserService.get() + .setKs(secondUserKs)); // Verify second user id return in the response - assertThat(ottUserResponse2.results.getId()).isEqualTo(secondUserId); - assertThat(ottUserResponse2.results.getUserState()).isEqualTo(UserState.OK); - + assertThat(ottUserResponse.results.getId()).isEqualTo(secondUserId); + assertThat(ottUserResponse.results.getUserState()).isEqualTo(UserState.OK); // Invoke session/action/get - - GetSessionBuilder getSessionBuilder = SessionService.get(secondUserKs); - getSessionBuilder.setKs(getAdministratorKs()); - Response getSessionResponse = executor.executeSync(getSessionBuilder); + Response getSessionResponse = executor.executeSync(SessionService.get(secondUserKs) + .setKs(getAdministratorKs())); // Verify second user id returned in the response assertThat(getSessionResponse.results.getUserId()).isEqualTo(secondUserId); assertThat(getSessionResponse.results.getUdid()).isEqualTo(udid); + + // cleanup - delete household + executor.executeSync(HouseholdService.delete().setKs(masterUserKs)); } + @Severity(SeverityLevel.MINOR) @Description("/session/action/switchUser - user switch to himself") @Test - private void SwitchUserToHimself() { - Household household = HouseholdUtils.createHousehold(2, 1, false); - String udid = HouseholdUtils.getDevicesListFromHouseHold(household).get(0).getUdid(); - String masterUserKs = HouseholdUtils.getHouseholdMasterUserKs(household, udid); - String masterUserId = HouseholdUtils.getMasterUserFromHousehold(household).getUserId(); + private void switchUserToHimself() { + Household household = createHousehold(numOfUsers, numOfDevices, false); + String udid = getDevicesList(household).get(0).getUdid(); + String masterUserId = getMasterUser(household).getUserId(); + String masterUserKs = OttUserUtils.getKs(Integer.parseInt(masterUserId), udid); // Invoke session/action/switchUser - Should return an error (user can't switched to himself - - SwitchUserSessionBuilder switchUserSessionBuilder = SessionService.switchUser(masterUserId); - switchUserSessionBuilder.setKs(masterUserKs); - Response loginSessionResponse = executor.executeSync(switchUserSessionBuilder); + Response loginSessionResponse = executor.executeSync(SessionService.switchUser(masterUserId) + .setKs(masterUserKs)); // Verify exception returned assertThat(loginSessionResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(1).getCode()); + // TODO: 6/19/2018 need to open a bug on error 1 + + // cleanup - delete household + executor.executeSync(HouseholdService.delete().setKs(masterUserKs)); } + @Severity(SeverityLevel.MINOR) @Description("/session/action/switchUser - switch to inactive user") - @Test - private void SwitchInactiveUser() { - + @Test(enabled = false) + private void switchToInactiveUser() { //TODO - replace hardcoded user id String inactiveUserId = "1543797"; - String UserKs = OttUserUtils.getKs(Integer.valueOf(UserId), null); - SwitchUserSessionBuilder switchUserSessionBuilder = SessionService.switchUser(inactiveUserId); - switchUserSessionBuilder.setKs(UserKs); - Response loginSessionResponse = executor.executeSync(switchUserSessionBuilder); + Response loginSessionResponse = executor.executeSync(SessionService.switchUser(inactiveUserId) + .setKs(userKs)); assertThat(loginSessionResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(2016).getCode()); } + @Severity(SeverityLevel.MINOR) @Description("/session/action/switchUser - switch to user from another HH") @Test private void switchToUserFromAnotherHousehold() { + Household household1 = createHousehold(numOfUsers, numOfDevices, false); + String masterUserKs1 = getHouseholdMasterUserKs(household1); - //TODO - replace hardcoded user id - String userIdFromHousehold1 = "1543798"; - String Use1rKs = OttUserUtils.getKs(Integer.valueOf(userIdFromHousehold1), null); - - //TODO - replace hardcoded user id - String userIdFromHousehold2 = "638731"; + Household household2 = createHousehold(numOfUsers, numOfDevices, false); + String masterUserId2 = getMasterUser(household2).getUserId(); - SwitchUserSessionBuilder switchUserSessionBuilder = SessionService.switchUser(userIdFromHousehold2); - switchUserSessionBuilder.setKs(Use1rKs); - Response loginSessionResponse = executor.executeSync(switchUserSessionBuilder); + Response loginSessionResponse = executor.executeSync(SessionService.switchUser(masterUserId2) + .setKs(masterUserKs1)); assertThat(loginSessionResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500055).getCode()); } - - @Description("/session/action/switchUser - No user id to switch provided") + @Severity(SeverityLevel.MINOR) + @Description("session/action/switchUser - No user id to switch provided") @Test private void switchToUserWithoutUserId() { - - SwitchUserSessionBuilder switchUserSessionBuilder = SessionService.switchUser(null); - switchUserSessionBuilder.setKs(userKs); - Response loginSessionResponse = executor.executeSync(switchUserSessionBuilder); + Response loginSessionResponse = executor.executeSync(SessionService.switchUser(null) + .setKs(userKs)); assertThat(loginSessionResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(500053).getCode()); } diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/transactionHistoryTests/TransactionHistoryListTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/transactionHistoryTests/TransactionHistoryListTests.java new file mode 100644 index 000000000..fdad52bb6 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/transactionHistoryTests/TransactionHistoryListTests.java @@ -0,0 +1,254 @@ +package com.kaltura.client.test.tests.servicesTests.transactionHistoryTests; + +import com.kaltura.client.Logger; +import com.kaltura.client.enums.*; +import com.kaltura.client.services.EntitlementService; +import com.kaltura.client.services.EntitlementService.ListEntitlementBuilder; +import com.kaltura.client.services.TransactionHistoryService; +import com.kaltura.client.services.TransactionHistoryService.ListTransactionHistoryBuilder; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.HouseholdUtils; +import com.kaltura.client.test.utils.PurchaseUtils; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.within; + +public class TransactionHistoryListTests extends BaseTest{ + + private static final String PPV_MODULE_ID_KEY = "ppvModuleId"; + private static final String PRICE_AMOUNT = "price"; + private static final String PRICE_CURRENCY = "currency"; + + //Epoch for transactionHistory filter (86400 sec = 24 hours) + private static final int yesterdayInEpoch = (int)((System.currentTimeMillis()/1000)-86400); + private static final int tomorrowInEpoch = (int)((System.currentTimeMillis()/1000)+86400); + + private ListTransactionHistoryBuilder listTransactionHistoryBuilder; + private EntitlementFilter entitlementFilter; + private TransactionHistoryFilter transactionHistoryFilter; + + private Response> listEntitlementServiceResponsePpv; + private Response> listEntitlementServiceResponseSubscription; + private Response> listBillingTransactionResponse; + private Response transactionResponseSubscription; + private Response transactionResponseCollection; + private Response transactionResponsePpv; + + private String masterUserKs; + private String userKs; + private String methodName; + + + @BeforeClass + public void transactionHistortTestSetup(){ + entitlementFilter = new EntitlementFilter(); + //Show entitlements per household + entitlementFilter.setEntityReferenceEqual(EntityReferenceBy.HOUSEHOLD); + //Don't show expired assets + entitlementFilter.setIsExpiredEqual(false); + transactionHistoryFilter = new TransactionHistoryFilter(); + //Start date from yesterday + transactionHistoryFilter.setStartDateGreaterThanOrEqual(yesterdayInEpoch); + //End date before tomorrow + transactionHistoryFilter.setEndDateLessThanOrEqual(tomorrowInEpoch); + + int numberOfUsersInHousehold = 2; + int numberOfDevicesInHousehold = 2; + Household household = HouseholdUtils.createHousehold(numberOfUsersInHousehold, numberOfDevicesInHousehold,true); + //Login with master to first device + masterUserKs = HouseholdUtils.getHouseholdMasterUserKs(household, HouseholdUtils.getDevicesList(household).get(0).getUdid()); + //Login with user to second device + userKs = HouseholdUtils.getHouseholdUserKs(household, HouseholdUtils.getDevicesList(household).get(1).getUdid()); + + //All transactions per household - empty + transactionHistoryFilter.setEntityReferenceEqual(EntityReferenceBy.HOUSEHOLD); + listTransactionHistoryBuilder = TransactionHistoryService.list(transactionHistoryFilter).setKs(masterUserKs); + //transactionHistory/action/list for household with master user ks + listBillingTransactionResponse = executor.executeSync(listTransactionHistoryBuilder); + //No errors appeared at response + assertThat(listBillingTransactionResponse.error).isNull(); + //No purchases were performed + assertThat(listBillingTransactionResponse.results.getTotalCount()).isEqualTo(0); + + //Purchase asset with non-master user + transactionResponsePpv = PurchaseUtils.purchasePpv(userKs, Optional.of(getSharedMediaAsset().getId().intValue()), Optional.of(getSharedWebMediaFile().getId()), Optional.empty()); + //Purchase subscription with non-master user + transactionResponseSubscription = PurchaseUtils.purchaseSubscription(userKs, Integer.parseInt(getSharedCommonSubscription().getId()), Optional.empty()); + //Purchase collection with master user + transactionResponseCollection = PurchaseUtils.purchaseCollection(masterUserKs, Integer.parseInt(getSharedCommonCollection().getId())); + + + //Show PPV entitlements + entitlementFilter.setProductTypeEqual(TransactionType.PPV); + ListEntitlementBuilder listEntitlementBuilder = EntitlementService.list(entitlementFilter).setKs(userKs); + //entitlement/action/list + listEntitlementServiceResponsePpv = executor.executeSync(listEntitlementBuilder); + //Verify response is correct + assertThat(listEntitlementServiceResponsePpv.error).isNull(); + assertThat(listEntitlementServiceResponsePpv.results.getObjects().get(0).getClass()).isEqualTo(PpvEntitlement.class); + assertThat(listEntitlementServiceResponsePpv.results.getTotalCount()).isEqualTo(1); + //Conversion from Entitlement to PpvEntitlement object + List ppvEntitlementList = new ArrayList<>(); + for(Entitlement entitlement:listEntitlementServiceResponsePpv.results.getObjects()){ + if(entitlement.getClass() == PpvEntitlement.class) { + ppvEntitlementList.add((PpvEntitlement) entitlement); + } + } + //Verify that PPV is correct + assertThat(ppvEntitlementList.get(0).getProductId()).isEqualTo(PurchaseUtils.purchasePpvDetailsMap.get(PPV_MODULE_ID_KEY)); + //Verify that asset file is correct + assertThat(ppvEntitlementList.get(0).getMediaFileId()).isEqualTo(getSharedWebMediaFile().getId()); + + //Show subscription entitlements + entitlementFilter.setProductTypeEqual(TransactionType.SUBSCRIPTION); + listEntitlementBuilder = EntitlementService.list(entitlementFilter).setKs(userKs); + //entitlement/action/list + listEntitlementServiceResponseSubscription = executor.executeSync(listEntitlementBuilder); + //Verify that subscription is correct + assertThat(listEntitlementServiceResponseSubscription.results.getTotalCount()).isEqualTo(1); + assertThat(listEntitlementServiceResponseSubscription.results.getObjects().get(0).getProductId()).isEqualTo(getSharedCommonSubscription().getId()); + assertThat(listEntitlementServiceResponseSubscription.results.getObjects().get(0).getClass()).isEqualTo(SubscriptionEntitlement.class); + } + + @Severity(SeverityLevel.BLOCKER) + @Description("/transactionHistory/action/list - test purchases per household are written correctly at transactionHistory for non-master user") + @Test + public void transactionHistoryPerHouseholdWithUserKs() { + //All transactions per non-master user + transactionHistoryFilter.setEntityReferenceEqual(EntityReferenceBy.HOUSEHOLD); + listTransactionHistoryBuilder = TransactionHistoryService.list(transactionHistoryFilter).setKs(userKs); + //transactionHistory/action/list for non-master user + listBillingTransactionResponse = executor.executeSync(listTransactionHistoryBuilder); + //No errors appeared at response + assertThat(listBillingTransactionResponse.error).isNull(); + assertThat(listBillingTransactionResponse.results).isNotNull(); + //Verify that two transactions were performed + assertThat(listBillingTransactionResponse.results.getTotalCount()).isEqualTo(3); + assertThat(listBillingTransactionResponse.results.getObjects().size()).isEqualTo(3); + List billingTransactionList = listBillingTransactionResponse.results.getObjects(); + methodName = new Object() {}.getClass().getEnclosingMethod().getName(); + assertMethod(methodName, billingTransactionList); + } + + @Severity(SeverityLevel.BLOCKER) + @Description("/transactionHistory/action/list - test purchases per user are written correctly at transactionHistory for non-master user") + @Test + public void transactionHistoryPerUserWithUserKs() { + //All transactions per non-master user + transactionHistoryFilter.setEntityReferenceEqual(EntityReferenceBy.USER); + listTransactionHistoryBuilder = TransactionHistoryService.list(transactionHistoryFilter).setKs(userKs); + //transactionHistory/action/list for non-master user + listBillingTransactionResponse = executor.executeSync(listTransactionHistoryBuilder); + //No errors appeared at response + assertThat(listBillingTransactionResponse.error).isNull(); + assertThat(listBillingTransactionResponse.results).isNotNull(); + //Verify that two transactions were performed + assertThat(listBillingTransactionResponse.results.getTotalCount()).isEqualTo(2); + assertThat(listBillingTransactionResponse.results.getObjects().size()).isEqualTo(2); + List billingTransactionList = listBillingTransactionResponse.results.getObjects(); + methodName = new Object() {}.getClass().getEnclosingMethod().getName(); + assertMethod(methodName, billingTransactionList); + } + + @Severity(SeverityLevel.BLOCKER) + @Description("/transactionHistory/action/list - test purchases per household are written correctly at transactionHistory for master user") + @Test + public void transactionHistoryPerHouseholdWithMasterKs() { + //All transactions per master user + transactionHistoryFilter.setEntityReferenceEqual(EntityReferenceBy.HOUSEHOLD); + listTransactionHistoryBuilder = TransactionHistoryService.list(transactionHistoryFilter).setKs(masterUserKs); + //transactionHistory/action/list for master user + listBillingTransactionResponse = executor.executeSync(listTransactionHistoryBuilder); + //No errors appeared at response + assertThat(listBillingTransactionResponse.error).isNull(); + assertThat(listBillingTransactionResponse.results).isNotNull(); + //Verify that two transactions were performed + assertThat(listBillingTransactionResponse.results.getTotalCount()).isEqualTo(3); + assertThat(listBillingTransactionResponse.results.getObjects().size()).isEqualTo(3); + List billingTransactionList = listBillingTransactionResponse.results.getObjects(); + methodName = new Object() {}.getClass().getEnclosingMethod().getName(); + assertMethod(methodName, billingTransactionList); + } + + @Severity(SeverityLevel.BLOCKER) + @Description("/transactionHistory/action/list - test no purchases per user were written at transactionHistory for master user") + @Test + public void transactionHistoryPerUserWithMasterKs() { + //All transactions per master user + transactionHistoryFilter.setEntityReferenceEqual(EntityReferenceBy.USER); + listTransactionHistoryBuilder = TransactionHistoryService.list(transactionHistoryFilter).setKs(masterUserKs); + //transactionHistory/action/list for master user + listBillingTransactionResponse = executor.executeSync(listTransactionHistoryBuilder); + //No errors appeared at response + assertThat(listBillingTransactionResponse.error).isNull(); + assertThat(listBillingTransactionResponse.results).isNotNull(); + //Verify that one transaction was performed + assertThat(listBillingTransactionResponse.results.getTotalCount()).isEqualTo(1); + assertThat(listBillingTransactionResponse.results.getObjects().size()).isEqualTo(1); + List billingTransactionList = listBillingTransactionResponse.results.getObjects(); + methodName = new Object() {}.getClass().getEnclosingMethod().getName(); + assertMethod(methodName, billingTransactionList); + } + + private void assertMethod(String methodName, List billingTransactionList) { + Logger.getLogger(TransactionHistoryListTests.class).debug(methodName); + for(BillingTransaction billingTransaction : billingTransactionList) { + assertThat(billingTransaction.getClass()).isEqualTo(BillingTransaction.class); + assertThat(billingTransaction.getBillingAction()).isEqualTo(BillingAction.PURCHASE); + assertThat(billingTransaction.getIsRecurring()).isEqualTo(false); + assertThat(billingTransaction.getBillingPriceType()).isEqualTo(BillingPriceType.FULLPERIOD); + switch (billingTransaction.getItemType()){ + case SUBSCRIPTION: + assertThat(billingTransaction.getRecieptCode()).isEqualTo(transactionResponseSubscription.results.getId()); + //TODO: Shared Subscription name not equals to transactionHistory name written (Title written). (deprecate this assertion or amend with another way) +// assertThat(billingTransactionSubscription.getPurchasedItemName()).isEqualTo(getSharedCommonSubscription().getName()); + assertThat(billingTransaction.getPurchasedItemCode()).isEqualTo(getSharedCommonSubscription().getId()); + assertThat(billingTransaction.getItemType()).isEqualTo(BillingItemsType.SUBSCRIPTION); + assertThat(billingTransaction.getPrice().getAmount().toString()).isEqualTo(PurchaseUtils.purchaseSubscriptionDetailsMap.get(PRICE_AMOUNT)); + assertThat(billingTransaction.getPrice().getCurrency()).isEqualTo(PurchaseUtils.purchaseSubscriptionDetailsMap.get(PRICE_CURRENCY)); + assertThat(billingTransaction.getStartDate().intValue()).isCloseTo(transactionResponseSubscription.results.getCreatedAt(), within(2)); + assertThat(billingTransaction.getActionDate().intValue()).isCloseTo(transactionResponseSubscription.results.getCreatedAt(), within(2)); + break; + + case PPV: + assertThat(billingTransaction.getRecieptCode()).isEqualTo(transactionResponsePpv.results.getId()); + assertThat(billingTransaction.getPurchasedItemName()).isEqualTo(getSharedMediaAsset().getName()); + assertThat(billingTransaction.getPurchasedItemCode()).isEqualTo(getSharedMediaAsset().getId().toString()); + assertThat(billingTransaction.getItemType()).isEqualTo(BillingItemsType.PPV); + assertThat(billingTransaction.getPrice().getAmount().toString()).isEqualTo(PurchaseUtils.purchasePpvDetailsMap.get(PRICE_AMOUNT)); + assertThat(billingTransaction.getPrice().getCurrency()).isEqualTo(PurchaseUtils.purchasePpvDetailsMap.get(PRICE_CURRENCY)); + assertThat(billingTransaction.getStartDate().intValue()).isCloseTo(transactionResponsePpv.results.getCreatedAt(), within(2)); + assertThat(billingTransaction.getActionDate().intValue()).isCloseTo(transactionResponsePpv.results.getCreatedAt(), within(2)); + break; + + case COLLECTION: + assertThat(billingTransaction.getRecieptCode()).isEqualTo(transactionResponseCollection.results.getId()); + assertThat(billingTransaction.getPurchasedItemName()).isEqualTo(getSharedCommonCollection().getMultilingualName().get(0).getValue()); + assertThat(billingTransaction.getPurchasedItemCode()).isEqualTo(getSharedCommonCollection().getId()); + assertThat(billingTransaction.getItemType()).isEqualTo(BillingItemsType.COLLECTION); + assertThat(billingTransaction.getPrice().getAmount().toString()).isEqualTo(PurchaseUtils.purchaseCollectionDetailsMap.get(PRICE_AMOUNT)); + assertThat(billingTransaction.getPrice().getCurrency()).isEqualTo(PurchaseUtils.purchaseCollectionDetailsMap.get(PRICE_CURRENCY)); + assertThat(billingTransaction.getStartDate().intValue()).isCloseTo(transactionResponseCollection.results.getCreatedAt(), within(2)); + assertThat(billingTransaction.getActionDate().intValue()).isCloseTo(transactionResponseCollection.results.getCreatedAt(), within(2)); + break; + + default: + Logger.getLogger(TransactionHistoryListTests.class).error("No valid item type found!"); + fail("No valid item type found!"); + break; + } + } + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/transactionTests/transactionPurchaseTests/TransactionPurchaseTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/transactionTests/transactionPurchaseTests/TransactionPurchaseTests.java new file mode 100644 index 000000000..46c764c52 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/transactionTests/transactionPurchaseTests/TransactionPurchaseTests.java @@ -0,0 +1,563 @@ +package com.kaltura.client.test.tests.servicesTests.transactionTests.transactionPurchaseTests; + +import com.kaltura.client.enums.PurchaseStatus; +import com.kaltura.client.enums.TransactionAdapterStatus; +import com.kaltura.client.enums.TransactionType; +import com.kaltura.client.services.HouseholdPaymentGatewayService; +import com.kaltura.client.services.PaymentGatewayProfileService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +import static com.kaltura.client.services.HouseholdService.delete; +import static com.kaltura.client.services.ProductPriceService.list; +import static com.kaltura.client.services.TransactionService.purchase; +import static com.kaltura.client.test.Properties.PAYMENT_GATEWAY_ADAPTER_URL; +import static com.kaltura.client.test.utils.HouseholdUtils.*; +import static com.kaltura.client.test.utils.ingestUtils.IngestPpvUtils.*; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.within; + +public class TransactionPurchaseTests extends BaseTest { + + private String masterUserKs; + private String userKs; + + @BeforeClass() + public void transaction_purchase_before_class(){ + // Prepare household with users and devices + int numOfUsers = 2; + int numOfDevices = 2; + + Household household = createHousehold(numOfUsers, numOfDevices, true); + + String masterUserUdid = getDevicesList(household).get(0).getUdid(); + masterUserKs = getHouseholdMasterUserKs(household, masterUserUdid); + + String userUdid = getDevicesList(household).get(1).getUdid(); + userKs = getHouseholdUserKs(household, userUdid); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("transaction/action/purchase - ppv with default PG") + @Test() + public void purchasePpvWithDefaultPG() { + // set product price filter + ProductPriceFilter productPriceFilter = new ProductPriceFilter(); + productPriceFilter.setFileIdIn(getSharedWebMediaFile().getId().toString()); + + // productPrice list + Response> productPriceResponse = executor.executeSync(list(productPriceFilter) + .setKs(masterUserKs)); + assertThat(productPriceResponse.results).isNotNull(); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + + // get ppv + PpvPrice productPricePpv = (PpvPrice) productPriceResponse.results.getObjects().get(0); + assertThat(productPricePpv.getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPricePpv.getFileId()).isEqualTo(getSharedWebMediaFile().getId()); + + // purchase ppv + Purchase purchase = new Purchase(); + purchase.setProductType(TransactionType.PPV); + purchase.setProductId(Integer.valueOf(productPricePpv.getPpvModuleId())); + purchase.setContentId(getSharedWebMediaFile().getId()); + purchase.setCurrency(productPricePpv.getPrice().getCurrency()); + purchase.setPrice(productPricePpv.getPrice().getAmount()); + + Transaction purchasePpvTransaction = executor.executeSync(purchase(purchase) + .setKs(masterUserKs)) + .results; + + // assert transaction + assertThat(purchasePpvTransaction).isNotNull(); + assertThat(purchasePpvTransaction.getCreatedAt()).isCloseTo((int) getEpoch(), within(120)); + assertThat(purchasePpvTransaction.getPaymentGatewayResponseId()).isEqualTo(TransactionAdapterStatus.OK.getValue()); + assertThat(purchasePpvTransaction.getState()).isEqualTo(TransactionAdapterStatus.OK.getValue()); + assertThat(purchasePpvTransaction.getFailReasonCode()).isEqualTo(0); + assertThat(purchasePpvTransaction.getRelatedObjects()).isNull(); + + // assert productPrice list with regular userKs + productPriceResponse = executor.executeSync(list(productPriceFilter) + .setKs(userKs)); + assertThat(productPriceResponse.results).isNotNull(); + + productPricePpv = (PpvPrice) productPriceResponse.results.getObjects().get(0); + assertThat(productPricePpv.getPurchaseStatus()).isEqualTo(PurchaseStatus.PPV_PURCHASED); + assertThat(productPricePpv.getFileId()).isEqualTo(getSharedWebMediaFile().getId()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("transaction/action/purchase - subscription with default PG") + @Test() + public void purchaseSubscriptionWithDefaultPG() { + // set product price filter + ProductPriceFilter productPriceFilter = new ProductPriceFilter(); + productPriceFilter.setSubscriptionIdIn(getSharedCommonSubscription().getId()); + + // productPrice list + Response> productPriceResponse = executor.executeSync(list(productPriceFilter) + .setKs(masterUserKs)); + assertThat(productPriceResponse.results).isNotNull(); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + + // purchase subscription + Purchase purchase = new Purchase(); + purchase.setProductType(TransactionType.SUBSCRIPTION); + purchase.setContentId(0); + purchase.setCurrency(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()); + purchase.setProductId(Integer.valueOf(getSharedCommonSubscription().getId())); + purchase.setPrice(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()); + + Transaction subscriptionTransaction = executor.executeSync(purchase(purchase) + .setKs(masterUserKs)) + .results; + + // assert transaction + assertThat(subscriptionTransaction).isNotNull(); + assertThat(subscriptionTransaction.getCreatedAt()).isCloseTo((int) getEpoch(), within(120)); + assertThat(subscriptionTransaction.getPaymentGatewayResponseId()).isEqualTo(TransactionAdapterStatus.OK.getValue()); + assertThat(subscriptionTransaction.getState()).isEqualTo(TransactionAdapterStatus.OK.getValue()); + assertThat(subscriptionTransaction.getFailReasonCode()).isEqualTo(0); + assertThat(subscriptionTransaction.getRelatedObjects()).isNull(); + + // assert productPrice list with regular userKs + productPriceResponse = executor.executeSync(list(productPriceFilter) + .setKs(userKs)); + assertThat(productPriceResponse.results).isNotNull(); + + SubscriptionPrice subscriptionPrice = (SubscriptionPrice) productPriceResponse.results.getObjects().get(0); + assertThat(subscriptionPrice.getPurchaseStatus()).isEqualTo(PurchaseStatus.SUBSCRIPTION_PURCHASED); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("transaction/action/purchase - collection with default PG") + @Test() + public void purchaseCollectionWithDefaultPG() { + // set product price filter + ProductPriceFilter productPriceFilter = new ProductPriceFilter(); + productPriceFilter.setCollectionIdIn(getSharedCommonCollection().getId()); + + // productPrice list + Response> productPriceResponse = executor.executeSync(list(productPriceFilter) + .setKs(masterUserKs)); + assertThat(productPriceResponse.results).isNotNull(); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + + // purchase collection + Purchase purchase = new Purchase(); + purchase.setCurrency(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()); + purchase.setPrice(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()); + purchase.setContentId(0); + purchase.setProductId(Integer.valueOf(getSharedCommonCollection().getId())); + purchase.setProductType(TransactionType.COLLECTION); + + Transaction collectionTransaction = executor.executeSync(purchase(purchase) + .setKs(masterUserKs)) + .results; + + // assert transaction + assertThat(collectionTransaction).isNotNull(); + assertThat(collectionTransaction.getCreatedAt()).isCloseTo((int) getEpoch(), within(120)); + assertThat(collectionTransaction.getPaymentGatewayResponseId()).isEqualTo(TransactionAdapterStatus.OK.getValue()); + assertThat(collectionTransaction.getState()).isEqualTo(TransactionAdapterStatus.OK.getValue()); + assertThat(collectionTransaction.getFailReasonCode()).isEqualTo(0); + assertThat(collectionTransaction.getRelatedObjects()).isNull(); + + // assert productPrice list with regular userKs + productPriceResponse = executor.executeSync(list(productPriceFilter) + .setKs(userKs)); + assertThat(productPriceResponse.results).isNotNull(); + + CollectionPrice collectionPrice = (CollectionPrice) productPriceResponse.results.getObjects().get(0); + assertThat(collectionPrice.getPurchaseStatus()).isEqualTo(PurchaseStatus.COLLECTION_PURCHASED); + } + + @Severity(SeverityLevel.NORMAL) + @Description("transaction/action/purchase - subscription with household without PG - error 6007") + @Test() + public void purchaseSubscriptionWithoutPG() { + // Prepare household with users and devices + Household household = createHousehold(1, 1, false); + String masterUserUdid = getDevicesList(household).get(0).getUdid(); + String masterUserKs = getHouseholdMasterUserKs(household, masterUserUdid); + + // set product price filter + ProductPriceFilter productPriceFilter = new ProductPriceFilter(); + productPriceFilter.setSubscriptionIdIn(getSharedCommonSubscription().getId()); + + // productPrice list + Response> productPriceResponse = executor.executeSync(list(productPriceFilter) + .setKs(masterUserKs)); + assertThat(productPriceResponse.results).isNotNull(); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + + // purchase collection + Purchase purchase = new Purchase(); + purchase.setCurrency(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()); + purchase.setPrice(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()); + purchase.setContentId(0); + purchase.setProductId(Integer.valueOf(getSharedCommonSubscription().getId())); + purchase.setProductType(TransactionType.SUBSCRIPTION); + + Response transactionResponse = executor.executeSync(purchase(purchase) + .setKs(masterUserKs)); + + // assert transaction + assertThat(transactionResponse.results).isNull(); + assertThat(transactionResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(6007).getCode()); + + //cleanup - delete hh + executor.executeSync(delete().setKs(masterUserKs)); + } + + @Severity(SeverityLevel.NORMAL) + @Description("transaction/action/purchase - collection with household with PG without charge id - error 6009") + @Test() + public void purchaseCollectionWithPGWithoutChargeId() { + // Prepare household with users and devices + Household household = createHousehold(1, 1, false); + String masterUserUdid = getDevicesList(household).get(0).getUdid(); + String masterUserKs = getHouseholdMasterUserKs(household, masterUserUdid); + + // create paymentGateway + DateFormat df = new SimpleDateFormat("yyMMddHHmmssSS"); + String externalIdentifier = df.format(new Date()); + + PaymentGatewayProfile pg = new PaymentGatewayProfile(); + pg.setName("paymentGateway_" + getEpoch()); + pg.setIsActive(1); + pg.setIsDefault(false); + pg.setRenewStartMinutes(-5); + pg.setRenewIntervalMinutes(15); + pg.setPendingRetries(0); + pg.setPendingInterval(0); + pg.setSharedSecret("123456"); + pg.setExternalIdentifier(externalIdentifier); + pg.setRenewUrl(PAYMENT_GATEWAY_ADAPTER_URL + "?StateCode=0"); + pg.setAdapterUrl(PAYMENT_GATEWAY_ADAPTER_URL); + + // add paymentGateway + pg = executor.executeSync(PaymentGatewayProfileService.add(pg) + .setKs(getOperatorKs())) + .results; + + // enable pg for hh + Response booleanResponse = executor.executeSync(HouseholdPaymentGatewayService.enable(pg.getId()) + .setKs(masterUserKs)); + assertThat(booleanResponse.results).isTrue(); + + // set product price filter + ProductPriceFilter productPriceFilter = new ProductPriceFilter(); + productPriceFilter.setCollectionIdIn(getSharedCommonCollection().getId()); + + // productPrice list + Response> productPriceResponse = executor.executeSync(list(productPriceFilter) + .setKs(masterUserKs)); + assertThat(productPriceResponse.results).isNotNull(); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + + // purchase collection + Purchase purchase = new Purchase(); + purchase.setCurrency(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()); + purchase.setPrice(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()); + purchase.setContentId(0); + purchase.setProductId(Integer.valueOf(getSharedCommonCollection().getId())); + purchase.setProductType(TransactionType.COLLECTION); + + Response transactionResponse = executor.executeSync(purchase(purchase) + .setKs(masterUserKs)); + + // assert transaction + assertThat(transactionResponse.results).isNull(); + assertThat(transactionResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(6009).getCode()); + + //cleanup - delete hh and pg + executor.executeSync(delete().setKs(masterUserKs)); + executor.executeSync(PaymentGatewayProfileService.delete(pg.getId()).setKs(getOperatorKs())); + } + + @Severity(SeverityLevel.NORMAL) + @Description("transaction/action/purchase - ppv configured to 'Subscription Only' - error 3023") + @Test() + public void purchaseSubscriptionOnlyPpv() { + // ingest ppv configured to 'Subscription Only' + PpvData ppvData = new PpvData().isSubscriptionOnly(true); + Ppv ppv = insertPpv(ppvData); + + VodData vodData = new VodData() + .ppvWebName(ppv.getName()) + .ppvMobileName(ppv.getName()); + MediaAsset mediaAsset = insertVod(vodData, true); + + // purchase ppv + Purchase purchase = new Purchase(); + purchase.setProductType(TransactionType.PPV); + purchase.setProductId(Integer.valueOf(ppv.getId())); + purchase.setContentId(mediaAsset.getMediaFiles().get(0).getId()); + purchase.setCurrency(ppv.getPrice().getPrice().getCurrency()); + purchase.setPrice(ppv.getPrice().getPrice().getAmount()); + + Response transactionResponse = executor.executeSync(purchase(purchase) + .setKs(masterUserKs)); + + // assert transaction + assertThat(transactionResponse.results).isNull(); + assertThat(transactionResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(3023).getCode()); + + //cleanup - delete ppv + deletePpv(ppv.getName()); + deleteVod(mediaAsset.getName()); + } + + @Severity(SeverityLevel.NORMAL) + @Description("transaction/action/purchase - subscription with invalid price - error 6000") + @Test() + public void purchaseSubscriptionWithInvalidPrice() { + // Prepare household with users and devices + Household household = createHousehold(1, 1, true); + String masterUserUdid = getDevicesList(household).get(0).getUdid(); + String masterUserKs = getHouseholdMasterUserKs(household, masterUserUdid); + + // set product price filter + ProductPriceFilter productPriceFilter = new ProductPriceFilter(); + productPriceFilter.setSubscriptionIdIn(getSharedCommonSubscription().getId()); + + // productPrice list + Response> productPriceResponse = executor.executeSync(list(productPriceFilter) + .setKs(masterUserKs)); + assertThat(productPriceResponse.results).isNotNull(); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + + // purchase subscription + Purchase purchase = new Purchase(); + purchase.setProductType(TransactionType.SUBSCRIPTION); + purchase.setContentId(0); + purchase.setCurrency(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()); + purchase.setProductId(Integer.valueOf(getSharedCommonSubscription().getId())); + purchase.setPrice(productPriceResponse.results.getObjects().get(0).getPrice().getAmount() + 1); + + Response transactionResponse = executor.executeSync(purchase(purchase) + .setKs(masterUserKs)); + + // assert transaction + assertThat(transactionResponse.results).isNull(); + assertThat(transactionResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(6000).getCode()); + + //cleanup - delete hh + executor.executeSync(delete().setKs(masterUserKs)); + } + + @Severity(SeverityLevel.NORMAL) + @Description("transaction/action/purchase - ppv with invalid ppv moduleId - error 6001") + @Test() + public void purchasePpvWithInvalidPpvModuleId() { + // Prepare household with users and devices + Household household = createHousehold(1, 1, true); + String masterUserUdid = getDevicesList(household).get(0).getUdid(); + String masterUserKs = getHouseholdMasterUserKs(household, masterUserUdid); + + // set product price filter + ProductPriceFilter productPriceFilter = new ProductPriceFilter(); + productPriceFilter.setFileIdIn(getSharedWebMediaFile().getId().toString()); + + // productPrice list + Response> productPriceResponse = executor.executeSync(list(productPriceFilter) + .setKs(masterUserKs)); + assertThat(productPriceResponse.results).isNotNull(); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + + // get ppv + PpvPrice productPricePpv = (PpvPrice) productPriceResponse.results.getObjects().get(0); + assertThat(productPricePpv.getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPricePpv.getFileId()).isEqualTo(getSharedWebMediaFile().getId()); + + // purchase ppv + Purchase purchase = new Purchase(); + purchase.setProductType(TransactionType.PPV); + purchase.setProductId(1); + purchase.setContentId(getSharedWebMediaFile().getId()); + purchase.setCurrency(productPricePpv.getPrice().getCurrency()); + purchase.setPrice(productPricePpv.getPrice().getAmount()); + + Response transactionResponse = executor.executeSync(purchase(purchase) + .setKs(masterUserKs)); + + // assert transaction + assertThat(transactionResponse.results).isNull(); + assertThat(transactionResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(6001).getCode()); + + //cleanup - delete hh + executor.executeSync(delete().setKs(masterUserKs)); + } + + @Severity(SeverityLevel.NORMAL) + @Description("transaction/action/purchase - same collection twice - error 3021") + @Test() + public void purchaseCollectionTwice() { + // Prepare household with users and devices + Household household = createHousehold(2, 2, true); + List devices = getDevicesList(household); + String masterUserKs = getHouseholdMasterUserKs(household, devices.get(0).getUdid()); + String userKs = getHouseholdUserKs(household, devices.get(1).getUdid()); + + // set product price filter + ProductPriceFilter productPriceFilter = new ProductPriceFilter(); + productPriceFilter.setCollectionIdIn(getSharedCommonCollection().getId()); + + // productPrice list + Response> productPriceResponse = executor.executeSync(list(productPriceFilter) + .setKs(masterUserKs)); + assertThat(productPriceResponse.results).isNotNull(); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + + // purchase collection + Purchase purchase = new Purchase(); + purchase.setCurrency(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()); + purchase.setPrice(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()); + purchase.setContentId(0); + purchase.setProductId(Integer.valueOf(getSharedCommonCollection().getId())); + purchase.setProductType(TransactionType.COLLECTION); + + // purchase collection - first time + executor.executeSync(purchase(purchase) + .setKs(masterUserKs)); + + // purchase collection - second time + Response transactionResponse = executor.executeSync(purchase(purchase) + .setKs(userKs)); + + // assert transaction + assertThat(transactionResponse.results).isNull(); + assertThat(transactionResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(3027).getCode()); + + //cleanup - delete hh + executor.executeSync(delete().setKs(masterUserKs)); + } + + @Severity(SeverityLevel.NORMAL) + @Description("transaction/action/purchase - same ppv twice - error 3021") + @Test() + public void purchasePpvTwice() { + // Prepare household with users and devices + Household household = createHousehold(2, 2, true); + List devices = getDevicesList(household); + String masterUserKs = getHouseholdMasterUserKs(household, devices.get(0).getUdid()); + String userKs = getHouseholdUserKs(household, devices.get(1).getUdid()); + + // set product price filter + ProductPriceFilter productPriceFilter = new ProductPriceFilter(); + productPriceFilter.setFileIdIn(getSharedWebMediaFile().getId().toString()); + + // productPrice list + Response> productPriceResponse = executor.executeSync(list(productPriceFilter) + .setKs(masterUserKs)); + assertThat(productPriceResponse.results).isNotNull(); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + + // get ppv + PpvPrice productPricePpv = (PpvPrice) productPriceResponse.results.getObjects().get(0); + assertThat(productPricePpv.getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPricePpv.getFileId()).isEqualTo(getSharedWebMediaFile().getId()); + + // purchase ppv + Purchase purchase = new Purchase(); + purchase.setProductType(TransactionType.PPV); + purchase.setProductId(Integer.valueOf(productPricePpv.getPpvModuleId())); + purchase.setContentId(getSharedWebMediaFile().getId()); + purchase.setCurrency(productPricePpv.getPrice().getCurrency()); + purchase.setPrice(productPricePpv.getPrice().getAmount()); + + // purchase ppv - first time + executor.executeSync(purchase(purchase) + .setKs(masterUserKs)); + + // purchase ppv - second time + Response transactionResponse = executor.executeSync(purchase(purchase) + .setKs(userKs)); + + // assert transaction + assertThat(transactionResponse.results).isNull(); + assertThat(transactionResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(3021).getCode()); + + //cleanup - delete hh + executor.executeSync(delete().setKs(masterUserKs)); + } + + @Severity(SeverityLevel.NORMAL) + @Description("transaction/action/purchase - same subscription twice - error 3024") + @Test() + public void purchaseSubscriptionTwice() { + // Prepare household with users and devices + Household household = createHousehold(2, 2, true); + List devices = getDevicesList(household); + String masterUserKs = getHouseholdMasterUserKs(household, devices.get(0).getUdid()); + String userKs = getHouseholdUserKs(household, devices.get(1).getUdid()); + + // set product price filter + ProductPriceFilter productPriceFilter = new ProductPriceFilter(); + productPriceFilter.setSubscriptionIdIn(getSharedCommonSubscription().getId()); + + // productPrice list + Response> productPriceResponse = executor.executeSync(list(productPriceFilter) + .setKs(masterUserKs)); + assertThat(productPriceResponse.results).isNotNull(); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + + // purchase subscription + Purchase purchase = new Purchase(); + purchase.setProductType(TransactionType.SUBSCRIPTION); + purchase.setContentId(0); + purchase.setCurrency(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()); + purchase.setProductId(Integer.valueOf(getSharedCommonSubscription().getId())); + purchase.setPrice(productPriceResponse.results.getObjects().get(0).getPrice().getAmount()); + + // purchase subscription - first time + executor.executeSync(purchase(purchase) + .setKs(masterUserKs)); + + // purchase subscription - second time - because of beo-5249 + executor.executeSync(purchase(purchase) + .setKs(masterUserKs)); + + // purchase subscription - third time + Response transactionResponse = executor.executeSync(purchase(purchase) + .setKs(userKs)); + + // assert transaction + assertThat(transactionResponse.results).isNull(); + assertThat(transactionResponse.error.getCode()).isEqualTo(getAPIExceptionFromList(3024).getCode()); + + //cleanup - delete hh + executor.executeSync(delete().setKs(masterUserKs)); + } + + // TODO: 8/15/2018 complete below scenarios: + // with discount + // ppv with expired file + // ppv with file off + // asset with future start date + // asset with off ppv + // asset with expired / off file + // + // + // check mpp + + @AfterClass + public void transaction_purchase_after_class() { + // cleanup + executor.executeSync(delete().setKs(masterUserKs)); + } +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/transactionTests/transactionPurchaseTests/TransactionPurchaseWithCouponTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/transactionTests/transactionPurchaseTests/TransactionPurchaseWithCouponTests.java new file mode 100644 index 000000000..daf5b9852 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/transactionTests/transactionPurchaseTests/TransactionPurchaseWithCouponTests.java @@ -0,0 +1,215 @@ +package com.kaltura.client.test.tests.servicesTests.transactionTests.transactionPurchaseTests; + +import com.kaltura.client.enums.CouponGroupType; +import com.kaltura.client.enums.PurchaseStatus; +import com.kaltura.client.enums.TransactionType; +import com.kaltura.client.services.*; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.test.utils.BaseUtils; +import com.kaltura.client.test.utils.ingestUtils.IngestPpvUtils; +import com.kaltura.client.test.utils.ingestUtils.IngestVodUtils; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; +import io.qameta.allure.Description; +import io.qameta.allure.Severity; +import io.qameta.allure.SeverityLevel; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.Arrays; +import java.util.Calendar; +import java.util.List; + +import static com.kaltura.client.services.CouponsGroupService.add; +import static com.kaltura.client.services.ProductPriceService.list; +import static com.kaltura.client.test.Properties.DISCOUNT_CODE_ID; +import static com.kaltura.client.test.Properties.getProperty; +import static com.kaltura.client.test.utils.HouseholdUtils.*; +import static com.kaltura.client.test.utils.ingestUtils.IngestMppUtils.*; +import static com.kaltura.client.test.utils.ingestUtils.IngestPpvUtils.deletePpv; +import static com.kaltura.client.test.utils.ingestUtils.IngestPpvUtils.insertPpv; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.deleteVod; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.insertVod; +import static org.assertj.core.api.Java6Assertions.assertThat; + +public class TransactionPurchaseWithCouponTests extends BaseTest { + + private static CouponsGroup cg; + private static List coupons; + private static String masterUserKs; + private static Integer discountPercentage; + + @BeforeClass + public void TransactionPurchaseWithCouponTests_beforeClass() { + // create household + Household household = createHousehold(); + List devices = getDevicesList(household); + masterUserKs = getHouseholdMasterUserKs(household, devices.get(0).getUdid()); + + // add coupon group + cg = new CouponsGroup(); + cg.setCouponGroupType(CouponGroupType.COUPON); + cg.setName("Coupon_" + BaseUtils.getEpoch()); + cg.setDiscountId(Long.parseLong(getProperty(DISCOUNT_CODE_ID))); + cg.setMaxUsesNumber(100); + cg.setStartDate(getEpoch(Calendar.MONTH, -1)); + cg.setEndDate(getEpoch(Calendar.YEAR, 100)); + + cg = executor.executeSync(add(cg) + .setKs(getOperatorKs())) + .results; + + // get discount details + DiscountDetailsFilter filter = new DiscountDetailsFilter(); + filter.setIdIn(getProperty(DISCOUNT_CODE_ID)); + DiscountDetails discountDetails = executor.executeSync(DiscountDetailsService.list(filter) + .setKs(getOperatorKs()) + .setCurrency("*")) + .results.getObjects().get(0); + discountPercentage = discountDetails.getMultiCurrencyDiscount().get(0).getPercentage(); + + // generate coupons + RandomCouponGenerationOptions options = new RandomCouponGenerationOptions(); + options.setNumberOfCoupons(10); + options.setUseLetters(true); + options.setUseNumbers(true); + options.setUseSpecialCharacters(true); + + coupons = executor.executeSync(CouponsGroupService.generate(Long.parseLong(cg.getId()), options) + .setKs(getOperatorKs())) + .results + .getObjects(); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("transaction/action/purchase - subscription with coupon") + @Test() + public void purchaseSubscriptionWithCoupon() { + // ingest mpp with coupon group + List couponsGroups = Arrays.asList(cg); + + MppData mppData = new MppData() + .pricePlanCode1(getSharedCommonPricePlan().getName()) + .couponGroups(couponsGroups); + Subscription subscription = insertMpp(mppData); + + // generate coupon + String couponValue = coupons.get(0).getValue(); + + // set product price filter + ProductPriceFilter productPriceFilter = new ProductPriceFilter(); + productPriceFilter.setSubscriptionIdIn(subscription.getId()); + productPriceFilter.setCouponCodeEqual(couponValue); + + // productPrice list + Response> productPriceResponse = executor.executeSync(list(productPriceFilter) + .setKs(masterUserKs)); + assertThat(productPriceResponse.results).isNotNull(); + ProductPrice productPrice = productPriceResponse.results.getObjects().get(0); + assertThat(productPrice.getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPrice.getPrice().getAmount()).isEqualTo(subscription.getPrice().getPrice().getAmount() * discountPercentage / 100); + assertThat(productPrice.getPrice().getCurrency()).isEqualTo(subscription.getPrice().getPrice().getCurrency()); + + // purchase subscription + Purchase purchase = new Purchase(); + purchase.setProductType(TransactionType.SUBSCRIPTION); + purchase.setProductId(Integer.valueOf(subscription.getId())); + purchase.setContentId(0); + purchase.setCurrency(productPrice.getPrice().getCurrency()); + purchase.setPrice(productPrice.getPrice().getAmount()); + purchase.setCoupon(couponValue); + + // purchase subscription + Response transactionResponse = executor.executeSync(TransactionService.purchase(purchase) + .setKs(masterUserKs)); + + assertThat(transactionResponse.error).isNull(); + assertThat(transactionResponse.results.getState()).isEqualTo("OK"); + + // productPrice list - assert purchase status + productPriceResponse = executor.executeSync(list(productPriceFilter) + .setKs(masterUserKs)); + + assertThat(productPriceResponse.results).isNotNull(); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.SUBSCRIPTION_PURCHASED); + + // cleanup + deleteMpp(subscription.getName()); + } + + @Severity(SeverityLevel.CRITICAL) + @Description("transaction/action/purchase - ppv with coupon") + @Test() + public void purchasePpvWithCoupon() { + IngestPpvUtils.PpvData ppvData = new IngestPpvUtils.PpvData().couponGroup(cg); + Ppv ppv = insertPpv(ppvData); + + IngestVodUtils.VodData vodData = new IngestVodUtils.VodData() + .ppvWebName(ppv.getName()) + .ppvMobileName(ppv.getName()); + MediaAsset mediaAsset = insertVod(vodData, true); + + // generate coupon + String couponValue = coupons.get(1).getValue(); + + // set product price filter - get full price + ProductPriceFilter productPriceFilter = new ProductPriceFilter(); + productPriceFilter.setFileIdIn(String.valueOf(mediaAsset.getMediaFiles().get(0).getId())); + productPriceFilter.setCouponCodeEqual(couponValue); + + // productPrice list + Response> productPriceResponse = executor.executeSync(ProductPriceService + .list(productPriceFilter) + .setKs(getAnonymousKs())); + assertThat(productPriceResponse.results).isNotNull(); + ProductPrice productPrice = productPriceResponse.results.getObjects().get(0); + assertThat(productPrice.getPurchaseStatus()).isEqualTo(PurchaseStatus.FOR_PURCHASE); + assertThat(productPrice.getPrice().getAmount()).isEqualTo(ppv.getPrice().getPrice().getAmount() * discountPercentage / 100); + assertThat(productPrice.getPrice().getCurrency()).isEqualTo(ppv.getPrice().getPrice().getCurrency()); + + // purchase ppv + Purchase purchase = new Purchase(); + purchase.setProductType(TransactionType.PPV); + purchase.setProductId(Integer.valueOf(ppv.getId())); + purchase.setContentId(mediaAsset.getMediaFiles().get(0).getId()); + purchase.setCurrency(productPrice.getPrice().getCurrency()); + purchase.setPrice(productPrice.getPrice().getAmount()); + purchase.setCoupon(couponValue); + + // purchase subscription + Response transactionResponse = executor.executeSync(TransactionService.purchase(purchase) + .setKs(masterUserKs)); + assertThat(transactionResponse.error).isNull(); + assertThat(transactionResponse.results.getState()).isEqualTo("OK"); + + // productPrice list - assert purchase status + productPriceResponse = executor.executeSync(list(productPriceFilter) + .setKs(masterUserKs)); + assertThat(productPriceResponse.results).isNotNull(); + assertThat(productPriceResponse.results.getObjects().get(0).getPurchaseStatus()).isEqualTo(PurchaseStatus.PPV_PURCHASED); + + // cleanup + deletePpv(ppv.getName()); + deleteVod(mediaAsset.getName()); + } + + @AfterClass + public void TransactionPurchaseWithCouponTests_afterClass() { + // delete couponGroup + executor.executeSync(CouponsGroupService.delete(Long.parseLong(cg.getId())) + .setKs(getOperatorKs())); + + // delete hh + executor.executeSync(HouseholdService.delete() + .setKs(masterUserKs)); + } + + // TODO: 8/20/2018 purchase ppv / collection with coupon + // TODO: 8/14/2018 purchase with not valid coupon + // TODO: 8/20/2018 purchase with not valid coupon - diffrent coupon group + // TODO: 8/20/2018 coupon end date expired + // TODO: 8/20/2018 coupon start date expired + // TODO: 8/20/2018 deleted coupon group + // TODO: 8/20/2018 cg.setCouponGroupType(CouponGroupType.COUPON); giftcard +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/transactionTests/transactionPurchaseTests/transactionPurchaseWithDiscountTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/transactionTests/transactionPurchaseTests/transactionPurchaseWithDiscountTests.java new file mode 100644 index 000000000..727ddcaad --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/transactionTests/transactionPurchaseTests/transactionPurchaseWithDiscountTests.java @@ -0,0 +1,8 @@ +package com.kaltura.client.test.tests.servicesTests.transactionTests.transactionPurchaseTests; + +import com.kaltura.client.test.tests.BaseTest; + +public class transactionPurchaseWithDiscountTests extends BaseTest { + + // TODO: 8/15/2018 purchase with discount +} diff --git a/src/test/java/com/kaltura/client/test/tests/servicesTests/transactionTests/transactionPurchaseTests/transactionPurchaseWithMultiCurrencyTests.java b/src/test/java/com/kaltura/client/test/tests/servicesTests/transactionTests/transactionPurchaseTests/transactionPurchaseWithMultiCurrencyTests.java new file mode 100644 index 000000000..a2bb366a3 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/tests/servicesTests/transactionTests/transactionPurchaseTests/transactionPurchaseWithMultiCurrencyTests.java @@ -0,0 +1,8 @@ +package com.kaltura.client.test.tests.servicesTests.transactionTests.transactionPurchaseTests; + +import com.kaltura.client.test.tests.BaseTest; + +public class transactionPurchaseWithMultiCurrencyTests extends BaseTest { + + // TODO: 8/15/2018 purchase with multi-currency +} diff --git a/src/test/java/com/kaltura/client/test/utils/AssetHistoryUtils.java b/src/test/java/com/kaltura/client/test/utils/AssetHistoryUtils.java index 2a15cf5cf..edb2bbdce 100644 --- a/src/test/java/com/kaltura/client/test/utils/AssetHistoryUtils.java +++ b/src/test/java/com/kaltura/client/test/utils/AssetHistoryUtils.java @@ -1,17 +1,9 @@ package com.kaltura.client.test.utils; -import com.kaltura.client.enums.AssetType; -import com.kaltura.client.enums.BookmarkActionType; import com.kaltura.client.enums.WatchStatus; -import com.kaltura.client.services.BookmarkService; import com.kaltura.client.types.AssetHistoryFilter; -import com.kaltura.client.types.Bookmark; -import com.kaltura.client.types.MediaAsset; - import javax.annotation.Nullable; -import java.util.Optional; -import static com.kaltura.client.test.tests.BaseTest.executor; public class AssetHistoryUtils extends BaseUtils { @@ -21,27 +13,10 @@ public static AssetHistoryFilter getAssetHistoryFilter(@Nullable String assetIdI assetHistoryFilter.setDaysLessThanOrEqual(days); assetHistoryFilter.setStatusEqual(statusEqual); assetHistoryFilter.setTypeIn(typeIn); + assetHistoryFilter.setOrderBy("NONE"); return assetHistoryFilter; } - // Ingest asset, bookmark it and return the asset id - public static Long ingestAssetAndPerformBookmark(String ks, String mediaType, int position, BookmarkActionType bookmarkActionType) { - // Ingest asset - MediaAsset mediaAsset = IngestUtils.ingestVOD(Optional.empty(), Optional.empty(), true, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), - Optional.empty(), Optional.empty(), Optional.empty(), Optional.of(String.valueOf(mediaType)), Optional.empty(), Optional.empty()); - Long assetId = mediaAsset.getId(); - int fileId = AssetUtils.getAssetFileIds(String.valueOf(assetId)).get(0); - - // Movie asset bookmark - AssetType assetType = AssetType.MEDIA; - Bookmark bookmark = BookmarkUtils.addBookmark(position, String.valueOf(assetId), fileId, assetType, bookmarkActionType); - - BookmarkService.AddBookmarkBuilder addBookmarkBuilder = BookmarkService.add(bookmark); - addBookmarkBuilder.setKs(ks); - executor.executeSync(addBookmarkBuilder); - - return assetId; - } } diff --git a/src/test/java/com/kaltura/client/test/utils/AssetRuleUtils.java b/src/test/java/com/kaltura/client/test/utils/AssetRuleUtils.java new file mode 100644 index 000000000..4d6efd4ac --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/AssetRuleUtils.java @@ -0,0 +1,27 @@ +package com.kaltura.client.test.utils; + +import com.kaltura.client.services.AssetRuleService; +import com.kaltura.client.test.tests.BaseTest; +import com.kaltura.client.types.AssetRule; +import com.kaltura.client.types.ListResponse; +import com.kaltura.client.utils.response.base.Response; + +import static com.kaltura.client.services.AssetRuleService.*; +import static com.kaltura.client.test.tests.BaseTest.executor; + +public class AssetRuleUtils extends BaseUtils { + + + // Delete all geo asset rules from DB (changed to status 2) + public static void deleteAllGeoAssetRules() { + ListAssetRuleBuilder listAssetRuleBuilder = AssetRuleService.list().setKs(BaseTest.getOperatorKs()); + Response> listAssetRule = executor.executeSync(listAssetRuleBuilder); + if (listAssetRule.results.getTotalCount() > 0) { + for (AssetRule rule : listAssetRule.results.getObjects()) { + DeleteAssetRuleBuilder deleteAssetRuleBuilder = AssetRuleService.delete(rule.getId()).setKs(BaseTest.getOperatorKs()); + executor.executeSync(deleteAssetRuleBuilder); + } + } + + } +} diff --git a/src/test/java/com/kaltura/client/test/utils/AssetStructMetaUtils.java b/src/test/java/com/kaltura/client/test/utils/AssetStructMetaUtils.java new file mode 100644 index 000000000..751a7847b --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/AssetStructMetaUtils.java @@ -0,0 +1,72 @@ +package com.kaltura.client.test.utils; + +import com.kaltura.client.services.AssetStructMetaService; +import com.kaltura.client.services.AssetStructService; +import com.kaltura.client.test.TestAPIOkRequestsExecutor; +import com.kaltura.client.test.tests.enums.AssetStructMetaType; +import com.kaltura.client.test.utils.dbUtils.DBUtils; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; +import org.apache.commons.lang3.StringUtils; + +import java.util.ArrayList; +import java.util.List; + +import static com.kaltura.client.test.tests.BaseTest.getOperatorKs; +import static com.kaltura.client.test.utils.dbUtils.DBUtils.getMetaNameById; +import static org.assertj.core.api.Assertions.assertThat; + +public class AssetStructMetaUtils extends BaseUtils { + + public static TestAPIOkRequestsExecutor executor = TestAPIOkRequestsExecutor.getExecutor(); + + public static AssetStructMeta loadAssetStructMeta(String metaName) { + Long metaId = DBUtils.getMetaIdByName(metaName, false); + AssetStructMetaFilter assetStructMetaFilter = new AssetStructMetaFilter(); + //assetStructMetaFilter.setAssetStructIdEqual(assetStructId); + assetStructMetaFilter.setMetaIdEqual(metaId); + AssetStructMetaService.ListAssetStructMetaBuilder listAssetStructMetaBuilder = AssetStructMetaService.list(assetStructMetaFilter); + Response> listAssetMetaStructResponse = executor.executeSync(listAssetStructMetaBuilder + .setKs(getOperatorKs())); + + return listAssetMetaStructResponse.results.getObjects().get(0); + } + + // TODO: probably can be useless as we do not have assetStructMeta/Add (only list and update) + public static AssetStructMeta getAssetStructMeta(String defaultIngestValue, String ingestReferencePath, + boolean isProtectFromIngest, boolean isInherited) { + AssetStructMeta assetStructMeta = new AssetStructMeta(); + assetStructMeta.setDefaultIngestValue(defaultIngestValue); + assetStructMeta.setIngestReferencePath(ingestReferencePath); + assetStructMeta.setProtectFromIngest(isProtectFromIngest); + // TODO: update library to have options update it + //assetStructMeta.setIsInherited(isInherited); + + return assetStructMeta; + } + +// TODO: COMPLETE THE METHOD +// public static List getAssetStructMetas(Long assetStructId, AssetStructMetaType type, boolean processBasicFields) { +// List result = new ArrayList<>(); +// +// AssetStructMetaFilter assetStructMetaFilter = new AssetStructMetaFilter(); +// assetStructMetaFilter.setAssetStructIdEqual(assetStructId); +// AssetStructMetaService.ListAssetStructMetaBuilder listAssetStructMetaBuilder = AssetStructMetaService.list(assetStructMetaFilter); +// Response> listAssetMetaStructResponse = executor.executeSync(listAssetStructMetaBuilder +// .setKs(getOperatorKs())); +// +// String name; +// for (AssetStructMeta assetStructMeta: listAssetMetaStructResponse.results.getObjects()) { +// name = getMetaNameById(assetStructMeta.getMetaId(), processBasicFields); +// if (StringUtils.isNotEmpty(name)) { +// if (!AssetStructMetaType.ALL.equals(type)) { +// +// } +// } +// } +// +// //assertThat(assetStructFromResponse.getParentId()).isEqualTo(0L); +// +// return result; +// } +} diff --git a/src/test/java/com/kaltura/client/test/utils/AssetStructUtils.java b/src/test/java/com/kaltura/client/test/utils/AssetStructUtils.java new file mode 100644 index 000000000..8bb809c60 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/AssetStructUtils.java @@ -0,0 +1,46 @@ +package com.kaltura.client.test.utils; + +import com.kaltura.client.types.AssetStruct; +import com.kaltura.client.types.TranslationToken; +import javax.annotation.Nullable; +import java.util.List; + +public class AssetStructUtils extends BaseUtils { + + public static AssetStruct getAssetStruct(String prefix, String language, boolean isProtected, String metaIds, + @Nullable Long parentId, @Nullable Long connectingMetaId, + @Nullable Long connectedParentMetaId) { + AssetStruct assetStruct = new AssetStruct(); + assetStruct.setSystemName(prefix + "_System_name"); + assetStruct.setMultilingualName(setTranslationToken(prefix + "_multiLingualName")); + assetStruct.setIsProtected(isProtected); + assetStruct.setMetaIds(metaIds); + assetStruct.setParentId(parentId); + assetStruct.setConnectingMetaId(connectingMetaId); + assetStruct.setConnectedParentMetaId(connectedParentMetaId); + + return assetStruct; + } + + public static AssetStruct copyAssetStructObject(AssetStruct assetStruct2Copy) { + AssetStruct result = new AssetStruct(); + result.setConnectedParentMetaId(assetStruct2Copy.getConnectedParentMetaId()); + result.setConnectingMetaId(assetStruct2Copy.getConnectingMetaId()); + result.setParentId(assetStruct2Copy.getParentId()); + result.setMetaIds(assetStruct2Copy.getMetaIds()); + result.setSystemName(assetStruct2Copy.getSystemName()); + result.setIsProtected(assetStruct2Copy.getIsProtected()); + result.setPluralName(assetStruct2Copy.getPluralName()); + result.setMultilingualName(assetStruct2Copy.getMultilingualName()); + result.setFeatures(assetStruct2Copy.getFeatures()); + + return result; + } + + public static void setInheritanceFieldsInAssetStruct(AssetStruct assetStruct, Long parentAssetStructId, + Long connectedParentMetaId, Long connectingMetaId) { + assetStruct.setParentId(parentAssetStructId); + assetStruct.setConnectedParentMetaId(connectedParentMetaId); + assetStruct.setConnectingMetaId(connectingMetaId); + } +} diff --git a/src/test/java/com/kaltura/client/test/utils/AssetUtils.java b/src/test/java/com/kaltura/client/test/utils/AssetUtils.java index d0b40b0ab..11a5bff90 100644 --- a/src/test/java/com/kaltura/client/test/utils/AssetUtils.java +++ b/src/test/java/com/kaltura/client/test/utils/AssetUtils.java @@ -1,26 +1,47 @@ package com.kaltura.client.test.utils; -import com.kaltura.client.enums.AssetReferenceType; +import com.kaltura.client.Logger; +import com.kaltura.client.enums.*; import com.kaltura.client.services.AssetService; +import com.kaltura.client.services.ProductPriceService; +import com.kaltura.client.services.SocialActionService; +import com.kaltura.client.test.tests.enums.MediaType; import com.kaltura.client.types.*; import com.kaltura.client.utils.response.base.Response; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; +import static com.kaltura.client.services.AssetFileService.GetContextAssetFileBuilder; +import static com.kaltura.client.services.AssetFileService.getContext; import static com.kaltura.client.services.AssetService.*; +import static com.kaltura.client.services.BookmarkService.AddBookmarkBuilder; +import static com.kaltura.client.services.BookmarkService.add; +import static com.kaltura.client.services.HouseholdService.delete; +import static com.kaltura.client.services.SocialActionService.AddSocialActionBuilder; +import static com.kaltura.client.test.Properties.MEDIA_PROTOCOL; +import static com.kaltura.client.test.Properties.STREAMER_TYPE; import static com.kaltura.client.test.tests.BaseTest.SharedHousehold.getSharedMasterUserKs; import static com.kaltura.client.test.tests.BaseTest.executor; +import static com.kaltura.client.test.tests.BaseTest.getOperatorKs; +import static com.kaltura.client.test.tests.enums.KsqlKey.ASSET_TYPE; +import static com.kaltura.client.test.utils.dbUtils.DBUtils.getMediaTypeId; +import static io.restassured.RestAssured.given; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; -public class AssetUtils extends BaseUtils { +public class AssetUtils extends BaseUtils { - public static SearchAssetFilter getSearchAssetFilter(@Nullable String ksql, @Nullable String idIn, @Nullable String typeIn, + // TODO: 6/21/2018 Use Optional instead of nullable + public static SearchAssetFilter getSearchAssetFilter(@Nullable String ksql, @Nullable String typeIn, @Nullable DynamicOrderBy dynamicOrderBy, List groupBy, String name, String orderBy) { SearchAssetFilter searchAssetFilter = new SearchAssetFilter(); searchAssetFilter.setKSql(ksql); - searchAssetFilter.setIdIn(idIn); searchAssetFilter.setTypeIn(typeIn); searchAssetFilter.setDynamicOrderBy(dynamicOrderBy); searchAssetFilter.setGroupBy(groupBy); @@ -30,32 +51,219 @@ public static SearchAssetFilter getSearchAssetFilter(@Nullable String ksql, @Nul return searchAssetFilter; } - public static ChannelFilter getChannelFilter(int idEqual, @Nullable String ksql, @Nullable DynamicOrderBy dynamicOrderBy, @Nullable String orderBy) { + public static SearchAssetFilter getSearchAssetFilter(String ksql) { + SearchAssetFilter searchAssetFilter = new SearchAssetFilter(); + searchAssetFilter.setKSql(ksql); + + return searchAssetFilter; + } + + public static ChannelFilter getChannelFilter(int idEqual, Optional ksql, Optional dynamicOrderBy, Optional orderBy) { ChannelFilter channelFilter = new ChannelFilter(); channelFilter.setIdEqual(idEqual); - channelFilter.setKSql(ksql); - channelFilter.setDynamicOrderBy(dynamicOrderBy); - channelFilter.setOrderBy(orderBy); + + ksql.ifPresent(channelFilter::setKSql); + dynamicOrderBy.ifPresent(channelFilter::setDynamicOrderBy); + orderBy.ifPresent(channelFilter::setOrderBy); return channelFilter; } public static List getAssetFileIds(String assetId) { + GetAssetBuilder getAssetBuilder = get(assetId, AssetReferenceType.MEDIA) + .setKs(getSharedMasterUserKs()); + Response assetResponse = executor.executeSync(getAssetBuilder); - AssetReferenceType assetReferenceType = AssetReferenceType.get(AssetReferenceType.MEDIA.getValue()); + List mediaFiles = assetResponse.results.getMediaFiles(); + assertThat(mediaFiles.size()).as("media files list").isGreaterThan(0); - GetAssetBuilder getAssetBuilder = AssetService.get(assetId,assetReferenceType); - getAssetBuilder.setKs(getSharedMasterUserKs()); - Response assetResponse = executor.executeSync(getAssetBuilder); + return mediaFiles.stream().map(MediaFile::getId).collect(Collectors.toList()); + } + + public static List getAssetsByType(String typeIn) { + AssetFilter assetFilter = getSearchAssetFilter(null, typeIn, null, null, null, null); + + FilterPager filterPager = new FilterPager(); + filterPager.setPageSize(20); + filterPager.setPageIndex(1); + + ListAssetBuilder listAssetBuilder = list(assetFilter, filterPager) + .setKs(getSharedMasterUserKs()); + Response> assetResponse = executor.executeSync(listAssetBuilder); + + return assetResponse.results.getObjects(); + } + + // TODO - need to make util more efficient (creating too many HH) + public static void addViewToAsset(Asset asset, AssetType assetType) { + //Create HH with 1 user and 1 device + Household household = HouseholdUtils.createHousehold(1, 1, true); + HouseholdUser householdUser = HouseholdUtils.getMasterUser(household); + + // Login user + String ks = OttUserUtils.getKs(Integer.parseInt(householdUser.getUserId()), HouseholdUtils.getDevicesList(household).get(0).getUdid()); + + // Purchase PPV (to allow bookmark + PurchaseUtils.purchasePpv(ks,Optional.of(Math.toIntExact(asset.getId())),Optional.empty(),Optional.empty()); + + Bookmark bookmark = BookmarkUtils.addBookmark(0, String.valueOf(asset.getId()), asset.getMediaFiles().get(0).getId(), assetType, BookmarkActionType.FIRST_PLAY); + //bookmark/action/add + AddBookmarkBuilder addBookmarkBuilder = add(bookmark).setKs(ks); + executor.executeSync(addBookmarkBuilder); + } + + public static void playbackAssetFilePreparation(String userKs, String assetId, String assetFileId, AssetType assetType, PlaybackContextType context, UrlType urlType) { + + PlaybackContextOptions playbackContextOptions = new PlaybackContextOptions(); + playbackContextOptions.setMediaProtocol(MEDIA_PROTOCOL); + playbackContextOptions.setStreamerType(STREAMER_TYPE); + playbackContextOptions.setAssetFileIds(assetFileId); + playbackContextOptions.setContext(context); + playbackContextOptions.setUrlType(urlType); + + GetPlaybackContextAssetBuilder getPlaybackContextAssetBuilder = getPlaybackContext(assetId, assetType, playbackContextOptions).setKs(userKs); + Response playbackContextResponse = executor.executeSync(getPlaybackContextAssetBuilder); + + assertThat(playbackContextResponse.error).isNull(); + assertThat(playbackContextResponse.results.getMessages().get(0).getCode()).isEqualTo("OK"); + assertThat(playbackContextResponse.results.getSources().size()).isGreaterThan(0); + assertThat(playbackContextResponse.results.getSources().get(0).getAssetId()).isEqualTo(Integer.valueOf(assetId)); + assertThat(playbackContextResponse.results.getSources().get(0).getId()).isEqualTo(Integer.valueOf(assetFileId)); + String playbackUrl = playbackContextResponse.results.getSources().get(0).getUrl(); + + if (urlType.equals(UrlType.PLAYMANIFEST)){ + io.restassured.response.Response resp = given() + .when().redirects().follow(false) + .get(playbackUrl); + assertThat(resp.getStatusCode()).isEqualTo(302); + assertThat(resp.getHeader("Location")).contains("switch3.castup.net"); + } + + GetContextAssetFileBuilder getContextAssetFileBuilder = getContext(assetFileId, ContextType.NONE).setKs(userKs); + Response assetFileContextResponse = executor.executeSync(getContextAssetFileBuilder); + + assertThat(assetFileContextResponse.error).isNull(); + assertThat(assetFileContextResponse.results.getFullLifeCycle()).isNotEqualTo("00:00:00"); + assertThat(assetFileContextResponse.results.getViewLifeCycle()).isNotEqualTo("00:00:00"); + } + + public static void addLikesToAsset(Long assetId, int numOfActions, AssetType assetType) { + if (numOfActions <= 0) { + Logger.getLogger("Value must be equal or greater than 0"); + } else { + for (int i = 0; i < numOfActions; i++) { + int j = 1; + Household household = HouseholdUtils.createHousehold(j, j, false); + HouseholdUser householdUser = HouseholdUtils.getMasterUser(household); - List mediafiles = assetResponse.results.getMediaFiles(); + SocialAction socialAction = SocialUtils.getSocialAction(SocialActionType.LIKE, null, assetId, assetType, null); - List fileIdsList = new ArrayList<>(); - for (MediaFile mediaFile : mediafiles) { - fileIdsList.add(mediaFile.getId()); + AddSocialActionBuilder addSocialActionBuilder = SocialActionService.add(socialAction) + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(householdUser.getUserId())); + executor.executeSync(addSocialActionBuilder); + + // cleanup - delete household + executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + } + } + } + + public static void addVotesToAsset(Long assetId, int numOfActions, AssetType assetType, int rate) { + if (numOfActions <= 0) { + Logger.getLogger("Value must be equal or greater than 0"); + } else { + for (int i = 0; i < numOfActions; i++) { + int j = 1; + Household household = HouseholdUtils.createHousehold(j, j, false); + HouseholdUser householdUser = HouseholdUtils.getMasterUser(household); + + SocialActionRate socialActionRate = SocialUtils.getSocialActionRate(SocialActionType.RATE, null, assetId, assetType, null, rate); + + AddSocialActionBuilder addSocialActionBuilder = SocialActionService.add(socialActionRate) + .setKs(getOperatorKs()) + .setUserId(Integer.valueOf(householdUser.getUserId())); + executor.executeSync(addSocialActionBuilder); + + // cleanup - delete household + executor.executeSync(delete(Math.toIntExact(household.getId())).setKs(getOperatorKs())); + } + } + } + + public static List getAssets(int numOfAssets, MediaType mediaType) { + SearchAssetFilter filter = new SearchAssetFilter(); + String query = new KsqlBuilder().equal(ASSET_TYPE.getValue(), getMediaTypeId(mediaType)).toString(); + filter.setKSql(query); + + FilterPager pager = new FilterPager(); + pager.setPageIndex(1); + pager.setPageSize(numOfAssets); + + return (List) (List) executor.executeSync(AssetService.list(filter, pager) + .setKs(getOperatorKs())).results.getObjects(); + } + + public static List getPrograms(int numOfAssets) { + SearchAssetFilter filter = new SearchAssetFilter(); + filter.setTypeIn("0"); + + FilterPager pager = new FilterPager(); + pager.setPageIndex(1); + pager.setPageSize(numOfAssets); + + return (List) (List) executor.executeSync(AssetService.list(filter, pager) + .setKs(getOperatorKs())).results.getObjects(); + } + + public static Asset getAssetByPurchaeStatus(List assets, PurchaseStatus purchaseStatus) { + Asset asset = null; + ProductPriceFilter filter = new ProductPriceFilter(); + + for (Asset a : assets) { + filter.setFileIdIn(String.valueOf(a.getMediaFiles().get(0).getId())); + ProductPrice productPrice = executor.executeSync(ProductPriceService.list(filter) + .setKs(getOperatorKs())) + .results.getObjects().get(0); + + if (productPrice.getPurchaseStatus().equals(purchaseStatus)) { + asset = a; + break; + } } - return fileIdsList; + if (asset == null) { + fail("No asset in the provided status in assets list"); + } + + return asset; + } + + public static String getCoguid(Asset asset) { + // TODO: 7/1/2018 finish util + //asset.getExternalId() can be used for ingested items + return null; + } + + public static MediaAsset getMediaAsset(Long type, String name, String description) { + MediaAsset result = new MediaAsset(); + result.setType(type.intValue()); + result.setMultilingualName(setTranslationToken(name)); + result.setMultilingualDescription(setTranslationToken(description)); + String currentDate = getCurrentDateInFormat("yyMMddHHmmss"); + result.setExternalId("Media_" + currentDate); + result.setStatus(true); + result.setEntryId(currentDate); + + //TODO: add others fields if needed + //result.setMetas(metas); + //result.setTags(tags); + + return result; } } + + + + diff --git a/src/test/java/com/kaltura/client/test/utils/BaseUtils.java b/src/test/java/com/kaltura/client/test/utils/BaseUtils.java index 8cc0c182b..aae41b653 100644 --- a/src/test/java/com/kaltura/client/test/utils/BaseUtils.java +++ b/src/test/java/com/kaltura/client/test/utils/BaseUtils.java @@ -2,6 +2,7 @@ import com.kaltura.client.Logger; import com.kaltura.client.types.APIException; +import com.kaltura.client.types.TranslationToken; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; @@ -10,19 +11,21 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; -import java.io.IOException; +import java.io.*; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.ThreadLocalRandom; -import static com.kaltura.client.test.Properties.API_VERSION; -import static com.kaltura.client.test.Properties.getProperty; +import static com.kaltura.client.test.Properties.*; +import static com.kaltura.client.test.tests.BaseTest.config; +import static com.kaltura.client.test.utils.ingestUtils.BaseIngestUtils.DEFAULT_LANGUAGE; +import static io.restassured.RestAssured.given; public class BaseUtils { - private static final String API_SCHEMA_URL = "https://api-preprod.ott.kaltura.com/" + getProperty(API_VERSION) + "/clientlibs/KalturaClient.xml"; + public static final String API_SCHEMA_URL = getProperty(API_BASE_URL) + "/" + getProperty(API_VERSION) + "/clientlibs/KalturaClient.xml"; private static List exceptions; // to get e.g. yesterday date in specific date format need call the method so: getOffsetDateInFormat(-1, pattern); @@ -35,32 +38,87 @@ public static String getOffsetDateInFormat(int offsetDay, String pattern) { return dateFormat.format(cal.getTime()); } - // Get Date time according to off set parameter provided (with the pattern: dd/MM/yyyy HH:mm:ss) - public static String getTimeInDate(int offSetInMinutes) { + // generate current data String in specified format + public static String getCurrentDateInFormat(String pattern) { + return getOffsetDateInFormat(0, pattern); + } + + // Get Date time according to offset parameter provided (with the pattern: dd/MM/yyyy HH:mm:ss) +// public static String getTimeFormatted(int offSetInMinutes, TimeZone timeZone) { +// DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); +// dateFormat.setTimeZone(timeZone); +// +// Date dNow = new Date(); +// Calendar calendar = Calendar.getInstance(); +// calendar.setTime(dNow); +// calendar.add(Calendar.MINUTE, offSetInMinutes); +// dNow = calendar.getTime(); +// +// return dateFormat.format(dNow); +// } +// +// // Get Date time according to offset parameter provided (with the pattern: dd/MM/yyyy HH:mm:ss) +// public static String getLocalTimeFormatted(int offSetInMinutes) { +// return getTimeFormatted(offSetInMinutes, TimeZone.getDefault()); +// } +// +// public static String getUtcTimeFormatted(int offSetInMinutes) { +// return getTimeFormatted(offSetInMinutes, TimeZone.getTimeZone("UTC")); +// } + + // Get epoch time in seconds according to off set parameter provided (in minutes) +// public static long getEpochInLocalTime(int offSetInMinutes) { +// Calendar calendar = Calendar.getInstance(); +// calendar.add(Calendar.MINUTE, offSetInMinutes); +// +// return calendar.toInstant().getEpochSecond(); +// } + + public static String getFormattedTime(int calendarType, int amount, TimeZone timeZone) { DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); - Date dNow = new Date(); + dateFormat.setTimeZone(timeZone); + + Date d = new Date(); Calendar calendar = Calendar.getInstance(); - calendar.setTime(dNow); - calendar.add(Calendar.MINUTE, offSetInMinutes); - dNow = calendar.getTime(); + calendar.setTime(d); + calendar.add(calendarType, amount); + d = calendar.getTime(); - return dateFormat.format(dNow); + return dateFormat.format(d); } - // Get epoch time in seconds according to off set parameter provided (in minutes) - public static long getTimeInEpoch(int offSetInMinutes) { - //DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); - Date dNow = new Date(); - Calendar calendar = Calendar.getInstance(); - calendar.setTime(dNow); - calendar.add(Calendar.MINUTE, offSetInMinutes); + public static String getFormattedTime(long epoch, TimeZone timeZone) { + return getFormattedDate(epoch, timeZone, "dd/MM/yyyy HH:mm:ss"); + } + + public static String getFormattedDate(long epoch, TimeZone timeZone, String format) { + DateFormat dateFormat = new SimpleDateFormat(format); + dateFormat.setTimeZone(timeZone); - return calendar.getTimeInMillis() / 1000; + return dateFormat.format(getDateFromEpoch(epoch)); } - // generate current data String in specified format - public static String getCurrentDataInFormat(String pattern) { - return getOffsetDateInFormat(0, pattern); + public static long getEpoch() { + return Calendar.getInstance().toInstant().getEpochSecond(); + } + + public static long getEpoch(int calendarType, int amount) { + Calendar c = Calendar.getInstance(); + c.add(calendarType, amount); + + return c.toInstant().getEpochSecond(); + } + + public static long getEpochInMillis() { + return System.currentTimeMillis(); + } + + public static Date getDateFromEpoch(long epoch) { + return new Date(epoch * 1000); + } + + public static long getEpochFromDate(Date date) { + return date.getTime() / 1000; } // generate string containing prefix and random long suffix @@ -69,6 +127,24 @@ public static String getRandomValue(String prefix, long maxValue) { return prefix + randomLongValue; } + public static String getRandomValue(String prefix) { + return prefix + getRandomLong(); + } + + public static long getRandomLong() { + long max = 9999999999L; + return ThreadLocalRandom.current().nextLong(max); + } + + public static double getRandomDouble() { + double max = 9999999.1; + return ThreadLocalRandom.current().nextDouble(max); + } + + public static boolean getRandomBoolean() { + return ThreadLocalRandom.current().nextBoolean(); + } + // generate random string public static String getRandomString() { String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; @@ -106,11 +182,10 @@ private static List getApiExceptionList() { e.printStackTrace(); } Document doc = null; + Logger.getLogger(BaseUtils.class).debug(API_SCHEMA_URL); try { doc = db.parse(new URL(API_SCHEMA_URL).openStream()); - } catch (SAXException e) { - e.printStackTrace(); - } catch (IOException e) { + } catch (SAXException | IOException e) { e.printStackTrace(); } NodeList nodeList = doc.getElementsByTagName("error"); @@ -127,11 +202,62 @@ private static List getApiExceptionList() { } // Get concatenated string - public static String getConcatenatedString(String... args) { - List assetIds = new ArrayList<>(); - for (String arg : args) { - assetIds.add(arg); + public static String getConcatenatedString(String... strings) { + List list = new ArrayList<>(); + for (String arg : strings) { + list.add(arg); } - return String.join(",", assetIds); + return String.join(",", list); + } + + public static String getConcatenatedString(List strings) { + return String.join(",", strings); + } + + public static String getFileContent(String filePath) { + String result = ""; + try { + StringBuilder sb = new StringBuilder(); + InputStream is = new FileInputStream(filePath); + BufferedReader buf = new BufferedReader(new InputStreamReader(is)); + + String line = buf.readLine(); + while (line != null) { + sb.append(line).append("\n"); + line = buf.readLine(); + } + + result = sb.toString(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + return result; + } + } + + public static void deleteFile(String filePath) { + File file = new File(filePath); + + if (file.delete()) { + Logger.getLogger(BaseUtils.class).debug("File deleted successfully: " + filePath); + } else { + Logger.getLogger(BaseUtils.class).error("Failed to delete the file: " + filePath); + } + } + + public static void clearCache() { + String url = config.getEndpoint() + "/clear_cache.aspx"; + given().queryParam("action", "clear_all").get(url); + } + + public static List setTranslationToken(String value) { + TranslationToken translationToken = new TranslationToken(); + translationToken.setLanguage(DEFAULT_LANGUAGE); + translationToken.setValue(value); + + List translationTokens = new ArrayList<>(); + translationTokens.add(translationToken); + + return translationTokens; } } diff --git a/src/test/java/com/kaltura/client/test/utils/ChannelUtils.java b/src/test/java/com/kaltura/client/test/utils/ChannelUtils.java index c6e3aaf52..560014811 100644 --- a/src/test/java/com/kaltura/client/test/utils/ChannelUtils.java +++ b/src/test/java/com/kaltura/client/test/utils/ChannelUtils.java @@ -1,25 +1,22 @@ package com.kaltura.client.test.utils; -import com.kaltura.client.enums.AssetOrderBy; -import com.kaltura.client.types.Channel; -import com.kaltura.client.types.IntegerValue; -import com.kaltura.client.types.MediaImage; +import com.kaltura.client.types.*; import javax.annotation.Nullable; import java.util.List; public class ChannelUtils extends BaseUtils { - public static Channel addChannel(String name, @Nullable String description, @Nullable Boolean isActive, @Nullable String filterExpression, - @Nullable AssetOrderBy orderBy, @Nullable List assetTypes, @Nullable List images) { - Channel channel = new Channel(); - channel.setName(name); - channel.setDescription(description); + public static DynamicChannel addDynamicChannel(String name, @Nullable String description, @Nullable Boolean isActive, @Nullable String ksqlExpression, + @Nullable ChannelOrder channelOrder, @Nullable List assetTypes) { + DynamicChannel channel = new DynamicChannel(); + channel.setMultilingualName(setTranslationToken(name)); + channel.setMultilingualDescription(setTranslationToken(description)); channel.setIsActive(isActive); - channel.setFilterExpression(filterExpression); - channel.setOrder(orderBy); channel.setAssetTypes(assetTypes); - channel.setImages(images); + channel.setKSql(ksqlExpression); + channel.setOrderBy(channelOrder); + channel.setSystemName(channel.getMultilingualName().get(0).getValue()); return channel; } diff --git a/src/test/java/com/kaltura/client/test/utils/DBUtils.java b/src/test/java/com/kaltura/client/test/utils/DBUtils.java deleted file mode 100644 index 5e2564293..000000000 --- a/src/test/java/com/kaltura/client/test/utils/DBUtils.java +++ /dev/null @@ -1,262 +0,0 @@ -package com.kaltura.client.test.utils; - -import com.kaltura.client.Logger; -import com.kaltura.client.test.tests.BaseTest; -import com.microsoft.sqlserver.jdbc.SQLServerDataSource; -import com.microsoft.sqlserver.jdbc.SQLServerException; -import org.json.JSONArray; -import org.json.JSONObject; - -import java.sql.*; - -import static com.kaltura.client.test.Properties.*; - -public class DBUtils extends BaseUtils { - - private static SQLServerDataSource dataSource; - private static Connection conn; - private static Statement stam; - private static ResultSet rs; - - //selects - private static final String ACTIVATION_TOKEN_SELECT = "SELECT [ACTIVATION_TOKEN] FROM [Users].[dbo].[users] WHERE [USERNAME] = '%S'"; - private static final String EPG_CHANNEL_ID_SELECT = "SELECT [ID] FROM [TVinci].[dbo].[epg_channels] WHERE [GROUP_ID] = %d AND [NAME] = '%S'"; - private static final String CHECK_IS_ACTIVATION_USERS_NEEDED = "select [IS_ACTIVATION_NEEDED]\n" + - "from [Users].[dbo].[groups_parameters]\n" + - "where group_id=%d"; - private static final String USER_BY_ROLE_SELECT = "select top(1) u.username, u.[password]\n" + - "from [Users].[dbo].[users] u with(nolock)\n" + - "join [Users].[dbo].[users_roles] ur with(nolock) on (u.id=ur.[user_id])\n" + - "join [TVinci].[dbo].[roles] r with(nolock) on (r.id=ur.role_id)\n" + - "where r.[NAME]='%S' and u.is_active=1 and u.[status]=1 and u.group_id=%d"; - private static final String DISCOUNT_BY_PERCENT_AND_CURRENCY = "select TOP (1) *\n" + - "from [Pricing].[dbo].[discount_codes] dc with(nolock)\n" + - "join [Pricing].[dbo].[lu_currency] lc with(nolock) on (dc.currency_cd=lc.id)\n" + - "where lc.code3='%S'\n" + // CURRENCY - "and dc.discount_percent=%d\n" + // percent amount - "and dc.group_id=%d\n" + // group - "and dc.[status]=1 and dc.is_active=1"; - - //TODO - change existing methods to work with the new convertToJSON method - - // Return json array from DB - public static JSONArray convertToJSON(String query) throws Exception { - openConnection(); - JSONArray jsonArray = new JSONArray(); - rs = stam.executeQuery(query); - ResultSetMetaData rsmd = rs.getMetaData(); - - if (rs != null && rs.isBeforeFirst()) { - while (rs.next()) { - int numColumns = rsmd.getColumnCount(); - JSONObject obj = new JSONObject(); - - for (int i = 1; i < numColumns + 1; i++) { - String column_name = rsmd.getColumnName(i).toLowerCase(); - - if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) { - obj.put(column_name, rs.getArray(column_name)); - } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) { - obj.put(column_name, rs.getInt(column_name)); - } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) { - obj.put(column_name, rs.getBoolean(column_name)); - } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) { - obj.put(column_name, rs.getBlob(column_name)); - } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) { - obj.put(column_name, rs.getDouble(column_name)); - } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) { - obj.put(column_name, rs.getFloat(column_name)); - } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) { - obj.put(column_name, rs.getInt(column_name)); - } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) { - obj.put(column_name, rs.getNString(column_name)); - } else if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) { - obj.put(column_name, rs.getString(column_name)); - } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) { - obj.put(column_name, rs.getInt(column_name)); - } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) { - obj.put(column_name, rs.getInt(column_name)); - } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) { - obj.put(column_name, rs.getDate(column_name)); - } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) { - obj.put(column_name, rs.getTimestamp(column_name)); - } else { - obj.put(column_name, rs.getObject(column_name)); - } - } - jsonArray.put(obj); - } - closeConnection(); - return jsonArray; - - } else { - Logger.getLogger(DBUtils.class).error("No result found"); - closeConnection(); - return null; - } - - } - - public static String getDiscountByPercentAndCurrency(String currency, int percent) { - openConnection(); - try { - rs = stam.executeQuery(String.format(DISCOUNT_BY_PERCENT_AND_CURRENCY, currency, percent, BaseTest.partnerId)); - } catch (SQLException e) { - e.printStackTrace(); - } - try { - rs.next(); - } catch (SQLException e) { - e.printStackTrace(); - Logger.getLogger(DBUtils.class).error("No data about discount with currency " + currency + "and percent " + percent + " in account " + BaseTest.partnerId); - } - String code = ""; - try { - code = rs.getString("code"); - if ("".equals(code)) { - throw new SQLException(); - } - } catch (SQLException e) { - e.printStackTrace(); - Logger.getLogger(DBUtils.class).error("code can't be null"); - } - closeConnection(); - return code; - } - - public static boolean isActivationOfUsersNeeded() { - openConnection(); - try { - rs = stam.executeQuery(String.format(CHECK_IS_ACTIVATION_USERS_NEEDED, BaseTest.partnerId)); - } catch (SQLException e) { - e.printStackTrace(); - } - try { - rs.next(); - } catch (SQLException e) { - e.printStackTrace(); - Logger.getLogger(DBUtils.class).error("No data about activation users in account " + BaseTest.partnerId); - } - int result =-1; - try { - result = rs.getInt("IS_ACTIVATION_NEEDED"); - } catch (SQLException e) { - e.printStackTrace(); - Logger.getLogger(DBUtils.class).error("IS_ACTIVATION_NEEDED can't be null"); - } - closeConnection(); - return result == 1; - } - - public static String getUserDataByRole(String userRole) { - String sqlQuery = USER_BY_ROLE_SELECT; - if (isActivationOfUsersNeeded()) { - sqlQuery += " and u.activate_status=1"; - } - openConnection(); - try { - rs = stam.executeQuery(String.format(sqlQuery, userRole, BaseTest.partnerId)); - } catch (SQLException e) { - e.printStackTrace(); - } - try { - rs.next(); - } catch (SQLException e) { - e.printStackTrace(); - Logger.getLogger(DBUtils.class).error("No data about user with role " + userRole + " in account " + BaseTest.partnerId); - } - String userdData = ""; - try { - userdData = rs.getString("username") + ":" + rs.getString("password"); - } catch (SQLException e) { - e.printStackTrace(); - Logger.getLogger(DBUtils.class).error("username/password can't be null"); - } - closeConnection(); - return userdData; - } - - public static String getActivationToken(String username) { - openConnection(); - try { - rs = stam.executeQuery(String.format(ACTIVATION_TOKEN_SELECT, username)); - } catch (SQLException e) { - e.printStackTrace(); - } - try { - rs.next(); - } catch (SQLException e) { - e.printStackTrace(); - } - String activationToken = null; - try { - activationToken = rs.getString("ACTIVATION_TOKEN"); - } catch (SQLException e) { - e.printStackTrace(); - Logger.getLogger(DBUtils.class).error("activationToken can't be null"); - } - closeConnection(); - return activationToken; - } - - public static int getEpgChannelId(String channelName) { - openConnection(); - try { - rs = stam.executeQuery(String.format(EPG_CHANNEL_ID_SELECT, BaseTest.partnerId + 1, channelName)); - } catch (SQLException e) { - e.printStackTrace(); - } - try { - rs.next(); - } catch (SQLException e) { - e.printStackTrace(); - } - int epgChannelId = -1; - try { - epgChannelId = rs.getInt("ID"); - } catch (SQLException e) { - e.printStackTrace(); - Logger.getLogger(DBUtils.class).error("epgChannelId can't be null"); - } - closeConnection(); - return epgChannelId; - } - - private static void openConnection() { - dataSource = new SQLServerDataSource(); - dataSource.setUser(getProperty(DB_USER)); - dataSource.setPassword(getProperty(DB_PASSWORD)); - dataSource.setServerName(getProperty(DB_URL)); - dataSource.setApplicationIntent("ReadOnly"); - dataSource.setMultiSubnetFailover(true); - - try { - conn = dataSource.getConnection(); - } catch (SQLServerException e) { - e.printStackTrace(); - } - try { - stam = conn.createStatement(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - private static void closeConnection() { - try { - rs.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - try { - stam.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - try { - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } -} diff --git a/src/test/java/com/kaltura/client/test/utils/EmailUtils.java b/src/test/java/com/kaltura/client/test/utils/EmailUtils.java new file mode 100644 index 000000000..41ebb10cc --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/EmailUtils.java @@ -0,0 +1,195 @@ +package com.kaltura.client.test.utils; + + +import org.awaitility.core.ConditionTimeoutException; + +import javax.mail.*; +import javax.mail.internet.MimeBodyPart; +import javax.mail.search.SearchTerm; +import java.io.IOException; +import java.util.Date; +import java.util.Properties; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.awaitility.Awaitility.await; + +public class EmailUtils extends BaseUtils { + + private static final String username = "ottbeqa@gmail.com"; + private static final String password = "ottbeqa2018"; + + public static boolean isEmailReceived(SearchTerm term, boolean deleteEmails) { + AtomicBoolean isReceived = new AtomicBoolean(false); + + // server setting + Properties props = System.getProperties(); + props.setProperty("mail.store.protocol", "imaps"); + + Session session = Session.getDefaultInstance(props); + Folder inbox = null; + Folder trash = null; + Store store = null; + + try { + // connects to the message store + store = session.getStore("imaps"); + store.connect("imap.gmail.com", username, password); + + // opens the inbox folder + inbox = store.getFolder("INBOX"); + inbox.open(Folder.READ_WRITE); + + // check if email found for 30 sec + Folder finalInbox = inbox; + + await() + .atMost(40, TimeUnit.SECONDS) + .pollInterval(5, TimeUnit.SECONDS) + .until(() -> { + Message[] foundMessages = finalInbox.search(term); + if (foundMessages.length > 0) { + isReceived.set(true); + } + return isReceived.get(); + }); + + // delete emails + if (deleteEmails) { + // delete inbox + Message inboxMessages[] = inbox.getMessages(); + for (Message m : inboxMessages) { + m.setFlag(Flags.Flag.DELETED, true); + } + + // delete trash + trash = store.getFolder("[Gmail]/Trash"); + trash.open(Folder.READ_WRITE); + Message trashMessages[] = trash.getMessages(); + for (Message m : trashMessages) { + m.setFlag(Flags.Flag.DELETED, true); + } + } + } catch (Exception e) { + if (e.getClass() != ConditionTimeoutException.class) { + e.printStackTrace(); + } + } finally { + try { + if (inbox != null) { + inbox.close(true); + } + if (trash != null) { + trash.close(true); + } + if (store != null) { + store.close(); + } + } catch (MessagingException e) { + e.printStackTrace(); + } + } + return isReceived.get(); + } + + // custom search terms + public static class SentDateSearchTerm extends SearchTerm { + private Date afterDate; + + public SentDateSearchTerm(Date afterDate) { + this.afterDate = afterDate; + } + + @Override + public boolean match(Message message) { + try { + if (message.getSentDate().after(afterDate)) { + return true; + } + } catch (MessagingException ex) { + ex.printStackTrace(); + } + return false; + } + } + + public static class SubjectSearchTerm extends SearchTerm { + private String subject; + + public SubjectSearchTerm(String subject) { + this.subject = subject; + } + + @Override + public boolean match(Message message) { + try { + if (message.getSubject().contains(subject)) { + return true; + } + } catch (MessagingException ex) { + ex.printStackTrace(); + } + return false; + } + } + + public static class FromFieldSearchTerm extends SearchTerm { + private String fromEmail; + + public FromFieldSearchTerm(String fromEmail) { + this.fromEmail = fromEmail; + } + + @Override + public boolean match(Message message) { + try { + Address[] fromAddress = message.getFrom(); + if (fromAddress != null && fromAddress.length > 0) { + if (fromAddress[0].toString().contains(fromEmail)) { + return true; + } + } + } catch (MessagingException ex) { + ex.printStackTrace(); + } + return false; + } + } + + public static class ContentSearchTerm extends SearchTerm { + private String content; + + public ContentSearchTerm(String content) { + this.content = content; + } + + @Override + public boolean match(Message message) { + try { + String contentType = message.getContentType().toLowerCase(); + + if (contentType.contains("text/plain") || contentType.contains("text/html")) { + String messageContent = message.getContent().toString(); + if (messageContent.contains(content)) { + return true; + } + } + + if (contentType.contains("multipart")) { + Multipart multiPart = (Multipart) message.getContent(); + int numberOfParts = multiPart.getCount(); + for (int partCount = 0; partCount < numberOfParts; partCount++) { + MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount); + String messageContent = part.getContent().toString(); + if (messageContent.contains(content)) { + return true; + } + } + } + } catch (MessagingException | IOException ex) { + ex.printStackTrace(); + } + return false; + } + } +} diff --git a/src/test/java/com/kaltura/client/test/utils/HouseholdUtils.java b/src/test/java/com/kaltura/client/test/utils/HouseholdUtils.java index 090e24e7e..6a02a6e73 100644 --- a/src/test/java/com/kaltura/client/test/utils/HouseholdUtils.java +++ b/src/test/java/com/kaltura/client/test/utils/HouseholdUtils.java @@ -1,29 +1,41 @@ package com.kaltura.client.test.utils; import com.kaltura.client.Logger; -import com.kaltura.client.services.*; +import com.kaltura.client.services.HouseholdDeviceService; +import com.kaltura.client.services.HouseholdPaymentGatewayService; +import com.kaltura.client.services.HouseholdService; +import com.kaltura.client.test.Properties; import com.kaltura.client.types.*; import com.kaltura.client.utils.response.base.Response; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Random; -import static com.kaltura.client.services.HouseholdDeviceService.*; -import static com.kaltura.client.services.HouseholdPaymentGatewayService.*; +import static com.kaltura.client.services.HouseholdDeviceService.AddHouseholdDeviceBuilder; +import static com.kaltura.client.services.HouseholdDeviceService.ListHouseholdDeviceBuilder; +import static com.kaltura.client.services.HouseholdPaymentGatewayService.SetChargeIDHouseholdPaymentGatewayBuilder; +import static com.kaltura.client.services.HouseholdService.AddHouseholdBuilder; import static com.kaltura.client.services.HouseholdUserService.*; +import static com.kaltura.client.services.HouseholdUserService.list; import static com.kaltura.client.services.OttUserService.*; -import static com.kaltura.client.services.HouseholdService.*; +import static com.kaltura.client.test.Properties.PAYMENT_GATEWAY_EXTERNAL_ID; import static com.kaltura.client.test.tests.BaseTest.*; -import static com.kaltura.client.test.tests.BaseTest.getAdministratorKs; import static com.kaltura.client.test.utils.OttUserUtils.generateOttUser; public class HouseholdUtils extends BaseUtils { - // create household - public static Household createHousehold(int numberOfUsersInHoushold, int numberOfDevicesInHousehold, boolean isPreparePG) { + // default household params + private static final int defaultNumOfUsers = 1; + private static final int defaultNumOfDevices = 1; + private static final boolean defaultIsPreparePG = true; + // create household with default params + public static Household createHousehold() { + return createHousehold(defaultNumOfUsers, defaultNumOfDevices, defaultIsPreparePG); + } + + public static Household createHousehold(int numOfUsers, int numOfDevices, boolean isPreparePG) { // register master user RegisterOttUserBuilder registerOttUserBuilder = register(partnerId, generateOttUser(), defaultUserPassword); OTTUser masterUser = executor.executeSync(registerOttUserBuilder).results; @@ -44,7 +56,7 @@ public static Household createHousehold(int numberOfUsersInHoushold, int numberO household = executor.executeSync(addHouseholdBuilder).results; // add additional users to household - for (int i = 0; i < numberOfUsersInHoushold; i++) { + for (int i = 0; i < numOfUsers; i++) { // register additional user registerOttUserBuilder = register(partnerId, generateOttUser(), defaultUserPassword); OTTUser additionalUser = executor.executeSync(registerOttUserBuilder).results; @@ -60,14 +72,9 @@ public static Household createHousehold(int numberOfUsersInHoushold, int numberO } // add household devices - for (int i = 0; i < numberOfDevicesInHousehold; i++) { + for (int i = 0; i < numOfDevices; i++) { // create household device - long uniqueString = System.currentTimeMillis(); - HouseholdDevice householdDevice = new HouseholdDevice(); - householdDevice.setUdid(String.valueOf(uniqueString)); - Random r = new Random(); - householdDevice.setBrandId(r.nextInt(30 - 1) + 1); - householdDevice.setName(String.valueOf(uniqueString) + "device"); + HouseholdDevice householdDevice = generateHouseholdDevice(); // add device to household AddHouseholdDeviceBuilder addHouseholdDeviceBuilder = HouseholdDeviceService.add(householdDevice) @@ -78,7 +85,8 @@ public static Household createHousehold(int numberOfUsersInHoushold, int numberO if (isPreparePG) { // TODO: there should be added logic with getting and using default PG currently it all hardcoded //HouseholdPaymentGateway/action/setChargeId - SetChargeIDHouseholdPaymentGatewayBuilder setChargeIDHouseholdPaymentGatewayBuilder = HouseholdPaymentGatewayService.setChargeID("0110151474255957105", "1234") + SetChargeIDHouseholdPaymentGatewayBuilder setChargeIDHouseholdPaymentGatewayBuilder = HouseholdPaymentGatewayService + .setChargeID(Properties.getProperty(PAYMENT_GATEWAY_EXTERNAL_ID), "1234") .setKs(getOperatorKs()) .setUserId(Integer.valueOf(masterUser.getId())); executor.executeSync(setChargeIDHouseholdPaymentGatewayBuilder); @@ -87,8 +95,20 @@ public static Household createHousehold(int numberOfUsersInHoushold, int numberO return household; } + // generate household device + public static HouseholdDevice generateHouseholdDevice() { + long uniqueString = System.currentTimeMillis(); + HouseholdDevice householdDevice = new HouseholdDevice(); + householdDevice.setUdid(String.valueOf(uniqueString)); + Random r = new Random(); + householdDevice.setBrandId(r.nextInt(28 - 1) + 1); + householdDevice.setName(String.valueOf(uniqueString) + "device"); + + return householdDevice; + } + // get users list from given household - public static List getDevicesListFromHouseHold(Household household) { + public static List getDevicesList(Household household) { HouseholdDeviceFilter filter = new HouseholdDeviceFilter(); filter.setHouseholdIdEqual(Math.toIntExact(household.getId())); @@ -102,7 +122,7 @@ public static List getDevicesListFromHouseHold(Household househ } // get users list from given household - public static List getUsersListFromHouseHold(Household household) { + public static List getUsersList(Household household) { HouseholdUserFilter filter = new HouseholdUserFilter(); filter.setHouseholdIdEqual(Math.toIntExact(household.getId())); @@ -114,8 +134,8 @@ public static List getUsersListFromHouseHold(Household household) } // get master user from given household - public static HouseholdUser getMasterUserFromHousehold(Household household) { - List users = getUsersListFromHouseHold(household); + public static HouseholdUser getMasterUser(Household household) { + List users = getUsersList(household); for (HouseholdUser user : users) { if (user.getIsMaster() != null && user.getIsMaster()) { @@ -128,8 +148,8 @@ public static HouseholdUser getMasterUserFromHousehold(Household household) { } // get default user from given household - public static HouseholdUser getDefaultUserFromHousehold(Household household) { - List users = getUsersListFromHouseHold(household); + public static HouseholdUser getDefaultUser(Household household) { + List users = getUsersList(household); for (HouseholdUser user : users) { if (user.getIsDefault() != null && user.getIsDefault()) { @@ -142,8 +162,8 @@ public static HouseholdUser getDefaultUserFromHousehold(Household household) { } // get regular users list from given household - public static List getRegularUsersListFromHouseHold(Household household) { - List users = getUsersListFromHouseHold(household); + public static List getRegularUsersList(Household household) { + List users = getUsersList(household); List usersToRemove = new ArrayList<>(); for (HouseholdUser user : users) { @@ -159,14 +179,26 @@ public static List getRegularUsersListFromHouseHold(Household hou } // Get master KS by providing household object - public static String getHouseholdMasterUserKs(Household household, @Nullable String udid) { - HouseholdUser masterUser = getMasterUserFromHousehold(household); + public static String getHouseholdMasterUserKs(Household household) { + HouseholdUser masterUser = getMasterUser(household); + return OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId())); + } + + // Get regular user KS by providing household object + public static String getHouseholdUserKs(Household household) { + HouseholdUser user = getRegularUsersList(household).get(0); + return OttUserUtils.getKs(Integer.parseInt(user.getUserId())); + } + + // Get master KS by providing household object + public static String getHouseholdMasterUserKs(Household household, String udid) { + HouseholdUser masterUser = getMasterUser(household); return OttUserUtils.getKs(Integer.parseInt(masterUser.getUserId()), udid); } // Get regular user KS by providing household object - public static String getHouseholdUserKs(Household household, @Nullable String udid) { - HouseholdUser user = getRegularUsersListFromHouseHold(household).get(0); + public static String getHouseholdUserKs(Household household, String udid) { + HouseholdUser user = getRegularUsersList(household).get(0); return OttUserUtils.getKs(Integer.parseInt(user.getUserId()), udid); } } diff --git a/src/test/java/com/kaltura/client/test/utils/InfraUtils.java b/src/test/java/com/kaltura/client/test/utils/InfraUtils.java new file mode 100644 index 000000000..87bb0115e --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/InfraUtils.java @@ -0,0 +1,88 @@ +package com.kaltura.client.test.utils; + +import com.google.common.reflect.ClassPath; +import io.qameta.allure.Description; +import org.apache.commons.io.FileUtils; +import org.testng.annotations.Test; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.nio.charset.Charset; +import java.util.Set; + +public class InfraUtils { + + public static void writeUtilsListToFile() throws IOException { + String packageName = "com.kaltura.client.test.utils"; + + File file = new File("src/test/resources/utils_list.txt"); + FileUtils.writeStringToFile(file, "package - " + packageName + "\n", Charset.defaultCharset()); + + Set allClasses = ClassPath.from(ClassLoader.getSystemClassLoader()).getTopLevelClasses(packageName); + for (ClassPath.ClassInfo classInfo: allClasses) { + FileUtils.writeStringToFile(file, "\n" + "class - " + classInfo.getSimpleName() + ":" + "\n", Charset.defaultCharset(), true); + + Class clazz = classInfo.load(); + Method[] methods = clazz.getDeclaredMethods(); + for (int i = 0; i < methods.length; i++) { + if (Modifier.isStatic(methods[i].getModifiers())) { + FileUtils.writeStringToFile(file, methods[i].getName() + "\n", Charset.defaultCharset(), true); + } + } + } + } + + public static void writeDbUtilsListToFile() throws IOException { + String packageName = "com.kaltura.client.test.utils.dbUtils"; + + File file = new File("src/test/resources/db_utils_list.txt"); + FileUtils.writeStringToFile(file, "package - " + packageName + "\n", Charset.defaultCharset()); + + Set allClasses = ClassPath.from(ClassLoader.getSystemClassLoader()).getTopLevelClasses(packageName); + for (ClassPath.ClassInfo classInfo: allClasses) { + FileUtils.writeStringToFile(file, "\n" + "class - " + classInfo.getSimpleName() + ":" + "\n", Charset.defaultCharset(), true); + + Class clazz = classInfo.load(); + Method[] methods = clazz.getDeclaredMethods(); + for (int i = 0; i < methods.length; i++) { + if (Modifier.isStatic(methods[i].getModifiers())) { + FileUtils.writeStringToFile(file, methods[i].getName() + "\n", Charset.defaultCharset(), true); + } + } + } + } + + public static void printTestsNameAndDescription() throws IOException { + String packageName = "com.kaltura.client.test.tests"; + + Set allClasses = ClassPath.from(ClassLoader.getSystemClassLoader()).getTopLevelClassesRecursive(packageName); + for (ClassPath.ClassInfo classInfo: allClasses) { + System.out.println("\n\n" + classInfo.getSimpleName()); + + Class clazz = classInfo.load(); + Method[] methods = clazz.getDeclaredMethods(); + for (Method method : methods) { + Description description = method.getAnnotation(Description.class); + if (description != null) { + System.out.println("Method: " + method.getName()); + System.out.println("Description: " + description.value() + "\n"); + } + + Test testAnnotation = method.getAnnotation(Test.class); + if (testAnnotation != null && !testAnnotation.toString().contains("description=,")) { + System.out.println("Method: " + method.getName()); + System.out.println("Description: " + getDescriptionFromTestAnnotation(testAnnotation.toString()) + "\n"); + } + } + } + } + + private static String getDescriptionFromTestAnnotation(String testAnnotationContent) { + String descriptionEqual = "description="; + int descriptionStartsPosition = testAnnotationContent.indexOf(descriptionEqual) + descriptionEqual.length(); + int descriptionEndsPosition = testAnnotationContent.indexOf(",", descriptionStartsPosition); + return testAnnotationContent.substring(descriptionStartsPosition, descriptionEndsPosition); + } +} diff --git a/src/test/java/com/kaltura/client/test/utils/IngestUtils.java b/src/test/java/com/kaltura/client/test/utils/IngestUtils.java deleted file mode 100644 index 5f07eca1b..000000000 --- a/src/test/java/com/kaltura/client/test/utils/IngestUtils.java +++ /dev/null @@ -1,988 +0,0 @@ -package com.kaltura.client.test.utils; - -import com.kaltura.client.Logger; -import com.kaltura.client.enums.AssetOrderBy; -import com.kaltura.client.enums.AssetReferenceType; -import com.kaltura.client.services.AssetService; -import com.kaltura.client.services.AssetService.*; -import com.kaltura.client.types.*; -import com.kaltura.client.utils.response.base.Response; -import io.restassured.RestAssured; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.concurrent.Callable; -import java.util.concurrent.TimeUnit; -import static com.kaltura.client.test.IngestConstants.*; -import static com.kaltura.client.test.Properties.*; -import static com.kaltura.client.test.tests.BaseTest.*; -import static io.restassured.path.xml.XmlPath.from; -import static org.awaitility.Awaitility.await; - -public class IngestUtils extends BaseUtils { - - // INGEST EPG PARAMS - // TODO: think about ENUMS if we really need it here? should we create new ENUM class for it? where? - public static final String DURATION_PERIOD_DAYS = "days"; - public static final String DURATION_PERIOD_HOURS = "hours"; - public static final String DURATION_PERIOD_MINUTES = "minutes"; - public static final String DURATION_PERIOD_SECONDS = "seconds"; - - // default values - public static final int EPG_DEFAULT_COUNT_OF_SEASONS = 1; - public static final int EPG_DEFAULT_COUNT_OF_PROGRAMMES = 2; - public static final int EPG_DEFAULT_PROGRAM_DURATION = 30; - public static final String EPG_DEFAULT_PROGRAM_DURATION_PERIOD_NAME = DURATION_PERIOD_MINUTES; - - private static List durationPeriodNames = new ArrayList<>(); - static { - durationPeriodNames.add(DURATION_PERIOD_DAYS); - durationPeriodNames.add(DURATION_PERIOD_HOURS); - durationPeriodNames.add(DURATION_PERIOD_MINUTES); - durationPeriodNames.add(DURATION_PERIOD_SECONDS); - } - - private static String titleOfIngestedItem = ""; - - // INGEST MPP PARAMS - private static boolean MPP_DEFAULT_IS_ACTIVE_VALUE = true; - private static String MPP_DEFAULT_DESCRIPTION_VALUE = "Ingest MPP description"; - private static String MPP_DEFAULT_START_DATE_VALUE = "20/03/2016 00:00:00"; - private static String MPP_DEFAULT_END_DATE_VALUE = "20/03/2099 00:00:00"; - private static boolean MPP_DEFAULT_IS_RENEWABLE_VALUE = false; - private static int MPP_DEFAULT_GRACE_PERIOD_VALUE = 0; - - // TODO: THIS VALUES RELATED TO OUR ENV ONLY discuss with Alon - private static String MPP_DEFAULT_COUPON_GROUP_VALUE = - "\n" + - "01/05/2017 00:00:00\n" + - "31/12/2099 23:59:59\n" + - "100% unlimited\n" + - "\n" + - "\n" + - "01/05/2017 00:00:00\n" + - "31/05/2017 23:59:59\n" + - "Expired coupon group 1\n" + - ""; - private static String MPP_DEFAULT_PRODUCT_CODES_VALUE = - "\n" + - "ProductCode1\n" + - "Google\n" + - "\n" + - "\n" + - "ProductCode2\n" + - "Apple\n" + - ""; - - // INGEST PP PARAMS - private static boolean PP_DEFAULT_IS_ACTIVE_VALUE = true; - private static int PP_DEFAULT_MAX_VIEWS_VALUE = 0; - private static boolean PP_DEFAULT_IS_RENEWABLE_VALUE = false; - private static int PP_DEFAULT_RECURRING_PERIODS_VALUE = 1; - - - // ingest new EPG (Programmes) // TODO: complete one-by-one needed fields to cover util ingest_epg from old project - public static Response> ingestEPG(String epgChannelName, Optional programCount, Optional firstProgramStartDate, - Optional programDuration, Optional programDurationPeriodName, - Optional isCridUnique4AllPrograms, Optional seasonCount, - Optional coguid, Optional crid, Optional seriesId) { - - int programCountValue = programCount.orElse(EPG_DEFAULT_COUNT_OF_PROGRAMMES); - if (programCountValue <= 0) { - Logger.getLogger(IngestUtils.class).error("Invalid programCount value " + programCount.get() + - ". Should be bigger than 0"); - return null; - } - int seasonCountValue = seasonCount.orElse(EPG_DEFAULT_COUNT_OF_SEASONS); - - String datePattern = "MM/yy/dd HH:mm:ss"; - SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern); - String firstProgramStartDateValue = firstProgramStartDate.orElse(getCurrentDataInFormat(datePattern)); - Calendar startDate = Calendar.getInstance(); - try { - startDate.setTime(dateFormat.parse(firstProgramStartDateValue)); - } catch (ParseException e) { - e.printStackTrace(); - } - - int programDurationValue = programDuration.orElse(EPG_DEFAULT_PROGRAM_DURATION); - if (programDurationValue <= 0) { - Logger.getLogger(IngestUtils.class).error("Invalid programDuration value " + programDuration.get() + - ". Should be bigger than 0"); - return null; - } - String programDurationPeriodNameValue = programDurationPeriodName.orElse(EPG_DEFAULT_PROGRAM_DURATION_PERIOD_NAME); - if (!durationPeriodNames.contains(programDurationPeriodNameValue)) { - Logger.getLogger(IngestUtils.class).error("Invalid programDurationPeriodName value " + programDurationPeriodName.get() + - ". Should be one from " + durationPeriodNames); - return null; - } - boolean isCridUnique4AllProgramsValue = isCridUnique4AllPrograms.orElse(true); - - String coguidValue = coguid.orElseGet(() -> getCurrentDataInFormat("yyMMddHHmmssSS")); - String cridValue = crid.orElse(coguidValue); - String seriesIdValue = seriesId.orElse(coguidValue); - int seasonId = 1; - Date endDate; - String output = ""; - String oneProgrammOutput = ""; - SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss"); - Date now = Calendar.getInstance().getTime(); - while (seasonId <= seasonCountValue) { - int idx = 1; - while(idx <= programCountValue) { - endDate = loadEndDate(startDate.getTime(), programDurationValue, programDurationPeriodNameValue); - oneProgrammOutput = getProgrammeXML(idx, df2.format(startDate.getTime()), df2.format(endDate), - epgChannelName, coguidValue, cridValue, "Program", df2.format(now), - seriesIdValue, String.valueOf(seasonId), isCridUnique4AllProgramsValue); - startDate.setTime(endDate); - output = output + oneProgrammOutput; - idx = idx + 1; - } - seasonId = seasonId + 1; - } - String epgChannelIngestXml = getChannelXML(partnerId, epgChannelName, output); - - String url = getProperty(INGEST_BASE_URL) + "/Ingest_" + getProperty(API_VERSION) + "/Service.svc?wsdl"; - HashMap headerMap = new HashMap<>(); - headerMap.put("Content-Type", "text/xml;charset=UTF-8"); - headerMap.put("SOAPAction", "\"http://tempuri.org/IService/IngestKalturaEpg\""); - String reqBody = "\n" + - " \n" + - " \n" + - " " + - " " + - " " + getProperty(INGEST_USER_USERNAME) + "" + getProperty(INGEST_USER_PASSWORD) + "" + - epgChannelIngestXml + "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; - io.restassured.response.Response resp = RestAssured.given() - .log().all() - .headers(headerMap) - .body(reqBody) - .post(url); - - Logger.getLogger(IngestUtils.class).debug(reqBody); - Logger.getLogger(IngestUtils.class).debug(resp.asString()); - int epgChannelId = DBUtils.getEpgChannelId(epgChannelName); - // TODO: create method getting epoch value from String and pattern - long epoch = 0L; - try { - Date firstProgramStartDateAsDate = dateFormat.parse(firstProgramStartDateValue); - epoch = firstProgramStartDateAsDate.getTime()/1000; // 1000 milliseconds in 1 second - } catch (ParseException e) { - e.printStackTrace(); - } - String firstProgramStartDateEpoch = String.valueOf(epoch); - - SearchAssetFilter assetFilter = new SearchAssetFilter(); - assetFilter.setOrderBy(AssetOrderBy.START_DATE_ASC.getValue()); - assetFilter.setKSql("(and epg_channel_id='" + epgChannelId + "' start_date >= '" + firstProgramStartDateEpoch + "' Series_ID='" + seriesIdValue + "' end_date >= '" + firstProgramStartDateEpoch + "')"); - int delayBetweenRetriesInSeconds = 3; - int maxTimeExpectingValidResponseInSeconds = 60; - await().pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS).atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) - .until(isDataReturned(getAnonymousKs(), assetFilter, programCountValue*seasonCountValue)); - - Response> ingestedProgrammes = executor.executeSync( - AssetService.list(assetFilter, null).setKs(getAnonymousKs())); - // TODO: complete Asset.json at least for programs - return ingestedProgrammes; - } - - private static Callable isDataReturned(String ks, SearchAssetFilter assetFilter, int totalCount) { - return () -> { - ListAssetBuilder listAssetBuilder = AssetService.list(assetFilter, null).setKs(ks); - return executor.executeSync(listAssetBuilder).error == null && - executor.executeSync(listAssetBuilder).results.getTotalCount() == totalCount; - }; - } - - private static String getChannelXML(int partnerId, String epgChannelName, String programsXml) { - return " " + - "" + - "" + - programsXml + - "" + - "]]>"; - } - - // generate XML for ingest of 1 program - private static String getProgrammeXML(int idx, String startDate, String endDate, String channel, String coguid, String crid, - String programNamePrefix, String currentDate, String seriesId, String seasonNumber, - boolean isCridUnique4AllPrograms) { - String name = programNamePrefix + "_" + startDate + "_ser" + seriesId + "_seas" + seasonNumber + "_e" + idx; - if ("".equals(titleOfIngestedItem)) { - titleOfIngestedItem = name; - } - // TODO: complete to cover util from old project completely - String CRID = "" + crid + "_" + idx + ""; - if (isCridUnique4AllPrograms) { - CRID = "" + crid + "_" + seasonNumber + "_" + idx + ""; - } - String output = - "" + - "" + name + "" + - CRID + - "" + startDate + " until " + endDate + "" + - "" + currentDate + "" + - "eng" + - //"" + - //"" + enableCDVR + "" + - //"" + enableCatchUp + ""+ - //"" + enableStartOver + "" + - //"" + enableTrickPlay + "" + - //"" + - //"" + metaName + "" + - //"" + metaValue + "" + - //"" + - "" + - // TODO: that meta should be added into property file - "season_num" + - "" + seasonNumber + "" + - "" + - "" + - // TODO: that meta should be added into property file - "Series_ID" + - "" + seriesId + "" + - "" + - "" + - // TODO: that meta should be added into property file - "Episode number" + - "" + idx + "" + - "" + - /* "" + - "Season" + - "" + seasonNumber + "" + - "" + - "" + - "Episode" + - "" + id + "" + - "" + - */ - //"" + - //"Country" + - //"Israel" + - //"" + - //"" + - //"YEAR" + - //"2015" + - //"" + - //"" + - //"Genre" + - //"" + genre + "" + - //"" + - //"" + - //"Actors" + - //"Shay" + - //"Ortal" + - //"" + - //"" + - //"" + tagName + "" + - //"" + tagValue + "" + - //"" + - //"" + - //"" + parentalFieldName + "" + - //"" + parentalValue + "" + - //"" + - //"" + - //"" + parentalFieldName + "" + - //"" + parentalValue2 + "" + - //"" + - ""; - return output; - } - - private static Date loadEndDate(Date startDate, int durationValue, String periodName) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(startDate); - switch (periodName) { - case DURATION_PERIOD_DAYS: - calendar.add(Calendar.DATE, durationValue); - break; - case DURATION_PERIOD_HOURS: - calendar.add(Calendar.HOUR, durationValue); - break; - case DURATION_PERIOD_MINUTES: - calendar.add(Calendar.MINUTE, durationValue); - break; - case DURATION_PERIOD_SECONDS: - calendar.add(Calendar.SECOND, durationValue); - } - return calendar.getTime(); - } - - /** - * IMPORTANT: please delete inserted by that method items - * - * @param action - can be "insert" or "delete" ("update" looks like broken) - * @param mppCode - should have value in case "action" is "delete" - * @param isActive - * @param title - * @param description - * @param startDate - * @param endDate - * @param internalDiscount - * @param productCode - * @param isRenewable - * @param gracePeriodMinute - * @param pricePlanCode1 - * @param pricePlanCode2 - * @param channel1 - * @param channel2 - * @param fileType1 - * @param fileType2 - * @param couponGroup - * @param productCodes - * @return MPP data - * - * !!!Only created by that method MPP can be deleted!!! - * - * to delete existed MPP use corresponded action and value mpp.getName() as "mppCode" - * (where mpp is a variable that contains mpp data). - * - * - * don't forget after deletion of mpp delete also price plan using by deleted mpp (if it was created by ingestPP method) - */ - // ingest new MPP - public static Subscription ingestMPP(Optional action, Optional mppCode, Optional isActive, - Optional title, Optional description, Optional startDate, - Optional endDate, Optional internalDiscount, - Optional productCode, Optional isRenewable, - Optional gracePeriodMinute, Optional pricePlanCode1, - Optional pricePlanCode2, Optional channel1, - Optional channel2, Optional fileType1, - Optional fileType2, Optional couponGroup, Optional productCodes) { - String mppCodeValue = mppCode.orElse(getRandomValue("MPP_", 9999999999L)); - String actionValue = action.orElse(INGEST_ACTION_INSERT); - boolean isActiveValue = isActive.orElse(MPP_DEFAULT_IS_ACTIVE_VALUE); - String titleValue = INGEST_ACTION_INSERT.equals(actionValue) ? mppCodeValue : title.orElse(mppCodeValue); - String descriptionValue = description.orElse(MPP_DEFAULT_DESCRIPTION_VALUE); - String startDateValue = startDate.orElse(MPP_DEFAULT_START_DATE_VALUE); - String endDateValue = endDate.orElse(MPP_DEFAULT_END_DATE_VALUE); - String defaultCurrencyOfDiscount4IngestMpp = "GBP"; - int defaultPercentageOfDiscount4IngestMpp = 100; - String internalDiscountValue = internalDiscount.orElse(DBUtils.getDiscountByPercentAndCurrency(defaultCurrencyOfDiscount4IngestMpp, defaultPercentageOfDiscount4IngestMpp)); - String productCodeValue = productCode.orElse(""); - boolean isRenewableValue = isRenewable.orElse(MPP_DEFAULT_IS_RENEWABLE_VALUE); - int gracePeriodMinuteValue = gracePeriodMinute.orElse(MPP_DEFAULT_GRACE_PERIOD_VALUE); - - String pricePlanCode1Value = pricePlanCode1.orElse(getProperty(DEFAULT_USAGE_MODULE_4_INGEST_MPP)); - String pricePlanCode2Value = pricePlanCode2.orElse(""); - String channel1Value = channel1.orElse(getProperty(DEFAULT_CHANNEL)); - String channel2Value = channel2.orElse(""); - String fileType1Value = fileType1.orElse(""); - String fileType2Value = fileType2.orElse(""); - String couponGroupValue = couponGroup.orElse(MPP_DEFAULT_COUPON_GROUP_VALUE); - String productCodesValue = productCodes.orElse(MPP_DEFAULT_PRODUCT_CODES_VALUE); - - - String url = getProperty(INGEST_BASE_URL) + "/Ingest_" + getProperty(API_VERSION) + "/Service.svc?wsdl"; - HashMap headerMap = new HashMap<>(); - headerMap.put("Content-Type", "text/xml;charset=UTF-8"); - headerMap.put("SOAPAction", "http://tempuri.org/IService/IngestBusinessModules"); - - String reqBody = "\n" + - " \n" + - " \n" + - " " + getProperty(INGEST_BUSINESS_MODULE_USER_USERNAME) + "" + - getProperty(INGEST_BUSINESS_MODULE_USER_PASSWORD) + "" + - " \n" + - " \n" + - ""; - - io.restassured.response.Response resp = RestAssured.given() - .log().all() - .headers(headerMap) - .body(reqBody) - .post(url); - - //Logger.getLogger(IngestUtils.class).debug(reqBody); - Logger.getLogger(IngestUtils.class).debug(resp.asString()); - - String reportId = from(resp.asString()).get("Envelope.Body.IngestBusinessModulesResponse.IngestBusinessModulesResult.ReportId").toString(); - //Logger.getLogger(IngestUtils.class).debug("ReportId = " + reportId); - - url = getProperty(INGEST_REPORT_URL) + "/" + getProperty(PARTNER_ID) + "/" + reportId; - resp = RestAssured.given() - .log().all() - .get(url); - - Logger.getLogger(IngestUtils.class).debug(resp.asString()); - //System.out.println(resp.asString().split(" = ")[1].replaceAll("\\.", "")); - - String id = resp.asString().split(" = ")[1].replaceAll("\\.", ""); - - Subscription subscription = new Subscription(); - subscription.setId(id); - subscription.setName(titleValue); - subscription.setDescription(descriptionValue); - // TODO: complete COMMENTED IF NEEDED - //subscription.setStartDate(); - //subscription.setEndDate(); - //subscription.setDiscountModule(); - //subscription.setProductCodes(); - subscription.isRenewable(String.valueOf(isRenewableValue)); - subscription.setGracePeriodMinutes(gracePeriodMinuteValue); - //subscription.setPricePlanIds(); - //subscription.setChannels(); - //subscription.setFileTypes(); - //subscription.setCouponsGroups(); - return subscription; - } - - private static String buildIngestMppXML(String action, String mppCode, boolean isActive, String title, String description, - String startDate, String endDate, String internalDiscount, String productCode, - boolean isRenewable, int gracePeriodMinute, String pricePlanCode1, - String pricePlanCode2, String channel1, String channel2, String fileType1, - String fileType2, String couponGroup, String productCodes) { - return "\n" + - "\n" + - "\n" + - "\n" + - "" + title + "\n" + - "\n" + - "\n" + - "" + description + "" + - "\n" + - "" + startDate + "\n" + - "" + endDate + "\n" + - "" + internalDiscount + "\n" + - "\n" + - "" + productCode + "\n" + - "" + isRenewable + "\n" + - "\n" + - "" + gracePeriodMinute + "\n" + - "\n" + - "" + pricePlanCode1 + "\n" + - "" + pricePlanCode2 + "\n" + - "\n" + - "\n" + - "" + channel1 + "\n" + - "" + channel2 + "\n" + - "\n" + - "\n" + - "" + fileType1 + "\n" + - "" + fileType2 + "\n" + - "\n" + - "\n" + - "" + couponGroup + "\n" + - "" + productCodes + "\n" + - "\n" + - "\n" + - "\n"; - } - - // ingest new PP - - /** - * IMPORTANT: please delete inserted by that method items - * - * @param action - can be "insert", "update" and "delete" - * @param ppCode - should have value in case "action" one of {"update" and "delete"} - * @param isActive - * @param fullLifeCycle - * @param viewLifeCycle - * @param maxViews - * @param price - * @param currency - * @param discount - * @param isRenewable - * @param recurringPeriods - * @return PricePlan data - * - * to update or delete existed price plan use corresponded action and value pricePlan.getName() as "ppCode" - * (where pricePlan is a variable that contains price plan data) - * - * !!!Only created by that method PP can be deleted/updated!!! - */ - public static PricePlan ingestPP(Optional action, Optional ppCode, Optional isActive, - Optional fullLifeCycle, Optional viewLifeCycle, Optional maxViews, - Optional price, Optional currency, - Optional discount, Optional isRenewable, - Optional recurringPeriods) { - String ppCodeValue = ppCode.orElse(getRandomValue("AUTOPricePlan_", MAX_RANDOM_GENERATED_VALUE_4_INGEST)); - String actionValue = action.orElse(INGEST_ACTION_INSERT); - boolean isActiveValue = isActive.orElse(PP_DEFAULT_IS_ACTIVE_VALUE); - String fullLifeCycleValue = fullLifeCycle.orElse(FIVE_MINUTES_PERIOD); - String viewLifeCycleValue = viewLifeCycle.orElse(FIVE_MINUTES_PERIOD); - int maxViewsValue = maxViews.orElse(PP_DEFAULT_MAX_VIEWS_VALUE); - String priceValue = price.orElse(getProperty(PRICE_CODE_AMOUNT)); - String currencyValue = currency.orElse(CURRENCY_EUR); - String defaultCurrencyOfDiscount4IngestMpp = "GBP"; - int defaultPercentageOfDiscount4IngestMpp = 100; - String discountValue = discount.orElse(DBUtils.getDiscountByPercentAndCurrency(defaultCurrencyOfDiscount4IngestMpp, defaultPercentageOfDiscount4IngestMpp)); - boolean isRenewableValue = isRenewable.orElse(PP_DEFAULT_IS_RENEWABLE_VALUE); - int recurringPeriodsValue = recurringPeriods.orElse(PP_DEFAULT_RECURRING_PERIODS_VALUE); - - String url = getProperty(INGEST_BASE_URL) + "/Ingest_" + getProperty(API_VERSION) + "/Service.svc?wsdl"; - HashMap headerMap = new HashMap<>(); - headerMap.put("Content-Type", "text/xml;charset=UTF-8"); - headerMap.put("SOAPAction", "http://tempuri.org/IService/IngestBusinessModules"); - - String reqBody = "\n" + - " \n" + - " \n" + - " " + getProperty(INGEST_BUSINESS_MODULE_USER_USERNAME) + "" + - getProperty(INGEST_BUSINESS_MODULE_USER_PASSWORD) + "" + - " \n" + - " \n" + - ""; - - io.restassured.response.Response resp = RestAssured.given() - .log().all() - .headers(headerMap) - .body(reqBody) - .post(url); - - Logger.getLogger(IngestUtils.class).debug(reqBody); - Logger.getLogger(IngestUtils.class).debug(resp.asString()); - - String reportId = from(resp.asString()).get("Envelope.Body.IngestBusinessModulesResponse.IngestBusinessModulesResult.ReportId").toString(); - //Logger.getLogger(IngestUtils.class).debug("ReportId = " + reportId); - - url = getProperty(INGEST_REPORT_URL) + "/" + getProperty(PARTNER_ID) + "/" + reportId; - resp = RestAssured.given() - .log().all() - .get(url); - - Logger.getLogger(IngestUtils.class).debug(resp.asString()); - //System.out.println(resp.asString().split(" = ")[1].replaceAll("\\.", "")); - - String id = resp.asString().split(" = ")[1].trim().replaceAll("\\.", ""); - //Logger.getLogger(IngestUtils.class).debug("ID: " + id); - - PricePlan pricePlan = new PricePlan(); - pricePlan.setId(Long.valueOf(id)); - pricePlan.setMaxViewsNumber(maxViewsValue); - pricePlan.setIsRenewable(isRenewableValue); - pricePlan.setRenewalsNumber(recurringPeriodsValue); - pricePlan.setName(ppCodeValue); - // TODO: complete COMMENTED IF NEEDED - //pricePlan.setFullLifeCycle(); - //pricePlan.setViewLifeCycle(); - //pricePlan.setPriceDetailsId(); - //pricePlan.setDiscountId(); - return pricePlan; - } - - private static String buildIngestPpXML(String action, String ppCode, boolean isActive, String fullLifeCycle, - String viewLifeCycle, int maxViews, String price, String currency, - String discount, boolean isRenewable, int recurringPeriods) { - String id = "reportIngestPricePlan" + action.substring(0, 1).toUpperCase() + action.substring(1); - return "\n" + - "\n" + - "\n" + - "" + fullLifeCycle + "\n" + - "" + viewLifeCycle + "\n" + - "" + maxViews + "\n" + - "\n" + - "" + price + "\n" + - "" + currency + "\n" + - "\n" + - "" + discount + "\n" + - "" + isRenewable + "\n" + - "" + recurringPeriods + "\n" + - "\n" + - "\n" + - "\n"; - } - - /** - * IMPORTANT: please delete inserted by that method items - * - * @param action - can be "insert", "update" and "delete" - * @param ppvCode - should have value in case "action" one of {"update" and "delete"} - * @param isActive - * @param description - * @param discount - * @param price - * @param currency - * @param usageModule - * @param isSubscriptionOnly - * @param isFirstDeviceLimitation - * @param productCode - * @param firstFileType - * @param secondFileType - * @return PPV data - * - * to update or delete existed ppv use corresponded action and value ppv.getName() as "ppvCode" - * (where ppv is a variable that contains ppv data) - * - * !!!Only created by that method PPV can be deleted/update!!! - */ - // ingest new PPV - public static Ppv ingestPPV(Optional action, Optional ppvCode, Optional isActive, Optional description, - Optional discount, Optional price, Optional currency, - Optional usageModule, Optional isSubscriptionOnly, - Optional isFirstDeviceLimitation, Optional productCode, - Optional firstFileType, Optional secondFileType) { - String actionValue = action.orElse(INGEST_ACTION_INSERT); - String ppvCodeValue = ppvCode.orElse(getRandomValue("PPV_", MAX_RANDOM_GENERATED_VALUE_4_INGEST)); - boolean isActiveValue = isActive.isPresent() ? isActive.get() : true; - String descriptionValue = description.orElse("My ingest PPV"); - String defaultCurrencyOfDiscount4IngestPpv = "ILS"; - int defaultPercentageOfDiscount4IngestPpv = 50; - String discountValue = discount.orElse(DBUtils.getDiscountByPercentAndCurrency(defaultCurrencyOfDiscount4IngestPpv, defaultPercentageOfDiscount4IngestPpv)); - double priceValue = price.orElse(Double.valueOf(getProperty(PRICE_CODE_AMOUNT))); - String currencyValue = currency.orElse(CURRENCY_EUR); - String usageModuleValue = usageModule.orElse(getProperty(DEFAULT_USAGE_MODULE_4_INGEST_PPV)); - boolean isSubscriptionOnlyValue = isSubscriptionOnly.isPresent() ? isSubscriptionOnly.get() : false; - boolean isFirstDeviceLimitationValue = isFirstDeviceLimitation.isPresent() ? isFirstDeviceLimitation.get() : false; - String productCodeValue = productCode.orElse(getProperty(DEFAULT_PRODUCT_CODE)); - String firstFileTypeValue = firstFileType.orElse(getProperty(WEB_FILE_TYPE)); - String secondFileTypeValue = secondFileType.orElse(getProperty(MOBILE_FILE_TYPE)); - - String url = getProperty(INGEST_BASE_URL) + "/Ingest_" + getProperty(API_VERSION) + "/Service.svc?wsdl"; - HashMap headerMap = new HashMap<>(); - headerMap.put("Content-Type", "text/xml;charset=UTF-8"); - headerMap.put("SOAPAction", "http://tempuri.org/IService/IngestBusinessModules"); - - String reqBody = "\n" + - " \n" + - " \n" + - " " + getProperty(INGEST_BUSINESS_MODULE_USER_USERNAME) + "" + - getProperty(INGEST_BUSINESS_MODULE_USER_PASSWORD) + "" + - " \n" + - " \n" + - ""; - - io.restassured.response.Response resp = RestAssured.given() - .log().all() - .headers(headerMap) - .body(reqBody) - .post(url); - - Logger.getLogger(IngestUtils.class).debug(reqBody); - Logger.getLogger(IngestUtils.class).debug(resp.asString()); - - String reportId = from(resp.asString()).get("Envelope.Body.IngestBusinessModulesResponse.IngestBusinessModulesResult.ReportId").toString(); - //System.out.println("ReportId = " + reportId); - - url = getProperty(INGEST_REPORT_URL) + "/" + getProperty(PARTNER_ID) + "/" + reportId; - resp = RestAssured.given() - .log().all() - .get(url); - - System.out.println(resp.asString()); - System.out.println(resp.asString().split(" = ")[1].replaceAll("\\.", "")); - - String id = resp.asString().split(" = ")[1].replaceAll("\\.", ""); - - Ppv ppv = new Ppv(); - ppv.setId(id); - List descriptions = new ArrayList<>(); - TranslationToken translationToken = new TranslationToken(); - translationToken.setValue(descriptionValue); - descriptions.add(translationToken); - ppv.setDescriptions(descriptions); - PriceDetails priceDetails = new PriceDetails(); - Price priceObj = new Price(); - priceObj.setAmount(priceValue); - priceObj.setCurrency(currencyValue); - priceDetails.setPrice(priceObj); - ppv.setPrice(priceDetails); - UsageModule usageModuleObj = new UsageModule(); - usageModuleObj.setName(usageModuleValue); - ppv.setUsageModule(usageModuleObj); - ppv.setIsSubscriptionOnly(isSubscriptionOnlyValue); - ppv.setFirstDeviceLimitation(isFirstDeviceLimitationValue); - ppv.setProductCode(productCodeValue); - ppv.setName(ppvCodeValue); - - return ppv; - } - - private static String buildIngestPpvXML(String action, String ppvCode, boolean isActive, String description, String discount, - double price, String currency, String usageModule, boolean isSubscriptionOnly, - boolean isFirstDeviceLimitation, String productCode, String firstFileType, - String secondFileType) { - return "\n" + - " \n" + - " \n" + - " \n" + - " " + description + "\n" + - " \n" + - " \n" + - " " + price + "\n" + - " " + currency + "\n" + - " \n" + - " " + usageModule + "\n" + - " " + discount + "\n" + - " \n" + - " " + isSubscriptionOnly + "\n" + - " " + isFirstDeviceLimitation + "\n" + - " " + productCode + "\n" + - " \n" + - " " + firstFileType + "\n" + - " " + secondFileType + "\n" + - " \n" + - " \n" + - " \n" + - "\n"; - } - - /** - * IMPORTANT: please delete inserted by that method items - * - * @param action - can be "insert", "update" and "delete" - * @param coguid - should have value in case "action" one of {"update" and "delete"} - * @param isActive - * @param name - * @param thumbUrl - * @param description - * @param catalogStartDate - * @param catalogEndDate - * @param startDate - * @param endDate - * @param mediaType - * @param ppvWebName - * @param ppvMobileName - * @return - * - * to update or delete existed VOD use corresponded action and value vod.getName() as "coguid" - * (where vod is a variable that contains VOD data) - * - * !!!Only created by that method VOD can be deleted/update!!! - */ - // ingest new VOD (Media) // TODO: complete one-by-one needed fields to cover util ingest_vod from old project - public static MediaAsset ingestVOD(Optional action, Optional coguid, boolean isActive, Optional name, Optional thumbUrl, Optional description, - Optional catalogStartDate, Optional catalogEndDate, Optional startDate, Optional endDate, - Optional mediaType, Optional ppvWebName, Optional ppvMobileName) { - String startEndDatePattern = "dd/MM/yyyy hh:mm:ss"; - String coguidDatePattern = "yyMMddHHmmssSS"; - String maxEndDateValue = "14/10/2099 17:00:00"; - String ppvModuleName = "Shai_Regression_PPV"; // TODO: update on any generated value - int defaultDayOffset =-1; - - String actionValue = action.orElse(INGEST_ACTION_INSERT); - String coguidValue = coguid.orElse(getCurrentDataInFormat(coguidDatePattern)); - String nameValue = INGEST_ACTION_INSERT.equals(actionValue) ? coguidValue : name.orElse(coguidValue); - String thumbUrlValue = thumbUrl.orElse(INGEST_VOD_DEFAULT_THUMB); - String descriptionValue = description.orElse("description of " + coguidValue); - String catalogStartDateValue = catalogStartDate.orElse(getOffsetDateInFormat(defaultDayOffset, startEndDatePattern)); - String catalogEndDateValue = catalogEndDate.orElse(maxEndDateValue); - String startDateValue = startDate.orElse(getOffsetDateInFormat(defaultDayOffset, startEndDatePattern)); - String endDateValue = endDate.orElse(maxEndDateValue); - String mediaTypeValue = mediaType.orElse(MOVIE_MEDIA_TYPE); - String ppvWebNameValue = ppvWebName.orElse(ppvModuleName); - String ppvMobileNameValue = ppvMobileName.orElse(ppvModuleName); - // TODO: check if ingest url is the same for all ingest actions - String url = getProperty(INGEST_BASE_URL) + "/Ingest_" + getProperty(API_VERSION) + "/Service.svc?wsdl"; - HashMap headerMap = new HashMap<>(); - headerMap.put("Content-Type", "text/xml;charset=UTF-8"); - headerMap.put("SOAPAction", "\"http://tempuri.org/IService/IngestTvinciData\""); - String reqBody = "\n" + - " \n" + - " \n" + - " " + getProperty(INGEST_USER_USERNAME) + "" + getProperty(INGEST_USER_PASSWORD) + "" + - " \n" + - " \n" + - ""; - io.restassured.response.Response resp = RestAssured.given() - .log().all() - .headers(headerMap) - .body(reqBody) - .post(url); - - Logger.getLogger(IngestUtils.class).debug(reqBody); - Logger.getLogger(IngestUtils.class).debug(resp.asString()); - - String id; - if (INGEST_ACTION_INSERT.equals(actionValue)) { - id = from(resp.asString()).get("Envelope.Body.IngestTvinciDataResponse.IngestTvinciDataResult.AssetsStatus.IngestAssetStatus.InternalAssetId").toString(); - } else { - id = from(resp.asString()).get("Envelope.Body.IngestTvinciDataResponse.IngestTvinciDataResult.tvmID").toString(); - } - - MediaAsset mediaAsset = new MediaAsset(); - mediaAsset.setName(nameValue); - mediaAsset.setId(Long.valueOf(id)); - mediaAsset.setDescription(descriptionValue); - //mediaAsset.setStartDate(startDate); - //mediaAsset.setEndDate(endDate); - - int delayBetweenRetriesInSeconds = 3; - int maxTimeExpectingValidResponseInSeconds = 60; - await().pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS).atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS).until(isDataReturned(getAnonymousKs(), id, actionValue)); - if (!INGEST_ACTION_DELETE.equals(actionValue)) { - mediaAsset.setMediaFiles(executor.executeSync( - AssetService.get(id, AssetReferenceType.MEDIA).setKs(getAnonymousKs())).results.getMediaFiles()); - } - - // TODO: 4/15/2018 add log for ingest and index failures - return mediaAsset; - } - - private static Callable isDataReturned(String ks, String mediaId, String action) { - GetAssetBuilder getAssetBuilder = AssetService.get(mediaId, AssetReferenceType.MEDIA).setKs(ks); - if (INGEST_ACTION_DELETE.equals(action)) { - return () -> (executor.executeSync(getAssetBuilder).error != null); - } else { - return () -> (executor.executeSync(getAssetBuilder).error == null); - } - } - - private static String buildIngestVodXml(String action, String coguid, boolean isActive, String name, String thumbUrl, - String description, String catalogStartDate, String catalogEndDate, - String startDate, String endDate, String mediaType, String ppvWebName, - String ppvMobileName) { - return "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " " + name + "\n" + - " \n" + - " \n" + - " \n" + - " " + description + "\n" + - " \n" + - " \n" + - " " + catalogStartDate + "\n" + - " " + startDate + "\n" + - " " + catalogEndDate + "\n" + - " " + endDate + "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " " + mediaType + "\n" + - " \n" + - //" ${#TestCase#i_geo_block_rule}\n" + - // TODO: check where to put that value (is it env-dependent?) - " Parent Allowed\n" + - //" ${#TestCase#i_device_block_rule}\n" + - " \n" + - " \n" + - " \n" + - //" \n" + - //" \n" + - //" syno pino sister\n" + - //" \n" + - //" \n" + - //" ${#TestCase#i_meta_value}\n" + - //" \n" + - //" \n" + - //" \n" + - //" \n" + - //" ${#TestCase#i_double_meta_value}\n" + - //" \n" + - //" \n" + - //" ${#TestCase#i_date_meta_value}\n" + - //" \n" + - //" \n" + - //" \n" + - //" \n" + - //" Costa Rica;Israel\n" + - //" \n" + - //" \n" + - //" \n" + - //" \n" + - //" GIH\n" + - //" \n" + - //" \n" + - //" ABC\n" + - //" \n" + - //" \n" + - //" DEF\n" + - //" \n" + - //" \n" + - //" \n" + - //" \n" + - //" Shay_Series\n" + - //" \n" + - //" \n" + - //" \n" + - //" \n" + - //" ${#TestCase#i_tag_free_value}\n" + - //" \n" + - //" \n" + - //" \n" + - //" \n" + - //" ${#TestCase#i_parental_value}\n" + - //" \n" + - //" \n" + - //" \n" + - //" \n" + - //" ${#TestCase#i_tag_value}\n" + - //" \n" + - //" \n" + - //" \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; - } - - // Provide only media type (mandatory) and media name (Optional - if not provided will generate a name) - public static MediaAsset ingestBasicVOD(Optional name, String mediaType) { - String coguidValue = getCurrentDataInFormat("yyMMddHHmmssSS"); - String nameValue = name.orElseGet(() -> MOVIE_MEDIA_TYPE + "_" + coguidValue); - String thumbUrlValue = INGEST_VOD_DEFAULT_THUMB; - String descriptionValue = "description of " + coguidValue; - String catalogStartDateValue = getOffsetDateInFormat(-1, "dd/MM/yyyy hh:mm:ss"); - String catalogEndDateValue = "14/10/2099 17:00:00"; - String startDateValue = getOffsetDateInFormat(-1, "dd/MM/yyyy hh:mm:ss"); - String endDateValue = "14/10/2099 17:00:00"; - String mediaTypeValue = mediaType; - String ppvWebNameValue = "Shai_Regression_PPV"; - String ppvMobileNameValue = "Shai_Regression_PPV"; // TODO: update on any generated value - // TODO: check if ingest url is the same for all ingest actions - String url = getProperty(INGEST_BASE_URL) + "/Ingest_" + getProperty(API_VERSION) + "/Service.svc?wsdl"; - HashMap headermap = new HashMap<>(); - headermap.put("Content-Type", "text/xml;charset=UTF-8"); - headermap.put("SOAPAction", "\"http://tempuri.org/IService/IngestTvinciData\""); - String reqBody = "\n" + - " \n" + - " \n" + - " " + getProperty(INGEST_USER_USERNAME) + "" + getProperty(INGEST_USER_PASSWORD) + "" + - " \n" + - " \n" + - ""; - io.restassured.response.Response resp = RestAssured.given() - .log().all() - .headers(headermap) - .body(reqBody) - .post(url); - //System.out.println("RESPONSE: " + resp.asString()); - String id = from(resp.asString()).get("Envelope.Body.IngestTvinciDataResponse.IngestTvinciDataResult.AssetsStatus.IngestAssetStatus.InternalAssetId").toString(); - - MediaAsset mediaAsset = new MediaAsset(); - mediaAsset.setName(nameValue); - mediaAsset.setId(Long.valueOf(id)); - mediaAsset.setDescription(descriptionValue); - //mediaAsset.setStartDate(startDate); - //mediaAsset.setEndDate(endDate); - - await().pollInterval(3, TimeUnit.SECONDS).atMost(45, TimeUnit.SECONDS).until(isDataReturned(getAnonymousKs(), id, INGEST_ACTION_INSERT)); - mediaAsset.setMediaFiles(executor.executeSync( - AssetService.get(id, AssetReferenceType.MEDIA).setKs(getAnonymousKs())).results.getMediaFiles()); - - // TODO: 4/15/2018 add log for ingest and index failures - return mediaAsset; - } -} diff --git a/src/test/java/com/kaltura/client/test/utils/KsqlBuilder.java b/src/test/java/com/kaltura/client/test/utils/KsqlBuilder.java new file mode 100644 index 000000000..0b67563f8 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/KsqlBuilder.java @@ -0,0 +1,125 @@ +package com.kaltura.client.test.utils; + +public class KsqlBuilder { + private StringBuilder sb; + + public KsqlBuilder() { + sb = new StringBuilder(); + } + + // numerical fields operators + public KsqlBuilder equal(String key, int value) { + sb.append(key).append("=").append("'").append(String.valueOf(value)).append("' "); + return this; + } + + public KsqlBuilder notEqual(String key, int value) { + sb.append(key).append("!=").append("'").append(String.valueOf(value)).append("' "); + return this; + } + + public KsqlBuilder greater(String key, int value) { + sb.append(key).append(">").append("'").append(String.valueOf(value)).append("' "); + return this; + } + + public KsqlBuilder less(String key, int value) { + sb.append(key).append("<").append("'").append(String.valueOf(value)).append("' "); + return this; + } + + public KsqlBuilder greaterOrEqual(String key, int value) { + sb.append(key).append(">=").append("'").append(String.valueOf(value)).append("' "); + return this; + } + + public KsqlBuilder greaterOrEqual(String key, long value) { + sb.append(key).append(">=").append("'").append(String.valueOf(value)).append("' "); + return this; + } + + public KsqlBuilder lessOrEqual(String key, int value) { + sb.append(key).append("<=").append("'").append(String.valueOf(value)).append("' "); + return this; + } + + // alpha-numerical fields + public KsqlBuilder equal(String key, String value) { + sb.append(key).append("=").append("'").append(String.valueOf(value)).append("' "); + return this; + } + + public KsqlBuilder notEqual(String key, String value) { + sb.append(key).append("!=").append("'").append(String.valueOf(value)).append("' "); + return this; + } + + public KsqlBuilder like(String key, String value) { + sb.append(key).append("~").append("'").append(String.valueOf(value)).append("' "); + return this; + } + + public KsqlBuilder notLike(String key, String value) { + sb.append(key).append("!~").append("'").append(String.valueOf(value)).append("' "); + return this; + } + + public KsqlBuilder startsWith(String key, String value) { + sb.append(key).append("^").append("'").append(String.valueOf(value)).append("' "); + return this; + } + + // searching one value in a list of numeric values operator + public KsqlBuilder inList(String key, String value) { + sb.append(key).append(":").append("'").append(String.valueOf(value)).append("' "); + return this; + } + + // exists operators + public KsqlBuilder exists(String key) { + sb.append(key).append("+''"); + return this; + } + + public KsqlBuilder notExists(String key) { + sb.append(key).append("!+''"); + return this; + } + + // logical conjunctions + public KsqlBuilder and(String statment) { + sb.append("(and ").append(statment).append(") "); + return this; + } + + public KsqlBuilder or(String statment) { + sb.append("(or ").append(statment).append(") "); + return this; + } + + public KsqlBuilder openAnd() { + sb.append("(and "); + return this; + } + + public KsqlBuilder openOr() { + sb.append("(or "); + return this; + } + + public KsqlBuilder closeAnd() { + String s = sb.toString().trim(); + sb = new StringBuilder(s).append(") "); + return this; + } + + public KsqlBuilder closeOr() { + String s = sb.toString().trim(); + sb = new StringBuilder(s).append(") "); + return this; + } + + public String toString() { + return sb.toString().trim(); + } +} diff --git a/src/test/java/com/kaltura/client/test/utils/OttUserUtils.java b/src/test/java/com/kaltura/client/test/utils/OttUserUtils.java index bea516dab..61a079739 100644 --- a/src/test/java/com/kaltura/client/test/utils/OttUserUtils.java +++ b/src/test/java/com/kaltura/client/test/utils/OttUserUtils.java @@ -3,12 +3,15 @@ import com.kaltura.client.services.OttUserService; import com.kaltura.client.types.LoginResponse; import com.kaltura.client.types.OTTUser; +import com.kaltura.client.types.StringValue; import com.kaltura.client.utils.response.base.Response; -import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; import java.util.Random; -import static com.kaltura.client.services.OttUserService.*; +import static com.kaltura.client.services.OttUserService.GetOttUserBuilder; +import static com.kaltura.client.services.OttUserService.LoginOttUserBuilder; import static com.kaltura.client.test.tests.BaseTest.*; public class OttUserUtils extends BaseUtils { @@ -28,13 +31,14 @@ public static OTTUser generateOttUser() { user.setEmail(emailPrefix + stamp + emailDomain); user.setAddress(randomString + " fake address"); user.setCity(randomString + " fake city"); + user.setExternalId(stamp); Random r = new Random(); user.setCountryId(r.nextInt(30 - 1) + 1); return user; } - public static OTTUser getUserById(int userId) { + public static OTTUser getOttUserById(int userId) { // OttUser/action/get GetOttUserBuilder getOttUserBuilder = OttUserService.get(); @@ -45,15 +49,37 @@ public static OTTUser getUserById(int userId) { return userResponse.results; } - public static String getKs(int userId, @Nullable String udid) { - OTTUser ottUser = getUserById(userId); + public static String getKs(int userId) { + OTTUser ottUser = getOttUserById(userId); - //OttUser/action/login + // ottUser/action/login + LoginOttUserBuilder loginOttUserBuilder = OttUserService.login(partnerId, ottUser.getUsername(), defaultUserPassword, null, null); + Response loginResponse = executor.executeSync(loginOttUserBuilder); + + return loginResponse.results.getLoginSession().getKs(); + } + + public static String getKs(int userId, String udid) { + OTTUser ottUser = getOttUserById(userId); + + // ottUser/action/login LoginOttUserBuilder loginOttUserBuilder = OttUserService.login(partnerId, ottUser.getUsername(), defaultUserPassword, null, udid); - loginOttUserBuilder.setKs(null); - loginOttUserBuilder.setUserId(userId); Response loginResponse = executor.executeSync(loginOttUserBuilder); return loginResponse.results.getLoginSession().getKs(); } + + public static Map dynamicDataMapBuilder(String key, String value) { + Map dynamicData = new HashMap<>(); + + String sk = key; + StringValue sv = new StringValue(); + sv.setValue(value); + dynamicData.put(sk, sv); + + return dynamicData; + } + + + } diff --git a/src/test/java/com/kaltura/client/test/utils/PerformanceAppLogUtils.java b/src/test/java/com/kaltura/client/test/utils/PerformanceAppLogUtils.java new file mode 100644 index 000000000..12398a583 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/PerformanceAppLogUtils.java @@ -0,0 +1,410 @@ +//package com.kaltura.client.test.utils; +// +//import com.kaltura.client.Logger; +//import lombok.Data; +//import org.apache.commons.io.FileUtils; +// +//import java.io.*; +//import java.net.HttpURLConnection; +//import java.net.URL; +//import java.nio.file.Files; +//import java.nio.file.Paths; +//import java.util.*; +//import java.util.stream.Stream; +// +//import static com.kaltura.client.test.Properties.*; +// +//public class PerformanceAppLogUtils extends BaseUtils { +// +// /** +// * class to save data about count of slow executions and count of total executions for methods checking in regression +// */ +// @Data +// static class SlowRatio { +// private int slowCount; +// private int totalCount; +// } +// +// private static final int maxAllowedPercentage = Integer.valueOf(getProperty(MAX_CODE_PERCENTAGE)); +// private static final String remoteSourceUrlFileDir = getProperty(LOGS_BASE_URL) + getProperty(API_VERSION) + "\\"; +// +// private static final String COUCHBASE_LOG_DATA = "\"e\":\"cb\""; +// private static final String DB_LOG_DATA = "\"e\":\"db\""; +// private static final String ELASTIC_SEARCH_LOG_DATA = "\"e\":\"es\""; +// private static final String RABBIT_LOG_DATA = "\"e\":\"rabbit\""; +// +// private static List appLogLocalFileNames = new ArrayList<>(); +// +// private static final List nonRelated2CodeStringsList = new ArrayList() {{ +// add("\"e\":\"start_api\""); +// add(COUCHBASE_LOG_DATA); +// add(DB_LOG_DATA); +// add(ELASTIC_SEARCH_LOG_DATA); +// add(RABBIT_LOG_DATA); +// }}; +// +// private static double timeOfCode; +// private static double timeOfCB; +// private static double timeOfDB; +// private static double timeOfES; +// private static double timeOfRabbit; +// private static double totalTime; +// private static boolean isKalturaSessionFoundInAppLogFile; +// private static int countOfCB; +// private static int countOfDB; +// private static int countOfES; +// private static int countOfRabbit; +// +// public static void createPerformanceCodeReport() { +// try { +// // copy log files to local machine +// List appRemoteFileNames = getRemoteAppLogFileNames(); +// for (String fileName : appRemoteFileNames) { +// copyRemoteFile2LocalMachine(fileName); +// } +// +// // aggregated last regression results +// Map> methodsAndKalturaSessions = loadMethodsAndSessionsFromTestFile(); +// +// Map methodsAndSlowRatioData = new HashMap<>(); +// SlowRatio slowRatio; +// for (String method : methodsAndKalturaSessions.keySet()) { +// methodsAndSlowRatioData.put(method, new SlowRatio()); +// //Logger.getLogger(PerformanceAppLogUtils.class).debug("Method: [" + method + "]"); +// for (String xKalturaSession : methodsAndKalturaSessions.get(method)) { +// slowRatio = methodsAndSlowRatioData.get(method); +// slowRatio.totalCount++; +// methodsAndSlowRatioData.put(method, slowRatio); +// //Logger.getLogger(PerformanceAppLogUtils.class).debug("xKalturaSession: [" + xKalturaSession + "]"); +// for (String appFileName : appRemoteFileNames) { +// isKalturaSessionFoundInAppLogFile = false; +// timeOfCode = 0.0; +// timeOfCB = 0.0; +// timeOfDB = 0.0; +// timeOfES = 0.0; +// timeOfRabbit = 0.0; +// totalTime = 0.0; +// +// countOfCB = 0; +// countOfDB = 0; +// countOfES = 0; +// countOfRabbit = 0; +// +// calcTimeExecution(appFileName, xKalturaSession); +// +// if (isKalturaSessionFoundInAppLogFile) { +// double percentageCodeTime2TotalTime = timeOfCode / totalTime * 100; +// +// // include in report only relevant cases +// if (percentageCodeTime2TotalTime > maxAllowedPercentage && +// totalTime > Double.parseDouble(getProperty(MAX_EXECUTION_TIME_IN_SEC))) { +// slowRatio = methodsAndSlowRatioData.get(method); +// slowRatio.slowCount++; +// methodsAndSlowRatioData.put(method, slowRatio); +// +// // save results +// writeReport2File(method, xKalturaSession, percentageCodeTime2TotalTime); +// } +// } +// } +// } +// } +// addSummary2Report(methodsAndSlowRatioData); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// } +// +// private static void addSummary2Report(Map methodsAndSlowRatioData) throws IOException { +// Logger.getLogger(PerformanceAppLogUtils.class).debug("addSummary2Report started"); +// if (methodsAndSlowRatioData.keySet().size() > 0) { +// String reportFileName = getProperty(LOGS_DIR) + +// getProperty(PERFORMANCE_REPORT_FILE); +// String summaryTemporaryFileName = getProperty(LOGS_DIR) + "SUMMARY" + +// getProperty(PERFORMANCE_REPORT_FILE); +// +// createSummaryFile(methodsAndSlowRatioData, summaryTemporaryFileName); +// addReportDataIntoSummaryFile(reportFileName, summaryTemporaryFileName); +// +// File source = new File(summaryTemporaryFileName); +// File target = new File(reportFileName); +// deleteFile(reportFileName); +// boolean success = source.renameTo(target); +// if (!success) { +// throw new IOException("File can't be renamed"); +// } +// Logger.getLogger(PerformanceAppLogUtils.class).debug("Report was successfully created: [" + reportFileName + "]"); +// } +// Logger.getLogger(PerformanceAppLogUtils.class).debug("addSummary2Report completed"); +// } +// +// private static void addReportDataIntoSummaryFile(String fromFile, String toFile) { +// Logger.getLogger(PerformanceAppLogUtils.class).debug("addReportDataIntoSummaryFile started"); +// Logger.getLogger(PerformanceAppLogUtils.class).debug(Paths.get(fromFile)); +// try (BufferedReader br = Files.newBufferedReader(Paths.get(fromFile)); +// FileWriter fw = new FileWriter(toFile, true); +// BufferedWriter bw = new BufferedWriter(fw); +// PrintWriter out = new PrintWriter(bw)) { +// Stream lines = br.lines(); +// lines.forEach(out::println); +// lines.close(); +// } catch (IOException e) { +// e.printStackTrace(); +// } finally { +// Logger.getLogger(PerformanceAppLogUtils.class).debug("addReportDataIntoSummaryFile completed"); +// } +// } +// +// private static void createSummaryFile(Map methodsAndSlowRatioData, String summaryTemporaryFileName) { +// Logger.getLogger(PerformanceAppLogUtils.class).debug("createSummaryFile started"); +// try (FileWriter fw = new FileWriter(summaryTemporaryFileName, true); +// BufferedWriter bw = new BufferedWriter(fw); +// PrintWriter out = new PrintWriter(bw)) { +// out.println("Report of slow methods on " + getCurrentDateInFormat("dd/MM/yyyy HH:mm") + " (" + getProperty(API_VERSION) + ")"); +// out.println("Max allowed percentage: " + getProperty(MAX_CODE_PERCENTAGE)); +// out.println("Max allowed execution time in seconds: " + getProperty(MAX_EXECUTION_TIME_IN_SEC)); +// out.println(); +// out.println("Summary of slow methods are below:"); +// out.println(); +// for (String method : methodsAndSlowRatioData.keySet()) { +// if (methodsAndSlowRatioData.get(method).slowCount > 0) { +// out.println(method + " was slow " + String.format("%.2f", methodsAndSlowRatioData.get(method).slowCount * +// 1.0 / methodsAndSlowRatioData.get(method).totalCount * 100) + "% of executions (" + +// methodsAndSlowRatioData.get(method).slowCount + "/" + methodsAndSlowRatioData.get(method).totalCount + ")"); +// } +// } +// +// out.println(); +// out.println("Details of slow methods are below:"); +// out.println(); +// } catch (IOException e) { +// e.printStackTrace(); +// } finally { +// Logger.getLogger(PerformanceAppLogUtils.class).debug("createSummaryFile completed"); +// } +// } +// +// private static void writeReport2File(String method, String xKalturaSession, double codeTimePercentage) { +// try (FileWriter fw = new FileWriter(getProperty(LOGS_DIR) + +// getProperty(PERFORMANCE_REPORT_FILE), true); +// BufferedWriter bw = new BufferedWriter(fw); +// PrintWriter out = new PrintWriter(bw)) { +// // we want to see only data where code time is less than 100% +// if (timeOfCB > 0 || timeOfDB > 0 || timeOfES > 0 || timeOfRabbit > 0) { +// out.println(method); +// out.println(xKalturaSession); +// out.println("Execution Time: " + String.format("%.3f", totalTime)); +// out.println("Code: " + String.format("%.2f", codeTimePercentage) + "% (" + String.format("%.3f", timeOfCode) + ")"); +// writeIfValueMoreThanZero(out, "Couchbase: ", timeOfCB, totalTime, countOfCB); +// writeIfValueMoreThanZero(out, "DB: ", timeOfDB, totalTime, countOfDB); +// writeIfValueMoreThanZero(out, "Elastic: ", timeOfES, totalTime, countOfES); +// writeIfValueMoreThanZero(out, "Rabbit: ", timeOfRabbit, totalTime, countOfRabbit); +// out.println(); +// } +// } catch (IOException e) { +// e.printStackTrace(); +// } +// } +// +// private static void writeIfValueMoreThanZero(PrintWriter out, String title, double timeOfEvent, double totalTime, int countOfEvent) { +// if (timeOfEvent > 0) { +// out.println(title + " " + String.format("%.2f", timeOfEvent / totalTime * 100) + "% (" + String.format("%.3f", timeOfEvent) + ") [" + countOfEvent + " queries]"); +// } +// } +// +// private static void copyRemoteFile2LocalMachine(String remoteFileName) throws IOException { +// Logger.getLogger(PerformanceAppLogUtils.class).debug("copyRemoteFile2LocalMachine() with [" + remoteFileName + "]: started"); +// +// // add local target folder in case it does not exist +// File localTargetFolderPath = new File(getProperty(LOGS_DIR)); +// if (!localTargetFolderPath.exists()) { +// boolean isDirCreated = localTargetFolderPath.mkdir(); +// Logger.getLogger(PerformanceAppLogUtils.class).debug("Directory [" + +// getProperty(LOGS_DIR) + "] was created == [" + isDirCreated + "]"); +// } +// +// String remoteFilePathUrl = remoteSourceUrlFileDir + remoteFileName; +// String localTargetFilePath = getProperty(LOGS_DIR) + "copied-" + remoteFileName; +// appLogLocalFileNames.add(localTargetFilePath); +// +// // remove local target file in case it exists and create it empty +// File targetFile = new File(localTargetFilePath); +// if (targetFile.exists()) { +// targetFile.delete(); +// } +// targetFile.createNewFile(); +// //FileObject destination = VFS.getManager().resolveFile(targetFile.getAbsolutePath()); +// +// //domain, username, password +// //DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(options, auth); +// +// //FileObject fileObject = VFS.getManager().resolveFile(remoteFilePath, options); +// +// // copy file from remote to local folder +//// if (fileObject.exists()) { +//// destination.copyFrom(fileObject, Selectors.SELECT_SELF); +//// } +// if (isUrlExists(remoteFilePathUrl)) { +// FileUtils.copyURLToFile(new URL(remoteFilePathUrl), targetFile); +// } +// //destination.close(); +// Logger.getLogger(PerformanceAppLogUtils.class).debug("File [" + remoteFilePathUrl + "] was copied into [" + localTargetFilePath + "]"); +// Logger.getLogger(PerformanceAppLogUtils.class).debug("copyRemoteFile2LocalMachine(): completed"); +// } +// +// public static List getRemoteAppLogFileNames() throws IOException { +// Logger.getLogger(PerformanceAppLogUtils.class).debug("getRemoteAppLogFileNames(): started"); +// List fileNames = new ArrayList<>(); +// String sourceFileName = getProperty(PHOENIX_SERVER_LOG_FILE_NAME_PREFIX) + getProperty(API_VERSION) + +// getProperty(PHOENIX_SERVER_LOG_FILE_EXTENSION); +// String remoteFilePathUrl = remoteSourceUrlFileDir + sourceFileName; +// Logger.getLogger(PerformanceAppLogUtils.class).debug("remoteFilePathUrl: " + remoteFilePathUrl); +// +//// //domain, username, password +//// DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(options, auth); +//// +//// FileObject fileObject = VFS.getManager().resolveFile(remoteFilePathUrl, options); +// +//// if (fileObject.exists()) { +//// fileNames.add(sourceFileName); +//// } else { +//// Logger.getLogger(PerformanceAppLogUtils.class).error("getRemoteAppLogFileNames(): file not found!"); +//// } +// if (isUrlExists(remoteFilePathUrl)) { +// fileNames.add(sourceFileName); +// } else { +// Logger.getLogger(PerformanceAppLogUtils.class).error("getRemoteAppLogFileNames(): file not found!"); +// } +// int idx = 1; +// while (isUrlExists(remoteFilePathUrl)) { +// // all files related needed logs have the same name as value from sourceFileName and additionally they have +// // suffixes that looks like ".1", ".2", etc... +// String name = sourceFileName + "." + idx; +// //fileObject = VFS.getManager().resolveFile(remoteSourceFileDir + name, options); +// idx++; +// remoteFilePathUrl = remoteSourceUrlFileDir + name; +// // sometimes file can be removed and it means we should one more time check names +// if (isUrlExists(remoteFilePathUrl)) { +// fileNames.add(name); +// } else { +// // to handle case when next file has difference in suffixes bigger than 1 +// name = sourceFileName + "." + idx; +// idx++; +// remoteFilePathUrl = remoteSourceUrlFileDir + name; +// if (isUrlExists(remoteFilePathUrl)) { +// fileNames.add(name); +// } +// } +// } +// Logger.getLogger(PerformanceAppLogUtils.class).debug("getRemoteAppLogFileNames(): completed"); +// return fileNames; +// } +// +// /*If the connection to a URL (made with HttpURLConnection) returns with HTTP status code 200 then the file exists. +// Since we only care it exists or not there is no need to request the entire document. +// We can just request the header using the HTTP HEAD request method to check if it exists.*/ +// private static boolean isUrlExists(String fileUrl) { +// try { +// HttpURLConnection.setFollowRedirects(false); +// // note : you may also need HttpURLConnection.setInstanceFollowRedirects(false) +// HttpURLConnection con = (HttpURLConnection) new URL(fileUrl).openConnection(); +// con.setRequestMethod("HEAD"); +// return (con.getResponseCode() == HttpURLConnection.HTTP_OK); +// } +// catch (Exception e) { +// e.printStackTrace(); +// return false; +// } +// } +// +// /** +// * We have file with name getProperty(LOGS_DIR) + getProperty(REGRESSION_LOGS_FILE) +// * that saves information about all executed methods and their kaltura sessions. +// * That file will be filled with data only in case test.properties has should_regression_logs_be_saved=true +// * +// * @return map contains all methods and kaltura sessions related to regression +// */ +// public static Map> loadMethodsAndSessionsFromTestFile() { +// Logger.getLogger(PerformanceAppLogUtils.class).debug("loadMethodsAndSessionsFromTestFile(): started"); +// Map> result = new HashMap<>(); +// String[] values; +// try { +// InputStream is = new FileInputStream(getProperty(LOGS_DIR) + +// getProperty(REGRESSION_LOGS_FILE)); +// BufferedReader buf = new BufferedReader(new InputStreamReader(is)); +// +// String line; +// List sessions; +// while ((line = buf.readLine()) != null) { +// values = line.split(":"); +// sessions = result.get(values[0]); +// if (sessions == null) { +// sessions = new ArrayList<>(); +// } +// sessions.add(values[1]); +// result.put(values[0], sessions); +// } +// } catch (IOException e) { +// e.printStackTrace(); +// } finally { +// Logger.getLogger(PerformanceAppLogUtils.class).debug("loadMethodsAndSessionsFromTestFile(): completed"); +// return result; +// } +// } +// +// private static void calcTimeExecution(String appFileName, String kalturaSession) { +// String path2File = getProperty(LOGS_DIR) + "copied-" + appFileName; +// +// String[] nonRelated2CodeStringsArray = new String[nonRelated2CodeStringsList.size()]; +// String executionTimeString; +// try (BufferedReader br = new BufferedReader(new FileReader(path2File))) { +// for (String line; (line = br.readLine()) != null; ) { +// if (line.contains(kalturaSession)) { +// isKalturaSessionFoundInAppLogFile = true; +// // this is a usual position of time in the whole string +// executionTimeString = line.split("\"")[3]; +// // "e": "ws" should be ignored as it partially described in other events +// if (stringContainsItemFromArray(line, nonRelated2CodeStringsList.toArray(nonRelated2CodeStringsArray))) { +// timeOfCode = timeOfCode - Double.valueOf(executionTimeString); +// } else { +// if (line.contains("\"e\":\"end_api\"")) { +// totalTime = Double.valueOf(executionTimeString); +// timeOfCode = timeOfCode + totalTime; +// } +// } +// if (line.contains(COUCHBASE_LOG_DATA)) { +// timeOfCB = timeOfCB + Double.valueOf(executionTimeString); +// countOfCB++; +// } +// if (line.contains(DB_LOG_DATA)) { +// timeOfDB = timeOfDB + Double.valueOf(executionTimeString); +// countOfDB++; +// } +// if (line.contains(ELASTIC_SEARCH_LOG_DATA)) { +// timeOfES = timeOfES + Double.valueOf(executionTimeString); +// countOfES++; +// } +// if (line.contains(RABBIT_LOG_DATA)) { +// timeOfRabbit = timeOfRabbit + Double.valueOf(executionTimeString); +// countOfRabbit++; +// } +// } +// } +// } catch (IOException e) { +// e.printStackTrace(); +// } +// } +// +// private static boolean stringContainsItemFromArray(String inputStr, String[] items) { +// return Arrays.stream(items).parallel().anyMatch(inputStr::contains); +// } +// +// /** +// * method removes from local computer copied on it from remote machine app log files +// */ +// public static void removeCopiedAppLogFiles() { +// for (String file : appLogLocalFileNames) { +// deleteFile(file); +// } +// } +//} \ No newline at end of file diff --git a/src/test/java/com/kaltura/client/test/utils/PerformanceUtils.java b/src/test/java/com/kaltura/client/test/utils/PerformanceUtils.java new file mode 100644 index 000000000..9b886dc90 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/PerformanceUtils.java @@ -0,0 +1,394 @@ +package com.kaltura.client.test.utils; + +import com.kaltura.client.ILogger; +import com.kaltura.client.Logger; +import lombok.AccessLevel; +import lombok.Getter; +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.json.JSONObject; +import org.jsoup.Jsoup; +import org.jsoup.nodes.Document; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.*; +import java.util.stream.Collectors; + +import static com.kaltura.client.test.Properties.*; + +public class PerformanceUtils extends BaseUtils { + + private static final ILogger logger = Logger.getLogger(PerformanceUtils.class); + + private static final int maxAllowedPercentage = Integer.parseInt(getProperty(MAX_CODE_PERCENTAGE)); + private static final float maxAllowedTime = Float.parseFloat(getProperty(MAX_EXECUTION_TIME_IN_SEC)); + + private static final String logsUrl = getProperty(LOGS_BASE_URL) + getProperty(API_VERSION) + "/"; + private static final String filesCssQuery = "a:contains(tvp-api-rest-monitor-" + getProperty(API_VERSION) + ")"; + private static final String reportFilePath = getProperty(LOGS_DIR) + getProperty(PERFORMANCE_REPORT_FILE); + + + public static void generatePerformanceReport() { + logger.debug("start generatePerformanceReport()"); + + // get aggregate regression sessions strings + List regressionSessions = getRegressionData().values() + .stream() + .flatMap(List::stream) + .collect(Collectors.toList()); + + // get sessions + List sessions = getSessions(regressionSessions); + + // write performance report + writeReport(sessions); + + logger.debug("finish generatePerformanceReport()"); + } + + private static Map> getRegressionData() { + logger.debug("start getRegressionData()"); + + File data = new File(getProperty(LOGS_DIR) + getProperty(REGRESSION_LOGS_FILE)); + List lines = null; + try { + lines = Files.readAllLines(data.toPath()); + } catch (IOException e) { + e.printStackTrace(); + } + + logger.debug("end getRegressionData()"); + + return lines + .stream() + .collect(Collectors.groupingBy( + s -> s.split(":")[0], + Collectors.mapping(s -> s.split(":")[1], + Collectors.toList()))); + } + + private static List getLogFilesUrls() { + logger.debug("start getLogFilesUrls()"); + + Document doc = null; + try { + doc = Jsoup.connect(logsUrl).get(); + } catch (IOException e) { + e.printStackTrace(); + File file = getReportFile(); + try { + FileUtils.writeStringToFile(file, ExceptionUtils.getStackTrace(e), Charset.defaultCharset(), true); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + + List urls = new ArrayList<>(); + + doc.select(filesCssQuery).forEach(element -> { + try { + URL url = new URL(logsUrl + element.text()); + urls.add(url); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + }); + + logger.debug("end getLogFilesUrls()"); + + return urls; + } + + private static List getLinesFromUrls(List urls) { + logger.debug("start getLinesFromUrls()"); + + List> data = new ArrayList<>(); + + urls.forEach(url -> { + URLConnection conn = null; + try { + conn = url.openConnection(); + } catch (IOException e) { + e.printStackTrace(); + } + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) { + List lines = reader.lines().collect(Collectors.toList()); + data.add(lines); + } catch (IOException e) { + e.printStackTrace(); + } + }); + + + logger.debug("end getLinesFromUrls()"); + + return data + .stream() + .flatMap(Collection::stream) + .collect(Collectors.toList()); + } + + private static List getSessions(List sessionStrings) { + logger.debug("start getSessions()"); + + List lines = getLinesFromUrls(getLogFilesUrls()); + + List sessionList = new ArrayList<>(); + sessionStrings.forEach(s -> { + Session session = getSession(lines, s); + if (session != null) { + sessionList.add(session); + } + }); + + logger.debug("end getSessions()"); + return sessionList; + } + + private static Session getSession(List lines, String session) { + List sessionData = new ArrayList<>(); + + lines.forEach(line -> { + if (line.contains(session)) { + JSONObject jo = new JSONObject(line.substring(line.indexOf("{"))); + sessionData.add(jo); + } + }); + + if (sessionData.size() == 0) { +// logger.debug("missing session from logs: " + session); + return null; + } + + return new Session(sessionData); + } + + private static List getSlowSessions(List sessions) { + return sessions + .stream() + .filter(Session::isSlow) + .collect(Collectors.toList()); + } + + private static File getReportFile() { + File file = new File(reportFilePath); + + if (file.exists()) { + file.delete(); + try { + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return file; + } + + private static void writeReport(List sessions) { + logger.debug("start writeReport()"); + + // get slow sessions + List slowSessions = getSlowSessions(sessions); + + // slow actions by count + Map slowActionsByCount = slowSessions.stream().collect(Collectors.groupingBy( + Session::getAction, + Collectors.counting() + )); + + // actions by count + Map actionsByCount = sessions.stream().collect(Collectors.groupingBy( + Session::getAction, + Collectors.counting() + )); + + // actions by average time + Map slowActionsByAverageTime = new HashMap<>(); + slowActionsByCount.keySet().forEach(s -> { + long actionTotalCount = actionsByCount.get(s); + + double averageTime = sessions.stream() + .filter(session -> session.getAction().equals(s)) + .mapToDouble(Session::getTotalTime).sum() / actionTotalCount; + + slowActionsByAverageTime.put(s, averageTime); + }); + + // sort actions by average time + List> slowActionsAverageTimeSortedList = slowActionsByAverageTime.entrySet().stream() + .sorted(Map.Entry.comparingByValue().reversed()) + .collect(Collectors.toList()); + + // write data to file + File file = getReportFile(); + + String reportSummary = "Performance Report - " + getCurrentDateInFormat("dd/MM/yyyy HH:mm") + " (" + getProperty(API_VERSION) + ")\n" + + "Max percentage: " + getProperty(MAX_CODE_PERCENTAGE) + "%\n" + + "Max execution time: " + getProperty(MAX_EXECUTION_TIME_IN_SEC) + " sec\n\n" + + "Slow Actions Summary:\n\n"; + try { + FileUtils.writeStringToFile(file, reportSummary, Charset.defaultCharset(), true); + + slowActionsAverageTimeSortedList.forEach(entry -> { + long actionSlowCount = slowActionsByCount.get(entry.getKey()); + long actionTotalCount = actionsByCount.get(entry.getKey()); + double slowPercentage = (double) actionSlowCount / actionTotalCount * 100; + double averageTime = entry.getValue(); + + try { + FileUtils.writeStringToFile(file, entry.getKey() + " - was slow " + String.format("%.0f", slowPercentage) + + "% of executions (" + actionSlowCount + "/" + actionTotalCount + ") " + "[average time: " + String.format("%.2f", averageTime) + " sec]\n", + Charset.defaultCharset(), true); + } catch (IOException e) { + e.printStackTrace(); + } + }); + + FileUtils.writeStringToFile(file, "\nSlow Actions Details: \n\n", Charset.defaultCharset(), true); + } catch (IOException e) { + e.printStackTrace(); + } + + slowSessions.forEach(session -> { + try { + FileUtils.writeStringToFile(file, session.toString() + "\n", Charset.defaultCharset(), true); + } catch (IOException e) { + e.printStackTrace(); + } + }); + + logger.debug("end writeReport()"); + } + + @Getter + private static class Session { + @Getter(AccessLevel.NONE) private final String numFormat = "%.3f"; + @Getter(AccessLevel.NONE) private final String newLine = "\n"; + + @Getter(AccessLevel.NONE) private final String CB_EVENT = "cb"; + @Getter(AccessLevel.NONE) private final String DB_EVENT = "db"; + @Getter(AccessLevel.NONE) private final String ES_EVENT = "elastic"; + @Getter(AccessLevel.NONE) private final String RABBIT_EVENT = "rabbit"; + @Getter(AccessLevel.NONE) private final String WS_EVENT = "ws"; + + @Getter(AccessLevel.NONE) private final String EVENT_KEY = "e"; + @Getter(AccessLevel.NONE) private final String EXECUTION_TIME_KEY = "x"; + + private String action; + private String session; + + private boolean isSlow; + + private long startTime; + private long endTime; + + private double totalTimeExcludeCode; + private double totalTime; + private double codeTime; + private double cbTime; + private double dbTime; + private double esTime; + private double rabbitTime; + private double wsTime; + private double codePercentage; + + private int cbCount; + private int dbCount; + private int esCount; + private int wsCount; + private int rabbitCount; + + Session(List sessionData) { + sessionData.forEach(line -> { + if (!line.getString(EVENT_KEY).equals("start_api") && !line.getString(EVENT_KEY).equals("end_api")) { + totalTimeExcludeCode = totalTimeExcludeCode + line.getFloat(EXECUTION_TIME_KEY); + } + + if (line.getString(EVENT_KEY).equals("start_api")) { + startTime = line.getLong("m"); + } + + if (line.getString(EVENT_KEY).equals("end_api")) { + endTime = line.getLong("m"); + } + + if (line.getString(EVENT_KEY).equals(CB_EVENT)) { + cbTime = cbTime + line.getDouble(EXECUTION_TIME_KEY); + cbCount++; + } + + if (line.getString(EVENT_KEY).equals(DB_EVENT)) { + dbTime = dbTime + line.getDouble(EXECUTION_TIME_KEY); + dbCount++; + } + + if (line.getString(EVENT_KEY).equals(ES_EVENT)) { + esTime = esTime + line.getDouble(EXECUTION_TIME_KEY); + esCount++; + } + + if (line.getString(EVENT_KEY).equals(RABBIT_EVENT)) { + rabbitTime = rabbitTime + line.getDouble(EXECUTION_TIME_KEY); + rabbitCount++; + } + + if (line.getString(EVENT_KEY).equals(WS_EVENT)) { + wsTime = wsTime + line.getDouble(EXECUTION_TIME_KEY); + wsCount++; + } + }); + + action = sessionData.get(0).getString("a"); + session = sessionData.get(0).getString("u"); + + totalTime = (double) (endTime - startTime) / 1000000; + codeTime = totalTime - totalTimeExcludeCode; + codePercentage = codeTime / totalTime * 100; + + + if ((totalTime > maxAllowedTime) && + (codePercentage > maxAllowedPercentage) && + (cbTime > 0 || dbTime > 0 || esTime > 0 || rabbitTime > 0 || wsTime > 0)) { + isSlow = true; + } + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder() + .append("action: ").append(this.getAction()).append(newLine) + .append("session: ").append(this.getSession()).append(newLine) + .append("total time: ").append(String.format(numFormat, this.getTotalTime())).append(newLine) + .append("code: ").append(String.format(numFormat, this.getCodePercentage())).append("% (" + String.format(numFormat, this.getCodeTime()) + ")").append(newLine); + + writeIfEventTimeGreaterThanZero(sb, this.getCbTime(), this.getCbCount(), this.CB_EVENT); + writeIfEventTimeGreaterThanZero(sb, this.getDbTime(), this.getDbCount(), this.DB_EVENT); + writeIfEventTimeGreaterThanZero(sb, this.getEsTime(), this.getEsCount(), this.ES_EVENT); + writeIfEventTimeGreaterThanZero(sb, this.getRabbitTime(), this.getRabbitCount(), this.RABBIT_EVENT); + writeIfEventTimeGreaterThanZero(sb, this.getWsTime(), this.getWsCount(), this.WS_EVENT); + + return sb.toString(); + } + + private void writeIfEventTimeGreaterThanZero(StringBuilder sb, double eventTime, int eventCount, String eventName) { + if (eventTime > 0) { + sb + .append(eventName + ": ") + .append(String.format(numFormat, eventTime / this.getTotalTime() * 100)) + .append("% (" + String.format(numFormat, eventTime) + ")") + .append(" [" + eventCount + " queries]") + .append("\n"); + } + } + } +} diff --git a/src/test/java/com/kaltura/client/test/utils/PermissionManagementUtils.java b/src/test/java/com/kaltura/client/test/utils/PermissionManagementUtils.java new file mode 100644 index 000000000..a349c7eb3 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/PermissionManagementUtils.java @@ -0,0 +1,395 @@ +package com.kaltura.client.test.utils; + +import com.google.gson.*; +import com.kaltura.client.Logger; +import com.kaltura.client.test.utils.dbUtils.PermissionsManagementDBUtils; +import lombok.Data; +import lombok.experimental.Accessors; +import java.io.*; +import java.util.ArrayList; +import java.util.List; + +import static com.kaltura.client.test.Properties.PERMISSION_CONSOLE_UTIL_FILE; +import static com.kaltura.client.test.Properties.PERMISSION_LOG_FILE; +import static com.kaltura.client.test.Properties.getProperty; + +public class PermissionManagementUtils extends BaseUtils { + + // that file generated automatically + public static String path2Log = getProperty(PERMISSION_LOG_FILE); + public static String path2Util = getProperty(PERMISSION_CONSOLE_UTIL_FILE); + public static String mainFile = "PermissionsDeployment.exe"; + public static String fullPath2Util = path2Util + mainFile; + + // these files are generated + public static String dataFilePath = path2Util + "333\\" + "exp1.txt"; + public static String path2JsonFolder = path2Util + "333\\JSON\\"; + public static String generatedDataFilePath = path2Util + "333\\" + "import.txt"; + public static String path2JsonRoles = path2JsonFolder + "roles.json"; + public static String path2JsonPermissions = path2JsonFolder + "permissions.json"; + public static String path2JsonMethods = path2JsonFolder + "permission_items\\controllers\\"; + + // json related strings + public static final String SERVICE_PERMISSION_ITEMS_NODE = "permission_items"; + public static final String SERVICE_TYPE_DEFAULT_VALUE = "Action"; + public static final String SERVICE_PERMISSIONS_NODE = "permissions"; + public static final String SERVICE_EXCLUDED_PERMISSIONS_NODE = "excluded_permissions"; + public static final String SERVICE_NAME_NODE = "name"; + public static final String SERVICE_SERVICE_NODE = "service"; + public static final String SERVICE_ACTION_NODE = "action"; + public static final String SERVICE_TYPE_NODE = "type"; + + public static final String PERMISSIONS_PERMISSIONS_NODE = "permissions"; + public static final String PERMISSIONS_NAME_NODE = "name"; + public static final String PERMISSIONS_USERS_GROUP_NODE = "users_group"; + + public static final String ROLES_ROLES_NODE = "roles"; + public static final String ROLES_PERMISSIONS_NODE = "permissions"; + public static final String ROLES_EXCLUDED_PERMISSIONS_NODE = "excluded_permissions"; + public static final String ROLES_NAME_NODE = "name"; + + @Accessors(fluent = true) + @Data + public static class PermissionItem { + private List permissions; + private List excludedPermissions; + private String name; + private String service; + private String action; + private String type; + } + + @Accessors(fluent = true) + @Data + public static class Permission { + private String name; + private String usersGroup; + } + + @Accessors(fluent = true) + @Data + public static class Role { + private List permissions; + private List excludedPermissions; + private String name; + } + + private static void fillRolesFile(String roleName) { + try { + // get from file array of permissions + JsonParser parser = new JsonParser(); + JsonElement jsonElement = parser.parse(new FileReader(path2JsonRoles)); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + JsonArray array = jsonObj.getAsJsonArray(ROLES_ROLES_NODE); + + // add into array of roles new role + List excludedPermissions = new ArrayList(); + List permissions = new ArrayList(); + permissions.add(roleName); + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + jsonObj = new JsonObject(); + jsonObj.add(ROLES_PERMISSIONS_NODE, gson.toJsonTree(permissions).getAsJsonArray()); + jsonObj.add(ROLES_EXCLUDED_PERMISSIONS_NODE, gson.toJsonTree(excludedPermissions).getAsJsonArray()); + jsonObj.addProperty(ROLES_NAME_NODE, roleName); + array.add(jsonObj); + + // overwrite role file + jsonObj = new JsonObject(); + jsonObj.add(ROLES_ROLES_NODE, array); + try (Writer writer = new FileWriter(path2JsonRoles, false)) { + gson.toJson(jsonObj, writer); + } catch (IOException e) { + e.printStackTrace(); + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + private static void fillServiceFile(String roleName, String permissionItemName, String serviceName, String actionName) { + try { + // get from file array of permissions related to service + JsonParser parser = new JsonParser(); + String path2serviceFile = path2JsonMethods + serviceName + ".json"; + JsonElement jsonElement = parser.parse(new FileReader(path2serviceFile)); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + JsonArray array = jsonObj.getAsJsonArray(SERVICE_PERMISSION_ITEMS_NODE); + + // create PermissionItem object with new data + List permissions = new ArrayList(); + permissions.add(roleName); + PermissionItem permissionItem = new PermissionItem() + .permissions(permissions) + .excludedPermissions(new ArrayList<>()) + .name(permissionItemName) + .service(serviceName) + .action(actionName) + .type(SERVICE_TYPE_DEFAULT_VALUE); + + // add into array of permissions the PermissionItem object + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + jsonObj = getPermissionItemAsJsonObject(permissionItem, gson); + array.add(jsonObj); + + // overwrite service file + jsonObj = new JsonObject(); + jsonObj.add(SERVICE_PERMISSION_ITEMS_NODE, array); + jsonObj.addProperty(SERVICE_TYPE_NODE, SERVICE_TYPE_DEFAULT_VALUE); + + try (Writer writer = new FileWriter(path2serviceFile, false)) { + gson.toJson(jsonObj, writer); + } catch (IOException e) { + e.printStackTrace(); + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + private static JsonObject getPermissionItemAsJsonObject(PermissionItem permissionItem, Gson gson) { + JsonObject result = new JsonObject(); + + result.add(SERVICE_PERMISSIONS_NODE, gson.toJsonTree(permissionItem.permissions()).getAsJsonArray()); + result.add(SERVICE_EXCLUDED_PERMISSIONS_NODE, gson.toJsonTree(permissionItem.excludedPermissions()).getAsJsonArray()); + result.addProperty(SERVICE_NAME_NODE, permissionItem.name()); + result.addProperty(SERVICE_SERVICE_NODE, permissionItem.service()); + result.addProperty(SERVICE_ACTION_NODE, permissionItem.action()); + result.addProperty(SERVICE_TYPE_NODE, SERVICE_TYPE_DEFAULT_VALUE); + + return result; + } + + private static void fillPermissionsFile(String roleName, String usersGroup) { + try { + // get from file array of permissions + JsonParser parser = new JsonParser(); + JsonElement jsonElement = parser.parse(new FileReader(path2JsonPermissions)); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + JsonArray array = jsonObj.getAsJsonArray(PERMISSIONS_PERMISSIONS_NODE); + + // add into array of permissions new permission data + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + jsonObj = new JsonObject(); + jsonObj.addProperty(PERMISSIONS_NAME_NODE, roleName); + jsonObj.addProperty(PERMISSIONS_USERS_GROUP_NODE, usersGroup); + array.add(jsonObj); + + // overwrite permissions file + jsonObj = new JsonObject(); + jsonObj.add(PERMISSIONS_PERMISSIONS_NODE, array); + try (Writer writer = new FileWriter(path2JsonPermissions, false)) { + gson.toJson(jsonObj, writer); + } catch (IOException e) { + e.printStackTrace(); + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + public static void fillFilesWithImportData(String roleName, String permissionItemName, String usersGroup, String serviceName, String actionName) { + fillRolesFile(roleName); + fillPermissionsFile(roleName, usersGroup); + fillServiceFile(roleName, permissionItemName, serviceName, actionName); + } + + public static void printPermissionPermissionItem(PrintWriter writer, long id, long permissionId, long permissionItemId, + int isExcluded, String permissionItemName, String permissionName) { + writer.println(""); + writer.println("" + id + ""); + writer.println("" + permissionId + ""); + writer.println("" + permissionItemId + ""); + writer.println("" + isExcluded + ""); + writer.println("" + permissionItemName + ""); + writer.println("" + permissionName + ""); + writer.println(""); + } + + public static void printPermissionItem(PrintWriter writer, long id, String name, int type, String service, String action, + String object, String parameter) { + writer.println(""); + writer.println("" + id + ""); + writer.println("" + name + ""); + writer.println("" + type + ""); + writer.println("" + service + ""); + writer.println("" + action + ""); + writer.println("" + object + ""); + writer.println("" + parameter + ""); + writer.println(""); + } + + public static void printPermission(PrintWriter writer, long id, String name, int type, String usersGroup) { + writer.println(""); + writer.println("" + id + ""); + writer.println("" + name + ""); + writer.println("" + type + ""); + writer.println("" + usersGroup + ""); + writer.println(""); + } + + public static void printRolePermission(PrintWriter writer, long permissionRoleId, long roleId, long permissionId, + int isExcluded, String roleName, String permissionName) { + writer.println(""); + writer.println("" + permissionRoleId + ""); + writer.println("" + roleId + ""); + writer.println("" + permissionId + ""); + writer.println("" + isExcluded + ""); + writer.println("" + roleName + ""); + writer.println("" + permissionName + ""); + writer.println(""); + } + + public static void printRole(PrintWriter writer, Long roleId, String roleName) { + writer.println(""); + writer.println("" + roleId + ""); + writer.println("" + roleName + ""); + writer.println(""); + } + + public static String executeCommandsInConsole(List commands) { + Logger.getLogger(PermissionManagementUtils.class).debug("started executeCommandsInConsole"); + StringBuilder output = new StringBuilder(); + StringBuilder input = new StringBuilder(); + for(String command: commands){ + input.append(command + " "); + } + Logger.getLogger(PermissionManagementUtils.class).debug("INPUT: " + input.toString()); + + ProcessBuilder pb = new ProcessBuilder(commands); + pb.redirectErrorStream(true); + BufferedReader inStreamReader; + try { + Process process = pb.start(); + inStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream())); + String line; + while((line = inStreamReader.readLine()) != null){ + output.append(line); + } + } catch (IOException e) { + e.printStackTrace(); + output.append(e.getMessage()); + } + + Logger.getLogger(PermissionManagementUtils.class).debug("OUTPUT: " + output.toString()); + return output.toString(); + } + + public static void insertDataInAllTables(String path2ResultFile, String role, String usersGroup, String permissionItemName, + String service, String action, String permissionItemObject, String parameter, boolean isJson) { + long roleId = PermissionsManagementDBUtils.insertRole(role); + long permissionId = PermissionsManagementDBUtils.insertPermission(role, 2, usersGroup); + long permissionRoleId = PermissionsManagementDBUtils.insertPermissionRole(roleId, permissionId, 0); + + long permissionItemId = PermissionsManagementDBUtils.insertPermissionItem(permissionItemName, 1, service, action, permissionItemObject, parameter); + long permissionPermissionItemId = PermissionsManagementDBUtils.insertPermissionPermissionItem(permissionId, permissionItemId, 0); + + generateFileWithInsertedIntoDBData(path2ResultFile, role, usersGroup, permissionItemName, service, action, + permissionItemObject, parameter, roleId, permissionId, permissionRoleId, permissionItemId, permissionPermissionItemId, isJson); + } + + public static void generateFileWithInsertedIntoDBData(String path2ResultFile, String role, String usersGroup, String permissionItemName, + String service, String action, String permissionItemObject, String parameter, long roleId, long permissionId, + long permissionRoleId, long permissionItemId, long permissionPermissionItemId, boolean isJson) { + try { + File file = new File(path2ResultFile); + PrintWriter writer = new PrintWriter(file); + if (isJson) { + printRolesFormat(writer, role); + // to separate + writer.println(";"); + printPermissionsFormat(writer, role, usersGroup); + // to separate + writer.println(";"); + printServiceFormat(writer, role, permissionItemName, service, action); + } else { + // XML + printOpenTag(writer); + printRole(writer, roleId, role); + printRolePermission(writer, permissionRoleId, roleId, permissionId, 0, role, role); + printPermission(writer, permissionId, role, 2, usersGroup); + printPermissionItem(writer, permissionItemId, permissionItemName, 1, service, action, permissionItemObject, parameter); + printPermissionPermissionItem(writer, permissionPermissionItemId, permissionId, permissionItemId, 0, permissionItemName, role); + printCloseTag(writer); + } + writer.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + private static void printServiceFormat(PrintWriter writer, String role, String permissionItemName, String service, String action) { + writer.println("{"); + writer.println("\"permissions\": ["); + writer.println("\"" + role + "\""); + writer.println("],"); + writer.println("\"excluded_permissions\": [],"); + writer.println("\"name\": \"" + permissionItemName + "\","); + writer.println("\"service\": \"" + service + "\","); + writer.println("\"action\": \"" + action + "\","); + writer.println("\"type\": \"Action\""); + writer.println("}"); + } + + private static void printPermissionsFormat(PrintWriter writer, String role, String usersGroup) { + writer.println("{"); + writer.println("\"name\": \"" + role + "\","); + writer.println("\"users_group\": \"" + usersGroup + "\""); + writer.println("}"); + } + + private static void printRolesFormat(PrintWriter writer, String role) { + writer.println("{"); + writer.println("\"permissions\": ["); + writer.println("\"" + role + "\""); + writer.println("],"); + writer.println("\"excluded_permissions\": [],"); + writer.println("\"name\": \"" + role + "\""); + writer.println("}"); + } + + public static void generateFileWithInvalidTagForRole(String path2ResultFile, String roleName, int roleId) { + try { + File file = new File(path2ResultFile); + PrintWriter writer = new PrintWriter(file); + printOpenTag(writer); + writer.println(""); // this 1 here to make tag invalid + writer.println("" + roleId + ""); + writer.println("" + roleName + ""); + writer.println(""); // this 1 here to make tag invalid + printCloseTag(writer); + writer.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + private static void printOpenTag(PrintWriter writer) { + writer.println(""); + writer.println(""); + } + + private static void printCloseTag(PrintWriter writer) { + writer.println(""); + } + + public static void generateFileForRole(String path2ResultFile, String roleName, long roleId) { + try { + File file = new File(path2ResultFile); + PrintWriter writer = new PrintWriter(file); + printOpenTag(writer); + printRole(writer, roleId, roleName); + printCloseTag(writer); + writer.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + public static List getConsoleCommand(String path2Util, String parameters) { + List commands = new ArrayList<>(); + commands.add(path2Util); + commands.add(parameters); + return commands; + } +} + diff --git a/src/test/java/com/kaltura/client/test/utils/PurchaseUtils.java b/src/test/java/com/kaltura/client/test/utils/PurchaseUtils.java index a54addd5f..91fd41f39 100644 --- a/src/test/java/com/kaltura/client/test/utils/PurchaseUtils.java +++ b/src/test/java/com/kaltura/client/test/utils/PurchaseUtils.java @@ -3,39 +3,38 @@ import com.kaltura.client.enums.AssetReferenceType; import com.kaltura.client.enums.ProductPriceOrderBy; import com.kaltura.client.enums.TransactionType; -import com.kaltura.client.services.AssetService; -import com.kaltura.client.services.AssetService.GetAssetBuilder; import com.kaltura.client.services.ProductPriceService; import com.kaltura.client.services.ProductPriceService.ListProductPriceBuilder; import com.kaltura.client.services.TransactionService; import com.kaltura.client.services.TransactionService.PurchaseTransactionBuilder; import com.kaltura.client.types.*; import com.kaltura.client.utils.response.base.Response; -import javax.annotation.Nullable; + import java.util.HashMap; import java.util.Map; import java.util.Optional; + +import static com.kaltura.client.services.AssetService.get; import static com.kaltura.client.test.tests.BaseTest.executor; public class PurchaseUtils { public static Map purchasePpvDetailsMap; public static Map purchaseSubscriptionDetailsMap; + public static Map purchaseCollectionDetailsMap; private static Response> productPriceResponse; private static Response assetResponse; - // TODO: 14/MAR/2018 add return - public static void purchasePpv(String ks, Optional mediaId, Optional fileId, @Nullable String purchaseCurrency) { + public static Response purchasePpv(String ks, Optional mediaId, Optional fileId, Optional currency) { purchasePpvDetailsMap = new HashMap<>(); - int paymentGatewayId = 0; - int internalFileId =-1; + int internalFileId; if (fileId.isPresent()) { internalFileId = fileId.get(); } else { - GetAssetBuilder mediaAsset = AssetService.get(String.valueOf(mediaId.get()), AssetReferenceType.MEDIA); - assetResponse = executor.executeSync(mediaAsset.setKs(ks)); + assetResponse = executor.executeSync(get(String.valueOf(mediaId.get()), AssetReferenceType.MEDIA) + .setKs(ks)); internalFileId = assetResponse.results.getMediaFiles().get(0).getId(); } @@ -44,8 +43,10 @@ public static void purchasePpv(String ks, Optional mediaId, Optional mediaId, Optional transactionResponse = executor.executeSync(transactionBuilder); // TODO: complete the purchase ppv test purchasePpvDetailsMap.put("price", String.valueOf(price)); - purchasePpvDetailsMap.put("currency", currency); + purchasePpvDetailsMap.put("currency", currencyValue); purchasePpvDetailsMap.put("ppvModuleId", ppvModuleId); purchasePpvDetailsMap.put("fileId", String.valueOf(internalFileId)); + + return transactionResponse; } - // TODO: 3/7/2018 add return - // private as not completed - private static void purchaseSubscription(int subscriptionId) { + public static Response purchaseSubscription(String ks, int subscriptionId, Optional currency) { purchaseSubscriptionDetailsMap = new HashMap<>(); - int paymentGatewayId = 0; ProductPriceFilter filter = new ProductPriceFilter(); filter.setSubscriptionIdIn(String.valueOf(subscriptionId)); filter.setIsLowest(false); - ListProductPriceBuilder productPriceListBeforePurchase = ProductPriceService.list(filter); - productPriceResponse = executor.executeSync(productPriceListBeforePurchase); - String currency = productPriceResponse.results.getObjects().get(0).getPrice().getCurrency(); + ListProductPriceBuilder listProductPriceBuilder = currency.isPresent() + ? ProductPriceService.list(filter).setKs(ks).setCurrency(currency.get()) + : ProductPriceService.list(filter).setKs(ks); + productPriceResponse = executor.executeSync(listProductPriceBuilder); + + String currencyValue = currency.orElse(productPriceResponse.results.getObjects().get(0).getPrice().getCurrency()); double price = productPriceResponse.results.getObjects().get(0).getPrice().getAmount(); Purchase purchase = new Purchase(); purchase.setProductId(subscriptionId); purchase.setContentId(0); - purchase.setCurrency(currency); + purchase.setCurrency(currencyValue); purchase.setPrice(price); purchase.setProductType(Optional.of(TransactionType.SUBSCRIPTION).get()); - purchase.setPaymentGatewayId(Optional.of(paymentGatewayId).get()); - PurchaseTransactionBuilder transactionBuilder = TransactionService.purchase(purchase); - executor.executeSync(transactionBuilder); + PurchaseTransactionBuilder purchaseTransactionBuilder = TransactionService.purchase(purchase).setKs(ks); + Response transactionResponse = executor.executeSync(purchaseTransactionBuilder); // TODO: complete the purchase subscription test purchaseSubscriptionDetailsMap.put("price", String.valueOf(price)); - purchaseSubscriptionDetailsMap.put("currency", currency); + purchaseSubscriptionDetailsMap.put("currency", currencyValue); + + return transactionResponse; + } + + public static Response purchaseCollection (String ks, int collectionId){ + purchaseCollectionDetailsMap = new HashMap<>(); + + ProductPriceFilter productPriceFilter = new ProductPriceFilter(); + productPriceFilter.setCollectionIdIn(String.valueOf(collectionId)); + + ListProductPriceBuilder listProductPriceBuilder = ProductPriceService.list(productPriceFilter).setKs(ks); + productPriceResponse = executor.executeSync(listProductPriceBuilder); + + String collectionPriceCurrency = productPriceResponse.results.getObjects().get(0).getPrice().getCurrency(); + double collectionPriceAmount = productPriceResponse.results.getObjects().get(0).getPrice().getAmount(); + + Purchase purchaseRequest = new Purchase(); + purchaseRequest.setCurrency(collectionPriceCurrency); + purchaseRequest.setPrice(collectionPriceAmount); + purchaseRequest.setContentId(0); + purchaseRequest.setProductId(collectionId); + purchaseRequest.setProductType(TransactionType.COLLECTION); + + PurchaseTransactionBuilder purchaseTransactionBuilder = TransactionService.purchase(purchaseRequest).setKs(ks); + Response transactionResponse = executor.executeSync(purchaseTransactionBuilder); + + purchaseCollectionDetailsMap.put("price", String.valueOf(collectionPriceAmount)); + purchaseCollectionDetailsMap.put("currency", collectionPriceCurrency); + + return transactionResponse; } } diff --git a/src/test/java/com/kaltura/client/test/utils/SocialUtils.java b/src/test/java/com/kaltura/client/test/utils/SocialUtils.java new file mode 100644 index 000000000..a035a3667 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/SocialUtils.java @@ -0,0 +1,37 @@ +package com.kaltura.client.test.utils; + +import com.kaltura.client.enums.AssetType; +import com.kaltura.client.enums.SocialActionType; +import com.kaltura.client.types.SocialAction; +import com.kaltura.client.types.SocialActionRate; + +import javax.annotation.Nullable; + +public class SocialUtils { + public static SocialAction getSocialAction(@Nullable SocialActionType socialActionType, @Nullable Long time, Long assetId, @Nullable AssetType assetType, + @Nullable String url) { + SocialAction socialAction = new SocialAction(); + socialAction.setActionType(socialActionType); + socialAction.setTime(time); + socialAction.setAssetId(assetId); + socialAction.setAssetType(assetType); + socialAction.setUrl(url); + + return socialAction; + } + + public static SocialActionRate getSocialActionRate(@Nullable SocialActionType socialActionType, @Nullable Long time, Long assetId, @Nullable AssetType assetType, + @Nullable String url, int rate) { + SocialActionRate socialActionRate = new SocialActionRate(); + socialActionRate.setActionType(socialActionType); + socialActionRate.setTime(time); + socialActionRate.setAssetId(assetId); + socialActionRate.setAssetType(assetType); + socialActionRate.setUrl(url); + socialActionRate.setRate(rate); + + return socialActionRate; + } + + +} diff --git a/src/test/java/com/kaltura/client/test/utils/StatisticsUtils.java b/src/test/java/com/kaltura/client/test/utils/StatisticsUtils.java new file mode 100644 index 000000000..deb105204 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/StatisticsUtils.java @@ -0,0 +1,62 @@ +package com.kaltura.client.test.utils; + +import com.google.common.reflect.ClassPath; +import com.kaltura.client.Logger; +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.text.DecimalFormat; +import java.util.Set; + +public class StatisticsUtils extends BaseUtils { + + /** + * method allows to get statistic about total count of tests in specified @param packageName and compare + * that value with count of failed and count of Critical tests from + * + * @param packageName + */ + public static void displayStatisticsDisabledAndCriticalTests(String packageName) { + Logger.getLogger(StatisticsUtils.class).debug("Package: [" + packageName + "]"); + Set allClasses = null; + try { + allClasses = ClassPath.from(ClassLoader.getSystemClassLoader()).getTopLevelClassesRecursive(packageName); + } catch (IOException e) { + e.printStackTrace(); + } + int totalTests = 0; + int disabledTests = 0; + int criticalSeverityTests = 0; + for (ClassPath.ClassInfo classInfo : allClasses) { + //Logger.getLogger(StatisticsUtils.class).debug("Class: [" + classInfo.getSimpleName() + "]"); + Class clazz = classInfo.load(); + Method[] methods = clazz.getDeclaredMethods(); + //Logger.getLogger(StatisticsUtils.class).debug("Methods:"); + for (int i = 0; i < methods.length; i++) { + //Logger.getLogger(StatisticsUtils.class).debug(methods[i].getName()); + //Logger.getLogger(StatisticsUtils.class).debug("Annotations:"); + for (Annotation annotation: methods[i].getDeclaredAnnotations()) { + if (annotation.toString().contains("org.testng.annotations.Test")) { + totalTests++; + if (annotation.toString().contains("enabled=false")) { + // Logger.getLogger(StatisticsUtils.class).debug(methods[i].getName()); + // Logger.getLogger(StatisticsUtils.class).debug(annotation.toString()); + disabledTests++; + } + } + if (annotation.toString().contains("io.qameta.allure.Severity(value=CRITICAL)")) { + criticalSeverityTests++; + } + } + } + //Logger.getLogger(StatisticsUtils.class).debug("________________________________________________"); + } + Logger.getLogger(StatisticsUtils.class).debug("total amount of tests: " + totalTests); + DecimalFormat df = new DecimalFormat("#.00"); + Logger.getLogger(StatisticsUtils.class).debug("disabled tests: " + disabledTests + " or " + + df.format(disabledTests*1.0/totalTests*100) + "%"); + Logger.getLogger(StatisticsUtils.class).debug("tests with critical severity: " + criticalSeverityTests + " or " + + df.format(criticalSeverityTests*1.0/totalTests*100) + "%"); + } +} + diff --git a/src/test/java/com/kaltura/client/test/utils/SubscriptionUtils.java b/src/test/java/com/kaltura/client/test/utils/SubscriptionUtils.java new file mode 100644 index 000000000..9bfbc9b2e --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/SubscriptionUtils.java @@ -0,0 +1,65 @@ +package com.kaltura.client.test.utils; + +import com.google.common.base.Verify; +import com.kaltura.client.enums.BundleType; +import com.kaltura.client.services.AssetService; +import com.kaltura.client.services.SubscriptionService; +import com.kaltura.client.services.SubscriptionService.ListSubscriptionBuilder; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static com.kaltura.client.test.tests.BaseTest.executor; +import static com.kaltura.client.test.tests.BaseTest.getOperatorKs; + +public class SubscriptionUtils extends BaseUtils { + + + public static List getAssetsListBySubscription(int subscriptionId, Optional numOfPages, boolean isListCanBeEmpty) { + Response> assetListResponse; + + // set filter + BundleFilter filter = new BundleFilter(); + filter.setBundleTypeEqual(BundleType.SUBSCRIPTION); + filter.setIdEqual(subscriptionId); + + if (numOfPages.isPresent()) { + FilterPager pager = new FilterPager(); + pager.setPageSize(numOfPages.get()); + pager.setPageIndex(1); + + assetListResponse = executor.executeSync(AssetService.list(filter, pager).setKs(getOperatorKs())); + } else { + assetListResponse = executor.executeSync(AssetService.list(filter).setKs(getOperatorKs())); + } + + List assets = assetListResponse.results.getObjects(); + // Asset list can be empty in case creation of new MPP + if (!isListCanBeEmpty) { + Verify.verify(assetListResponse.results.getTotalCount() > 0, "Asset list can't be empty"); + // remove assets without media files from list + List assetsToRemove = new ArrayList<>(); + + for (Asset asset : assets) { + if (asset.getMediaFiles().size() < 1) { + assetsToRemove.add(asset); + } + } + + assets.removeAll(assetsToRemove); + } + return assets; + } + + public static List getChannelsListBySubscription(String subscriptionId) { + SubscriptionFilter filter = new SubscriptionFilter(); + filter.setSubscriptionIdIn(subscriptionId); + ListSubscriptionBuilder listSubscriptionBuilder = SubscriptionService.list(filter); + Response> listResponse = executor.executeSync(listSubscriptionBuilder.setKs(getOperatorKs())); + Verify.verify(listResponse.results.getObjects().get(0).getChannels().size() > 0); + return listResponse.results.getObjects().get(0).getChannels(); + } +} diff --git a/src/test/java/com/kaltura/client/test/utils/UserRoleUtils.java b/src/test/java/com/kaltura/client/test/utils/UserRoleUtils.java new file mode 100644 index 000000000..410aa74b9 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/UserRoleUtils.java @@ -0,0 +1,20 @@ +package com.kaltura.client.test.utils; + +import com.kaltura.client.types.UserRole; + +import java.util.Random; + +public class UserRoleUtils extends BaseUtils { + + + public static UserRole generateUserRole() { + Random r = new Random(); + int low = 9000; + int max = 10000; + long roleId = r.nextInt(max - low) + low; + + UserRole userRole = new UserRole(); + userRole.setName(String.valueOf(roleId)); + return userRole; + } +} diff --git a/src/test/java/com/kaltura/client/test/utils/XmlUtils.java b/src/test/java/com/kaltura/client/test/utils/XmlUtils.java new file mode 100644 index 000000000..6b211e266 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/XmlUtils.java @@ -0,0 +1,33 @@ +package com.kaltura.client.test.utils; + +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import java.util.AbstractList; +import java.util.Collections; +import java.util.List; +import java.util.RandomAccess; + +public class XmlUtils extends BaseUtils { + + public static List asList(NodeList n) { + return n.getLength() == 0 ? Collections.emptyList() : new NodeListWrapper(n); + } + + static final class NodeListWrapper extends AbstractList implements RandomAccess { + private final NodeList list; + + NodeListWrapper(NodeList nodeList) { + list = nodeList; + } + + public Node get(int index) { + return list.item(index); + } + + public int size() { + return list.getLength(); + } + } + +} diff --git a/src/test/java/com/kaltura/client/test/utils/annotations/Shared.java b/src/test/java/com/kaltura/client/test/utils/annotations/Shared.java new file mode 100644 index 000000000..33f6cccd0 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/annotations/Shared.java @@ -0,0 +1,8 @@ +package com.kaltura.client.test.utils.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +public @interface Shared { +} diff --git a/src/test/java/com/kaltura/client/test/utils/dbUtils/DBConstants.java b/src/test/java/com/kaltura/client/test/utils/dbUtils/DBConstants.java new file mode 100644 index 000000000..8eaf8aa60 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/dbUtils/DBConstants.java @@ -0,0 +1,275 @@ +package com.kaltura.client.test.utils.dbUtils; + +import com.kaltura.client.test.tests.enums.ChannelType; + +public class DBConstants { + + // fields: + static final String ACTIVATION_TOKEN = "activation_token"; + static final String CODE = "code"; + static final String CHANNEL_TYPE = "channel_type"; + static final String CP_TOKEN = "cp_token"; + static final String FILTER_EXPRESSION = "ksql_filter"; + static final String FULL_LIFE_CYCLE_MINUTES = "full_life_cycle_min"; + static final String ID = "id"; + static final String INT_DISCOUNT_ID = "internal_discount_id"; + static final String IS_ACTIVATION_NEEDED = "is_activation_needed"; + static final String IS_BASIC = "is_basic"; + static final String IS_RENEWED = "is_renew"; + static final String MAX_VIEWS_COUNT = "max_views_number"; + static final String NAME = "name"; + static final String NUMBER_OF_REC_PERIODS = "num_of_rec_periods"; + static final String PASSWORD = "password"; + static final String PRICE_PLAN_ID = "usage_module_code"; + static final String PRICING_ID = "pricing_id"; + static final String ROW_COUNT = "row_count"; + static final String SERV_ID = "serv_id"; + static final String SUBSCRIPTION_ONLY = "subscription_only"; + static final String SUB_ID = "sub_id"; + static final String SYSTEM_NAME = "system_name"; + static final String TAG_NAME = "tag_name"; + static final String TAG_VALUE = "tag_value"; + static final String USERNAME = "username"; + static final String VIEW_LIFE_CYCLE_MINUTES = "view_life_cycle_min"; + + //queries + static final String ACTIVATION_TOKEN_SELECT = "SELECT [ACTIVATION_TOKEN] FROM [Users].[dbo].[users] WHERE [USERNAME] = ?"; + + static final String AND_ACTIVE_STATUS = " and u.activate_status=1"; + + static final String BASIC_META_SELECT = "SELECT * FROM [TVinci].[dbo].[topics]\n" + + "WHERE [STATUS]=1 AND IS_BASIC=1 AND GROUP_ID=?\n"; + + static final String RESET_PASSWORD_TOKEN_SELECT = "SELECT [CP_TOKEN] FROM [Users].[dbo].[users] WHERE [USERNAME] = ?"; + + static final String CHANNEL_EXPRESSION_SELECT = "select t.tag_type_id as tag_name, t.value as tag_value\n" + + "from [TVinci].[dbo].[tags] t, [TVinci].[dbo].[channel_tags] ct\n" + + "where ct.status=1 and t.status=1 and ct.channel_id=? and ct.tag_id=t.id"; + + static final String CHANNEL_SELECT = "select *\n" + + "from [TVinci].[dbo].[channels]\n" + + "where id=?"; + + static final String CHECK_IS_ACTIVATION_USERS_NEEDED = "select [IS_ACTIVATION_NEEDED]\n" + + "from [Users].[dbo].[groups_parameters]\n" + + "where group_id= ?"; + + static final String CURRENCY_CODE_SELECT = "select ID from [Pricing].[dbo].[lu_currency] WHERE CODE3=?"; + + static final String DISCOUNT_BY_PERCENT = "select TOP (1) *\n" + + "from [Pricing].[dbo].[discount_codes] dc \n" + + "where dc.discount_percent=?\n" + // percent amount + "and dc.group_id=?\n" + // group + "and dc.[status]=1 and dc.is_active=1"; + + static final String DISCOUNT_BY_PERCENT_AND_CURRENCY = "select TOP (1) *\n" + + "from [Pricing].[dbo].[discount_codes] dc with(nolock)\n" + + "join [Pricing].[dbo].[lu_currency] lc with(nolock) on (dc.currency_cd=lc.id)\n" + + "where lc.code3=?\n" + // CURRENCY + "and dc.discount_percent=?\n" + // percent amount + "and dc.group_id=?\n" + // group + "and dc.[status]=1 and dc.is_active=1"; + + static final String DISCOUNT_BY_PRICE_AND_PERCENT_SELECT = "select TOP (1) *\n" + + "from [Pricing].[dbo].[discount_codes]\n" + + "where [status]=1 and is_active=1\n" + + "and group_id=?\n" + // group + "and price=?\n" + // price amount + "and discount_percent=?"; // percent amount + + static final String DISCOUNT_BY_ID = "select CODE\n" + + "from [Pricing].[dbo].[discount_codes]\n" + + "where GROUP_ID = ? \n" + + "and id = ?"; + + static final String EPG_CHANNEL_ID_SELECT = "SELECT [ID] FROM [TVinci].[dbo].[epg_channels] WHERE [GROUP_ID] = ? AND [NAME] = ?"; + + static final String INGEST_ITEMS_DATA_SELECT = "select TOP (1) *\n" + + "from [Tvinci].[dbo].[groups_passwords]\n" + + "where [group_id]=? and is_active=1 and [status]=1 order by UPDATE_DATE DESC"; + + static final String META_ID_SELECT_BY_ASSET_STRUCT_ID = "SELECT * FROM [TVinci].[dbo].[template_topics]\n" + + "WHERE [STATUS]=1 AND GROUP_ID=? AND TEMPLATE_ID=?\n"; + + static final String META_SELECT = "SELECT TOP (?) * FROM [TVinci].[dbo].[topics]\n" + + "WHERE IS_BASIC=? AND GROUP_ID=? AND [STATUS]=1 AND TOPIC_TYPE_ID !=4"; // 4 IS FOR TAGS + + static final String META_NAME_SELECT_BY_ID = "SELECT * FROM [TVinci].[dbo].[topics]\n" + + "WHERE [STATUS]=1 AND GROUP_ID=? AND ID=?\n"; +// +// static final String META_NAME_SELECT_BY_IDS = "SELECT * FROM [TVinci].[dbo].[topics]\n" + +// "WHERE [STATUS]=1 AND GROUP_ID=? AND ID in (?)\n"; + + static final String META_OR_TAG_SELECT_BY_NAME = "SELECT * FROM [TVinci].[dbo].[topics]\n" + + "WHERE [STATUS]=1 AND GROUP_ID=? AND SYSTEM_NAME=?\n"; + + static final String PPV_SELECT_BY_PRICE_PLAN = "select top 1 * from [Pricing].[dbo].[ppv_modules]\n" + + "where [status]=1 and is_active=1\n" + + "and group_id=? and usage_module_code=?\n" + + "order by create_date"; + + static final String PRICE_CODE_SELECT = "select top 1 * from [Pricing].[dbo].[price_codes] pc\n" + + "join [Pricing].[dbo].[lu_currency] lc with(nolock) on (pc.currency_cd=lc.id)\n" + + "where pc.[status]=1 and pc.is_active=1\n" + + "and pc.group_id=? and pc.price=? and lc.CODE3=?"; + + static final String PRICE_PLAN_SELECT = "select top 1 * from [Pricing].[dbo].[usage_modules]\n" + + "where [status]=1 and is_active=1\n" + + "and group_id=? and internal_discount_id=? and pricing_id=?"; + + static final String PRICE_PLAN_WITH_WAVER_SELECT = "SELECT TOP 1 * FROM [Pricing].[dbo].[usage_modules]\n" + + "WHERE group_id=? AND WAIVER=1 AND WAIVER_PERIOD>0 AND IS_ACTIVE=1 AND [STATUS]=1"; + + static final String PRICE_PLAN_WITHOUT_WAVER_SELECT = "SELECT TOP 1 * FROM [Pricing].[dbo].[usage_modules]\n" + + "WHERE group_id=? AND WAIVER=0 AND IS_ACTIVE=1 AND [STATUS]=1 AND EXT_DISCOUNT_ID IS NOT NULL AND INTERNAL_DISCOUNT_ID IS NOT NULL"; + + static final String PPV_SELECT_BY_PRICE_PLAN_WITHOUT_WAIVER = "select top 1 * from [Pricing].[dbo].[ppv_modules] as ppvm\n" + + "join [Pricing].[dbo].[usage_modules] um on um.id=ppvm.usage_module_code\n" + + "where um.WAIVER=0 and um.group_id=? and ppvm.[status]=1 and ppvm.is_active=1 and \n" + + "um.[status]=1 and um.is_active=1"; + + static final String PRICE_PLAN_5_MIN_RENEW_SELECT = "select top 1 * from [Pricing].[dbo].[usage_modules]\n" + + "where [status]=1 and is_active=1\n" + + "and view_life_cycle_min = 5\n" + + "and full_life_cycle_min = 5\n" + + "and is_renew=1\n" + + "and ((num_of_rec_periods > 2) or (num_of_rec_periods = 0))\n" + // TODO: do we really want it "num_of_rec_periods > 2"? + "and group_id=?"; + + static final String SUBSCRIPTION_SELECT = "select top 1 * from [Pricing].[dbo].[subscriptions] s with(nolock)\n" + + "join [Pricing].[dbo].[subscriptions_channels] sc with(nolock) on (sc.subscription_id=s.id)\n" + + "join [TVinci].[dbo].[channels] c with(nolock) on (c.id=sc.channel_id)\n" + + "where s.[status]=1 and s.is_active=1\n" + + "and s.group_id=? and s.usage_module_code=? and s.discount_module_code=? and c.channel_type!=" + + ChannelType.MANUAL_CHANNEL_TYPE.getValue() + " and sc.is_active=1 and sc.[status]=1\n" + + "order by s.create_date"; + + static final String SUBSCRIPTION_5_MIN_RENEW_SELECT = "select top 1 * from [Pricing].[dbo].[subscriptions] s with(nolock)\n" + + "join [Pricing].[dbo].[usage_modules] um with(nolock) on (s.usage_module_code=um.id)\n" + + "join [Pricing].[dbo].[subscriptions_channels] sc with(nolock) on (sc.subscription_id=s.id)\n" + + "join [TVinci].[dbo].[channels] c with(nolock) on (c.id=sc.channel_id)\n" + + "where um.[status]=1 and um.is_active=1 and um.view_life_cycle_min=5 and um.full_life_cycle_min=5 and " + + // TODO: not sure about um.num_of_rec_periods > 2 + "um.is_renew=1 and ((um.num_of_rec_periods > 2) or (um.num_of_rec_periods = 0))\n" + + "and s.is_recurring=1 and c.channel_type!=" + ChannelType.MANUAL_CHANNEL_TYPE.getValue() + " " + + "and s.group_id=? and s.is_active=1 and s.[status]=1 and s.[type]=0 and sc.is_active=1 and sc.[status]=1\n" + + "order by s.create_date desc"; + + static final String SUBSCRIPTION_WITH_PREMIUM_SERVICE_SELECT = "select TOP (1) " + + "SUBSCRIPTION_ID as " + SUB_ID + ", " + + "SERVICE_ID as " + SERV_ID + " " + + "FROM [Pricing].[dbo].[subscriptions] s " + + "INNER JOIN [Pricing].[dbo].[subscriptions_services] ss " + + "ON s.ID = SS.SUBSCRIPTION_ID " + + "where s.group_id = ? " + + "and s.IS_ACTIVE = 1 " + + "and s.status = 1 " + + "and ss.STATUS = 1 " + + "and ss.SERVICE_ID = ?"; + + static final String COLLECTION_SELECT = "select top 1 * from [Pricing].[dbo].[collections]\n" + + "where [status]=1 and is_active=1\n" + + "and group_id=? and discount_id=? and price_id=? and usage_module_id=?\n" + + "order by create_date"; + + static final String USER_BY_ROLE_SELECT = "select top(1) u.username, u.[password]\n" + + "from [Users].[dbo].[users] u with(nolock)\n" + + "join [Users].[dbo].[users_roles] ur with(nolock) on (u.id=ur.[user_id])\n" + + "join [TVinci].[dbo].[roles] r with(nolock) on (r.id=ur.role_id)\n" + + // TODO: find instead of and u.username <> 'lfaingold' how to exclude suspended users + "where r.[NAME]=? and u.is_active=1 and u.[status]=1 and u.group_id=? and u.username <> 'lfaingold'"; + + static final String COUNT_RECORDS_BY_ROLE_NAME_IN_ROLES_SELECT = "select count(*) as " + ROW_COUNT + "\n" + + "from [TVinci].[dbo].[roles]\n" + + "where [NAME]=? and is_active=1 and [status]=1 and group_id=?"; + + static final String ID_BY_ROLE_NAME_IN_ROLES_SELECT = "select " + ID + "\n" + + "from [TVinci].[dbo].[roles]\n" + + "where [NAME]=? and is_active=1 and [status]=1 and group_id=?"; + + static final String COUNT_RECORDS_BY_ROLE_NAME_IN_PERMISSIONS_SELECT = "select count(*) as " + ROW_COUNT + "\n" + + "from [TVinci].[dbo].[permissions]\n" + + "where [NAME]=? and is_active=1 and [status]=1 and group_id=?"; + + static final String ID_BY_ROLE_NAME_IN_PERMISSIONS_SELECT = "select " + ID + "\n" + + "from [TVinci].[dbo].[permissions]\n" + + "where [NAME]=? and is_active=1 and [status]=1 and group_id=?"; + + static final String COUNT_RECORDS_IN_ROLES_PERMISSIONS_SELECT = "select count(*) as " + ROW_COUNT + "\n" + + "from [TVinci].[dbo].[roles_permissions]\n" + + "where role_id=? and permission_id=? and is_active=1 and [status]=1 and group_id=?"; + + static final String COUNT_RECORDS_BY_NAME_IN_PERMISSION_ITEMS_SELECT = "select count(*) as " + ROW_COUNT + "\n" + + "from [TVinci].[dbo].[permission_items]\n" + + "where [NAME]=? and is_active=1 and [status]=1"; + + static final String ID_BY_NAME_IN_PERMISSION_ITEMS_SELECT = "select " + ID + "\n" + + "from [TVinci].[dbo].[permission_items]\n" + + "where [NAME]=? and is_active=1 and [status]=1"; + + static final String COUNT_RECORDS_IN_PERMISSIONS_PERMISSIONS_ITEMS_SELECT = "select count(*) as " + ROW_COUNT + "\n" + + "from [TVinci].[dbo].[permissions_permission_items]\n" + + "where permission_id=? and permission_item_id=? and is_active=1 and [status]=1 and group_id=?"; + + static final String LINEAR_ASSET_ID_AND_EPG_CHANNEL_NAME_SELECT = "SELECT ec.ID, ec.NAME, m.ID as 'media_id' " + + "FROM [TVinci].[dbo].[media] m " + + "inner join [TVinci].[dbo].[epg_channels] ec on m.EPG_IDENTIFIER = ec.ID " + + "where m.GROUP_ID = ? " + + "and MEDIA_TYPE_ID = 427 " + + "and m.IS_ACTIVE = 1 " + + "and m.STATUS = 1 " + + "and EPG_IDENTIFIER != ''"; + + //"SELECT [media_id],[name] FROM [TVinci].[dbo].[epg_channels] WHERE group_id=? and status=1 and DATALENGTH(media_id) > 0"; + + static final String UNACTIVE_ASSET_ID_SELECT = "SELECT top 1 [id] FROM [TVinci].[dbo].[media] where group_id = ? and status = 2"; + + static final String HOUSEHOLD_BY_ID_SELECT = "SELECT * from [Users].[dbo].[domains] where group_id = ? and ID = ?"; + + static final String USER_BY_ID_SELECT = "SELECT * from [Users].[dbo].[users] where group_id = ? and ID = ?"; + + static final String PROGRAMS_SELECT = "SELECT top (?) ID, NAME " + + "FROM [TVinci].[dbo].[epg_channels_schedule] " + + "where status = 1 " + + "and is_active = 1 " + + "and group_id = ? " + + "order by id desc"; + + static final String ASSETS_SELECT = "SELECT top (?) ID, NAME " + + "FROM [TVinci].[dbo].[media] " + + "where group_id = ? " + + "and status = 1 " + + "and is_Active = 1 " + + "order by id desc"; + + static final String ASSETS_SELECT_WITH_MEDIA_TYPE = "SELECT top (?) m.ID, m.NAME, m.MEDIA_TYPE_ID, mt.NAME " + + "FROM [TVinci].[dbo].[media] m " + + "inner join [TVinci].[dbo].[media_types] mt " + + "on m.MEDIA_TYPE_ID = mt.ID " + + "where m.group_id = ? " + + "and m.status = 1 " + + "and m.is_Active = 1 " + + "and mt.NAME = ? " + + "order by m.id desc"; + + static final String MEDIA_TYPE_ID_SELECT = "SELECT [ID] ,[NAME] FROM [TVinci].[dbo].[media_types] where (GROUP_ID = ? OR GROUP_ID = ?) and name = ?"; + + static final String MEDIA_FILE_TYPE_ID_SELECT = "SELECT [NAME] FROM [TVinci].[dbo].[groups_media_type] where GROUP_ID = ? and ID = ?"; + + static final String MEDIA_FILE_TYPE_IDS_SELECT = "SELECT top (?) [NAME] FROM [TVinci].[dbo].[groups_media_type] where GROUP_ID = ? and status = 1 and IS_ACTIVE = 1 and DESCRIPTION <> ''"; + + static final String RESULT_MESSAGE_ID_SELECT = "SELECT result_message_id FROM [MessageBox].[dbo].[message_announcements] WHERE group_id = ? AND ID = ?"; + + static final String PPV_NAME_AND_ID_SELECT = "select top (?) ID, NAME FROM [Pricing].[dbo].[ppv_modules] where group_id= ? and STATUS = 1 and IS_ACTIVE = 1"; + + // STORED PROCEDURES: + static final String SP_INSERT_PERMISSION = "{call TVinci.dbo.__482V0__Insert_Permission(?, ?, ?, ?)}"; + static final String SP_INSERT_PERMISSION_ITEM = "{call TVinci.dbo.__482V0__Insert_PermissionItem(?, ?, ?, ?, ?, ?)}"; + static final String SP_INSERT_PERMISSION_PERMISSION_ITEM = "{call TVinci.dbo.__482V0__Insert_PermissionPermissionItem(?, ?, ?, ?)}"; + static final String SP_INSERT_PERMISSION_ROLE = "{call TVinci.dbo.__482V0__Insert_PermissionRole(?, ?, ?, ?)}"; + static final String SP_INSERT_ROLE = "{call TVinci.dbo.__482V0__Insert_Role(?, ?)}"; + static final String SP_DELETE_PERMISSION = "{call TVinci.dbo.__482V0__Delete_Permission(?)}"; + static final String SP_DELETE_PERMISSION_ITEM = "{call TVinci.dbo.__482V0__Delete_PermissionItem(?)}"; + static final String SP_DELETE_PERMISSION_PERMISSION_ITEM = "{call TVinci.dbo.__482V0__Delete_PermissionPermissionItem(?)}"; + static final String SP_DELETE_ROLE_AND_ITS_PERMISSIONS = "{call TVinci.dbo.__482V0__Delete_RolePermission(?, ?)}"; +} diff --git a/src/test/java/com/kaltura/client/test/utils/dbUtils/DBUtils.java b/src/test/java/com/kaltura/client/test/utils/dbUtils/DBUtils.java new file mode 100644 index 000000000..f6e26c1d5 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/dbUtils/DBUtils.java @@ -0,0 +1,430 @@ +package com.kaltura.client.test.utils.dbUtils; + +import com.kaltura.client.Logger; +import com.kaltura.client.services.SubscriptionService; +import com.kaltura.client.test.tests.enums.AssetStructMetaType; +import com.kaltura.client.test.tests.enums.MediaType; +import com.kaltura.client.test.tests.enums.PremiumService; +import com.kaltura.client.test.utils.BaseUtils; +import com.kaltura.client.types.*; +import com.microsoft.sqlserver.jdbc.SQLServerDataSource; +import org.apache.commons.dbutils.DbUtils; +import org.apache.commons.lang3.StringUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import javax.annotation.Nonnull; +import java.sql.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + +import static com.kaltura.client.test.Properties.*; +import static com.kaltura.client.test.tests.BaseTest.*; +import static com.kaltura.client.test.tests.enums.AssetStructMetaType.getIdsOfMetaTypes; +import static com.kaltura.client.test.utils.dbUtils.DBConstants.*; +import static com.kaltura.client.test.utils.dbUtils.IngestFixtureData.loadFirstPricePlanFromJsonArray; +import static org.assertj.core.api.Assertions.fail; + +public class DBUtils extends BaseUtils { + + private static final String ERROR_MESSAGE = "*** no data found ***"; + + private static boolean isActivationNeeded = false; + private static boolean isActivationNeededWasLoaded = false; + + @Nonnull + private static Stream arrayToStream(JSONArray array) { + return StreamSupport.stream(array.spliterator(), false); + } + + private static JSONArray buildJsonArrayFromQueryResult(ResultSet rs) throws SQLException { + JSONArray jsonArray = new JSONArray(); + ResultSetMetaData rsmd = rs.getMetaData(); + + while (rs.next()) { + int numColumns = rsmd.getColumnCount(); + JSONObject obj = new JSONObject(); + + for (int i = 1; i < numColumns + 1; i++) { + String column_name = rsmd.getColumnName(i).toLowerCase(); + + if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) { + obj.put(column_name, rs.getArray(column_name)); + } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) { + obj.put(column_name, rs.getInt(column_name)); + } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) { + obj.put(column_name, rs.getBoolean(column_name)); + } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) { + obj.put(column_name, rs.getBlob(column_name)); + } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) { + obj.put(column_name, rs.getDouble(column_name)); + } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) { + obj.put(column_name, rs.getFloat(column_name)); + } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) { + obj.put(column_name, rs.getInt(column_name)); + } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) { + obj.put(column_name, rs.getNString(column_name)); + } else if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) { + obj.put(column_name, rs.getString(column_name)); + } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) { + obj.put(column_name, rs.getInt(column_name)); + } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) { + obj.put(column_name, rs.getInt(column_name)); + } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) { + obj.put(column_name, rs.getDate(column_name)); + } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) { + obj.put(column_name, rs.getTimestamp(column_name)); + } else { + obj.put(column_name, rs.getObject(column_name)); + } + } + jsonArray.put(obj); + } + return jsonArray; + } + + protected static SQLServerDataSource getDataSource() { + SQLServerDataSource dataSource = new SQLServerDataSource(); + dataSource.setUser(getProperty(DB_USER)); + dataSource.setPassword(getProperty(DB_PASSWORD)); + dataSource.setServerName(getProperty(DB_URL)); + dataSource.setApplicationIntent("ReadOnly"); + dataSource.setMultiSubnetFailover(true); + + return dataSource; + } + + // Return json array from DB + static JSONArray getJsonArrayFromQueryResult(String query, Object... queryParams) { + SQLServerDataSource dataSource = getDataSource(); + Connection conn = null; + PreparedStatement pstm = null; + ResultSet rs = null; + JSONArray jsonArray = null; + + try { + conn = dataSource.getConnection(); + if (queryParams.length > 0) { + pstm = preparedStatementExecution(conn, query, queryParams); + } else { + pstm = conn.prepareStatement(query); + } + + rs = pstm.executeQuery(); + + if (rs != null && rs.isBeforeFirst()) { + jsonArray = buildJsonArrayFromQueryResult(rs); + Logger.getLogger(DBUtils.class).debug("query: " + query + "\nparams: " + Arrays.deepToString(queryParams)); + Logger.getLogger(DBUtils.class).debug("DB jsonArray: " + jsonArray.toString()); + } else { + // TODO: 6/25/2018 move query log once we'll have private repo + fail(ERROR_MESSAGE + "\nquery: " + query + "\nparams: " + Arrays.deepToString(queryParams)); + } + } catch (SQLException e) { + e.printStackTrace(); + } finally { + DbUtils.closeQuietly(rs); + DbUtils.closeQuietly(pstm); + DbUtils.closeQuietly(conn); + } + + return jsonArray; + } + + protected static PreparedStatement preparedStatementExecution(Connection conn, String query, Object... args) { + PreparedStatement pstm = null; + try { + pstm = conn.prepareStatement(query); + for (int i = 0; i < args.length; i++) { + switch (args[i].getClass().getSimpleName()) { + case "String": + pstm.setString(i + 1, (String) args[i]); + break; + case "Integer": + pstm.setInt(i + 1, (int) args[i]); + break; + case "Double": + pstm.setDouble(i + 1, (double) args[i]); + break; + case "Long": + pstm.setLong(i + 1, (long) args[i]); + break; + default: + fail("No valid type found!"); + break; + } + } + } catch (SQLException e) { + e.printStackTrace(); + } + return pstm; + } + + + // queries + public static boolean isActivationOfUsersNeeded() { + if (isActivationNeededWasLoaded) { + return isActivationNeeded; + } + + JSONArray jsonArray = getJsonArrayFromQueryResult(CHECK_IS_ACTIVATION_USERS_NEEDED, partnerId); + int result = jsonArray.getJSONObject(0).getInt(IS_ACTIVATION_NEEDED); + + isActivationNeeded = result == 1; + isActivationNeededWasLoaded = true; + + return isActivationNeeded; + } + + public static String getUserData(String userRole) { + String sqlQuery = USER_BY_ROLE_SELECT; + + if (isActivationOfUsersNeeded()) { + sqlQuery += AND_ACTIVE_STATUS; + } + + JSONArray jsonArray = getJsonArrayFromQueryResult(sqlQuery, userRole, partnerId); + return jsonArray.getJSONObject(0).getString(USERNAME) + ":" + jsonArray.getJSONObject(0).getString(PASSWORD); + } + + public static String getActivationToken(String username) { + return getJsonArrayFromQueryResult(ACTIVATION_TOKEN_SELECT, username) + .getJSONObject(0) + .getString(ACTIVATION_TOKEN); + } + + public static String getResetPasswordToken(String username) { + try { + return getJsonArrayFromQueryResult(RESET_PASSWORD_TOKEN_SELECT, username) + .getJSONObject(0) + .getString(CP_TOKEN); + } catch (JSONException e) { + return null; + } + } + + // Get epg channel name and linear asset id json array + public static JSONArray getLinearAssetIdAndEpgChannelNameJsonArray() { + return getJsonArrayFromQueryResult(LINEAR_ASSET_ID_AND_EPG_CHANNEL_NAME_SELECT, partnerId + 1); + } + + // Get un active asset from DB (status = 2) + public static int getUnActiveAsset() { + return getJsonArrayFromQueryResult(UNACTIVE_ASSET_ID_SELECT, partnerId + 1) + .getJSONObject(0) + .getInt(ID); + } + + public static Subscription getSubscriptionWithPremiumService(PremiumService premiumService) { + int subscriptionId = getJsonArrayFromQueryResult(SUBSCRIPTION_WITH_PREMIUM_SERVICE_SELECT, partnerId, premiumService.getValue()) + .getJSONObject(0) + .getInt(SUB_ID); + + SubscriptionFilter filter = new SubscriptionFilter(); + filter.setSubscriptionIdIn(String.valueOf(subscriptionId)); + + return executor.executeSync(SubscriptionService.list(filter) + .setKs(getOperatorKs())).results.getObjects().get(0); + } + + public static PricePlan loadPPWithWaiver() { + JSONArray jsonArray = getJsonArrayFromQueryResult(PRICE_PLAN_WITH_WAVER_SELECT, partnerId); + return loadFirstPricePlanFromJsonArray(jsonArray); + } + + public static PricePlan loadPPWithoutWaiver() { + JSONArray jsonArray = getJsonArrayFromQueryResult(PRICE_PLAN_WITHOUT_WAVER_SELECT, partnerId); + return loadFirstPricePlanFromJsonArray(jsonArray); + } + + public static Ppv loadPPVByPPWithoutWaiver() { + JSONArray jsonArray = getJsonArrayFromQueryResult(PPV_SELECT_BY_PRICE_PLAN_WITHOUT_WAIVER, partnerId); + + Ppv ppv = new Ppv(); + ppv.setId(String.valueOf(jsonArray.getJSONObject(0).getInt(ID))); + ppv.setName(jsonArray.getJSONObject(0).getString(NAME)); + ppv.setIsSubscriptionOnly(jsonArray.getJSONObject(0).getInt(SUBSCRIPTION_ONLY) == 0); + // TODO: add more data in case it needed + + return ppv; + } + + public static JSONObject getHouseholdById(int householdId) { + return getJsonArrayFromQueryResult(HOUSEHOLD_BY_ID_SELECT, partnerId, householdId) + .getJSONObject(0); + } + + public static JSONObject getUserById(int userId) { + return getJsonArrayFromQueryResult(USER_BY_ID_SELECT, partnerId, userId) + .getJSONObject(0); + } + + public static int getMediaTypeId(MediaType mediaType) { + if (isOpcGroup) { + return getJsonArrayFromQueryResult(MEDIA_TYPE_ID_SELECT, partnerId, partnerId, mediaType.getValue()) + .getJSONObject(0) + .getInt(ID); + } else { + return getJsonArrayFromQueryResult(MEDIA_TYPE_ID_SELECT, partnerId + 1, partnerId + 2, mediaType.getValue()) + .getJSONObject(0) + .getInt(ID); + } + } + + public static String getMediaFileTypeName(int mediaFileId) { + return getJsonArrayFromQueryResult(MEDIA_FILE_TYPE_ID_SELECT, partnerId + 1, mediaFileId) + .getJSONObject(0) + .getString(NAME); + } + + public static List getMediaFileTypeNames(int amount) { + if (isOpcGroup) { + JSONArray jsonArray = getJsonArrayFromQueryResult(MEDIA_FILE_TYPE_IDS_SELECT, amount, partnerId); + + return arrayToStream(jsonArray) + .map(JSONObject.class::cast) + .map(jsonObject -> jsonObject.getString(NAME)) + .collect(Collectors.toList()); + } else { + JSONArray jsonArray = getJsonArrayFromQueryResult(MEDIA_FILE_TYPE_IDS_SELECT, amount, partnerId + 1); + + return arrayToStream(jsonArray) + .map(JSONObject.class::cast) + .map(jsonObject -> jsonObject.getString(NAME)) + .collect(Collectors.toList()); + } + } + + public static List getAnnouncementResultMessageId(int announcementId) { + List ids = null; + + String s = getJsonArrayFromQueryResult(RESULT_MESSAGE_ID_SELECT, partnerId, announcementId) + .getJSONObject(0) + .getString("result_message_id"); + + if (StringUtils.isNotEmpty(s)) { + ids = Arrays.asList(s.split("\\s*,\\s*")); + } + + return ids; + } + + public static List getPpvNames(int amount) { + JSONArray jsonArray = getJsonArrayFromQueryResult(PPV_NAME_AND_ID_SELECT, amount, partnerId); + + return arrayToStream(jsonArray) + .map(JSONObject.class::cast) + .map(jsonObject -> jsonObject.getString(NAME)) + .collect(Collectors.toList()); + } + + public static Long getMetaIdByName(String metaName, boolean processBasicFields) { + JSONObject jsonObject = + getJsonArrayFromQueryResult(META_OR_TAG_SELECT_BY_NAME, partnerId, metaName) + .getJSONObject(0); + return (processBasicFields || (jsonObject.getInt(IS_BASIC) == 0)) ? jsonObject.getLong(ID) : -1; + } + + public static String getMetaNameById(Long id, boolean processBasicFields) { + JSONObject jsonObject = + getJsonArrayFromQueryResult(META_NAME_SELECT_BY_ID, partnerId, id) + .getJSONObject(0); + return (processBasicFields || (jsonObject.getInt(IS_BASIC) == 0)) ? jsonObject.getString(SYSTEM_NAME) : null; + } +// TODO: probably have to be removed as has select with IN that we aren't process +// public static List getMetaNamesByAssetStructId(Long assetStructId, AssetStructMetaType type) { +// List result = new ArrayList<>(); +// +// List metaIds = new ArrayList<>(); +// JSONArray jsonArrayFromQueryResult = getJsonArrayFromQueryResult(META_ID_SELECT_BY_ASSET_STRUCT_ID, partnerId, assetStructId); +// for (int i=0; i < jsonArrayFromQueryResult.length(); i++) { +// metaIds.add(String.valueOf(jsonArrayFromQueryResult.getJSONObject(i).getLong("topic_id"))); +// } +// if (metaIds.size() > 0) { +// List idsOfMetaTypes = getIdsOfMetaTypes(); +// int idOfType = getIdOfSelectedMetaType(type, idsOfMetaTypes); +// +// String ids = String.join(",", metaIds); +// JSONArray dbResult; +// if (idOfType ==-1) { +// // if type was not specified +// for (int i=0; i < idsOfMetaTypes.size(); i++) { +// dbResult = getJsonArrayFromQueryResult(META_NAME_SELECT_BY_IDS + " AND TOPIC_TYPE_ID=?", +// partnerId, ids, idsOfMetaTypes.get(i)); +// for (int j=0; j < dbResult.length(); j++) { +// result.add(dbResult.getJSONObject(j).getString(SYSTEM_NAME)); +// } +// } +// } else { +// dbResult = getJsonArrayFromQueryResult(META_NAME_SELECT_BY_IDS + " AND TOPIC_TYPE_ID=?", +// partnerId, ids, idOfType); +// for (int i=0; i < dbResult.length(); i++) { +// result.add(dbResult.getJSONObject(i).getString(SYSTEM_NAME)); +// } +// } +// } +// +// return result; +// } + + // TODO: check if it be used after completing functionality + public static Long loadBasicAssetStructMetaId() { + return getJsonArrayFromQueryResult(BASIC_META_SELECT, partnerId) + .getJSONObject(0) + .getLong(ID); + } + + public static List getAssetStructMetas(AssetStructMetaType type, int countItems) { + List result = new ArrayList<>(); + List idsOfMetaTypes = getIdsOfMetaTypes(); + int idOfType = getIdOfSelectedMetaType(type, idsOfMetaTypes); + + JSONArray dbResult; + if (idOfType ==-1) { + // if type was not specified + for (int i=0; i < idsOfMetaTypes.size(); i++) { + dbResult = getJsonArrayFromQueryResult(META_SELECT + " AND TOPIC_TYPE_ID=?", countItems, 0, partnerId, idsOfMetaTypes.get(i)); + for (int j=0; j < dbResult.length(); j++) { + result.add(dbResult.getJSONObject(j).getString(SYSTEM_NAME)); + } + } + } else { + dbResult = getJsonArrayFromQueryResult(META_SELECT + " AND TOPIC_TYPE_ID=?", countItems, 0, partnerId, idOfType); + for (int i=0; i < dbResult.length(); i++) { + result.add(dbResult.getJSONObject(i).getString(SYSTEM_NAME)); + } + } + + return result; + } + + static int getIdOfSelectedMetaType(AssetStructMetaType type, List idTypes) { + int idOfType =-1; + switch (type) { + case MULTI_LINGUAL_TEXT: + idOfType = idTypes.get(0); + break; + case NUMBER: + idOfType = idTypes.get(1); + break; + case DATE: + idOfType = idTypes.get(2); + break; + case BOOLEAN: + idOfType = idTypes.get(3); + break; + case STRING: + idOfType = idTypes.get(4); + break; + default: + // all types + break; + } + return idOfType; + } +} diff --git a/src/test/java/com/kaltura/client/test/utils/dbUtils/IngestFixtureData.java b/src/test/java/com/kaltura/client/test/utils/dbUtils/IngestFixtureData.java new file mode 100644 index 000000000..eaa394ba7 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/dbUtils/IngestFixtureData.java @@ -0,0 +1,182 @@ +package com.kaltura.client.test.utils.dbUtils; + +import com.kaltura.client.Logger; +import com.kaltura.client.enums.SubscriptionDependencyType; +import com.kaltura.client.services.PriceDetailsService; +import com.kaltura.client.services.PriceDetailsService.ListPriceDetailsBuilder; +import com.kaltura.client.services.PricePlanService; +import com.kaltura.client.services.PricePlanService.ListPricePlanBuilder; +import com.kaltura.client.test.utils.BaseUtils; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; +import org.json.JSONArray; + +import static com.kaltura.client.test.tests.BaseTest.*; +import static com.kaltura.client.test.utils.dbUtils.DBConstants.*; +import static com.kaltura.client.test.utils.dbUtils.DBUtils.getJsonArrayFromQueryResult; + +public class IngestFixtureData extends BaseUtils { + + public static PriceDetails loadPriceCode(Double priceAmount, String currency) { + Logger.getLogger(IngestFixtureData.class).debug("loadPriceCode(): priceAmount = " + priceAmount + " currency = " + currency); + + JSONArray jsonArray = getJsonArrayFromQueryResult(PRICE_CODE_SELECT, partnerId, priceAmount, currency); + PriceDetailsFilter filter = new PriceDetailsFilter(); + filter.setIdIn(String.valueOf(jsonArray.getJSONObject(0).getInt(ID))); + ListPriceDetailsBuilder priceDetailsBuilder = PriceDetailsService.list(filter); + Response> priceDetailsListResponse = executor.executeSync(priceDetailsBuilder.setKs(getOperatorKs())); + + return priceDetailsListResponse.results.getObjects().get(0); + } + + public static DiscountModule loadDiscount(Double discountPrice, Double discountPercent) { + Logger.getLogger(IngestFixtureData.class).debug("loadDiscount(): discountPrice = " + discountPrice + " discountPercent = " + discountPercent); + + JSONArray jsonArray = getJsonArrayFromQueryResult(DISCOUNT_BY_PRICE_AND_PERCENT_SELECT, partnerId, discountPrice, discountPercent); + DiscountModule result = new DiscountModule(); + result.setToken(ID, String.valueOf(jsonArray.getJSONObject(0).getInt(ID))); + result.setToken(NAME, jsonArray.getJSONObject(0).getString(CODE)); + result.setPercent(discountPercent); + + return result; + } + + public static PricePlan loadPricePlan(Double priceAmount, String currency, DiscountModule discountModule) { + Logger.getLogger(IngestFixtureData.class).debug("loadPricePlan(): priceAmount = " + priceAmount + " currency = " + currency + + " discountPercent = " + discountModule.getPercent()); + + PriceDetails priceCode = loadPriceCode(priceAmount, currency); + JSONArray jsonArray = getJsonArrayFromQueryResult(PRICE_PLAN_SELECT, partnerId, + Integer.valueOf(discountModule.toParams().get("id").toString()), priceCode.getId()); + + return loadFirstPricePlanFromJsonArray(jsonArray); + } + + static PricePlan loadFirstPricePlanFromJsonArray(JSONArray jsonArray) { + PricePlanFilter filter = new PricePlanFilter(); + filter.setIdIn(String.valueOf(jsonArray.getJSONObject(0).getLong(ID))); + ListPricePlanBuilder pricePlanBuilder = PricePlanService.list(filter); + com.kaltura.client.utils.response.base.Response> pricePlanListResponse = + executor.executeSync(pricePlanBuilder.setKs(getOperatorKs())); + return pricePlanListResponse.results.getObjects().get(0); + } + + public static PricePlan load5MinRenewablePricePlan() { + Logger.getLogger(IngestFixtureData.class).debug("load5MinRenewablePricePlan()"); + + JSONArray jsonArray = getJsonArrayFromQueryResult(PRICE_PLAN_5_MIN_RENEW_SELECT, partnerId); + + return loadFirstPricePlanFromJsonArray(jsonArray); + } + + public static Subscription loadSharedCommonSubscription(PricePlan pricePlan) { + Logger.getLogger(IngestFixtureData.class).debug("loadSharedCommonSubscription(): pricePlan id = " + pricePlan.getId()); + + JSONArray jsonArray = getJsonArrayFromQueryResult(SUBSCRIPTION_SELECT, partnerId, + pricePlan.getId(), getSharedCommonDiscount().toParams().get("id")); + + Subscription subscription = new Subscription(); + subscription.setId(String.valueOf(jsonArray.getJSONObject(0).getInt(ID))); + subscription.setMultilingualName(setTranslationToken(jsonArray.getJSONObject(0).getString(NAME))); + subscription.setPricePlanIds(String.valueOf(jsonArray.getJSONObject(0).getLong(PRICE_PLAN_ID))); + subscription.setIsRenewable(false); + subscription.setDependencyType(SubscriptionDependencyType.BASE); + + return subscription; + } + + public static Collection loadSharedCommonCollection(PricePlan pricePlan) { + Logger.getLogger(IngestFixtureData.class).debug("loadSharedCommonCollection(): price_id = " + pricePlan.getPriceDetailsId() + + "discount_id = " + pricePlan.getDiscountId() + "usage_module_id = " + pricePlan.getId()); + + JSONArray jsonArray = getJsonArrayFromQueryResult(COLLECTION_SELECT, partnerId, + getSharedCommonDiscount().toParams().get("id"), pricePlan.getPriceDetailsId(), pricePlan.getId()); + Collection collection = new Collection(); + collection.setId(String.valueOf(jsonArray.getJSONObject(0).getInt(ID))); + collection.setMultilingualName(setTranslationToken(jsonArray.getJSONObject(0).getString(NAME))); + // TODO: add more data in case it needed + return collection; + } + + public static String getDiscountByPercentAndCurrency(String currency, int percent) { + Logger.getLogger(IngestFixtureData.class).debug("getDiscountByPercent(): currency = " + currency + " percent = " + percent); + + JSONArray jsonArray = getJsonArrayFromQueryResult(DISCOUNT_BY_PERCENT_AND_CURRENCY, currency, percent, partnerId); + + return jsonArray.getJSONObject(0).getString(CODE); + } + + public static String getDiscountById(String id) { + JSONArray jsonArray = getJsonArrayFromQueryResult(DISCOUNT_BY_ID, partnerId, id); + return jsonArray.getJSONObject(0).getString(CODE); + } + + public static DiscountModule getDiscountByPercent(int percent) { + Logger.getLogger(IngestFixtureData.class).debug("getDiscountByPercent(): percent = " + percent); + + JSONArray jsonArray = getJsonArrayFromQueryResult(DISCOUNT_BY_PERCENT, + percent, partnerId); + DiscountModule result = new DiscountModule(); + result.setPercent((double) percent); + result.setToken(CODE, jsonArray.getJSONObject(0).getString(CODE)); + result.setToken(ID, String.valueOf(jsonArray.getJSONObject(0).getInt(ID))); + + return result; + } + + public static int getEpgChannelId(String channelName) { + Logger.getLogger(IngestFixtureData.class).debug("getEpgChannelId(): channelName = " + channelName); + + JSONArray jsonArray = getJsonArrayFromQueryResult(EPG_CHANNEL_ID_SELECT, partnerId + 1, channelName); + int epgChannelId = jsonArray.getJSONObject(0).getInt("id"); + + return epgChannelId; + } + + public static String getIngestItemUserData(int accountId) { + Logger.getLogger(IngestFixtureData.class).debug("getIngestItemUserData(): accountId = " + accountId); + + JSONArray jsonArray = getJsonArrayFromQueryResult(INGEST_ITEMS_DATA_SELECT, accountId); + + return jsonArray.getJSONObject(0).getString(USERNAME) + ":" + + jsonArray.getJSONObject(0).getString(PASSWORD); + } + + public static Ppv loadSharedCommonPpv(PricePlan pricePlan) { + Logger.getLogger(IngestFixtureData.class).debug("loadSharedCommonPpv(): pricePlan id = " + pricePlan.getId()); + + JSONArray jsonArray = getJsonArrayFromQueryResult(PPV_SELECT_BY_PRICE_PLAN, partnerId, + pricePlan.getId()); + Ppv ppv = new Ppv(); + ppv.setId(String.valueOf(jsonArray.getJSONObject(0).getInt(ID))); + ppv.setName(jsonArray.getJSONObject(0).getString(NAME)); + ppv.setIsSubscriptionOnly(jsonArray.getJSONObject(0).getInt(SUBSCRIPTION_ONLY) == 0); + // TODO: add more data in case it needed + + return ppv; + } + + public static Subscription loadShared5MinutesRenewableSubscription() { + Logger.getLogger(IngestFixtureData.class).debug("loadShared5MinutesRenewableSubscription()"); + + JSONArray jsonArray = getJsonArrayFromQueryResult(SUBSCRIPTION_5_MIN_RENEW_SELECT, partnerId); + Subscription subscription = new Subscription(); + subscription.setId(String.valueOf(jsonArray.getJSONObject(0).getInt(ID)).trim()); + subscription.setMultilingualName(setTranslationToken(jsonArray.getJSONObject(0).getString(NAME))); + subscription.setPricePlanIds(String.valueOf(jsonArray.getJSONObject(0).getLong(PRICE_PLAN_ID))); + subscription.setIsRenewable(false); + subscription.setDependencyType(SubscriptionDependencyType.BASE); + // TODO: add more data in case it needed + + return subscription; + } + + public static String getAutomaticChannelExpression(int channelId) { + Logger.getLogger(IngestFixtureData.class).debug("getAutomaticChannelExpression(): channelId = " + channelId); + + JSONArray jsonArray = getJsonArrayFromQueryResult(CHANNEL_EXPRESSION_SELECT, channelId); + + return jsonArray.getJSONObject(0).getInt(TAG_NAME) + ":" + + jsonArray.getJSONObject(0).getString(TAG_VALUE); + } +} diff --git a/src/test/java/com/kaltura/client/test/utils/dbUtils/PermissionsManagementDBUtils.java b/src/test/java/com/kaltura/client/test/utils/dbUtils/PermissionsManagementDBUtils.java new file mode 100644 index 000000000..0f50ee71d --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/dbUtils/PermissionsManagementDBUtils.java @@ -0,0 +1,224 @@ +package com.kaltura.client.test.utils.dbUtils; + +import com.microsoft.sqlserver.jdbc.SQLServerDataSource; +import org.apache.commons.dbutils.DbUtils; +import org.json.JSONArray; +import java.sql.*; + +import static com.kaltura.client.test.utils.dbUtils.DBConstants.*; + +public class PermissionsManagementDBUtils extends DBUtils { + + /** + * Call Stored Procedure to create role + */ + public static int insertRole(String role) { + JSONArray jsonArray = getJsonArrayFromQueryResult(SP_INSERT_ROLE, 0, role); // group_id == 0 + return Integer.valueOf(jsonArray.getJSONObject(0).get(ID).toString()); + } + + /** + * Call Stored Procedure to delete role and its permissions + */ + public static void deleteRoleAndItsPermissions(int roleId) { + executeQuery(SP_DELETE_ROLE_AND_ITS_PERMISSIONS, 0, roleId); // group_id == 0 + } + + /** + * Call Stored Procedure to insert permissions + */ + public static int insertPermission(String name, int type, String usersGroup) { + JSONArray jsonArray = getJsonArrayFromQueryResult(SP_INSERT_PERMISSION, 0, name, type, usersGroup); // group_id == 0 + return Integer.valueOf(jsonArray.getJSONObject(0).get(ID).toString()); + } + + /** + * Call Stored Procedure to delete permission + */ + public static void deletePermission(int id) { + executeQuery(SP_DELETE_PERMISSION, id); + } + + /** + * Call Stored Procedure to insert permission role + */ + public static int insertPermissionRole(long roleId, long permissionId, int isExcluded) { + JSONArray jsonArray = getJsonArrayFromQueryResult(SP_INSERT_PERMISSION_ROLE, 0, roleId, permissionId, isExcluded); // group_id == 0 + return Integer.valueOf(jsonArray.getJSONObject(0).get(ID).toString()); + } + + /** + * Call Stored Procedure to insert permission item + */ + public static int insertPermissionItem(String name, int type, String service, String action, String permissionItemObject, String parameter) { + JSONArray jsonArray = getJsonArrayFromQueryResult(SP_INSERT_PERMISSION_ITEM, name, type, service, action, permissionItemObject, parameter); + return Integer.valueOf(jsonArray.getJSONObject(0).get(ID).toString()); + } + + /** + * Call Stored Procedure to delete permission item + */ + public static void deletePermissionItem(int id) { + executeQuery(SP_DELETE_PERMISSION_ITEM, id); + } + + /** + * Call Stored Procedure to insert permission permission item + */ + public static int insertPermissionPermissionItem(long permissionId, long permissionItemId, int isExcluded) { + JSONArray jsonArray = getJsonArrayFromQueryResult(SP_INSERT_PERMISSION_PERMISSION_ITEM, 0, permissionId, permissionItemId, isExcluded); // group_id == 0 + return Integer.valueOf(jsonArray.getJSONObject(0).get(ID).toString()); + } + + /** + * Call Stored Procedure to delete permission permission item + */ + public static void deletePermissionPermissionItem(int id) { + executeQuery(SP_DELETE_PERMISSION_PERMISSION_ITEM, id); + } + + static void executeQuery(String query, Object... queryParams) { + SQLServerDataSource dataSource = DBUtils.getDataSource(); + Connection conn = null; + PreparedStatement pstm = null; + ResultSet rs = null; + + try { + conn = dataSource.getConnection(); + if (queryParams.length > 0) { + pstm = preparedStatementExecution(conn, query, queryParams); + } else { + pstm = conn.prepareStatement(query); + } + + pstm.execute(); + } catch (SQLException e) { + e.printStackTrace(); + } finally { + DbUtils.closeQuietly(rs); + DbUtils.closeQuietly(pstm); + DbUtils.closeQuietly(conn); + } + } + + + public static int getCountRowsHavingRoleNameInRoles(String name, int groupId) { + int count = 0; + try { + JSONArray jsonArray = getJsonArrayFromQueryResult(String.format(COUNT_RECORDS_BY_ROLE_NAME_IN_ROLES_SELECT), + name, groupId); + if (!jsonArray.isNull(0)) { + count = jsonArray.getJSONObject(0).getInt(ROW_COUNT); + } + } catch (Exception e) { + e.printStackTrace(); + } + + return count; + } + + public static int getIdRecordHavingRoleNameInRoles(String name, int groupId) { + int id =-1; + try { + JSONArray jsonArray = getJsonArrayFromQueryResult(String.format(ID_BY_ROLE_NAME_IN_ROLES_SELECT), + name, groupId); + if (!jsonArray.isNull(0)) { + id = jsonArray.getJSONObject(0).getInt(ID); + } + } catch (Exception e) { + e.printStackTrace(); + } + + return id; + } + + public static int getCountRowsHavingRoleNameInPermissions(String name, int groupId) { + int count = 0; + try { + JSONArray jsonArray = getJsonArrayFromQueryResult(String.format(COUNT_RECORDS_BY_ROLE_NAME_IN_PERMISSIONS_SELECT), + name, groupId); + if (!jsonArray.isNull(0)) { + count = jsonArray.getJSONObject(0).getInt(ROW_COUNT); + } + } catch (Exception e) { + e.printStackTrace(); + } + + return count; + } + + public static int getIdRecordHavingRoleNameInPermissions(String name, int groupId) { + int id =-1; + try { + JSONArray jsonArray = getJsonArrayFromQueryResult(String.format(ID_BY_ROLE_NAME_IN_PERMISSIONS_SELECT), + name, groupId); + if (!jsonArray.isNull(0)) { + id = jsonArray.getJSONObject(0).getInt(ID); + } + } catch (Exception e) { + e.printStackTrace(); + } + + return id; + } + + public static int getCountSpecificRowsFromRolesPermissions(int roleId, int permissionId, int groupId) { + int count = 0; + try { + JSONArray jsonArray = getJsonArrayFromQueryResult(String.format(COUNT_RECORDS_IN_ROLES_PERMISSIONS_SELECT), + roleId, permissionId, groupId); + if (!jsonArray.isNull(0)) { + count = jsonArray.getJSONObject(0).getInt(ROW_COUNT); + } + } catch (Exception e) { + e.printStackTrace(); + } + + return count; + } + + public static int getCountRowsHavingNameInPermissionItems(String name) { + int count = 0; + try { + JSONArray jsonArray = getJsonArrayFromQueryResult(String.format(COUNT_RECORDS_BY_NAME_IN_PERMISSION_ITEMS_SELECT), + name); + if (!jsonArray.isNull(0)) { + count = jsonArray.getJSONObject(0).getInt(ROW_COUNT); + } + } catch (Exception e) { + e.printStackTrace(); + } + + return count; + } + + public static int getIdRecordHavingNameInPermissionItems(String name) { + int id =-1; + try { + JSONArray jsonArray = getJsonArrayFromQueryResult(String.format(ID_BY_NAME_IN_PERMISSION_ITEMS_SELECT), + name); + if (!jsonArray.isNull(0)) { + id = jsonArray.getJSONObject(0).getInt(ID); + } + } catch (Exception e) { + e.printStackTrace(); + } + + return id; + } + + public static int getCountSpecificRowsFromPermissionsPermissionsItems(int permissionId, int permissionItemId, int groupId) { + int count = 0; + try { + JSONArray jsonArray = getJsonArrayFromQueryResult(String.format(COUNT_RECORDS_IN_PERMISSIONS_PERMISSIONS_ITEMS_SELECT), + permissionId, permissionItemId, groupId); + if (!jsonArray.isNull(0)) { + count = jsonArray.getJSONObject(0).getInt(ROW_COUNT); + } + } catch (Exception e) { + e.printStackTrace(); + } + + return count; + } +} diff --git a/src/test/java/com/kaltura/client/test/utils/ingestUtils/BaseIngestUtils.java b/src/test/java/com/kaltura/client/test/utils/ingestUtils/BaseIngestUtils.java new file mode 100644 index 000000000..ba9340e9f --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/ingestUtils/BaseIngestUtils.java @@ -0,0 +1,115 @@ +package com.kaltura.client.test.utils.ingestUtils; + +import com.kaltura.client.Logger; +import io.restassured.http.Header; +import io.restassured.response.Response; +import org.w3c.dom.Document; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.io.StringWriter; +import java.io.Writer; + +import static com.kaltura.client.test.Properties.*; +import static com.kaltura.client.test.Properties.PARTNER_ID; +import static io.restassured.RestAssured.given; + +public class BaseIngestUtils { + + // urls + static final String ingestUrl = getProperty(INGEST_BASE_URL) + "/Ingest_" + getProperty(API_VERSION) + "/Service.svc?wsdl"; + private static final String ingestBaseReportUrl = getProperty(INGEST_REPORT_URL) + "/" + getProperty(PARTNER_ID) + "/"; + + // headers + static final Header contentTypeXml = new Header("Content-Type", "text/xml;charset=UTF-8"); + static final Header soapActionIngestTvinciData = new Header("SOAPAction", "http://tempuri.org/IService/IngestTvinciData"); + static final Header soapActionIngestBusinessModules = new Header("SOAPAction", "http://tempuri.org/IService/IngestBusinessModules"); + static final Header soapActionIngestKalturaEpg = new Header("SOAPAction", "http://tempuri.org/IService/IngestKalturaEpg"); + + // wait configuration + public static final int delayBetweenRetriesInSeconds = 5; + public static final int maxTimeExpectingValidResponseInSeconds = 120; + + // life cycles periods + public static final String FIVE_MINUTES_PERIOD = "5 Minutes"; + + // data + public static final String DEFAULT_THUMB = "http://opengameart.org/sites/default/files/styles/thumbnail/public/pictures/picture-1760-1321510314.png"; + + // language + public static final String DEFAULT_LANGUAGE = "eng"; + + /*// PG adapter data + public static final String PG_DEFAULT_ADAPTER_URL = "http://172.31.6.89:90/PGAdapter/Service.svc"; + public static final String PG_DEFAULT_RENEW_URL = PG_DEFAULT_ADAPTER_URL + "?StateCode=0"; + public static final String PG_DEFAULT_SHARED_SECRET = "123456"; + public static final int PG_DEFAULT_PENDING_INTERVAL = 0; + public static final int PG_DEFAULT_PENDING_RETRIES = 0; + public static final int PG_DEFAULT_RENEW_INTERVAL_MINUTES = 15; + public static final int PG_DEFAULT_RENEW_START_MINUTES =-5; + public static final String PG_DEFAULT_PG_SETTINGS = "{}"; + */ + + public static Document getDocument(String uri) { + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder; + Document doc = null; + + try { + docBuilder = docFactory.newDocumentBuilder(); + doc = docBuilder.parse(uri); + } catch (Exception e) { + e.printStackTrace(); + } + + return doc; + } + + static String docToString(Document doc) { + try { + StringWriter sw = new StringWriter(); + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer transformer = tf.newTransformer(); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + + transformer.transform(new DOMSource(doc), new StreamResult(sw)); + return sw.toString(); + } catch (Exception ex) { + throw new RuntimeException("Error converting to String", ex); + } + } + + static void prettyPrint(Document doc) throws Exception { + Transformer tf = TransformerFactory.newInstance().newTransformer(); + tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + tf.setOutputProperty(OutputKeys.INDENT, "yes"); + Writer out = new StringWriter(); + tf.transform(new DOMSource(doc), new StreamResult(out)); + } + + static String uncommentCdataSection(String docAsString) { + docAsString = docAsString + .replace("", "-->", "]]>"); + + return docAsString; + } + + static Response executeIngestReportRequest(String reportId) { + String reportUrl = ingestBaseReportUrl + reportId; + Logger.getLogger(IngestMppUtils.class).debug(reportUrl); + + Response resp = given().get(reportUrl); + Logger.getLogger(IngestMppUtils.class).debug(resp.asString()); + + return resp; + } +} diff --git a/src/test/java/com/kaltura/client/test/utils/ingestUtils/IngestEpgUtils.java b/src/test/java/com/kaltura/client/test/utils/ingestUtils/IngestEpgUtils.java new file mode 100644 index 000000000..1b7aaef7d --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/ingestUtils/IngestEpgUtils.java @@ -0,0 +1,315 @@ +package com.kaltura.client.test.utils.ingestUtils; + +import com.kaltura.client.Logger; +import com.kaltura.client.enums.AssetOrderBy; +import com.kaltura.client.test.tests.enums.DurationPeriod; +import com.kaltura.client.test.utils.KsqlBuilder; +import com.kaltura.client.test.utils.dbUtils.IngestFixtureData; +import com.kaltura.client.types.Asset; +import com.kaltura.client.types.ListResponse; +import com.kaltura.client.types.ProgramAsset; +import com.kaltura.client.types.SearchAssetFilter; +import com.kaltura.client.utils.response.base.Response; +import lombok.AccessLevel; +import lombok.Data; +import lombok.NonNull; +import lombok.Setter; +import lombok.experimental.Accessors; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; + +import static com.kaltura.client.services.AssetService.ListAssetBuilder; +import static com.kaltura.client.services.AssetService.list; +import static com.kaltura.client.test.tests.BaseTest.*; +import static com.kaltura.client.test.tests.enums.KsqlKey.*; +import static com.kaltura.client.test.utils.BaseUtils.*; +import static io.restassured.RestAssured.given; +import static io.restassured.path.xml.XmlPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public class IngestEpgUtils extends BaseIngestUtils { + private static final SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); + + private static Response> assetListResponse; + private static int epgChannelId; + + + @Accessors(fluent = true) + @Data + public static class EpgData { + @Setter(AccessLevel.NONE) private String coguid; + @Setter(AccessLevel.NONE) @NonNull private String epgChannelName; + + private boolean isCridUnique4AllPrograms = true; + + private String crid; + private String seriesId; + private String thumb; + private String programNamePrefix; + + private int episodesNum; + private int seasonsNum; + private int programDuration; + + private Long startDate; + private DurationPeriod programDurationPeriod; + + private Map metas; + private Map tags; + } + + public static List insertEpg(EpgData epgData) { + final String coguidDatePattern = "yyMMddHHmmssSS"; + final int DEFAULT_SEASONS_COUNT = 2; + final int DEFAULT_PROGRAMMES_COUNT = 2; + final int DEFAULT_PROGRAM_DURATION = 30; + + df.setTimeZone(TimeZone.getDefault()); + + // TODO: complete one-by-one needed fields to cover util ingest_epg from old project + epgData.coguid = getCurrentDateInFormat(coguidDatePattern); + + if (epgData.crid == null) { epgData.crid = epgData.coguid; } + if (epgData.seriesId == null) { epgData.seriesId = epgData.coguid; } + if (epgData.episodesNum == 0) { epgData.episodesNum = DEFAULT_PROGRAMMES_COUNT; } + if (epgData.seasonsNum == 0) { epgData.seasonsNum = DEFAULT_SEASONS_COUNT; } + if (epgData.startDate == null) { epgData.startDate = getEpoch(); } + if (epgData.programDuration == 0) { epgData.programDuration = DEFAULT_PROGRAM_DURATION; } + if (epgData.programDurationPeriod == null) { epgData.programDurationPeriod = DurationPeriod.MINUTES; } + if (epgData.thumb == null) { epgData.thumb = DEFAULT_THUMB; } + if (epgData.programNamePrefix == null) { epgData.programNamePrefix = "Program"; } + + long firstProgramStartDateEpoch = epgData.startDate; + + epgChannelId = IngestFixtureData.getEpgChannelId(epgData.epgChannelName); + String reqBody = buildIngestEpgXml(epgData); + executeIngestEpgRequest(reqBody); + + // TODO: create method getting epoch value from String and pattern + SearchAssetFilter assetFilter = new SearchAssetFilter(); + assetFilter.setOrderBy(AssetOrderBy.START_DATE_ASC.getValue()); + + String query = new KsqlBuilder() + .openAnd() + .equal(EPG_CHANNEL_ID.getValue(), epgChannelId) + .greaterOrEqual(START_DATE.getValue(), firstProgramStartDateEpoch) + .equal("Series_ID", epgData.seriesId) + .greaterOrEqual(END_DATE.getValue(), firstProgramStartDateEpoch) + .closeAnd() + .toString(); + assetFilter.setKSql(query); + + ListAssetBuilder listAssetBuilder = list(assetFilter).setKs(getAnonymousKs()); + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(isDataReturned(listAssetBuilder, epgData.seasonsNum * epgData.episodesNum)); + + // TODO: complete Asset.json at least for programs + return (List) (Object) assetListResponse.results.getObjects(); + } + + // private methods + private static Callable isDataReturned(ListAssetBuilder listAssetBuilder, int totalCount) { + return () -> { + assetListResponse = executor.executeSync(listAssetBuilder); + return assetListResponse.error == null && + assetListResponse.results.getTotalCount() == totalCount; + }; + } + + private static io.restassured.response.Response executeIngestEpgRequest(String reqBody) { + final String ingestDataResultPath = "Envelope.Body.IngestKalturaEpgResponse.IngestKalturaEpgResult."; + final String ingestStatusMessagePath = ingestDataResultPath + "IngestStatus.Message"; + final String ingestInternalAssetIdPath = ingestDataResultPath + "AssetsStatus.IngestAssetStatus.InternalAssetId"; + + io.restassured.response.Response resp = given() + .header(contentTypeXml) + .header(soapActionIngestKalturaEpg) + .body(reqBody) + .when() + .post(ingestUrl); + + Logger.getLogger(IngestVodUtils.class).debug(reqBody + "\n"); + Logger.getLogger(IngestVodUtils.class).debug(resp.asString()); + + // response assertions + assertThat(resp).isNotNull(); + assertThat(from(resp.asString()).getString(ingestStatusMessagePath)).isEqualTo("OK"); + assertThat(from(resp.asString()).getList(ingestInternalAssetIdPath)).containsOnly(String.valueOf(epgChannelId)); + + return resp; + } + + private static String buildIngestEpgXml(EpgData epgData) { + Document doc = getDocument("src/test/resources/ingest_xml_templates/ingestEPG.xml"); + + // user and password + doc.getElementsByTagName("userName").item(0).setTextContent(getIngestBusinessModuleUserName()); + doc.getElementsByTagName("passWord").item(0).setTextContent(getIngestBusinessModuleUserPassword()); + + // EpgChannels + Element epgChannels = (Element) doc.getElementsByTagName("EpgChannels").item(0); + epgChannels.setAttribute("parent-group-id", String.valueOf(partnerId)); + epgChannels.setAttribute("group-id", String.valueOf(partnerId + 1)); + + // channel + Element channel = (Element) epgChannels.getElementsByTagName("channel").item(0); + channel.setAttribute("id", epgData.epgChannelName); + + // programme + int seasonNum = 1; + while (seasonNum <= epgData.seasonsNum) { + int episodeNum = 1; + while (episodeNum <= epgData.episodesNum) { + Date endDate = loadEndDate(epgData.startDate, epgData.programDuration, epgData.programDurationPeriod); + String startDateFormatted = df.format(getDateFromEpoch(epgData.startDate)); + String endDateFormatted = df.format(endDate); + + Element programmeNode = getProgrammeNode(doc, episodeNum, seasonNum, startDateFormatted, endDateFormatted, epgData); + epgChannels.appendChild(programmeNode); + + epgData.startDate(getEpochFromDate(endDate)); + episodeNum++; + } + seasonNum++; + } + + // uncomment cdata + return uncommentCdataSection(docToString(doc)); + } + + private static Element getProgrammeNode(Document doc, int episodeNum, int seasonNum, String startDate, String endDate, EpgData epgData) { + String name = epgData.programNamePrefix + "_" + startDate + "_ser" + epgData.seriesId + "_seas" + seasonNum + "_e" + episodeNum; + String crid = epgData.isCridUnique4AllPrograms ? epgData.crid + "_" + seasonNum + "_" + episodeNum : epgData.crid + "_" + episodeNum; + + // programme + Element programme = doc.createElement("programme"); + programme.setAttribute("start", startDate); + programme.setAttribute("stop", endDate); + programme.setAttribute("channel", epgData.epgChannelName); + programme.setAttribute("external_id", epgData.coguid + "_" + seasonNum + "_" + episodeNum); + + // title + Element title = doc.createElement("title"); + title.setAttribute("lang", DEFAULT_LANGUAGE); + title.setTextContent(name); + programme.appendChild(title); + + // crid + Element cridElement = doc.createElement("crid"); + cridElement.setTextContent(crid); + programme.appendChild(cridElement); + + // desc + Element desc = doc.createElement("desc"); + desc.setAttribute("lang", DEFAULT_LANGUAGE); + desc.setTextContent(startDate + " until " + endDate); + programme.appendChild(desc); + + // date + Element date = doc.createElement("date"); + date.setTextContent(df.format(Calendar.getInstance().getTime())); + programme.appendChild(date); + + // language + Element lang = doc.createElement("language"); + lang.setAttribute("lang", DEFAULT_LANGUAGE); + lang.setTextContent(DEFAULT_LANGUAGE); + programme.appendChild(lang); + + // icon + Element icon = doc.createElement("icon"); + icon.setAttribute("ratio", "16:9"); + icon.setAttribute("src", epgData.thumb); + programme.appendChild(icon); + + // season num meta + programme.appendChild(generateMetasNode(doc, "season_num", String.valueOf(seasonNum))); + + // series id meta + programme.appendChild(generateMetasNode(doc, "series_id", epgData.seriesId)); + + // episode num meta + programme.appendChild(generateMetasNode(doc, "episode_num", String.valueOf(episodeNum))); + + // custom metas + if (epgData.metas != null) { + for (Map.Entry entry : epgData.metas.entrySet()) { + programme.appendChild(generateMetasNode(doc, entry.getKey(), entry.getValue())); + } + } + + // custom tags + if (epgData.tags != null) { + for (Map.Entry entry : epgData.tags.entrySet()) { + programme.appendChild(generateTagsNode(doc, entry.getKey(), entry.getValue())); + } + } + + // TODO: 6/19/2018 add missing parameters according to needed tests + + return programme; + } + + private static Element generateMetasNode(Document doc, String metaTypeString, String metaValuesString) { + // metas node + Element metas = doc.createElement("metas"); + + // metaType + Element metaType = doc.createElement("MetaType"); + metaType.setTextContent(metaTypeString); + metas.appendChild(metaType); + + // metaValues + Element metaValues = doc.createElement("MetaValues"); + metaValues.setAttribute("lang", DEFAULT_LANGUAGE); + metaValues.setTextContent(metaValuesString); + metas.appendChild(metaValues); + + return metas; + } + + private static Element generateTagsNode(Document doc, String tagTypeString, String tagValuesString) { + // tags node + Element tags = doc.createElement("tags"); + + // TagType + Element tagType = doc.createElement("TagType"); + tagType.setTextContent(tagTypeString); + tags.appendChild(tagType); + + // TagValues + Element tagValues = doc.createElement("TagValues"); + tagValues.setAttribute("lang", DEFAULT_LANGUAGE); + tagValues.setTextContent(tagValuesString); + tags.appendChild(tagValues); + + return tags; + } + + private static Date loadEndDate(long startDate, int durationValue, DurationPeriod durationPeriod) { + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(startDate * 1000); + switch (durationPeriod) { + case DAYS: + calendar.add(Calendar.DATE, durationValue); + break; + case HOURS: + calendar.add(Calendar.HOUR, durationValue); + break; + case MINUTES: + calendar.add(Calendar.MINUTE, durationValue); + break; + case SECONDS: + calendar.add(Calendar.SECOND, durationValue); + } + return calendar.getTime(); + } +} diff --git a/src/test/java/com/kaltura/client/test/utils/ingestUtils/IngestMppUtils.java b/src/test/java/com/kaltura/client/test/utils/ingestUtils/IngestMppUtils.java new file mode 100644 index 000000000..5ae716f4d --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/ingestUtils/IngestMppUtils.java @@ -0,0 +1,314 @@ +package com.kaltura.client.test.utils.ingestUtils; + +import com.kaltura.client.Logger; +import com.kaltura.client.services.SubscriptionService; +import com.kaltura.client.test.tests.enums.IngestAction; +import com.kaltura.client.test.utils.dbUtils.IngestFixtureData; +import com.kaltura.client.types.CouponsGroup; +import com.kaltura.client.types.ProductCode; +import com.kaltura.client.types.Subscription; +import com.kaltura.client.types.SubscriptionFilter; +import io.restassured.response.Response; +import lombok.AccessLevel; +import lombok.Data; +import lombok.Setter; +import lombok.experimental.Accessors; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import java.util.List; + +import static com.kaltura.client.test.Properties.*; +import static com.kaltura.client.test.tests.BaseTest.*; +import static com.kaltura.client.test.tests.enums.IngestAction.DELETE; +import static com.kaltura.client.test.tests.enums.IngestAction.INSERT; +import static com.kaltura.client.test.utils.BaseUtils.getFormattedTime; +import static com.kaltura.client.test.utils.BaseUtils.getRandomValue; +import static io.restassured.RestAssured.given; +import static io.restassured.path.xml.XmlPath.from; +import static java.util.TimeZone.getTimeZone; +import static org.assertj.core.api.Assertions.assertThat; + +public class IngestMppUtils extends BaseIngestUtils { + + private static final String ingestDataResultPath = "Envelope.Body.IngestBusinessModulesResponse.IngestBusinessModulesResult."; + private static final String ingestStatusMessagePath = ingestDataResultPath + "Status.Message"; + private static final String ingestReportIdPath = ingestDataResultPath + "ReportId"; + + // TODO: THIS VALUES RELATED TO OUR ENV ONLY discuss with Alon + private static final String DEFAULT_COUPON_GROUP = + "\n" + + "01/05/2017 00:00:00\n" + + "31/12/2099 23:59:59\n" + + "100% unlimited\n" + + "\n" + + "\n" + + "01/05/2017 00:00:00\n" + + "31/05/2017 23:59:59\n" + + "Expired coupon group 1\n" + + ""; + + private static final String DEFAULT_PRODUCT_CODES = + "\n" + + "ProductCode1\n" + + "Google\n" + + "\n" + + "\n" + + "ProductCode2\n" + + "Apple\n" + + ""; + + @Accessors(fluent = true) + @Data + public static class MppData { + @Setter(AccessLevel.NONE) private boolean isActive = true; + @Setter(AccessLevel.NONE) private String mppCode; + @Setter(AccessLevel.NONE) private String title; + + private boolean isRenewable = false; + + private String description; + private String startDate; + private String endDate; + private String internalDiscount; + private String productCode; + private String pricePlanCode1; + private String pricePlanCode2; + private String channel1; + private String channel2; + private String fileType1; + private String fileType2; + + private List couponGroups; + private List productCodes; + + private Integer gracePeriodMinute; + } + + /** + * IMPORTANT: In order to update or delete existing MPP use subscription.getName() as "mppCode" + * Don't forget after deletion of mpp delete also price plan using by deleted mpp (if it was created by ingestPP method) + **/ + + public static Subscription insertMpp(MppData mppData) { + final String DEFAULT_START_DATE = "20/03/2016 00:00:00"; + final String DEFAULT_END_DATE = "20/03/2099 00:00:00"; + final int DEFAULT_GRACE_PERIOD = 0; + + final String currencyOfDiscount = "GBP"; + final int percentageOfDiscount = 100; + + mppData.mppCode = getRandomValue("MPP_"); + mppData.title = mppData.mppCode; + + if (mppData.description == null) { mppData.description = "Description of " + mppData.mppCode; } + if (mppData.startDate == null) { mppData.startDate = DEFAULT_START_DATE; } + if (mppData.endDate == null) { mppData.endDate = DEFAULT_END_DATE; } + if (mppData.internalDiscount == null) { mppData.internalDiscount = IngestFixtureData + .getDiscountByPercentAndCurrency(currencyOfDiscount, percentageOfDiscount); } + if (mppData.gracePeriodMinute == null) { mppData.gracePeriodMinute = DEFAULT_GRACE_PERIOD; } + if (mppData.pricePlanCode1 == null) { mppData.pricePlanCode1 = getProperty(DEFAULT_USAGE_MODULE_4_INGEST_MPP); } + if (mppData.channel1 == null) { mppData.channel1 = getProperty(DEFAULT_CHANNEL); } +// if (mppData.couponGroup == null) { mppData.couponGroup = DEFAULT_COUPON_GROUP; } +// if (mppData.productCodes == null) { mppData.productCodes = DEFAULT_PRODUCT_CODES; } + + String reqBody = buildIngestMppXml(mppData, INSERT); + Response resp = executeIngestMppRequest(reqBody); + String reportId = from(resp.asString()).getString(ingestReportIdPath); + + resp = executeIngestReportRequest(reportId); + + String id = resp.asString().split(" = ")[1].replaceAll("\\.", "").trim(); + + // TODO: 7/1/2018 add wait until in case needed + SubscriptionFilter filter = new SubscriptionFilter(); + filter.setSubscriptionIdIn(id); + + return executor.executeSync(SubscriptionService.list(filter) + .setKs(getAnonymousKs())) + .results.getObjects().get(0); + } + + /** Mpp update seems to be broken */ +/* public static Subscription updateMpp(String mppCode, MppData mppData) { + mppData.mppCode = mppCode; + String reqBody = buildIngestMppXml(mppData, INGEST_ACTION_UPDATE); + Response resp = executeIngestMppRequest(reqBody); + String reportId = from(resp.asString()).getString(ingestReportIdPath); + + resp = executeIngestReportRequest(reportId); + + String id = resp.asString().split(" = ")[1].replaceAll("\\.", "").trim(); + + SubscriptionFilter filter = new SubscriptionFilter(); + filter.setSubscriptionIdIn(id); + + return executor.executeSync(SubscriptionService.list(filter) + .setKs(getAnonymousKs())) + .results.getObjects().get(0); + + // TODO: 7/1/2018 add wait until SubscriptionService.list(filter) is updated in case needed + }*/ + + public static void deleteMpp(String mppCode) { + MppData mppData = new MppData(); + mppData.mppCode = mppCode; + String reqBody = buildIngestMppXml(mppData, DELETE); + + Response resp = executeIngestMppRequest(reqBody); + String reportId = from(resp.asString()).getString(ingestReportIdPath); + + resp = executeIngestReportRequest(reportId); + + assertThat(resp.asString()).contains("delete succeeded"); + + // TODO: 7/1/2018 add wait until SubscriptionService.list(filter) is empty in case needed + } + + // private methods + private static Response executeIngestMppRequest(String reqBody) { + Response resp = given() + .header(contentTypeXml) + .header(soapActionIngestBusinessModules) + .body(reqBody) + .when() + .post(ingestUrl); + + Logger.getLogger(IngestVodUtils.class).debug(reqBody + "\n"); + Logger.getLogger(IngestVodUtils.class).debug(resp.asString()); + + assertThat(resp).isNotNull(); + assertThat(from(resp.asString()).getString(ingestStatusMessagePath)).isEqualTo("OK"); + + return resp; + } + + private static String buildIngestMppXml(MppData mppData, IngestAction action) { + Document doc = getDocument("src/test/resources/ingest_xml_templates/ingestMPP.xml"); + + // user and password + doc.getElementsByTagName("tem:username").item(0).setTextContent(getIngestBusinessModuleUserName()); + doc.getElementsByTagName("tem:password").item(0).setTextContent(getIngestBusinessModuleUserPassword()); + + // ingest + Element ingest = (Element) doc.getElementsByTagName("ingest").item(0); + ingest.setAttribute("id", mppData.mppCode); + + // multi price plan + Element mpp = (Element) ingest.getElementsByTagName("multi_price_plan").item(0); + mpp.setAttribute("code", mppData.mppCode); + mpp.setAttribute("action", action.getValue()); + mpp.setAttribute("is_active", Boolean.toString(mppData.isActive)); + + if (action.equals(DELETE)) { + return uncommentCdataSection(docToString(doc)); + } + + // title + mpp.getElementsByTagName("title").item(0).setTextContent(mppData.title); + + // description + mpp.getElementsByTagName("description").item(0).setTextContent(mppData.description); + + // start date + mpp.getElementsByTagName("start_date").item(0).setTextContent(mppData.startDate); + + // end date + mpp.getElementsByTagName("end_date").item(0).setTextContent(mppData.endDate); + + // internal discount + mpp.getElementsByTagName("internal_discount").item(0).setTextContent(mppData.internalDiscount); + + // product code + mpp.getElementsByTagName("product_code").item(0).setTextContent(mppData.productCode); + + // is renewable + mpp.getElementsByTagName("is_renewable").item(0).setTextContent(Boolean.toString(mppData.isRenewable)); + + // grace period minutes + mpp.getElementsByTagName("grace_period_minutes").item(0).setTextContent(String.valueOf(mppData.gracePeriodMinute)); + + // price plan codes + mpp.getElementsByTagName("price_plan_code").item(0).setTextContent(mppData.pricePlanCode1); + mpp.getElementsByTagName("price_plan_code").item(1).setTextContent(mppData.pricePlanCode2); + + // channels + mpp.getElementsByTagName("channel").item(0).setTextContent(mppData.channel1); + mpp.getElementsByTagName("channel").item(1).setTextContent(mppData.channel2); + + // file types + mpp.getElementsByTagName("file_type").item(0).setTextContent(mppData.fileType1); + mpp.getElementsByTagName("file_type").item(1).setTextContent(mppData.fileType2); + + // subscription coupon group + if (mppData.couponGroups != null && mppData.couponGroups.size() > 0) { + Element subscriptionCouponGroup = (Element) mpp.getElementsByTagName("subscription_coupon_group").item(0); + + for (CouponsGroup cg : mppData.couponGroups) { + subscriptionCouponGroup.appendChild(addCouponsGroup(doc, cg)); + } + } + + // product codes + if (mppData.productCodes != null && mppData.productCodes.size() > 0) { + Element productCodes = (Element) mpp.getElementsByTagName("product_codes").item(0); + + for (ProductCode pc : mppData.productCodes) { + productCodes.appendChild(addProductCode(doc, pc)); + } + } + + // uncomment cdata + return uncommentCdataSection(docToString(doc)); + } + + private static Element addCouponsGroup(Document doc, CouponsGroup cg) { + // coupon_group_id node + Element couponsGroup = doc.createElement("coupon_group_id"); + + // start_date node + if (cg.getStartDate() != null) { + Element startDate = doc.createElement("start_date"); + startDate.setTextContent(getFormattedTime(cg.getStartDate(), getTimeZone("UTC"))); + couponsGroup.appendChild(startDate); + } + + // end_date node + if (cg.getEndDate() != null) { + Element endDate = doc.createElement("end_date"); + endDate.setTextContent(getFormattedTime(cg.getEndDate(), getTimeZone("UTC"))); + couponsGroup.appendChild(endDate); + } + + // code node + if (cg.getName() != null) { + Element code = doc.createElement("code"); + code.setTextContent(cg.getName()); + couponsGroup.appendChild(code); + } + + // TODO: 8/16/2018 add relevant CouponsGroup fields in case needed + return couponsGroup; + } + + private static Element addProductCode(Document doc, ProductCode pc) { + // product_code node + Element productCode = doc.createElement("product_code"); + + // code node + if (pc.getCode() != null) { + Element code = doc.createElement("code"); + code.setTextContent(pc.getCode()); + productCode.appendChild(code); + } + + // verification_payment_gateway node + if (pc.getInappProvider() != null) { + Element verificationPaymentGateway = doc.createElement("verification_payment_gateway"); + verificationPaymentGateway.setTextContent(pc.getInappProvider()); + productCode.appendChild(verificationPaymentGateway); + } + + return productCode; + } +} diff --git a/src/test/java/com/kaltura/client/test/utils/ingestUtils/IngestPpUtils.java b/src/test/java/com/kaltura/client/test/utils/ingestUtils/IngestPpUtils.java new file mode 100644 index 000000000..08835d34c --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/ingestUtils/IngestPpUtils.java @@ -0,0 +1,204 @@ +package com.kaltura.client.test.utils.ingestUtils; + +import com.kaltura.client.Logger; +import com.kaltura.client.services.PricePlanService; +import com.kaltura.client.test.tests.enums.IngestAction; +import com.kaltura.client.test.utils.dbUtils.IngestFixtureData; +import com.kaltura.client.types.DiscountModule; +import com.kaltura.client.types.PricePlan; +import com.kaltura.client.types.PricePlanFilter; +import io.restassured.response.Response; +import lombok.AccessLevel; +import lombok.Data; +import lombok.Setter; +import lombok.experimental.Accessors; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import static com.kaltura.client.test.Properties.*; +import static com.kaltura.client.test.tests.BaseTest.*; +import static com.kaltura.client.test.tests.enums.Currency.EUR; +import static com.kaltura.client.test.tests.enums.IngestAction.DELETE; +import static com.kaltura.client.test.tests.enums.IngestAction.INSERT; +import static com.kaltura.client.test.tests.enums.IngestAction.UPDATE; +import static com.kaltura.client.test.utils.BaseUtils.getRandomValue; +import static io.restassured.RestAssured.given; +import static io.restassured.path.xml.XmlPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +public class IngestPpUtils extends BaseIngestUtils { + + private static final String ingestDataResultPath = "Envelope.Body.IngestBusinessModulesResponse.IngestBusinessModulesResult."; + private static final String ingestStatusMessagePath = ingestDataResultPath + "Status.Message"; + private static final String ingestReportIdPath = ingestDataResultPath + "ReportId"; + + @Accessors(fluent = true) + @Data + public static class PpData { + @Setter(AccessLevel.NONE) private boolean isActive = true; + @Setter(AccessLevel.NONE) private String ppCode; + + private boolean isRenewable = false; + + private String fullLifeCycle; + private String viewLifeCycle; + private String price; + private String currency; + private String discount; + + private Integer maxViews; + private Integer recurringPeriods; + } + + /** + * IMPORTANT: In order to update or delete existed price plan use pricePlan.getName() as "ppCode" + */ + public static PricePlan insertPp(PpData ppData) { + final int DEFAULT_MAX_VIEWS = 0; + final int DEFAULT_RECURRING_PERIODS = 1; + + final int defaultPercentageOfDiscount = 100; + DiscountModule discountModule = IngestFixtureData.getDiscountByPercent(defaultPercentageOfDiscount); + + ppData.ppCode = getRandomValue("AUTOPricePlan_"); + + if (ppData.fullLifeCycle == null) { + ppData.fullLifeCycle = FIVE_MINUTES_PERIOD; + } + if (ppData.viewLifeCycle == null) { + ppData.viewLifeCycle = FIVE_MINUTES_PERIOD; + } + if (ppData.maxViews == null) { + ppData.maxViews = DEFAULT_MAX_VIEWS; + } + if (ppData.price == null) { + ppData.price = getProperty(PRICE_CODE_AMOUNT); + } + if (ppData.currency == null) { + ppData.currency = EUR.getValue(); + } + if (ppData.discount == null) { + ppData.discount = discountModule.toParams().get("code").toString(); + } + if (ppData.recurringPeriods == null) { + ppData.recurringPeriods = DEFAULT_RECURRING_PERIODS; + } + + String reqBody = buildIngestPpXml(ppData, INSERT); + Response resp = executeIngestPpRequest(reqBody); + String reportId = from(resp.asString()).getString(ingestReportIdPath); + + resp = executeIngestReportRequest(reportId); + + String id = resp.asString().split(" = ")[1].trim().replaceAll("\\.", ""); + + PricePlanFilter filter = new PricePlanFilter(); + filter.setIdIn(id); + + return executor.executeSync(PricePlanService.list(filter) + .setKs(getOperatorKs())) + .results.getObjects().get(0); + } + + public static PricePlan updatePp(String ppCode, PpData ppData) { + ppData.ppCode = ppCode; + + String reqBody = buildIngestPpXml(ppData, UPDATE); + Response resp = executeIngestPpRequest(reqBody); + String reportId = from(resp.asString()).getString(ingestReportIdPath); + + resp = executeIngestReportRequest(reportId); + + String id = resp.asString().split(" = ")[1].trim().replaceAll("\\.", ""); + + PricePlanFilter filter = new PricePlanFilter(); + filter.setIdIn(id); + + return executor.executeSync(PricePlanService.list(filter) + .setKs(getOperatorKs())) + .results.getObjects().get(0); + + // TODO: 7/1/2018 add wait until PricePlanService.list(filter) is updated in case needed + } + + public static void deletePp(String ppCode) { + PpData ppData = new PpData(); + ppData.ppCode = ppCode; + String reqBody = buildIngestPpXml(ppData, DELETE); + + Response resp = executeIngestPpRequest(reqBody); + String reportId = from(resp.asString()).getString(ingestReportIdPath); + + resp = executeIngestReportRequest(reportId); + + assertThat(resp.asString()).contains("delete succeeded"); + + // TODO: 7/1/2018 add wait until SubscriptionService.list(filter) is empty in case needed + } + + //private methods + private static Response executeIngestPpRequest(String reqBody) { + Response resp = + given() + .header(contentTypeXml) + .header(soapActionIngestBusinessModules) + .body(reqBody) + .when() + .post(ingestUrl); + + Logger.getLogger(IngestPpUtils.class).debug(reqBody); + Logger.getLogger(IngestPpUtils.class).debug(resp.asString()); + + assertThat(resp).isNotNull(); + assertThat(from(resp.asString()).getString(ingestStatusMessagePath)).isEqualTo("OK"); + + return resp; + } + + private static String buildIngestPpXml(PpData ppData, IngestAction action) { + Document doc = getDocument("src/test/resources/ingest_xml_templates/ingestPP.xml"); + + // user and password + doc.getElementsByTagName("tem:username").item(0).setTextContent(getIngestBusinessModuleUserName()); + doc.getElementsByTagName("tem:password").item(0).setTextContent(getIngestBusinessModuleUserPassword()); + + // ingest + Element ingest = (Element) doc.getElementsByTagName("ingest").item(0); + ingest.setAttribute("id", "reportIngestPricePlan"); + + // price plan + Element pp = (Element) ingest.getElementsByTagName("price_plan").item(0); + pp.setAttribute("code", ppData.ppCode); + pp.setAttribute("action", action.getValue()); + pp.setAttribute("is_active", Boolean.toString(ppData.isActive)); + + if (action.equals(DELETE)) { + return uncommentCdataSection(docToString(doc)); + } + + // full life cycles + pp.getElementsByTagName("full_life_cycle").item(0).setTextContent(ppData.fullLifeCycle); + + // view life cycle + pp.getElementsByTagName("view_life_cycle").item(0).setTextContent(ppData.viewLifeCycle); + + // max views + pp.getElementsByTagName("max_views").item(0).setTextContent(String.valueOf(ppData.maxViews)); + + // price code + pp.getElementsByTagName("price").item(0).setTextContent(ppData.price); + pp.getElementsByTagName("currency").item(0).setTextContent(ppData.currency); + + // discount + pp.getElementsByTagName("discount").item(0).setTextContent(ppData.discount); + + // is renewable + pp.getElementsByTagName("is_renewable").item(0).setTextContent(Boolean.toString(ppData.isRenewable)); + + // recurring periods + pp.getElementsByTagName("recurring_periods").item(0).setTextContent(String.valueOf(ppData.recurringPeriods)); + + // uncomment cdata + return uncommentCdataSection(docToString(doc)); + } +} diff --git a/src/test/java/com/kaltura/client/test/utils/ingestUtils/IngestPpvUtils.java b/src/test/java/com/kaltura/client/test/utils/ingestUtils/IngestPpvUtils.java new file mode 100644 index 000000000..20b75682e --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/ingestUtils/IngestPpvUtils.java @@ -0,0 +1,190 @@ +package com.kaltura.client.test.utils.ingestUtils; + +import com.kaltura.client.Logger; +import com.kaltura.client.test.tests.enums.IngestAction; +import com.kaltura.client.types.CouponsGroup; +import com.kaltura.client.types.Ppv; +import io.restassured.response.Response; +import lombok.AccessLevel; +import lombok.Data; +import lombok.Setter; +import lombok.experimental.Accessors; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import static com.kaltura.client.services.PpvService.get; +import static com.kaltura.client.test.Properties.*; +import static com.kaltura.client.test.tests.BaseTest.*; +import static com.kaltura.client.test.tests.enums.Currency.EUR; +import static com.kaltura.client.test.tests.enums.IngestAction.DELETE; +import static com.kaltura.client.test.tests.enums.IngestAction.INSERT; +import static com.kaltura.client.test.tests.enums.IngestAction.UPDATE; +import static com.kaltura.client.test.utils.BaseUtils.getRandomValue; +import static io.restassured.RestAssured.given; +import static io.restassured.path.xml.XmlPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +public class IngestPpvUtils extends BaseIngestUtils { + + private static final String ingestDataResultPath = "Envelope.Body.IngestBusinessModulesResponse.IngestBusinessModulesResult."; + private static final String ingestStatusMessagePath = ingestDataResultPath + "Status.Message"; + private static final String ingestReportIdPath = ingestDataResultPath + "ReportId"; + + @Accessors(fluent = true) + @Data + public static class PpvData { + @Setter(AccessLevel.NONE) private boolean isActive = true; + @Setter(AccessLevel.NONE) private String ppvCode; + + private boolean isSubscriptionOnly = false; + private boolean isFirstDeviceLimitation = false; + + private String description; + private String discountCode; + private String currency; + private String usageModule; + private String productCode; + private String firstFileType; + private String secondFileType; + + private Double price; + + private CouponsGroup couponGroup; + } + + /** IMPORTANT: In order to update or delete existed ppv use ppv.getName() as "ppvCode" */ + + public static Ppv insertPpv(PpvData ppvData) { + ppvData.ppvCode = getRandomValue("PPV_"); + + if (ppvData.description == null) { ppvData.description = ppvData.ppvCode; } + if (ppvData.price == null) { ppvData.price = Double.valueOf(COMMON_PRICE_CODE_AMOUNT); } + if (ppvData.currency == null) { ppvData.currency = EUR.getValue(); } + if (ppvData.usageModule == null) { ppvData.usageModule = getProperty(DEFAULT_USAGE_MODULE_4_INGEST_PPV); } + if (ppvData.productCode == null) { ppvData.productCode = getProperty(DEFAULT_PRODUCT_CODE); } + if (ppvData.firstFileType == null) { ppvData.firstFileType = getProperty(WEB_FILE_TYPE); } + if (ppvData.secondFileType == null) { ppvData.secondFileType = getProperty(MOBILE_FILE_TYPE); } + + String reqBody = buildIngestPpvXml(ppvData, INSERT); + Response resp = executeIngestPpvRequest(reqBody); + String reportId = from(resp.asString()).getString(ingestReportIdPath); + + resp = executeIngestReportRequest(reportId); + + String id = resp.asString().split(" = ")[1].replaceAll("\\.", "").trim(); + + // TODO: 7/1/2018 add wait until in case needed + return executor.executeSync(get(Long.valueOf(id)) + .setKs(getOperatorKs())) + .results; + } + + public static Ppv updatePpv(String ppvCode, PpvData ppvData) { + ppvData.ppvCode = ppvCode; + + String reqBody = buildIngestPpvXml(ppvData, UPDATE); + Response resp = executeIngestPpvRequest(reqBody); + String reportId = from(resp.asString()).getString(ingestReportIdPath); + + resp = executeIngestReportRequest(reportId); + + String id = resp.asString().split(" = ")[1].replaceAll("\\.", "").trim(); + + // TODO: 7/1/2018 add wait until in case needed + return executor.executeSync(get(Long.valueOf(id)) + .setKs(getOperatorKs())) + .results; + } + + public static void deletePpv(String ppvCode) { + PpvData ppvData = new PpvData(); + ppvData.ppvCode = ppvCode; + String reqBody = buildIngestPpvXml(ppvData, DELETE); + + Response resp = executeIngestPpvRequest(reqBody); + String reportId = from(resp.asString()).getString(ingestReportIdPath); + + resp = executeIngestReportRequest(reportId); + + assertThat(resp.asString()).contains("delete succeeded"); + } + + // private methods + private static Response executeIngestPpvRequest(String reqBody) { + Response resp = + given() + .header(contentTypeXml) + .header(soapActionIngestBusinessModules) + .body(reqBody) + .when() + .post(ingestUrl); + + Logger.getLogger(IngestPpvUtils.class).debug(reqBody); + Logger.getLogger(IngestPpvUtils.class).debug(resp.asString()); + + assertThat(resp).isNotNull(); + assertThat(from(resp.asString()).getString(ingestStatusMessagePath)).isEqualTo("OK"); + + return resp; + } + + private static String buildIngestPpvXml(PpvData ppvData, IngestAction action) { + Document doc = getDocument("src/test/resources/ingest_xml_templates/ingestPPV.xml"); + + // user and password + doc.getElementsByTagName("tem:username").item(0).setTextContent(getIngestBusinessModuleUserName()); + doc.getElementsByTagName("tem:password").item(0).setTextContent(getIngestBusinessModuleUserPassword()); + + // ingest + Element ingest = (Element) doc.getElementsByTagName("ingest").item(0); + ingest.setAttribute("id", ppvData.ppvCode); + + // ppv + Element ppv = (Element) ingest.getElementsByTagName("ppv").item(0); + ppv.setAttribute("code", ppvData.ppvCode); + ppv.setAttribute("action", action.getValue()); + ppv.setAttribute("is_active", Boolean.toString(ppvData.isActive)); + + if (action.equals(DELETE)) { + return uncommentCdataSection(docToString(doc)); + } + + // description + ppv.getElementsByTagName("description").item(0).setTextContent(ppvData.description); + + // price code + ppv.getElementsByTagName("price").item(0).setTextContent(String.valueOf(ppvData.price)); + ppv.getElementsByTagName("currency").item(0).setTextContent(ppvData.currency); + + // usage module + ppv.getElementsByTagName("usage_module").item(0).setTextContent(ppvData.usageModule); + + // discount code + if (ppvData.discountCode != null) { + ppv.getElementsByTagName("discountCode").item(0).setTextContent(ppvData.discountCode); + } + + // subscription only + ppv.getElementsByTagName("subscription_only").item(0).setTextContent(Boolean.toString(ppvData.isSubscriptionOnly)); + + // first device limitation + ppv.getElementsByTagName("first_device_limitation").item(0).setTextContent(Boolean.toString(ppvData.isFirstDeviceLimitation)); + + // product_code + ppv.getElementsByTagName("product_code").item(0).setTextContent(ppvData.productCode); + + // file types + ppv.getElementsByTagName("file_type").item(0).setTextContent(ppvData.firstFileType); + ppv.getElementsByTagName("file_type").item(1).setTextContent(ppvData.secondFileType); + + + // coupon_group + if (ppvData.couponGroup != null) { + Element couponGroup = (Element) ppv.getElementsByTagName("coupon_group").item(0); + couponGroup.getElementsByTagName("code").item(0).setTextContent(ppvData.couponGroup.getName()); + } + + // uncomment cdata + return uncommentCdataSection(docToString(doc)); + } +} diff --git a/src/test/java/com/kaltura/client/test/utils/ingestUtils/IngestVodOpcUtils.java b/src/test/java/com/kaltura/client/test/utils/ingestUtils/IngestVodOpcUtils.java new file mode 100644 index 000000000..822eee162 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/ingestUtils/IngestVodOpcUtils.java @@ -0,0 +1,196 @@ +package com.kaltura.client.test.utils.ingestUtils; + +import com.kaltura.client.enums.AssetOrderBy; +import com.kaltura.client.test.tests.enums.IngestAction; +import com.kaltura.client.test.tests.enums.MediaType; +import com.kaltura.client.test.utils.BaseUtils; +import com.kaltura.client.types.*; +import com.kaltura.client.utils.response.base.Response; + +import java.util.*; + +import static com.kaltura.client.services.AssetService.list; +import static com.kaltura.client.test.tests.BaseTest.executor; +import static com.kaltura.client.test.tests.BaseTest.getAnonymousKs; +import static com.kaltura.client.test.tests.enums.IngestAction.INSERT; +import static com.kaltura.client.test.tests.enums.IngestAction.UPDATE; +import static com.kaltura.client.test.utils.BaseUtils.*; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.*; +import static com.kaltura.client.test.utils.ingestUtils.IngestVodUtils.VodFile; + +public class IngestVodOpcUtils extends BaseIngestUtils { + + private static String stringMetaValue; + private static String dateMetaValue; + private static double numberMetaValue; + private static boolean booleanMetaValue; + private static List tagMetaValue; + + // TODO: how to get these data from DB or request? + // Movie fields + public static final String mediaTextFieldName = "BoxOffice"; + public static final String mediaDateFieldName = "ReleaseDate"; + public static final String mediaNumberFieldName = "Runtime2"; + public static final String mediaBooleanFieldName = "IsAgeLimited"; + public static final String mediaTagFieldName = "Actors"; + + // Episode fields + public static final String episodeTextFieldName = "TwitterHashtag"; + public static final String episodeDateFieldName = "Date"; + public static final String episodeNumberFieldName = "CommonIpAddress"; + public static final String episodeBooleanFieldName = "CyyNCAh"; + public static final String episodeTagFieldName = "Studio"; + + // Series fields + public static final String seriesTextFieldName = "SeriesID"; + public static final String seriesDateFieldName = "DateField"; + public static final String seriesNumberFieldName = "ReleaseYear"; + public static final String seriesBooleanFieldName = "IsWestern"; + public static final String seriesTagFieldName = "Studio"; + + // fields & values + private static HashMap stringMetaMap = new HashMap<>(); + private static HashMap numberMetaMap = new HashMap<>(); + private static HashMap booleanHashMap = new HashMap<>(); + private static HashMap datesMetaMap = new HashMap<>(); + private static HashMap> tagsMetaMap = new HashMap<>(); + + private static String tagValue1 = "Jack Nicholson"; + private static String tagValue2 = "Natalie Portman"; + + public static VodData getVodData(MediaType mediaType, IngestAction action) { + if (action == INSERT) { + initDefaultValues4Insert(mediaType); + } else if (action == UPDATE) { + initDefaultValues4Update(booleanMetaValue, mediaType); + } + + VodData data = new VodData() + .setDefaultValues() + .stringsMeta(stringMetaMap) + .booleansMeta(booleanHashMap) + .numbersMeta(numberMetaMap) + .datesMeta(datesMetaMap) + .tags(tagsMetaMap); + + switch (mediaType) { + case MOVIE: + data.mediaType(MediaType.MOVIE).isVirtual(false).setDefaultTagsAndMetas(); + return data; + case EPISODE: + data.mediaType(MediaType.EPISODE).isVirtual(false).setDefaultTagsAndMetas(); + return data; + case SERIES: + data.mediaType(MediaType.SERIES).isVirtual(true).setDefaultTagsAndMetas(); + return data; + case LINEAR: + data.mediaType(MediaType.LINEAR).isVirtual(false).setDefaultTagsAndMetas(); + return data; + default: + data.isVirtual(false); + return data; +// return null; + } + } + + private static void initDefaultValues4Update(boolean previousValue, MediaType mediaType) { + stringMetaValue = "stringMetaValue_" + getCurrentDateInFormat("MM/dd/yyyy") + "_updated"; + dateMetaValue = getOffsetDateInFormat(1, "MM/dd/yyyy"); + numberMetaValue = Math.round(getRandomDouble() * 100.0) / 100.0; + booleanMetaValue = !previousValue; + tagMetaValue = Arrays.asList(tagValue1 + "_updated", tagValue2 + "_updated", stringMetaValue + "_updated"); + + fillMapsWithData(mediaType); + } + + private static void initDefaultValues4Insert(MediaType mediaType) { + stringMetaValue = "stringMetaValue_" + getCurrentDateInFormat("MM/dd/yyyy"); + dateMetaValue = getCurrentDateInFormat("MM/dd/yyyy"); + numberMetaValue = Math.round(getRandomDouble() * 100.0) / 100.0; + booleanMetaValue = getRandomBoolean(); + tagMetaValue = Arrays.asList(tagValue1, tagValue2, stringMetaValue); + + fillMapsWithData(mediaType); + } + + private static void fillMapsWithData(MediaType mediaType) { + stringMetaMap = new HashMap<>(); + numberMetaMap = new HashMap<>(); + booleanHashMap = new HashMap<>(); + datesMetaMap = new HashMap<>(); + tagsMetaMap = new HashMap<>(); + + switch (mediaType) { + case MOVIE: + stringMetaMap.put(mediaTextFieldName, stringMetaValue); + numberMetaMap.put(mediaNumberFieldName, numberMetaValue); + datesMetaMap.put(mediaDateFieldName, dateMetaValue); + booleanHashMap.put(mediaBooleanFieldName, booleanMetaValue); + tagsMetaMap.put(mediaTagFieldName, tagMetaValue); + break; + + case EPISODE: + stringMetaMap.put(episodeTextFieldName, stringMetaValue); + numberMetaMap.put(episodeNumberFieldName, numberMetaValue); + datesMetaMap.put(episodeDateFieldName, dateMetaValue); + booleanHashMap.put(episodeBooleanFieldName, booleanMetaValue); + tagsMetaMap.put(episodeTagFieldName, tagMetaValue); + break; + + case SERIES: + stringMetaMap.put(seriesTextFieldName, stringMetaValue); + numberMetaMap.put(seriesNumberFieldName, numberMetaValue); + datesMetaMap.put(seriesDateFieldName, dateMetaValue); + booleanHashMap.put(seriesBooleanFieldName, booleanMetaValue); + tagsMetaMap.put(seriesTagFieldName, tagMetaValue); + break; + + default: + break; + } + } + + public static String getCoguidOfActiveMediaAsset(int assetType) { + SearchAssetFilter assetFilter = new SearchAssetFilter(); + assetFilter.setOrderBy(AssetOrderBy.CREATE_DATE_DESC.getValue()); + assetFilter.setTypeIn(String.valueOf(assetType)); + FilterPager pager = new FilterPager(); + pager.setPageSize(1); + pager.setPageIndex(1); + + Response> assetListResponse = executor.executeSync(list(assetFilter, pager) + .setKs(getAnonymousKs())); + + return assetListResponse.results.getObjects().get(0).getExternalId(); + } + + public static List get2AssetFiles(String fileType1, String fileType2, String ppvs1, String ppvs2) { + List result = new ArrayList<>(); + + long e = getEpoch(); + String r = String.valueOf(BaseUtils.getRandomLong()); + + String coguid1 = "file_1_" + e + "_" + r; + String coguid2 = "file_2_" + e + "_" + r; + + VodFile file1 = new VodFile(fileType1, ppvs1).coguid(coguid1); + VodFile file2 = new VodFile(fileType2, ppvs2).coguid(coguid2); + + result.add(file1); + result.add(file2); + + return result; + } + + public static boolean isTagValueFound(String value2Found, Asset asset) { + Map tags = asset.getTags(); + Map.Entry entry = tags.entrySet().iterator().next(); + List tagsValues = entry.getValue().getObjects(); + for (MultilingualStringValue tagValue: tagsValues) { + if (value2Found.equals(tagValue.getValue())) { + return true; + } + } + return false; + } +} diff --git a/src/test/java/com/kaltura/client/test/utils/ingestUtils/IngestVodUtils.java b/src/test/java/com/kaltura/client/test/utils/ingestUtils/IngestVodUtils.java new file mode 100644 index 000000000..5869b2172 --- /dev/null +++ b/src/test/java/com/kaltura/client/test/utils/ingestUtils/IngestVodUtils.java @@ -0,0 +1,661 @@ +package com.kaltura.client.test.utils.ingestUtils; + +import com.kaltura.client.Logger; +import com.kaltura.client.enums.AssetReferenceType; +import com.kaltura.client.test.tests.enums.IngestAction; +import com.kaltura.client.test.tests.enums.MediaType; +import com.kaltura.client.test.utils.dbUtils.DBUtils; +import com.kaltura.client.types.Asset; +import com.kaltura.client.types.MediaAsset; +import io.restassured.response.Response; +import lombok.Data; +import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import java.util.*; +import java.util.concurrent.TimeUnit; + +import static com.google.common.base.Verify.verify; +import static com.kaltura.client.services.AssetService.GetAssetBuilder; +import static com.kaltura.client.services.AssetService.get; +import static com.kaltura.client.test.tests.BaseTest.*; +import static com.kaltura.client.test.tests.enums.IngestAction.*; +import static com.kaltura.client.test.utils.BaseUtils.*; +import static io.restassured.RestAssured.given; +import static io.restassured.path.xml.XmlPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public class IngestVodUtils extends BaseIngestUtils { + + // response paths + private static final String ingestDataResultPath = "Envelope.Body.IngestTvinciDataResponse.IngestTvinciDataResult."; + private static final String ingestAssetStatusPath = ingestDataResultPath + "AssetsStatus.IngestAssetStatus[0]."; + + public static final String ingestStatusMessagePath = ingestDataResultPath + "IngestStatus.Message"; + public static final String ingestStatusPath = ingestDataResultPath + "status"; + public static final String ingestAssetStatusMessagePath = ingestAssetStatusPath + "Status.Message"; + public static final String ingestAssetStatusWarningMessagePath = ingestAssetStatusPath + "Warnings.Status.Message"; + public static final String ingestAssetIdPath = ingestAssetStatusPath + "InternalAssetId"; + + private static final String datePattern = "dd/MM/yyyy hh:mm:ss"; + private static final String endDateValue = "14/10/2099 17:00:00"; + private static final String offsetDateValue = getOffsetDateInFormat(-1, datePattern); + + private static final List ppvNames = DBUtils.getPpvNames(2); + + @Accessors(fluent = true) + @Data + public static class VodData { + private boolean isActive = true; + private boolean isVirtual = false; + private boolean isErase = false; + + private String coguid; + private String name; + private String description; + private String lang; + private String thumbUrl; + private String catalogStartDate; + private String catalogEndDate; + private String startDate; + private String endDate; + private String ppvWebName; + private String ppvMobileName; + private String geoBlockRule; + + private MediaType mediaType; + + private Map> tags; + private Map stringsMeta; + private Map datesMeta; + private Map numbersMeta; + private Map booleansMeta; + + private Map multilingualName; + private Map multilingualDescription; + private Map> multilingualStringsMeta; + private Map>> multilingualTags; + + private List thumbRatios; + private List files; + + private String customMediaType; + + public VodData setDefaultValues() { + coguid = String.valueOf(getEpochInMillis()); + name = coguid; + description = "description of " + coguid; + lang = DEFAULT_LANGUAGE; + thumbUrl = DEFAULT_THUMB; + catalogStartDate = offsetDateValue; + catalogEndDate = endDateValue; + startDate = offsetDateValue; + endDate = endDateValue; + mediaType = MediaType.MOVIE; + ppvWebName = ppvNames.get(0); + ppvMobileName = ppvNames.get(1); + files = getDefaultAssetFiles(ppvWebName, ppvMobileName); + thumbRatios = Arrays.asList("4:3", "16:9"); + + return this; + } + + public VodData setDefaultTagsAndMetas() { + tags = getDefaultTags(); + stringsMeta = getDefaultStrings(); + datesMeta = getDefaultDates(); + numbersMeta = getDefaultNumbers(); + + return this; + } + + // custom setters for multilingual fields to reset the parallel regular fields + public VodData multilingualName(Map multilingualName) { + this.name = null; + this.multilingualName = multilingualName; + return this; + } + + public VodData multilingualDescription(Map multilingualDescription) { + this.description = null; + this.multilingualDescription = multilingualDescription; + return this; + } + + public VodData multilingualStringsMeta(Map> multilingualStringsMeta) { + this.stringsMeta = null; + this.multilingualStringsMeta = multilingualStringsMeta; + return this; + } + + public VodData multilingualTags(Map>> multilingualTags) { + this.tags = null; + this.multilingualTags = multilingualTags; + return this; + } + } + + @Accessors(fluent = true) + @Getter + public static class VodFile { + private String quality; + private String handling_type; + private String cdn_name; + private String cdn_code; + private String alt_cdn_code; + private String billing_type; + private String product_code; + + @Setter + private String coguid; + @Setter + private String assetDuration; + @Setter + private String type; + @Setter + private String ppvModule; + + public VodFile(String type, String ppvModule) { + quality = "HIGH"; + handling_type = "CLIP"; + cdn_name = "Default CDN"; + cdn_code = "http://cdntesting.qa.mkaltura.com/p/231/sp/23100/playManifest/entryId/0_3ugsts44/format/hdnetworkmanifest/tags/mbr/protocol/http/f/a.a4m"; + alt_cdn_code = "http://alt_cdntesting.qa.mkaltura.com/p/231/sp/23100/playManifest/entryId/0_3ugsts44/format/hdnetworkmanifest/tags/mbr/protocol/http/f/a.a4m"; + billing_type = "Tvinci"; + product_code = "productExampleCode"; + assetDuration = "1000"; + + coguid = "file_" + getEpoch() + "_" + getRandomLong(); + this.type = type; + this.ppvModule = ppvModule; + } + } + + /** + * IMPORTANT: In order to update or delete existing asset use asset.getName() as "coguid" + **/ + public static MediaAsset insertVod(VodData vodData, boolean useDefaultValues) { + if (vodData.coguid == null) { + vodData.coguid = String.valueOf(getEpochInMillis()); + } + + if (useDefaultValues) { + if (vodData.name == null) { + vodData.name = vodData.coguid; + } + if (vodData.description == null) { + vodData.description = "description of " + vodData.coguid; + } + if (vodData.lang == null) { + vodData.lang = DEFAULT_LANGUAGE; + } + if (vodData.thumbUrl == null) { + vodData.thumbUrl = DEFAULT_THUMB; + } + if (vodData.catalogStartDate == null) { + vodData.catalogStartDate = offsetDateValue; + } + if (vodData.catalogEndDate == null) { + vodData.catalogEndDate = endDateValue; + } + if (vodData.startDate == null) { + vodData.startDate = offsetDateValue; + } + if (vodData.endDate == null) { + vodData.endDate = endDateValue; + } + if (vodData.mediaType == null) { + vodData.mediaType = MediaType.MOVIE; + } + if (vodData.tags == null) { + vodData.tags = getDefaultTags(); + } + if (vodData.stringsMeta == null) { + vodData.stringsMeta = getDefaultStrings(); + } + if (vodData.datesMeta == null) { + vodData.datesMeta = getDefaultDates(); + } + if (vodData.numbersMeta == null) { + vodData.numbersMeta = getDefaultNumbers(); + } + if (vodData.ppvWebName == null) { + vodData.ppvWebName = ppvNames.get(0); + } + if (vodData.ppvMobileName == null) { + vodData.ppvMobileName = ppvNames.get(1); + } + if (vodData.files == null) { + vodData.files = getDefaultAssetFiles(vodData.ppvWebName, vodData.ppvMobileName); + } + if (vodData.thumbRatios == null) { + vodData.thumbRatios = Arrays.asList("4:3", "16:9"); + } + } + + String reqBody = buildIngestVodXml(vodData, INSERT); + + Response resp = executeIngestVodRequestWithAssertion(reqBody); + String id = from(resp.asString()).get(ingestAssetIdPath).toString(); + + GetAssetBuilder getAssetBuilder = get(id, AssetReferenceType.MEDIA).setKs(getAnonymousKs()); + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() -> (executor.executeSync(getAssetBuilder).error == null)); + + Asset asset = executor.executeSync(getAssetBuilder).results; + verify(asset.getId().toString().equals(id)); + return (MediaAsset) asset; + } + + public static MediaAsset updateVod(String coguid, VodData vodData) { + vodData.coguid = coguid; + String reqBody = buildIngestVodXml(vodData, UPDATE); + + Response resp = executeIngestVodRequestWithAssertion(reqBody); + String id = from(resp.asString()).get(ingestAssetIdPath).toString(); + + GetAssetBuilder getAssetBuilder = get(id, AssetReferenceType.MEDIA).setKs(getAnonymousKs()); + await() + .pollInterval(delayBetweenRetriesInSeconds, TimeUnit.SECONDS) + .atMost(maxTimeExpectingValidResponseInSeconds, TimeUnit.SECONDS) + .until(() -> (executor.executeSync(getAssetBuilder).error == null)); + + Asset asset = executor.executeSync(getAssetBuilder).results; + verify(asset.getId().toString().equals(id)); + return (MediaAsset) asset; + } + + public static void deleteVod(String coguid) { + VodData vodData = new VodData(); + vodData.coguid = coguid; + String reqBody = buildIngestVodXml(vodData, DELETE); + + Response resp = executeIngestVodRequestWithAssertion(reqBody); + + // on delete it returns media id + // assertThat(from(resp.asString()).getInt(ingestAssetIdPath)).isEqualTo(0); + } + + public static Response executeIngestVodRequest(String reqBody) { + Response resp = given() + .header(contentTypeXml) + .header(soapActionIngestTvinciData) + .body(reqBody) + .when() + .post(ingestUrl); + + assertThat(resp).isNotNull(); + + Logger.getLogger(IngestVodUtils.class).debug(reqBody + "\n"); + Logger.getLogger(IngestVodUtils.class).debug(resp.asString()); + + return resp; + } + + // private methods + private static Response executeIngestVodRequestWithAssertion(String reqBody) { + Response resp = executeIngestVodRequest(reqBody); + + assertThat(from(resp.asString()).getString(ingestStatusMessagePath)).isEqualTo("OK"); + assertThat(from(resp.asString()).getString(ingestAssetStatusMessagePath)).isEqualTo("OK"); + + return resp; + } + + public static String buildIngestVodXml(VodData vodData, IngestAction action) { + Document doc = getDocument("src/test/resources/ingest_xml_templates/ingestVOD.xml"); + + // user and password + if (vodData.isVirtual()) { + doc.getElementsByTagName("userName").item(0).setTextContent(getIngestVirtualAssetUserName()); + doc.getElementsByTagName("passWord").item(0).setTextContent(getIngestVirualAssetUserPassword()); + } else { + doc.getElementsByTagName("userName").item(0).setTextContent(getIngestAssetUserName()); + doc.getElementsByTagName("passWord").item(0).setTextContent(getIngestAssetUserPassword()); + } + + // add CDATA section +// CDATASection cdata = doc.createCDATASection(""); +// doc.getElementsByTagName("tem:request").item(0).appendChild(cdata); + + // media + Element media = (Element) doc.getElementsByTagName("media").item(0); + media.setAttribute("co_guid", vodData.coguid()); + media.setAttribute("entry_id", "entry_" + vodData.coguid()); + media.setAttribute("action", action.getValue()); + media.setAttribute("is_active", Boolean.toString(vodData.isActive())); + media.setAttribute("erase", Boolean.toString(vodData.isErase())); + + if (action.equals(DELETE)) { + return uncommentCdataSection(docToString(doc)); + } + + // name + if (vodData.name() != null) { + Element nameElement = (Element) media.getElementsByTagName("name").item(0); + Element value = doc.createElement("value"); + value.setAttribute("lang", vodData.lang != null ? vodData.lang : DEFAULT_LANGUAGE); + value.setTextContent(vodData.name); + nameElement.appendChild(value); + } + + // thumb + if (vodData.thumbUrl() != null) { + Element thumb = (Element) media.getElementsByTagName("thumb").item(0); + thumb.setAttribute("url", vodData.thumbUrl()); + } + + // description + if (vodData.description() != null) { + Element descriptionElement = (Element) media.getElementsByTagName("description").item(0); + Element value = doc.createElement("value"); + value.setAttribute("lang", vodData.lang != null ? vodData.lang : DEFAULT_LANGUAGE); + value.setTextContent(vodData.description); + descriptionElement.appendChild(value); + } + + // dates + Element datesElement = (Element) media.getElementsByTagName("dates").item(0); + if (vodData.catalogStartDate() != null) { + datesElement.getElementsByTagName("catalog_start").item(0).setTextContent(vodData.catalogStartDate()); + } + if (vodData.startDate() != null) { + datesElement.getElementsByTagName("start").item(0).setTextContent(vodData.startDate()); + } + if (vodData.catalogEndDate() != null) { + datesElement.getElementsByTagName("catalog_end").item(0).setTextContent(vodData.catalogEndDate()); + } + if (vodData.endDate() != null) { + datesElement.getElementsByTagName("end").item(0).setTextContent(vodData.endDate()); + } + + // pic_ratios + if (vodData.thumbRatios() != null && vodData.thumbRatios().size() > 0) { + Element picRatios = (Element) media.getElementsByTagName("pic_ratios").item(0); + vodData.thumbRatios().forEach(s -> { + Element ratio = doc.createElement("ratio"); + ratio.setAttribute("ratio", s); + ratio.setAttribute("thumb", vodData.thumbUrl() != null ? vodData.thumbUrl() : BaseIngestUtils.DEFAULT_THUMB); + picRatios.appendChild(ratio); + }); + } + + // media type + if (vodData.customMediaType() != null) { + vodData.mediaType(null); + media.getElementsByTagName("media_type").item(0).setTextContent(vodData.customMediaType()); + } + + if (vodData.mediaType() != null) { + media.getElementsByTagName("media_type").item(0).setTextContent(vodData.mediaType().getValue()); + } + + // geo block rule + if (vodData.geoBlockRule() != null) { + media.getElementsByTagName("geo_block_rule").item(0).setTextContent(vodData.geoBlockRule()); + } + + // stringsMeta + if (vodData.stringsMeta() != null) { + Element stringsElement = (Element) media.getElementsByTagName("strings").item(0); + for (Map.Entry entry : vodData.stringsMeta().entrySet()) { + // meta node + Element meta = generateAndAppendMetaNode(doc, stringsElement, entry.getKey()); + + // value node + Element value = doc.createElement("value"); + value.setAttribute("lang", DEFAULT_LANGUAGE); + value.setTextContent(entry.getValue()); + meta.appendChild(value); + } + } + + // booleansMeta + if (vodData.booleansMeta() != null) { + Element booleansElement = (Element) media.getElementsByTagName("booleans").item(0); + for (Map.Entry entry : vodData.booleansMeta().entrySet()) { + // meta node + Element meta = generateAndAppendMetaNode(doc, booleansElement, entry.getKey()); + meta.setTextContent(String.valueOf(entry.getValue())); + } + } + + // doublesMeta + if (vodData.numbersMeta() != null) { + Element doublesElement = (Element) media.getElementsByTagName("doubles").item(0); + for (Map.Entry entry : vodData.numbersMeta().entrySet()) { + // meta node + Element meta = generateAndAppendMetaNode(doc, doublesElement, entry.getKey()); + meta.setTextContent(String.valueOf(entry.getValue())); + } + } + + // datesMeta + if (vodData.datesMeta() != null) { + Element datesMetaElement = (Element) media.getElementsByTagName("dates").item(1); + for (Map.Entry entry : vodData.datesMeta().entrySet()) { + // meta node + Element metaElement = generateAndAppendMetaNode(doc, datesMetaElement, entry.getKey()); + metaElement.setTextContent(entry.getValue()); + } + } + + // tags + if (vodData.tags() != null) { + Element metasElement = (Element) media.getElementsByTagName("metas").item(0); + for (Map.Entry> entry : vodData.tags().entrySet()) { + // meta node + Element metaElement = generateAndAppendMetaNode(doc, metasElement, entry.getKey()); + if (entry.getValue() != null) { + // container node + for (String s : entry.getValue()) { + Element container = doc.createElement("container"); + metaElement.appendChild(container); + + // value node + Element value = doc.createElement("value"); + value.setTextContent(s); + value.setAttribute("lang", DEFAULT_LANGUAGE); + container.appendChild(value); + } + } + } + } + + // files + if (vodData.files != null && vodData.files.size() > 0) { + Element files = (Element) media.getElementsByTagName("files").item(0); + + for (VodFile vodFile : vodData.files) { + files.appendChild(addFile(doc, vodFile)); + } + } + + // multilingual fields + // multilingual name + if (vodData.multilingualName() != null) { + Element nameElement = (Element) media.getElementsByTagName("name").item(0); + vodData.multilingualName().forEach((lang, name) -> { + Element value = doc.createElement("value"); + value.setAttribute("lang", lang); + value.setTextContent(name); + nameElement.appendChild(value); + }); + } + + // multilingual description + if (vodData.multilingualDescription() != null) { + Element descriptionElement = (Element) media.getElementsByTagName("description").item(0); + vodData.multilingualDescription.forEach((lang, name) -> { + Element value = doc.createElement("value"); + value.setAttribute("lang", lang); + value.setTextContent(name); + descriptionElement.appendChild(value); + }); + } + + // multilingual stringsMeta + if (vodData.multilingualStringsMeta() != null) { + Element stringsElement = (Element) media.getElementsByTagName("strings").item(0); + vodData.multilingualStringsMeta().forEach((meta, langValueMap) -> { + // meta node + Element metaElement = generateAndAppendMetaNode(doc, stringsElement, meta); + langValueMap.forEach((lang, name) -> { + // value node + Element value = doc.createElement("value"); + value.setAttribute("lang", lang); + value.setTextContent(name); + metaElement.appendChild(value); + }); + }); + } + + // multilingual tags + if (vodData.multilingualTags() != null) { + Element metasElement = (Element) media.getElementsByTagName("metas").item(0); + vodData.multilingualTags().forEach((tag, tagsValuesMap) -> { + // meta node + Element metaElement = generateAndAppendMetaNode(doc, metasElement, tag); + tagsValuesMap.forEach(langValueMap -> { + // container node + Element container = doc.createElement("container"); + metaElement.appendChild(container); + langValueMap.forEach((lang, name) -> { + // value node + Element value = doc.createElement("value"); + value.setAttribute("lang", lang); + value.setTextContent(name); + container.appendChild(value); + }); + }); + }); + } + + // uncomment cdata + String docAsString = docToString(doc); + return uncommentCdataSection(docAsString); + } + + private static Element addFile(Document doc, VodFile vodFile) { + // file node + Element file = doc.createElement("file"); + + if (vodFile.assetDuration != null) { + file.setAttribute("assetDuration", vodFile.assetDuration); + } + if (vodFile.quality != null) { + file.setAttribute("quality", vodFile.quality); + } + if (vodFile.handling_type != null) { + file.setAttribute("handling_type", vodFile.handling_type); + } + if (vodFile.cdn_name != null) { + file.setAttribute("cdn_name", vodFile.cdn_name); + } + if (vodFile.cdn_code != null) { + file.setAttribute("cdn_code", vodFile.cdn_code); + } + if (vodFile.alt_cdn_code != null) { + file.setAttribute("alt_cdn_code", vodFile.alt_cdn_code); + } + if (vodFile.billing_type != null) { + file.setAttribute("billing_type", vodFile.billing_type); + } + if (vodFile.product_code != null) { + file.setAttribute("product_code", vodFile.product_code); + } + if (vodFile.coguid != null) { + file.setAttribute("co_guid", vodFile.coguid); + } + if (vodFile.type != null) { + file.setAttribute("type", vodFile.type); + } + if (vodFile.ppvModule != null) { + file.setAttribute("PPV_MODULE", vodFile.ppvModule); + } + + return file; + } + + private static Element generateAndAppendMetaNode(Document doc, Element rootElement, String name) { + // meta node + Element meta = doc.createElement("meta"); + meta.setAttribute("name", name); + meta.setAttribute("ml_handling", "unique"); + rootElement.appendChild(meta); + + return meta; + } + + // TODO: these values should be get in another way than now + private static Map> getDefaultTags() { + Map> tags = new HashMap<>(); + + List tagValues = new ArrayList<>(); + tagValues.add("Costa Rica;Israel"); + tags.put("Country", tagValues); + + tagValues = new ArrayList<>(); + tagValues.add("GIH"); + tagValues.add("ABC"); + tagValues.add("DEF"); + tags.put("Genre", tagValues); + + tagValues = new ArrayList<>(); + tagValues.add("Shay_Series"); + tags.put("Series name", tagValues); + + tagValues = new ArrayList<>(); + tagValues.add("KSQL channel_573349"); + tags.put("Free", tagValues); + + tagValues = new ArrayList<>(); + tags.put("Parental Rating", tagValues); + + return tags; + } + + // TODO: these values should be get in another way than now + private static Map getDefaultStrings() { + Map strings = new HashMap<>(); + strings.put("Synopsis", "syno pino sister"); + strings.put("meta_name", "meta_value"); + + return strings; + } + + // TODO: these values should be get in another way than now + private static Map getDefaultNumbers() { + Map doubles = new HashMap<>(); + doubles.put("Release year", 1900d); + + return doubles; + } + + // TODO: these values should be get in another way than now + private static Map getDefaultDates() { + Map dates = new HashMap<>(); + dates.put("Life cycle start date", "23/03/2017 12:34:56"); + + return dates; + } + + public static List getDefaultAssetFiles(String ppvModuleName1, String ppvModuleName2) { + List assetFiles = new ArrayList<>(); + List fileTypeNames = DBUtils.getMediaFileTypeNames(2); + + VodFile file1 = new VodFile(fileTypeNames.get(0), ppvModuleName1); + VodFile file2 = new VodFile(fileTypeNames.get(1), ppvModuleName2); + + assetFiles.add(file1); + assetFiles.add(file2); + + return assetFiles; + } +} diff --git a/src/test/java/resources/ott.test.template.properties b/src/test/java/resources/ott.test.template.properties deleted file mode 100644 index e0360c236..000000000 --- a/src/test/java/resources/ott.test.template.properties +++ /dev/null @@ -1,5 +0,0 @@ -partnerId=@YOUR_PARTNER_ID@ -serviceUrl=@SERVICE_URL@ -userName=@USER_NAME@ -userPassword=@USER_PASSWORD@ -mediaId=@MEDIA_ID@ diff --git a/src/test/resources/WORK_PLAN.md b/src/test/resources/WORK_PLAN.md new file mode 100644 index 000000000..29efc3b4f --- /dev/null +++ b/src/test/resources/WORK_PLAN.md @@ -0,0 +1,180 @@ +# PHASE 1 +Migrate services tests from ReadyAPI + +# PHASE 2 +Migrate features tests from ReadyAPI + + +### Services List: + +| Service | Status | +|------------------------------|--------| +| announcement | Alon - in progress | +| appToken | Done | +| asset | Shmulik/Alon - in progress | +| assetComment | Done | +| assetFile | | +| assetHistory | Done | +| assetRule | | +| assetStatistics | Michael | +| assetUserRule | | +| bookmark | Done | +| cDVRAdapterProfile | | +| cdnAdapterProfile | | +| cdnPartnerSettings | | +| channel | Shmulik - in progress | +| collection | | +| compensation | | +| configurationGroup | | +| configurationGroupDevice | | +| configurationGroupTag | | +| configurations | | +| country | Shmulik - in progress | +| coupon | | +| couponsGroup | | +| currency | | +| deviceBrand | | +| deviceFamily | | +| email | | +| engagement | | +| engagementAdapter | | +| entitlement | Maksim - in progress, actions: cancel - done, cancelRenewal, cancelScheduledSubscription, externalReconcile, forceCancel, getNextRenewal, grant - CHECK, list - done, swap, update +| exportTask | | +| externalChannelProfile | | +| favorite | | +| followTvSeries | | +| homeNetwork | | +| household | Done | +| householdDevice | | +| householdLimitations | | +| householdPaymentGateway | | +| householdPaymentMethod | | +| householdPremiumService | | +| householdQuota | | +| householdUser | | +| inboxMessage | | +| language | | +| licensedUrl | | +| messageTemplate | | +| meta | | +| notification | | +| notificationsPartnerSettings | | +| notificationsSettings | | +| ossAdapterProfile | | +| ottCategory | | +| ottUser | Done | +| parentalRule | | +| partnerConfiguration | | +| paymentGatewayProfile | | +| paymentMethodProfile | | +| personalFeed | | +| pin | | +| ppv | | +| priceDetails | | +| pricePlan | | +| productPrice | Done | +| purchaseSettings | | +| recommendationProfile | | +| recording | | +| region | | +| registrySettings | | +| reminder | | +| report | | +| searchHistory | | +| seriesRecording | | +| session | Done | +| social | | +| socialAction | | +| socialComment | | +| socialFriendActivity | | +| subscription | | +| subscriptionSet | | +| system | | +| timeShiftedTvPartnerSettings | | +| topic | | +| transaction | Alon - in progress | +| transactionHistory | Michael - in progress | +| unifiedPayment | | +| userAssetRule | | +| userAssetsListItem | | +| userInterest | | +| userLoginPin | | +| userRole | | + + +### Features List: + +| Features | Status | +|-------------------------------------------------------------------------------------------------------|--------| +| Thor - Search recordings | | +| Thor - New DMS | | +| Thor - C-DVR bookmarks | | +| Thor - Social settings and actions | | +| Thor - Social feed | | +| Thor - Verify playback license for recordings | | +| Ultron - Delete_close household [BEO-2723] | | +| Ultron - Automated email configuration | | +| Ultron - Purchase email to be sent to the HH master only [BEO-2780] | | +| Ultron - Revoke KS | | +| Ultron - Reminders | | +| TVPAPItokens [BEO-2911] | | +| Ultron - Change subscription PM [BEO-2766] | | +| FinancialReports | | +| Ultron - Change subscription | | +| Ultron - Support for secure player playback on Phoenix | | +| Ultron - Gift Cards [BEO-2730] | | +| Vision - Elastic search events notifications | | +| Vision - Grant gift - next subscription charges discount | | +| Vision - Multi-currency support | | +| Vision - Holistic Freemium solution [BEO-3166] | | +| Vision - get seasons/episodes APIs [BEO-3234] | | +| Vision - Quota Overage [BEO-3163] | | +| Vision - Enable delete household account from TVM | | +| Vision - DRM security with DRM ID | | +| Vision - Holdback Mechanism [BEO-3122] | | +| Vision - holistic freemium solution - Ads Control as premium service (Updated in Yoda - BEO-BEO-4090] | | +| Vision - Grace period for auto-deleted recordings [BEO-3214] | | +| Vision - Cancel purchase event [BEO-3475] | | +| Wonder woman - soundex search research | | +| Wonder woman - Engagement Notification | | +| Wonder woman - Enable app-token to all users [BEO-3172] | | +| WW - Multiple coupons per subscription [BEO-2643] | | +| Wonder Woman - Maxmind enchancements [BEO-3523] | | +| WW - Multiple subscription product codes [BEO-3631] | | +| Wonder woman - subscription dependencies_groups [BEO-3516] | | +| Wonder woman - Interests | | +| Wonder woman - Series Reminders | | +| KSQL - exists / not exists operator | | +| WW - HouseholdDevice LoginwithPin [BEO-3787] | | +| Wonder Woman - scheduling rules - add rule end-date [BEO-3788] | | +| Xena - Dependency subscriptionset [BEO-3840] | | +| Xena - Package price update from BSS [BEO-3796] | | +| Xena - Content de-duplication in a channel list [BEO-3854] | | +| Xena - KalturaScheduledRecordingProgramFilter [BEO-3890] | | +| Xena - unified billing cycle [BEO-4022] | | +| Yoda - aggregated renewals transaction [BEO-4023] | | +| Yoda - Graceful subscription renewal for external wallet[BEO-3940] | | +| Yoda - Email OTP enablement [BEO-4085] | | +| Yoda - Suspend/Resume Household service (Profiles)[BEO-4088] | Tests moved to HouseholdSuspendTests | +| Zatanna - Improving concurrency - group of media assets[BEO-4294] | | +| Zatanna - Concurrency EPG [BEO - 4255] | | +| Zatanna - Collections | | +| Zatanna - Improving concurrency - updated downgrade handling [BEO-4292] | | +| Zattana - Deleted expired VOD assets from Kaltura DB [BEO-4354] | | +| Zattana - Nagra SSP integration - New Adapter [BEO-4288] | | +| Zatanna - Next Package price [BEO-4234] | | +| Zatanna - Purchase flow adjustments [BEO-3968] | | +| Zatanna - Email for X days before renewal [BEO-4381] | | +| Zatanna - Events for end of subscriptions [BEO-4483] | | +| Zatanna - GDPR - API to delete HH data [BEO-4482] | | +| 4.7.2 - Email notifications control by the user | | +| 4.7.2 - SMS notifications | | +| 4_7_2 - Nokia nPVR - Backward compatibility | | +| 4.8 - Partial billing for promo (Coupons) [BEO-4763] | | +| 4.8 - Purchased content should not be displayed in recommendations [BEO-4764] | | +| 4.8 - Watched content should not be displayed in recommendations [BEO-4823] | | +| 4.8 - Scheduling rule for business model change[BEO-4221] | | +| 4.8 - Coupons Updates[BEO-4901] | | +| 4.8.2 - GDPR - create scripts that delete the deleted and purged HH[BEO-5010] | Tests moved to HouseholdPurgeTests | +| 4.8.2 - Multi-Geo Asset Availability Windowing | | +| 4.8.2 - Master user can hide part of the linear channel[BEO-4765] | | \ No newline at end of file diff --git a/src/test/resources/ingest_xml_templates/ingestEPG.xml b/src/test/resources/ingest_xml_templates/ingestEPG.xml new file mode 100644 index 000000000..06bbeede8 --- /dev/null +++ b/src/test/resources/ingest_xml_templates/ingestEPG.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/ingest_xml_templates/ingestMPP.xml b/src/test/resources/ingest_xml_templates/ingestMPP.xml new file mode 100644 index 000000000..5321fcaaf --- /dev/null +++ b/src/test/resources/ingest_xml_templates/ingestMPP.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + </titles> + <descriptions> + <description lang="eng"/> + </descriptions> + <start_date/> + <end_date/> + <internal_discount/> + <coupon_group/> + <product_code/> + <is_renewable/> + <priview_module/> + <grace_period_minutes/> + <price_plan_codes> + <price_plan_code/> + <price_plan_code/> + </price_plan_codes> + <channels> + <channel/> + <channel/> + </channels> + <file_types> + <file_type/> + <file_type/> + </file_types> + <order_number/> + <subscription_coupon_group/> + <product_codes/> + </multi_price_plan> + </multi_price_plans> + </ingest> + <!--]]>--> + </tem:xml> + </tem:IngestBusinessModules> + </soapenv:Body> +</soapenv:Envelope> \ No newline at end of file diff --git a/src/test/resources/ingest_xml_templates/ingestPP.xml b/src/test/resources/ingest_xml_templates/ingestPP.xml new file mode 100644 index 000000000..fea426d7e --- /dev/null +++ b/src/test/resources/ingest_xml_templates/ingestPP.xml @@ -0,0 +1,30 @@ +<?xml version='1.0' encoding='utf-8'?> +<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/"> + <soapenv:Header/> + <soapenv:Body> + <tem:IngestBusinessModules> + <tem:username/> + <tem:password/> + <tem:xml> + <!--<![CDATA[--> + <ingest> + <price_plans> + <price_plan> + <full_life_cycle/> + <view_life_cycle/> + <max_views/> + <price_code> + <price/> + <currency/> + </price_code> + <discount/> + <is_renewable/> + <recurring_periods/> + </price_plan> + </price_plans> + </ingest> + <!--]]>--> + </tem:xml> + </tem:IngestBusinessModules> + </soapenv:Body> +</soapenv:Envelope> \ No newline at end of file diff --git a/src/test/resources/ingest_xml_templates/ingestPPV.xml b/src/test/resources/ingest_xml_templates/ingestPPV.xml new file mode 100644 index 000000000..de824c843 --- /dev/null +++ b/src/test/resources/ingest_xml_templates/ingestPPV.xml @@ -0,0 +1,41 @@ +<?xml version='1.0' encoding='utf-8'?> +<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:tem='http://tempuri.org/'> + <soapenv:Header/> + <soapenv:Body> + <tem:IngestBusinessModules> + <tem:username/> + <tem:password/> + <tem:xml> + <!--<![CDATA[--> + <ingest> + <ppvs> + <ppv> + <descriptions> + <description lang="eng"/> + </descriptions> + <price_code> + <price/> + <currency/> + </price_code> + <usage_module/> + <discount/> + <coupon_group> + <code/> + </coupon_group> + <subscription_only/> + <first_device_limitation/> + <product_code/> + <file_types> + <file_type/> + <file_type/> + </file_types> + </ppv> + </ppvs> + </ingest> + <!--]]>--> + </tem:xml> + </tem:IngestBusinessModules> + </soapenv:Body> +</soapenv:Envelope> + + diff --git a/src/test/resources/ingest_xml_templates/ingestVOD.xml b/src/test/resources/ingest_xml_templates/ingestVOD.xml new file mode 100644 index 000000000..983b5a9bc --- /dev/null +++ b/src/test/resources/ingest_xml_templates/ingestVOD.xml @@ -0,0 +1,48 @@ +<?xml version='1.0' encoding='utf-8'?> +<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/"> + <soapenv:Header/> + <soapenv:Body> + <tem:IngestTvinciData> + <tem:request> + <userName/> + <passWord/> + <data> + <!--<![CDATA[--> + <feed> + <export> + <media> + <basic> + <name/> + <thumb/> + <description/> + <dates> + <catalog_start/> + <start/> + <catalog_end/> + <end/> + </dates> + <pic_ratios/> + <media_type/> + <rules> + <geo_block_rule/> + <watch_per_rule>Parent Allowed</watch_per_rule> + <device_rule/> + </rules> + </basic> + <structure> + <strings/> + <booleans/> + <doubles/> + <dates/> + <metas/> + </structure> + <files/> + </media> + </export> + </feed> + <!--]]>--> + </data> + </tem:request> + </tem:IngestTvinciData> + </soapenv:Body> +</soapenv:Envelope> \ No newline at end of file diff --git a/src/test/resources/ingest_xml_templates/test.xml b/src/test/resources/ingest_xml_templates/test.xml new file mode 100644 index 000000000..e69de29bb diff --git a/src/test/resources/permission_management_data/empty_file.txt b/src/test/resources/permission_management_data/empty_file.txt new file mode 100644 index 000000000..e69de29bb diff --git a/src/test/resources/permission_management_data/importOnly4Tables.txt b/src/test/resources/permission_management_data/importOnly4Tables.txt new file mode 100644 index 000000000..fcd358f48 --- /dev/null +++ b/src/test/resources/permission_management_data/importOnly4Tables.txt @@ -0,0 +1,30 @@ +<?xml version="1.0" standalone="yes"?> +<permissions_dataset> + <role> + <id>485</id> + <name>MaxTest1526998432</name> + </role> + <role_permission> + <id>637</id> + <role_id>485</role_id> + <permission_id>33</permission_id> + <is_excluded>0</is_excluded> + <role_name>MaxTest1526998432</role_name> + <permission_name>MaxTest1526998432</permission_name> + </role_permission> + <permission> + <id>33</id> + <name>MaxTest1526998432</name> + <type>2</type> + <users_group>partner*</users_group> + </permission> + <permission_item> + <id>548</id> + <name>Asset_List_Max1526998432</name> + <type>1</type> + <service>asset</service> + <action>list</action> + <object>permissionItemObject1526998432</object> + <parameter>parameter1526998432</parameter> + </permission_item> +</permissions_dataset> diff --git a/src/test/resources/schemas/Announcement.json b/src/test/resources/schemas/Announcement.json new file mode 100644 index 000000000..8ddfea914 --- /dev/null +++ b/src/test/resources/schemas/Announcement.json @@ -0,0 +1,88 @@ +{ + "$id": "Announcement", + "type": "object", + "properties": { + "executionTime": { + "type": "number", + "minimum": 0 + }, + "result": { + "type": "object", + "properties": { + "objectType": { + "type": "string", + "minLength": 0 + }, + "enabled": { + "type": "boolean" + }, + "id": { + "type": "integer", + "minimum": 0 + }, + "imageUrl": { + "type": "string", + "minLength": 0 + }, + "includeMail": { + "type": "boolean" + }, + "includeSms": { + "type": "boolean" + }, + "mailSubject": { + "type": "string", + "minLength": 0 + }, + "mailTemplate": { + "type": "string", + "minLength": 0 + }, + "message": { + "type": "string", + "minLength": 0 + }, + "name": { + "type": "string", + "minLength": 0 + }, + "recipients": { + "type": "string", + "minLength": 0 + }, + "startTime": { + "type": "integer", + "minimum": 0 + }, + "status": { + "type": "string", + "minLength": 0 + }, + "timezone": { + "type": "string", + "minLength": 0 + } + }, + "required": [ + "objectType", + "enabled", + "id", + "imageUrl", + "includeMail", + "includeSms", + "mailSubject", + "mailTemplate", + "message", + "name", + "recipients", + "startTime", + "status", + "timezone" + ] + } + }, + "required": [ + "executionTime", + "result" + ] +} \ No newline at end of file diff --git a/src/test/resources/schemas/Asset.json b/src/test/resources/schemas/Asset.json index 22a7e00b3..1525ba8ee 100644 --- a/src/test/resources/schemas/Asset.json +++ b/src/test/resources/schemas/Asset.json @@ -4,10 +4,7 @@ "Asset": { "type": "object", "properties": { - "objectType": { - "type": "string", - "minLength": 0 - } + "objectType": {"type": "string", "minLength": 0} } } }, diff --git a/src/test/resources/schemas/AssetCount.json b/src/test/resources/schemas/AssetCount.json new file mode 100644 index 000000000..bed7656bd --- /dev/null +++ b/src/test/resources/schemas/AssetCount.json @@ -0,0 +1,75 @@ +{ + "$id": "AssetCount", + "definitions": { + "AssetCount": { + "type": "object", + "properties": { + "objectType": { + "type": "string", + "minLength": 0 + }, + "count": { + "type": "integer", + "minimum": 0 + }, + "subs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "objectType": { + "type": "string", + "minLength": 0 + }, + "field": { + "type": "string", + "minLength": 0 + }, + "objects": { + "type": "array", + "items": { + "type": "object", + "properties": { + "objectType": { + "type": "string", + "minLength": 0 + }, + "count": { + "type": "integer", + "minimum": 0 + }, + "subs": { + "type": "array" + }, + "value": { + "type": "string", + "minLength": 0 + } + } + } + } + } + } + } + }, + "required": [ + "objectType", + "count", + "subs" + ] + } + }, + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/AssetCount" + }, + "executionTime": { + "type": "number" + } + }, + "required": [ + "result", + "executionTime" + ] +} \ No newline at end of file diff --git a/src/test/resources/schemas/AssetFileContext.json b/src/test/resources/schemas/AssetFileContext.json new file mode 100644 index 000000000..c9b4e5c99 --- /dev/null +++ b/src/test/resources/schemas/AssetFileContext.json @@ -0,0 +1,38 @@ +{ + "$id": "AssetFileContext", + "type": "object", + "properties": { + "result": { + "type": "object", + "properties": { + "fullLifeCycle": { + "type": "string" + }, + "isOfflinePlayBack": { + "type": "boolean" + }, + "viewLifeCycle": { + "type": "string" + }, + "objectType": { + "type": "string", + "enum": [ + "KalturaAssetFileContext" + ] + } + }, + "required": [ + "fullLifeCycle", + "isOfflinePlayBack", + "viewLifeCycle" + ] + }, + "executionTime": { + "type": "number" + } + }, + "required": [ + "result", + "executionTime" + ] +} \ No newline at end of file diff --git a/src/test/resources/schemas/AssetStruct.json b/src/test/resources/schemas/AssetStruct.json new file mode 100644 index 000000000..75df257d5 --- /dev/null +++ b/src/test/resources/schemas/AssetStruct.json @@ -0,0 +1,110 @@ +{ + "$id": "AssetStruct", + "definitions": { + "AssetStruct": { + "type": "object", + "properties": { + "objectType": { + "type": "string", + "enum": ["KalturaAssetStruct"] + }, + "connectedParentMetaId": { + "type": "integer", + "minimum": 0 + }, + "connectingMetaId": { + "type": "integer", + "minimum": 0 + }, + "createDate": { + "type": "integer", + "minimum": 1 + }, + "features": { + "type": "string", + "minLength": 0 + }, + "id": { + "type": "integer", + "minimum": 1 + }, + "isProtected": { + "type": "boolean" + }, + "metaIds": { + "type": "string", + "minLength": 1 + }, + "name": { + "type": "string", + "minLength": 0 + }, + "multilingualName": { + "type": "array", + "items": { + "type": "object", + "properties": { + "objectType": { + "type": "string", + "enum": ["KalturaTranslationToken"] + }, + "language": { + "type": "string", + "minLength": 3 + }, + "value": { + "type": "string" + } + }, + "required": [ + "objectType", + "language", + "value" + ] + } + }, + "parentId": { + "type": "integer", + "minimum": 0 + }, + "pluralName": { + "type": "string", + "minLength": 0 + }, + "systemName": { + "type": "string", + "minLength": 1 + }, + "updateDate": { + "type": "integer", + "minimum": 1 + } + }, + "required": [ + "id", + "connectedParentMetaId", + "connectingMetaId", + "createDate", + "features", + "isProtected", + "objectType", + "name", + "multilingualName", + "parentId", + "pluralName", + "systemName", + "updateDate" + ] + } + }, + "type": "object", + "properties": { + "executionTime": { + "type": "number", + "minimum": 0 + }, + "result": { + "ref": "#/definitions/AssetStruct" + } + } +} \ No newline at end of file diff --git a/src/test/resources/schemas/AssetStructMeta.json b/src/test/resources/schemas/AssetStructMeta.json new file mode 100644 index 000000000..b8416684c --- /dev/null +++ b/src/test/resources/schemas/AssetStructMeta.json @@ -0,0 +1,64 @@ +{ + "$id": "AssetStructMeta", + "definitions": { + "AssetStructMeta": { + "type": "object", + "properties": { + "objectType": { + "type": "string", + "enum": ["KalturaAssetStructMeta"] + }, + "assetStructId": { + "type": "integer", + "minimum": 1 + }, + "metaId": { + "type": "integer", + "minimum": 1 + }, + "ingestReferencePath": { + "type": "string", + "minLength": 0 + }, + "protectFromIngest": { + "type": "boolean" + }, + "defaultIngestValue": { + "type": "string", + "minLength": 0 + }, + "createDate": { + "type": "integer", + "minimum": 1 + }, + "updateDate": { + "type": "integer", + "minimum": 1 + }, + "isInherited": { + "type": "boolean" + } + }, + "required": [ + "assetStructId", + "metaId", + "ingestReferencePath", + "protectFromIngest", + "defaultIngestValue", + "createDate", + "updateDate", + "isInherited" + ] + } + }, + "type": "object", + "properties": { + "executionTime": { + "type": "number", + "minimum": 0 + }, + "result": { + "$ref": "#/definitions/AssetStructMeta" + } + } +} \ No newline at end of file diff --git a/src/test/resources/schemas/CouponsGroup.json b/src/test/resources/schemas/CouponsGroup.json new file mode 100644 index 000000000..9d9eddde1 --- /dev/null +++ b/src/test/resources/schemas/CouponsGroup.json @@ -0,0 +1,75 @@ +{ + "$id": "CouponsGroup", + "definitions": { + "CouponsGroup": { + "type": "object", + "properties": { + "objectType": { + "type": "string", + "minLength": 0 + }, + "couponGroupType": { + "type": "string", + "minLength": 0 + }, + "discountId": { + "type": "integer", + "minimum": 0 + }, + "endDate": { + "type": "integer", + "minimum": 0 + }, + "id": { + "type": "string", + "minLength": 0 + }, + "maxHouseholdUses": { + "type": "integer", + "minimum": 0 + }, + "maxUsesNumber": { + "type": "integer", + "minimum": 0 + }, + "maxUsesNumberOnRenewableSub": { + "type": "integer", + "minimum": 0 + }, + "name": { + "type": "string", + "minLength": 0 + }, + "startDate": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "objectType", + "couponGroupType", + "discountId", + "endDate", + "id", + "maxHouseholdUses", + "maxUsesNumber", + "maxUsesNumberOnRenewableSub", + "name", + "startDate" + ] + } + }, + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CouponsGroup" + }, + "executionTime": { + "type": "number" + } + }, + "required": [ + "result", + "executionTime" + ] +} \ No newline at end of file diff --git a/src/test/resources/schemas/DiscountDetails.json b/src/test/resources/schemas/DiscountDetails.json new file mode 100644 index 000000000..3bc814900 --- /dev/null +++ b/src/test/resources/schemas/DiscountDetails.json @@ -0,0 +1,79 @@ +{ + "$id": "DiscountDetails", + "definitions": { + "DiscountDetails": { + "type": "object", + "properties": { + "objectType": { + "type": "string", + "minLength": 0 + }, + "endDate": { + "type": "number", + "minimum": 0.0 + }, + "id": { + "type": "number", + "minimum": 0.0 + }, + "multiCurrencyDiscount": { + "type": "array", + "items": { + "type": "object", + "properties": { + "objectType": { + "type": "string", + "minLength": 0 + }, + "amount": { + "type": "number", + "minimum": 0.0 + }, + "currency": { + "type": "string", + "minLength": 0 + }, + "currencySign": { + "type": "string", + "minLength": 0 + }, + "percentage": { + "type": "number", + "minimum": 0.0 + } + } + } + }, + "name": { + "type": "string", + "minLength": 0 + }, + "startDate": { + "type": "number", + "minimum": 0.0 + } + }, + "required": [ + "objectType", + "endDate", + "id", + "multiCurrencyDiscount", + "name", + "startDate" + ] + } + }, + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/DiscountDetails" + }, + "executionTime": { + "type": "number" + } + }, + "required": [ + "result", + "executionTime" + ] +} \ No newline at end of file diff --git a/src/test/resources/schemas/DynamicChannel.json b/src/test/resources/schemas/DynamicChannel.json new file mode 100644 index 000000000..8a91cc056 --- /dev/null +++ b/src/test/resources/schemas/DynamicChannel.json @@ -0,0 +1,149 @@ +{ + "$id": "DynamicChannel", + "type": "object", + "definitions": { + "DynamicChannel": { + "type": "object", + "properties": { + "executionTime": { + "type": "number", + "minimum": 0 + }, + "result": { + "type": "object", + "properties": { + "objectType": { + "type": "string", + "minLength": 0 + }, + "createDate": { + "type": "integer", + "minimum": 0 + }, + "description": { + "type": "string", + "minLength": 0 + }, + "multilingualDescription": { + "type": "array", + "items": { + "type": "object", + "properties": { + "objectType": { + "type": "string", + "minLength": 0 + }, + "language": { + "type": "string", + "minLength": 0 + }, + "value": { + "type": "string", + "minLength": 0 + } + }, + "required": [ + "objectType", + "language", + "value" + ] + } + }, + "id": { + "type": "integer", + "minimum": 0 + }, + "isActive": { + "type": "boolean" + }, + "name": { + "type": "string", + "minLength": 0 + }, + "multilingualName": { + "type": "array", + "items": { + "type": "object", + "properties": { + "objectType": { + "type": "string", + "minLength": 0 + }, + "language": { + "type": "string", + "minLength": 0 + }, + "value": { + "type": "string", + "minLength": 0 + } + }, + "required": [ + "objectType", + "language", + "value" + ] + } + }, + "orderBy": { + "type": "object", + "properties": { + "objectType": { + "type": "string", + "minLength": 0 + }, + "orderBy": { + "type": "string", + "minLength": 0 + } + }, + "required": [ + "objectType", + "orderBy" + ] + }, + "systemName": { + "type": "string", + "minLength": 0 + }, + "updateDate": { + "type": "integer", + "minimum": 0 + }, + "assetTypes": { + "type": "array" + }, + "kSql": { + "type": "string", + "minLength": 0 + } + }, + "required": [ + "objectType", + "createDate", + "description", + "multilingualDescription", + "id", + "isActive", + "name", + "multilingualName", + "orderBy", + "systemName", + "updateDate", + "assetTypes", + "kSql" + ] + } + } + } + }, + "properties": { + "result": { + "ref": "#/definitions/DynamicChannel" + }, + "executionTime": { + "type": "number", + "minimum": 0 + } + } +} \ No newline at end of file diff --git a/src/test/resources/schemas/Language.json b/src/test/resources/schemas/Language.json new file mode 100644 index 000000000..0e0a03f2b --- /dev/null +++ b/src/test/resources/schemas/Language.json @@ -0,0 +1,49 @@ +{ + "$id": "Language", + "definitions": { + "Language": { + "type": "object", + "properties": { + "objectType": { + "type": "string", + "enum": ["KalturaLanguage"] + }, + "code": { + "type": "string", + "minLength": 0 + }, + "direction": { + "type": "string", + "minLength": 0 + }, + "isDefault": { + "type": "boolean" + }, + "name": { + "type": "string", + "minLength": 0 + }, + "systemName": { + "type": "string", + "minLength": 0 + } + }, + "required": [ + "objectType", + "code", + "direction", + "isDefault", + "name", + "systemName" + ] + } + }, + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/Language" + }, + "executionTime": {"type": "number"} + }, + "required": ["result", "executionTime"] +} diff --git a/src/test/resources/schemas/LicensedUrl.json b/src/test/resources/schemas/LicensedUrl.json new file mode 100644 index 000000000..0e3250738 --- /dev/null +++ b/src/test/resources/schemas/LicensedUrl.json @@ -0,0 +1,35 @@ +{ + "$id": "LicensedUrl", + "type": "object", + "properties": { + "result": { + "type": "object", + "properties": { + "mainUrl": { + "type": "string" + }, + "altUrl": { + "type": "string" + }, + "objectType": { + "type": "string", + "enum": [ + "KalturaLicensedUrl" + ] + } + }, + "required": [ + "mainUrl", + "altUrl", + "objectType" + ] + }, + "executionTime": { + "type": "number" + } + }, + "required": [ + "result", + "executionTime" + ] +} \ No newline at end of file diff --git a/src/test/resources/schemas/ListResponse.json b/src/test/resources/schemas/ListResponse.json index bfec96dc2..ff4981682 100644 --- a/src/test/resources/schemas/ListResponse.json +++ b/src/test/resources/schemas/ListResponse.json @@ -38,6 +38,36 @@ }, { "$ref": "HouseholdDevice.json#/definitions/HouseholdDevice" + }, + { + "$ref": "UserRole.json#/definitions/UserRole" + }, + { + "$ref": "Subscription.json#/definitions/Subscription" + }, + { + "$ref": "PaymentGatewayProfile.json#/definitions/PaymentGatewayProfile" + }, + { + "$ref": "PriceDetails.json#/definitions/PriceDetails" + }, + { + "$ref": "PricePlan.json#/definitions/PricePlan" + }, + { + "$ref": "DynamicChannel.json#/definitions/DynamicChannel" + }, + { + "$ref": "DiscountDetails.json#/definitions/DiscountDetails" + }, + { + "$ref": "AssetStructMeta.json#/definitions/AssetStructMeta" + }, + { + "$ref": "AssetStruct.json#/definitions/AssetStruct" + }, + { + "$ref": "Language.json#/definitions/Language" } ] } @@ -58,7 +88,18 @@ "KalturaProductPriceListResponse", "KalturaBookmarkListResponse", "KalturaAssetCommentListResponse", - "KalturaAssetHistoryListResponse" + "KalturaAssetHistoryListResponse", + "KalturaUserRoleListResponse", + "KalturaSubscriptionListResponse", + "KalturaPaymentGatewayProfileListResponse", + "KalturaPriceDetailsListResponse", + "KalturaPricePlanListResponse", + "KalturaDynamicChannelListResponse", + "KalturaDiscountDetailsListResponse", + "KalturaAssetStructMetaListResponse", + "KalturaAssetStructListResponse", + "KalturaCountryListResponse", + "KalturaLanguageListResponse" ] } }, diff --git a/src/test/resources/schemas/LiveAsset.json b/src/test/resources/schemas/LiveAsset.json new file mode 100644 index 000000000..2586efb8c --- /dev/null +++ b/src/test/resources/schemas/LiveAsset.json @@ -0,0 +1,448 @@ +{ + "$id": "LiveAsset", + "type": "object", + "properties": { + "executionTime": { + "type": "number" + }, + "result": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "createDate": { + "type": "integer" + }, + "description": { + "type": "string" + }, + "endDate": { + "type": "integer" + }, + "externalId": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "images": { + "type": "array", + "items": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "height": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "isDefault": { + "type": "boolean" + }, + "ratio": { + "type": "string" + }, + "url": { + "type": "string" + }, + "version": { + "type": "integer" + }, + "width": { + "type": "integer" + } + } + } + }, + "mediaFiles": { + "type": "array", + "items": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "altCdnCode": { + "type": "string" + }, + "assetId": { + "type": "integer" + }, + "cdnCode": { + "type": "string" + }, + "duration": { + "type": "integer" + }, + "externalId": { + "type": "string" + }, + "fileSize": { + "type": "integer" + }, + "id": { + "type": "integer" + }, + "type": { + "type": "string" + }, + "url": { + "type": "string" + } + } + } + }, + "metas": { + "type": "object", + "properties": { + "synopsis": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "value": { + "type": "string" + } + } + }, + "Short title": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "value": { + "type": "string" + } + } + }, + "Runtime": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "value": { + "type": "string" + } + } + }, + "Catchup logo URL": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "value": { + "type": "string" + } + } + }, + "App Link": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "value": { + "type": "string" + } + } + }, + "meta_name": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "value": { + "type": "string" + } + } + }, + "groupBy_id": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "value": { + "type": "string" + } + } + }, + "External program ID": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "value": { + "type": "string" + } + } + }, + "Release year1": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "value": { + "type": "integer" + } + } + }, + "Catchup allowed": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "value": { + "type": "boolean" + } + } + }, + "testing": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "value": { + "type": "boolean" + } + } + } + } + }, + "name": { + "type": "string" + }, + "startDate": { + "type": "integer" + }, + "tags": { + "type": "object", + "properties": { + "Free": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "objects": { + "type": "array", + "items": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "value": { + "type": "string" + } + } + } + } + } + }, + "Genre": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "objects": { + "type": "array", + "items": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "value": { + "type": "string" + } + } + } + } + } + }, + "Parental Rating": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "objects": { + "type": "array", + "items": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "value": { + "type": "string" + } + } + } + } + } + }, + "Director": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "objects": { + "type": "array", + "items": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "value": { + "type": "string" + } + } + } + } + } + }, + "Country": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "objects": { + "type": "array", + "items": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "value": { + "type": "string" + } + } + } + } + } + }, + "Series name": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "objects": { + "type": "array", + "items": { + "type": "object", + "properties": { + "objectType": { + "type": "string" + }, + "value": { + "type": "string" + } + } + } + } + } + } + }, + "required": [ + "Genre", + "Parental Rating", + "Director", + "Country", + "Series name" + ] + }, + "type": { + "type": "integer" + }, + "updateDate": { + "type": "integer" + }, + "entryId": { + "type": "string" + }, + "externalIds": { + "type": "string" + }, + "status": { + "type": "boolean" + }, + "typeDescription": { + "type": "string" + }, + "enableCatchUp": { + "type": "boolean" + }, + "enableCdvr": { + "type": "boolean" + }, + "enableRecordingPlaybackNonEntitledChannel": { + "type": "boolean" + }, + "enableStartOver": { + "type": "boolean" + }, + "catchUpBuffer": { + "type": "integer" + }, + "trickPlayBuffer": { + "type": "integer" + }, + "enableTrickPlay": { + "type": "boolean" + } + }, + "required": [ + "objectType", + "createDate", + "description", + "endDate", + "externalId", + "id", + "images", + "mediaFiles", + "metas", + "name", + "startDate", + "tags", + "type", + "updateDate", + "entryId", + "externalIds", + "status", + "typeDescription", + "enableCatchUp", + "enableCdvr", + "enableRecordingPlaybackNonEntitledChannel", + "enableStartOver", + "catchUpBuffer", + "trickPlayBuffer", + "enableTrickPlay" + ] + } + }, + "required": [ + "executionTime", + "result" + ] +} \ No newline at end of file diff --git a/src/test/resources/schemas/MediaAsset.json b/src/test/resources/schemas/MediaAsset.json index f9c21435b..780562cb0 100644 --- a/src/test/resources/schemas/MediaAsset.json +++ b/src/test/resources/schemas/MediaAsset.json @@ -34,7 +34,7 @@ }, "description": { "type": "string", - "minLength": 1 + "minLength": 0 }, "images": { "type": "array", diff --git a/src/test/resources/schemas/OTTUser.json b/src/test/resources/schemas/OTTUser.json index 41ea9045d..f2e6120af 100644 --- a/src/test/resources/schemas/OTTUser.json +++ b/src/test/resources/schemas/OTTUser.json @@ -5,7 +5,7 @@ "type": "object", "properties": { "householdId": {"type": "integer", "minimum": 0}, - "email": {"type": "string", "minLength": 5}, + "email": {"type": "string"}, "country": { "type": "object", "properties": { @@ -32,8 +32,8 @@ "userState": {"type": "string", "minLength": 1}, "id": {"type": "string", "minLength": 1}, "username": {"type": "string", "minLength": 1}, - "firstName": {"type": "string", "minLength": 1}, - "lastName": {"type": "string", "minLength": 1}, + "firstName": {"type": "string"}, + "lastName": {"type": "string"}, "objectType": {"type": "string", "enum": ["KalturaOTTUser"]} }, "required": ["householdId", "email", "countryId", "dynamicData", "isHouseholdMaster", "suspentionState", diff --git a/src/test/resources/schemas/PaymentGatewayProfile.json b/src/test/resources/schemas/PaymentGatewayProfile.json new file mode 100644 index 000000000..c43a11126 --- /dev/null +++ b/src/test/resources/schemas/PaymentGatewayProfile.json @@ -0,0 +1,43 @@ +{ + "$id": "PaymentGatewayProfile", + "definitions": { + "PaymentGatewayProfile": { + "type": "object", + "properties": { + "isActive": {"type": "integer", "minimum": 0}, + "adapterUrl": {"type": "string", "minLength": 0}, + "transactUrl": {"type": "string", "minLength": 0}, + "statusUrl": {"type": "string","minLength": 0}, + "renewUrl": {"type": "string","minLength": 0}, + "paymentGatewaySettings": {"type": "object"}, + "externalIdentifier": {"type": "string","minLength": 0}, + "pendingInterval": {"type": "integer","minimum": 0}, + "pendingRetries": {"type": "integer","minimum": 0}, + "sharedSecret": {"type": "string","minLength": 0}, + "renewIntervalMinutes": {"type": "integer","minimum": 0}, + "renewStartMinutes": {"type": "integer"}, + "externalVerification": {"type": "boolean"}, + "id": {"type": "integer","minimum": 0}, + "name": {"type": "string","minLength": 0}, + "isDefault": {"type": "boolean"}, + "paymentMethods": {"type": "array"}, + "objectType": {"type": "string","minLength": 0} + }, + "required": ["isActive", "adapterUrl", "transactUrl", "statusUrl","renewUrl","paymentGatewaySettings","externalIdentifier","pendingInterval","pendingRetries","sharedSecret", + "renewIntervalMinutes","renewStartMinutes","externalVerification","id","name","isDefault","objectType"] + } + }, + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/PaymentGatewayProfile" + }, + "executionTime": { + "type": "number" + } + }, + "required": [ + "result", + "executionTime" + ] +} \ No newline at end of file diff --git a/src/test/resources/schemas/PlaybackContext.json b/src/test/resources/schemas/PlaybackContext.json new file mode 100644 index 000000000..74aa0967f --- /dev/null +++ b/src/test/resources/schemas/PlaybackContext.json @@ -0,0 +1,43 @@ +{ + "$id": "PlaybackContext", + "definitions": { + "PlaybackContext": { + "type": "object", + "properties": { + "result": { + "type": "object", + "properties": { + "sources": { + "type": "array" + }, + "actions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": {"type": "string", "minLength": 1}, + "objectType": {"type": "string", "minLength": 1} + } + } + }, + "messages": { + "type": "array", + "items": { + "type": "object", + "properties": { + "message": {"type": "string", "minLength": 1}, + "code": {"type": "string", "minLength": 1}, + "objectType": {"type": "string", "minLength": 1} + } + } + }, + "objectType": {"type": "string", "minLength": 1} + }, + "required": ["sources", "actions", "messages", "objectType"] + }, + "executionTime": {"type": "number", "minimum": 0} + } + } + }, + "ref": "#/definitions/PlaybackContext" +} \ No newline at end of file diff --git a/src/test/resources/schemas/Ppv.json b/src/test/resources/schemas/Ppv.json new file mode 100644 index 000000000..09e5b2faa --- /dev/null +++ b/src/test/resources/schemas/Ppv.json @@ -0,0 +1,201 @@ +{ + "$id": "Ppv", + "definitions": { + "Ppv": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 0 + }, + "name": { + "type": "string", + "minLength": 0 + }, + "price": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "minimum": 0 + }, + "name": { + "type": "string", + "minLength": 0 + }, + "price": { + "type": "object", + "properties": { + "amount": { + "type": "number", + "minimum": 0 + }, + "currency": { + "type": "string", + "minLength": 0 + }, + "currencySign": { + "type": "string", + "minLength": 0 + }, + "objectType": { + "type": "string", + "minLength": 0 + } + } + }, + "descriptions": { + "type": "array" + }, + "objectType": { + "type": "string", + "minLength": 0 + } + }, + "required": [ + "price" + ] + }, + "fileTypes": { + "type": "array", + "items": { + "type": "object", + "properties": { + "value": { + "type": "integer", + "minimum": 0 + }, + "objectType": { + "type": "string", + "minLength": 0 + } + } + } + }, + "discountModule": { + "type": "object", + "properties": { + "percent": { + "type": "integer", + "minimum": 0 + }, + "startDate": { + "type": "integer", + "minimum": 0 + }, + "endDate": { + "type": "integer", + "minimum": 0 + }, + "objectType": { + "type": "string", + "minLength": 0 + } + } + }, + "descriptions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "language": { + "type": "string", + "minLength": 0 + }, + "value": { + "type": "string", + "minLength": 0 + }, + "objectType": { + "type": "string", + "minLength": 0 + } + } + } + }, + "productCode": { + "type": "string", + "minLength": 0 + }, + "isSubscriptionOnly": { + "type": "boolean" + }, + "firstDeviceLimitation": { + "type": "boolean" + }, + "usageModule": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "minimum": 0 + }, + "name": { + "type": "string", + "minLength": 0 + }, + "maxViewsNumber": { + "type": "integer", + "minimum": 0 + }, + "viewLifeCycle": { + "type": "integer", + "minimum": 0 + }, + "fullLifeCycle": { + "type": "integer", + "minimum": 0 + }, + "couponId": { + "type": "integer", + "minimum": 0 + }, + "waiverPeriod": { + "type": "integer", + "minimum": 0 + }, + "isWaiverEnabled": { + "type": "boolean" + }, + "isOfflinePlayback": { + "type": "boolean" + }, + "objectType": { + "type": "string", + "minLength": 0 + } + } + }, + "objectType": { + "type": "string", + "minLength": 0 + } + }, + "required": [ + "id", + "name", + "price", + "fileTypes", + "descriptions", + "productCode", + "isSubscriptionOnly", + "firstDeviceLimitation", + "usageModule" + ] + } + }, + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/Ppv" + }, + "executionTime": { + "type": "number" + } + }, + "required": [ + "result", + "executionTime" + ] +} + diff --git a/src/test/resources/schemas/PriceDetails.json b/src/test/resources/schemas/PriceDetails.json new file mode 100644 index 000000000..25e9aa97e --- /dev/null +++ b/src/test/resources/schemas/PriceDetails.json @@ -0,0 +1,35 @@ +{ + "$id": "PriceDetails", + "definitions": { + "PriceDetails": { + "type": "object", + "properties": { + "id": {"type": "integer", "minimum": 0}, + "name": {"type": "string", "minLength": 0}, + "multiCurrencyPrice": { + "type": "array", + "items": { + "type": "object", + "properties": { + "amount": {"type": "integer", "minimum": 0}, + "currency": {"type": "string", "minLength": 0}, + "currencySign": {"type": "string", "minLength": 0}, + "objectType": {"type": "string", "enum": ["KalturaPriceDetails"]} + }, + "required": ["amount", "currency", "currencySign", "objectType"] + } + }, + "objectType": {"type": "string", "minLength": 0} + }, + "required": ["id", "name", "multiCurrencyPrice"] + } + }, + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/PriceDetails" + }, + "executionTime": {"type": "number"} + }, + "required": ["result", "executionTime"] +} \ No newline at end of file diff --git a/src/test/resources/schemas/PricePlan.json b/src/test/resources/schemas/PricePlan.json new file mode 100644 index 000000000..ac495ae12 --- /dev/null +++ b/src/test/resources/schemas/PricePlan.json @@ -0,0 +1,92 @@ +{ + "$id": "PricePlan", + "definitions": { + "PricePlan": { + "type": "object", + "properties": { + "isRenewable": { + "type": "boolean" + }, + "renewalsNumber": { + "type": "integer", + "minimum": 0 + }, + "discountId": { + "type": "integer", + "minimum": 0 + }, + "priceDetailsId": { + "type": "integer", + "minimum": 0 + }, + "id": { + "type": "integer", + "minimum": 0 + }, + "name": { + "type": "string", + "minLength": 0 + }, + "maxViewsNumber": { + "type": "integer", + "minimum": 0 + }, + "viewLifeCycle": { + "type": "integer", + "minimum": 0 + }, + "fullLifeCycle": { + "type": "integer", + "minimum": 0 + }, + "couponId": { + "type": "integer", + "minimum": 0 + }, + "waiverPeriod": { + "type": "integer", + "minimum": 0 + }, + "isWaiverEnabled": { + "type": "boolean" + }, + "isOfflinePlayback": { + "type": "boolean" + }, + "objectType": { + "type": "string", + "enum": ["KalturaPricePlan"] + } + }, + "required": [ + "isRenewable", + "renewalsNumber", + "discountId", + "priceDetailsId", + "id", + "name", + "maxViewsNumber", + "viewLifeCycle", + "fullLifeCycle", + "couponId", + "waiverPeriod", + "isWaiverEnabled", + "isOfflinePlayback", + "objectType" + ] + } + }, + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/PricePlan" + }, + "executionTime": { + "type": "number" + } + }, + "required": [ + "result", + "executionTime" + ] +} \ No newline at end of file diff --git a/src/test/resources/schemas/ProgramAsset.json b/src/test/resources/schemas/ProgramAsset.json new file mode 100644 index 000000000..188be0f8b --- /dev/null +++ b/src/test/resources/schemas/ProgramAsset.json @@ -0,0 +1,138 @@ +{ + "$id": "ProgramAsset", + "type": "object", + "definitions": { + "ProgramAsset": { + "type": "object", + "properties": { + "epgChannelId": { + "type": "integer", + "minimum": 0 + }, + "epgId": { + "type": "string", + "minLength": 0 + }, + "relatedMediaId": { + "type": "integer", + "minimum": 0 + }, + "crid": { + "type": "string", + "minLength": 0 + }, + "linearAssetId": { + "type": "integer", + "minimum": 0 + }, + "id": { + "type": "integer", + "minimum": 0 + }, + "type": { + "type": "integer", + "minimum": 0 + }, + "name": { + "type": "string", + "minLength": 0 + }, + "description": { + "type": "string", + "minLength": 0 + }, + "images": { + "type": "array" + }, + "metas": { + "type": "object", + "properties": { + "season_num": { + "type": "object", + "properties": { + "value": { + "type": "string", + "minLength": 0 + }, + "objectType": { + "type": "string", + "minLength": 0 + } + } + }, + "Series_ID": { + "type": "object", + "properties": { + "value": { + "type": "string", + "minLength": 0 + }, + "objectType": { + "type": "string", + "minLength": 0 + } + } + }, + "Episode number": { + "type": "object", + "properties": { + "value": { + "type": "string", + "minLength": 0 + }, + "objectType": { + "type": "string", + "minLength": 0 + } + } + } + } + }, + "tags": { + "type": "object" + }, + "startDate": { + "type": "integer", + "minimum": 0 + }, + "endDate": { + "type": "integer", + "minimum": 0 + }, + "enableCdvr": { + "type": "boolean" + }, + "enableCatchUp": { + "type": "boolean" + }, + "enableStartOver": { + "type": "boolean" + }, + "enableTrickPlay": { + "type": "boolean" + }, + "objectType": { + "type": "string", + "minLength": 0 + } + }, + "required": [ + "epgChannelId", + "epgId", + "type", + "name", + "startDate", + "endDate" + ] + } + }, + "properties": { + "result": { + "ref":"#/definitions/ProgramAsset" + }, + "executionTime": { + "type": "number", + "minimum": 0 + } + } +} \ No newline at end of file diff --git a/src/test/resources/schemas/Recording.json b/src/test/resources/schemas/Recording.json new file mode 100644 index 000000000..c1d1cb836 --- /dev/null +++ b/src/test/resources/schemas/Recording.json @@ -0,0 +1,66 @@ +{ + "$id": "Recording", + "definitions": { + "Recording": { + "type": "object", + "properties": { + "assetId": { + "type": "integer", + "minimum": 0 + }, + "createDate": { + "type": "integer", + "minimum": 0 + }, + "id": { + "type": "integer", + "minimum": 0 + }, + "isProtected": { + "type": "boolean" + }, + "status": { + "type": "string", + "minLength": 0 + }, + "type": { + "type": "string", + "minLength": 0 + }, + "updateDate": { + "type": "integer", + "minimum": 0 + }, + "objectType": { + "type": "string", + "enum": [ + "KalturaRecording" + ] + } + }, + "required": [ + "objectType", + "assetId", + "createDate", + "id", + "isProtected", + "status", + "type", + "updateDate" + ] + } + }, + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/Recording" + }, + "executionTime": { + "type": "number" + } + }, + "required": [ + "result", + "executionTime" + ] +} diff --git a/src/test/resources/schemas/StringValueArray.json b/src/test/resources/schemas/StringValueArray.json new file mode 100644 index 000000000..b2ec7fbe2 --- /dev/null +++ b/src/test/resources/schemas/StringValueArray.json @@ -0,0 +1,33 @@ +{ + "$id": "StringValueArray", + "definitions": { + "StringValueArray": { + "$id": "StringValueArray", + "type": "object", + "properties": { + "objectType": { + "type": "string", + "minLength": 0 + }, + "objects": { + "type": "array", + "items": { + "$ref": "StringValue.json" + } + } + }, + "required": [ + "objectType", + "objects" + ] + } + }, + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/StringValueArray" + }, + "executionTime": {"type": "number"} + }, + "required": ["result", "executionTime"] +} \ No newline at end of file diff --git a/src/test/resources/schemas/Subscription.json b/src/test/resources/schemas/Subscription.json new file mode 100644 index 000000000..4eeb100ac --- /dev/null +++ b/src/test/resources/schemas/Subscription.json @@ -0,0 +1,297 @@ +{ + "$id": "Subscription", + "definitions": { + "Subscription": { + "type": "object", + "properties": { + "result": { + "type": "object", + "additionalProperties": false, + "properties": { + "objects": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string", + "default": "" + }, + "channels": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "integer", + "default": 0 + }, + "objectType": { + "type": "string", + "default": "KalturaBaseChannel" + } + }, + "required": [ + "id", + "objectType" + ] + } + }, + "startDate": { + "type": "integer", + "default": 0 + }, + "endDate": { + "type": "integer", + "default": 0 + }, + "fileTypes": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "value": { + "type": "integer", + "default": 0 + }, + "objectType": { + "type": "string", + "default": "KalturaIntegerValue" + } + }, + "required": [ + "value", + "objectType" + ] + } + }, + "isRenewable": { + "type": "boolean", + "default": false + }, + "renewalsNumber": { + "type": "integer", + "default": 0 + }, + "isInfiniteRenewal": { + "type": "boolean", + "default": false + }, + "price": { + "$ref": "Price.json#/definitions/Price" + }, + "discountModule": { + "type": "object", + "additionalProperties": false, + "properties": { + "percent": { + "type": "integer", + "default": 0 + }, + "startDate": { + "type": "integer", + "default": 0 + }, + "endDate": { + "type": "integer", + "default": 0 + }, + "objectType": { + "type": "string", + "default": "KalturaDiscountModule" + } + }, + "required": [ + "percent", + "startDate", + "endDate", + "objectType" + ] + }, + "name": { + "type": "string", + "default": "" + }, + "description": { + "type": "string", + "default": "" + }, + "mediaId": { + "type": "integer", + "default": 0 + }, + "prorityInOrder": { + "type": "integer", + "default": 0 + }, + "pricePlanIds": { + "type": "string", + "default": "" + }, + "householdLimitationsId": { + "type": "integer", + "default": 0 + }, + "gracePeriodMinutes": { + "type": "integer", + "default": 0 + }, + "premiumServices": { + "type": "array" + }, + "maxViewsNumber": { + "type": "integer", + "default": 0 + }, + "viewLifeCycle": { + "type": "integer", + "default": 0 + }, + "waiverPeriod": { + "type": "integer", + "default": 0 + }, + "isWaiverEnabled": { + "type": "boolean", + "default": false + }, + "userTypes": { + "type": "array" + }, + "couponsGroups": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string", + "default": "" + }, + "name": { + "type": "string", + "default": "" + }, + "startDate": { + "type": "integer", + "default": 0 + }, + "endDate": { + "type": "integer", + "default": 0 + }, + "maxUsesNumber": { + "type": "integer", + "default": 0 + }, + "maxUsesNumberOnRenewableSub": { + "type": "integer", + "default": 0 + }, + "couponGroupType": { + "type": "string", + "default": "" + }, + "maxHouseholdUses": { + "type": "integer", + "default": 0 + }, + "objectType": { + "type": "string", + "default": "KalturaCouponsGroup" + } + }, + "required": [ + "id", + "name", + "startDate", + "endDate", + "maxUsesNumber", + "maxUsesNumberOnRenewableSub", + "couponGroupType", + "maxHouseholdUses", + "objectType" + ] + } + }, + "productCodes": { + "type": "array" + }, + "dependencyType": { + "type": "string", + "default": "" + }, + "externalId": { + "type": "string", + "default": "" + }, + "isCancellationBlocked": { + "type": "boolean", + "default": false + }, + "objectType": { + "type": "string", + "default": "KalturaSubscription" + } + }, + "required": [ + "id", + "channels", + "startDate", + "endDate", + "fileTypes", + "isRenewable", + "renewalsNumber", + "isInfiniteRenewal", + "name", + "description", + "mediaId", + "prorityInOrder", + "pricePlanIds", + "householdLimitationsId", + "gracePeriodMinutes", + "premiumServices", + "maxViewsNumber", + "viewLifeCycle", + "waiverPeriod", + "isWaiverEnabled", + "userTypes", + "couponsGroups", + "productCodes", + "dependencyType", + "externalId", + "isCancellationBlocked", + "objectType" + ] + } + }, + "totalCount": { + "type": "integer", + "default": 0 + }, + "objectType": { + "type": "string", + "default": "KalturaSubscriptionListResponse" + } + }, + "required": [ + "objects", + "totalCount", + "objectType" + ] + } + } + } + }, + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/Subscription" + }, + "executionTime": {"type": "number"} + }, + "required": ["result", "executionTime"] +} diff --git a/src/test/resources/schemas/SubscriptionEntitlement.json b/src/test/resources/schemas/SubscriptionEntitlement.json index 800dc8869..ac86f8d88 100644 --- a/src/test/resources/schemas/SubscriptionEntitlement.json +++ b/src/test/resources/schemas/SubscriptionEntitlement.json @@ -100,6 +100,12 @@ "enum": [ "KalturaSubscriptionEntitlement" ] + }, + "type": { + "type": "string", + "enum": [ + "subscription" + ] } }, "required": [ diff --git a/src/test/resources/schemas/UserRole.json b/src/test/resources/schemas/UserRole.json new file mode 100644 index 000000000..1d41dc593 --- /dev/null +++ b/src/test/resources/schemas/UserRole.json @@ -0,0 +1,24 @@ +{ + "$id": "UserRole", + "definitions": { + "UserRole": { + "type": "object", + "properties": { + "id": {"type": "integer", "minimum": 0}, + "name": {"type": "string"}, + "permissionNames": {"type": "string"}, + "excludedPermissionNames": {"type": "string"}, + "objectType": {"type": "string", "minLength": 0} + }, + "required": ["id", "objectType"] + } + }, + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/UserRole" + }, + "executionTime": {"type": "number"} + }, + "required": ["result", "executionTime"] +} diff --git a/src/test/resources/schemas/UserSocialActionResponse.json b/src/test/resources/schemas/UserSocialActionResponse.json new file mode 100644 index 000000000..b9fbc0bed --- /dev/null +++ b/src/test/resources/schemas/UserSocialActionResponse.json @@ -0,0 +1,56 @@ +{ + "$id": "UserSocialActionResponse", + "definitions": { + "UserSocialActionResponse": { + "type": "object", + "properties": { + "socialAction": { + "type": "object", + "properties": { + "id": {"type": "string", "minLength": 0}, + "actionType": {"type": "string", "minLength": 0}, + "time": {"type": "integer", "minimum": 0}, + "assetId": {"type": "integer", "minimum": 0}, + "assetType": {"type": "string", "minLength": 0}, + "objectType": {"type": "string", "minLength": 0} + }, + "required": ["id", "actionType", "time", "assetId", "assetType"] + }, + "failStatus": { + "type": "array", + "items": { + "type": "object", + "properties": { + "status": { + "type": "string", + "minLength": 0 + }, + "network": { + "type": "string", + "minLength": 0 + }, + "objectType": { + "type": "string", + "minLength": 0 + } + } + } + }, + "objectType": { + "type": "string", + "minLength": 0 + } + } + } + }, + "type": "object", + "properties": { + "result": { + "ref": "#/definitions/UserSocialActionResponse" + }, + "executionTime": { + "type": "number", + "minimum": 0 + } + } +} \ No newline at end of file diff --git a/src/test/resources/test.template.properties b/src/test/resources/test.template.properties index 597b29e24..a6ce2efa8 100644 --- a/src/test/resources/test.template.properties +++ b/src/test/resources/test.template.properties @@ -2,8 +2,10 @@ api_base_url=@API_BASE_URL@ api_version=@API_VERSION@ partner_id=@PARTNER_ID@ +is_opc_group=@IS_OPC@ ingest_base_url=@INGEST_BASE_URL@ ingest_report_url=@INGEST_REPORT_URL@ +default_timeout_in_sec=@DEFAULT_TIMEOUT_IN_SEC@ # DB SQL Properties db_url=@DB_URL@ @@ -13,13 +15,6 @@ db_password=@DB_PASSWORD@ # Global Users Properties default_user_password=@DEFAULT_USER_PASSWORD@ -# Ingest Users properties -ingest_user_username=@INGEST_USER_USERNAME@ -ingest_user_password=@INGEST_USER_PASSWORD@ - -ingest_business_module_user_username=@INGEST_BUSINESS_MODULE_USER_USERNAME@ -ingest_business_module_user_password=@INGEST_BUSINESS_MODULE_USER_PASSWORD@ - # File Types web_file_type=@WEB_FILE_TYPE@ mobile_file_type=@MOBILE_FILE_TYPE@ @@ -39,4 +34,18 @@ default_product_code=@DEFAULT_PRODUCT_CODE@ # media types ids movie_media_type_id=@MOVIE_MEDIA_TYPE_ID@ -episode_media_type_id=@EPISODE_MEDIA_TYPE_ID@ \ No newline at end of file +episode_media_type_id=@EPISODE_MEDIA_TYPE_ID@ + +# Phoenix logs remote access +phoenix_server_domain_name=@PHOENIX_SERVER_DOMAIN_NAME@ +phoenix_server_user_name=@PHOENIX_SERVER_USER_NAME@ +phoenix_server_password=@PHOENIX_SERVER_PASSWORD@ +phoenix_server_logs_directory=@PHOENIX_SERVER_LOGS_DIRECTORY@ +phoenix_server_logs_directory_url=@PHOENIX_SERVER_LOGS_DIRECTORY_URL@ +phoenix_server_logs_file_name_prefix=@PHOENIX_SERVER_LOGS_FILE_NAME_PREFIX@ +phoenix_server_logs_file_extension=@PHOENIX_SERVER_LOGS_FILE_EXTENSION@ +phoenix_server_logs_local_folder_path=@PHOENIX_SERVER_LOGS_LOCAL_FOLDER_PATH@ +regression_logs_local_file=@REGRESSION_LOGS_LOCAL_FILE@ +code_performance_report_file=@CODE_PERFORMANCE_REPORT_FILE@ +should_regression_logs_be_saved=@SHOULD_REGRESSION_LOGS_BE_SAVED@ +max_allowed_percentage=@MAX_ALLOWED_PERCENTAGE@ \ No newline at end of file diff --git a/src/test/resources/testng.xml b/src/test/resources/testng.xml index c49991c68..0835589ed 100644 --- a/src/test/resources/testng.xml +++ b/src/test/resources/testng.xml @@ -1,24 +1,8 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> -<suite name="Main Suite" parallel="tests" thread-count="3" configfailurepolicy="continue"> - <test name="Services Tests"> - <groups> - <run> - <exclude name="slow" /> - </run> - </groups> - - <packages> - <package name="com.kaltura.client.test.tests.servicesTests.*"/> - <package name="com.kaltura.client.test.tests.featuresTests.*"/> - </packages> - - <!--<classes>--> - <!--<class name="com.kaltura.client.test.tests.servicesTests.ottUserTests.LoginTests" >--> - <!--<methods>--> - <!--<include name="login" />--> - <!--</methods>--> - <!--</class>--> - <!--</classes>--> - </test> +<suite name="AllSuites"> + <suite-files> + <suite-file path="testng_regular.xml"/> + <suite-file path="testng_opc.xml"/> + </suite-files> </suite> \ No newline at end of file diff --git a/src/test/resources/testng_opc.xml b/src/test/resources/testng_opc.xml new file mode 100644 index 000000000..0f03cfa07 --- /dev/null +++ b/src/test/resources/testng_opc.xml @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> +<suite name="Regression_OPC" parallel="tests" thread-count="1" configfailurepolicy="continue"> + <parameter name="accountType" value="opc"/> + <test name="OPC Tests"> + <groups> + <run> + <include name="opc"/> + </run> + </groups> + + <packages> + <package name="com.kaltura.client.test.tests.servicesTests.*"/> + <package name="com.kaltura.client.test.tests.featuresTests.*"/> + </packages> + + <!--<classes>--> + <!--<class name="com.kaltura.client.test.tests.featuresTests.versions.five_zero_two.IngestVodOpcTests">--> + <!--<methods>--> + <!--<include name="updateImages"/>--> + <!--</methods>--> + <!--</class>--> + <!--</classes>--> + + </test> +</suite> diff --git a/src/test/resources/testng_regular.xml b/src/test/resources/testng_regular.xml new file mode 100644 index 000000000..53c698962 --- /dev/null +++ b/src/test/resources/testng_regular.xml @@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> +<suite name="Regression" parallel="tests" thread-count="2" configfailurepolicy="continue"> + <parameter name = "accountType" value="regular"/> + <test name="Fast Tests"> + <groups> + <run> + <exclude name="slowBefore"/> + <exclude name="slowAfter"/> + <exclude name="Permission management"/> + <exclude name="opc"/> + </run> + </groups> + <packages> + <package name="com.kaltura.client.test.tests.servicesTests.*"/> + <package name="com.kaltura.client.test.tests.featuresTests.*"/> + </packages> + + <!--<classes>--> + <!--<class name="com.kaltura.client.test.tests.servicesTests.ottUserTests.OttUserGetTests"/>--> + <!--</classes>--> + </test> + + <test name="Slow Tests"> + <groups> + <run> + <include name="slowBefore"/> + <include name="slowAfter"/> + </run> + </groups> + <packages> + <package name="com.kaltura.client.test.tests.servicesTests.*"/> + <package name="com.kaltura.client.test.tests.featuresTests.*"/> + </packages> + </test> +</suite> diff --git a/src/test/resources/tests_documentation/SearchAssetFilterTests.md b/src/test/resources/tests_documentation/SearchAssetFilterTests.md new file mode 100644 index 000000000..654127dfa --- /dev/null +++ b/src/test/resources/tests_documentation/SearchAssetFilterTests.md @@ -0,0 +1,91 @@ +asset/action/list with KalturaSearchAssetFilter + +Inherited from KalturaFilter +---------------------------- +1. OrderBy: + * VIEWS_DESC + * NAME_ASC + * NAME_DESC + * LIKES_DESC + * VOTES_DESC + * RATINGS_DESC + * START_DATE_DESC + * START_DATE_ASC + * RELEVANCY_DESC (edge case) + + +Inherited from KalturaPersistedFilter +------------------------------------- +* Should be tested in /searchhistory/action/list tests +name - Name for the persisted filter. +If empty, no action will be done. If has value, the filter will be saved and persisted in user's search history. + +Inherited from KalturaAssetFilter +--------------------------------- +2. dynamicOrderBy + * order by meta + * META_ASC (BEO-5254) + * META_DESC (BEO-5254) + +Inherited from KalturaBaseSearchAssetFilter +------------------------------------------- +3. Filter by KSQL - Search assets using various dynamic criteria +* by asset name +* by tag value +* by meta value + +* By reserved keys + * media_id + * epg_id + * epg_channel_id + * asset start date (TODO) + * asset end date (TODO) + * asset_type - valid values: + * media (TODO) + * epg (TODO) + * recording (TODO) + * asset type id + * geo_block - only valid value is "true": When enabled, only assets that are not restricted to the user by geo-block rules will return (TODO) + * parental_rules - only valid value is "true": When enabled, only assets that the user doesn't need to provide PIN code will return (TODO) + * user_interests - only valid value is "true". When enabled, only assets that the user defined as his interests (by tags and metas) (TODO) + * entitled_assets - valid values: + * free - gets only free to watch assets(TODO) + * entitled - only those that the user is implicitly entitled to watch + * "both" (TODO) + +* Logical conjunction + * or + * and + +* Comparison operators + * For numeric fields: + * = (TODO) + * > (TODO) + * < (TODO) + * >= (edge case) + * <= (edge case) + * : (in)(edge case) + + * For alpha numeric fields: + * Any word starts with(^) + * phrase starts with(^=)(edge case) + * not (!=) + * like (~) + * Not like (!~)(edge case) + * Exists (+) + * Not exists (!+)(edge case) + + +* limitations + * search values - 20 characters (TODO) + * entire filter - 2048 characters (Edge case) + + +KalturaSearchAssetFilter +---------------------------- +4. Filter by asset type (typeIn) - DEPRECATED (use KalturaBaseSearchAssetFilter kSql) + * specific asset type + * list of assets types + + +