Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change api provider TestCase Added #13304

Merged
merged 9 commits into from
Feb 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4267,7 +4267,106 @@ paths:
- lang: Shell
source: 'curl -k -X POST -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8"
-F "type=WSO2-IS" "https://127.0.0.1:9443/api/am/admin/v4/key-managers/discover"'
######################################################
# The "API Collection" resource APIs
######################################################
/apis:
get:
tags:
- APIs
summary: |
Retrieve/Search APIs
description: |
This operation provides you a list of available APIs qualifying under a given search condition.
Each retrieved API is represented with a minimal amount of attributes. If you want to get complete details of an API, you need to use **Get details of an API** operation.
parameters:
- $ref: '#/components/parameters/limit'
- $ref: '#/components/parameters/offset'
- name: query
in: query
description: |
**Search and get all apis in admin portal**.

You can search by proving a keyword.
schema:
type: string
- $ref: '#/components/parameters/If-None-Match'
responses:
200:
description: |
OK.
List of qualifying APIs is returned.
headers:
ETag:
description: |
Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future).
schema:
type: string
Content-Type:
description: The content type of the body.
schema:
type: string
content:
application/json:
schema:
$ref: '#/components/schemas/SearchResultList'
304:
description: |
Not Modified.
Empty body because the client has already the latest version of the requested resource (Will be supported in future).
content: { }
406:
$ref: '#/components/responses/NotAcceptable'
security:
- OAuth2Security:
- apim:admin
- apim:api_provider_change
x-code-samples:
- lang: Curl
source: 'curl -k -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8"
"https://127.0.0.1:9443/api/am/publisher/v4/apis"'
operationId: getAllAPIs
######################################################
# Change Api Provider
######################################################
/apis/{apiId}/change-provider:
post:
tags:
- Api Provider Change
summary: Update the api provider
description: |
Update the api provider
operationId: providerNamePost
parameters:
- name: provider
in: query
required: true
schema:
type: string
- $ref: '#/components/parameters/apiId'
responses:
200:
description: |
OK.
Api Provider updated.
headers:
Content-Type:
description: |
The content type of the body.
schema:
type: string
400:
$ref: '#/components/responses/BadRequest'
404:
$ref: '#/components/responses/NotFound'
security:
- OAuth2Security:
- apim:admin
- apim:api_provider_change
x-code-samples:
- lang: Curl
source: 'curl -k -X PUT -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8"
-H "Content-Type: application/json" "https://127.0.0.1:9443/api/am/admin/v4/provider/admin/apis/33662a62-8db1-4d75-af08-afd63c6bd0b4"'
components:
schemas:
Error:
Expand Down Expand Up @@ -5977,6 +6076,57 @@ components:
- Internal/subscriber
items:
type: string
SearchResultList:
title: Unified Search Result List
type: object
properties:
apis:
type: array
items:
$ref: '#/components/schemas/ApiResult'
count:
type: integer
description: |
Number of results returned.
example: 1
pagination:
$ref: '#/components/schemas/Pagination'
ApiResult:
type: object
properties:
provider:
type: string
name:
type: string
version:
type: string
id:
type: string
Pagination:
title: Pagination
type: object
properties:
offset:
type: integer
example: 0
limit:
type: integer
example: 1
total:
type: integer
example: 10
next:
type: string
description: |
Link to the next subset of resources qualified.
Empty if no more resources are to be returned.
example: ""
previous:
type: string
description: |
Link to the previous subset of resources qualified.
Empty if current subset is the first subset returned.
example: ""
responses:
BadRequest:
description: Bad Request. Invalid request or validation error.
Expand Down Expand Up @@ -6272,6 +6422,14 @@ components:
required: true
schema:
type: string
apiId:
name: apiId
in: path
description: |
**API ID** consisting of the **UUID** of the API.
required: true
schema:
type: string
securitySchemes:
OAuth2Security:
type: oauth2
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2013,7 +2013,7 @@ public boolean equals(Object o) {

@Override
public int hashCode() {
return Objects.hash(id, name, description, context, version, provider, lifeCycleStatus, wsdlInfo, wsdlUrl, responseCachingEnabled, cacheTimeout, hasThumbnail, isDefaultVersion, isRevision, revisionedApiId, revisionId, enableSchemaValidation, enableSubscriberVerification, type, audience, transport, tags, policies, apiThrottlingPolicy, authorizationHeader, apiKeyHeader, securityScheme, maxTps, visibility, visibleRoles, visibleTenants, mediationPolicies, apiPolicies, subscriptionAvailability, subscriptionAvailableTenants, additionalProperties, additionalPropertiesMap, monetization, accessControl, accessControlRoles, businessInformation, corsConfiguration, websubSubscriptionConfiguration, workflowStatus, createdTime, lastUpdatedTimestamp, lastUpdatedTime, endpointConfig, endpointImplementationType, scopes, operations, threatProtectionPolicies, categories, keyManagers, serviceInfo, advertiseInfo, gatewayVendor, gatewayType, asyncTransportProtocols);
return Objects.hash(id, name, description, context, version, provider, lifeCycleStatus, wsdlInfo, wsdlUrl, responseCachingEnabled, cacheTimeout, hasThumbnail, isDefaultVersion, isRevision, revisionedApiId, revisionId, enableSchemaValidation, enableSubscriberVerification, type, audience, transport, tags, policies, apiThrottlingPolicy, authorizationHeader, apiKeyHeader, securityScheme, maxTps, visibility, visibleRoles, visibleTenants, mediationPolicies, apiPolicies, subscriptionAvailability, subscriptionAvailableTenants, additionalProperties, additionalPropertiesMap, monetization, accessControl, accessControlRoles, businessInformation, corsConfiguration, websubSubscriptionConfiguration, workflowStatus, createdTime, lastUpdatedTimestamp, lastUpdatedTime, endpointConfig, endpointImplementationType, scopes, operations, threatProtectionPolicies, categories, keyManagers, serviceInfo, advertiseInfo, gatewayVendor, asyncTransportProtocols);
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public class RestAPIAdminImpl {
private ThrottlingPolicySearchApi throttlingPolicySearchApi = new ThrottlingPolicySearchApi();
private SystemScopesApi systemScopesApi = new SystemScopesApi();
private ApplicationApi applicationApi = new ApplicationApi();
private ApiProviderChangeApi apiProviderChangeApi = new ApiProviderChangeApi();
private LabelApi labelApi = new LabelApi();
private LabelCollectionApi labelCollectionApi = new LabelCollectionApi();
private EnvironmentApi environmentApi = new EnvironmentApi();
Expand Down Expand Up @@ -152,6 +153,7 @@ public RestAPIAdminImpl(String username, String password, String tenantDomain, S
systemScopesApi.setApiClient(apiAdminClient);
tenantConfigApi.setApiClient(apiAdminClient);
tenantConfigSchemaApi.setApiClient(apiAdminClient);
apiProviderChangeApi.setApiClient(apiAdminClient);
this.tenantDomain = tenantDomain;
}

Expand Down Expand Up @@ -700,6 +702,11 @@ public ApiResponse<Void> changeApplicationOwner(String newOwner, String applicat
return applicationApi.applicationsApplicationIdChangeOwnerPostWithHttpInfo(newOwner, applicationId);
}


public ApiResponse<Void> changeApiProvider(String newProvider, String apiId) throws ApiException {
return apiProviderChangeApi.providerNamePostWithHttpInfo(newProvider, apiId);
}

/**
* This method is used to retrieve scopes for a particular user.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
/*
* Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.wso2.am.integration.tests.admin;
shnrndk marked this conversation as resolved.
Show resolved Hide resolved

import jdk.internal.joptsimple.internal.Strings;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.junit.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import org.wso2.am.integration.clients.admin.ApiResponse;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyGenerateRequestDTO;
import org.wso2.am.integration.test.impl.RestAPIAdminImpl;
import org.wso2.am.integration.test.impl.RestAPIStoreImpl;
import org.wso2.am.integration.test.utils.base.APIMIntegrationBaseTest;
import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants;
import org.wso2.am.integration.test.utils.bean.APILifeCycleAction;
import org.wso2.am.integration.test.utils.bean.APIRequest;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
import org.wso2.carbon.integration.common.admin.client.UserManagementClient;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import static org.testng.Assert.assertEquals;
import static org.wso2.am.integration.test.utils.base.APIMIntegrationConstants.SUPER_TENANT_DOMAIN;

public class ChangeApiProviderTestCase extends APIMIntegrationBaseTest {

private String publisherURLHttp;
private RestAPIAdminImpl restAPIAdminClient;
private String BEARER = "Bearer ";
private String APIName = "NewApiForProviderChange";
private String APIContext = "NewApiForProviderChange";
private String tags = "youtube, token, media";
private String apiEndPointUrl;
private String description = "This is test API create by API manager integration test";
private String APIVersion = "1.0.0";
private String apiID;
private String newUser = "peter123";
private String firstUserName = "admin";
private String newUserPass = "test123";
private String[] subscriberRole = {APIMIntegrationConstants.APIM_INTERNAL_ROLE.CREATOR};
private String APPLICATION_NAME = "testApplicationForProviderChange";
private String applicationId;
private String TIER_GOLD = "Gold";
private String API_ENDPOINT_POSTFIX_URL = "jaxrs_basic/services/customers/customerservice/";
private String API_ENDPOINT_METHOD = "customers/123";
private int HTTP_RESPONSE_CODE_OK = Response.Status.OK.getStatusCode();
private String RESPONSE_CODE_MISMATCH_ERROR_MESSAGE = "Response code mismatch";

@Factory(dataProvider = "userModeDataProvider")
public ChangeApiProviderTestCase(TestUserMode userMode) {

this.userMode = userMode;
}

@DataProvider
public static Object[][] userModeDataProvider() {

return new Object[][]{new Object[]{TestUserMode.SUPER_TENANT_ADMIN},
new Object[]{TestUserMode.TENANT_ADMIN},};
}

@BeforeClass(alwaysRun = true)
public void setEnvironment() throws Exception {

super.init(userMode);
publisherURLHttp = getPublisherURLHttp();
userManagementClient = new UserManagementClient(keyManagerContext.getContextUrls().getBackEndUrl(),
createSession(keyManagerContext));
userManagementClient.addUser(newUser, newUserPass, subscriberRole, newUser);
restAPIStore =
new RestAPIStoreImpl(storeContext.getContextTenant().getContextUser().getUserNameWithoutDomain(),
storeContext.getContextTenant().getContextUser().getPassword(),
storeContext.getContextTenant().getDomain(), storeURLHttps);
apiEndPointUrl = backEndServerUrl.getWebAppURLHttp() + API_ENDPOINT_POSTFIX_URL;
}

@Test(groups = {"wso2.am"}, description = "Calling API with invalid token")
public void ChangeApiProvider() throws Exception {
String providerName = user.getUserName();
APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(apiEndPointUrl));
apiRequest.setTags(tags);
apiRequest.setProvider(providerName);
apiRequest.setDescription(description);
apiRequest.setVersion(APIVersion);
apiRequest.setResourceMethod("GET");
//add test api
HttpResponse serviceResponse = restAPIPublisher.addAPI(apiRequest);
assertEquals(serviceResponse.getResponseCode(), Response.Status.CREATED.getStatusCode(),
"Response Code miss matched when creating the API");
apiID = serviceResponse.getData();

// Create Revision and Deploy to Gateway
createAPIRevisionAndDeployUsingRest(apiID, restAPIPublisher);

//publish the api
restAPIPublisher.changeAPILifeCycleStatus(apiID, APILifeCycleAction.PUBLISH.getAction(), null);

HttpResponse applicationResponse = restAPIStore.createApplication(APPLICATION_NAME, Strings.EMPTY,
APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED,
ApplicationDTO.TokenTypeEnum.JWT);

applicationId = applicationResponse.getData();

restAPIStore.subscribeToAPI(apiID, applicationId, TIER_GOLD);
ArrayList<String> grantTypes = new ArrayList<>();
grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.CLIENT_CREDENTIAL);
ApplicationKeyDTO applicationKeyDTO = restAPIStore.generateKeys(applicationId,
APIMIntegrationConstants.DEFAULT_TOKEN_VALIDITY_TIME,
null,
ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION,
null, grantTypes);
Assert.assertNotNull(applicationKeyDTO.getToken());
String accessToken = applicationKeyDTO.getToken().getAccessToken();

HashMap<String, String> requestHeaders = new HashMap<>();
requestHeaders.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
requestHeaders.put(HttpHeaders.AUTHORIZATION, BEARER + accessToken);
HttpResponse apiInvokeResponse = HttpRequestUtil.doGet(
getAPIInvocationURLHttps(APIContext.replace(File.separator, Strings.EMPTY), APIVersion)
+ File.separator + API_ENDPOINT_METHOD, requestHeaders);
assertEquals(apiInvokeResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK, RESPONSE_CODE_MISMATCH_ERROR_MESSAGE);

//Update provider of the api
restAPIAdminClient = new RestAPIAdminImpl(firstUserName, firstUserName, "carbon.super",
adminURLHttps);
if(user.getUserName().equals(firstUserName)){
ApiResponse<Void> changeProviderResponse = restAPIAdminClient.changeApiProvider(newUser, apiID);
Assert.assertEquals(changeProviderResponse.getStatusCode(), HttpStatus.SC_OK);
}
apiInvokeResponse = HttpRequestUtil.doGet(
getAPIInvocationURLHttps(APIContext.replace(File.separator, Strings.EMPTY), APIVersion)
+ File.separator + API_ENDPOINT_METHOD, requestHeaders);
assertEquals(apiInvokeResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK, RESPONSE_CODE_MISMATCH_ERROR_MESSAGE);
}

@AfterClass(alwaysRun = true)
public void destroy() throws Exception {
undeployAndDeleteAPIRevisionsUsingRest(apiID, restAPIPublisher);
restAPIStore.deleteApplication(applicationId);
restAPIPublisher.deleteAPI(apiID);
userManagementClient.deleteUser(newUser);
super.cleanUp();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@
<class name="org.wso2.am.integration.tests.other.APIMANAGER5326CustomStatusMsgTestCase"/>
<!--<class name="org.wso2.am.integration.tests.application.ApplicationCallbackURLTestCase"/-->
<class name="org.wso2.am.integration.tests.admin.OAuthApplicationOwnerUpdateTestCase"/>
<class name="org.wso2.am.integration.tests.admin.ChangeApiProviderTestCase"/>
<class name="org.wso2.am.integration.tests.jwt.JWTGrantTestCase"/>
<class name="org.wso2.am.integration.tests.api.sdk.SDKGenerationTestCase"/>
<class name="org.wso2.am.integration.tests.application.CAPIMGT12CallBackURLOverwriteTestCase"/>
Expand Down
Loading
Loading