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

feat: deprecate index_name in ExecuteMetadataQuery #800

Merged
merged 2 commits into from
Feb 7, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
37 changes: 37 additions & 0 deletions Box.V2.Test.IntegrationNew/BoxMetadataManagerIntegrationTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Box.V2.Models;
using Box.V2.Models.Request;
using Box.V2.Test.IntegrationNew.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Box.V2.Test.IntegrationNew
{
[TestClass]
public class BoxMetadataManagerIntegrationTest : TestInFolder
{
[TestMethod]
public async Task ExecuteMetadataQuery_ForSmallFile_ShouldBeAbleToFindThisFileByMetadata()
{
var adminFolder = await CreateFolderAsAdmin("0");
var metadataFields = new Dictionary<string, object> { { "status", "active" } };
var uploadedFileWithTemplateKey = await CreateSmallFileWithMetadata(adminFolder.Id, metadataFields);
var templateKey = uploadedFileWithTemplateKey.Item2;

var metadataQueryKey = $"enterprise_{EnterpriseId}.{templateKey}";
var queryRequest = new BoxMetadataQueryRequest
{
AncestorFolderId = adminFolder.Id,
From = metadataQueryKey,
Fields = new List<string>() { $"metadata.{metadataQueryKey}.status" },
Query = "status = :value",
QueryParameters = new Dictionary<string, object>() { { "value", "active" } }
};

var response = await AdminClient.MetadataManager.ExecuteMetadataQueryAsync(queryRequest);

Assert.AreEqual(response.Entries.Count, 1);
Assert.AreEqual(((BoxFile)response.Entries[0]).Metadata[$"enterprise_{EnterpriseId}"][templateKey]["status"].Value, "active");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Box.V2.Test.IntegrationNew.Configuration.Commands.DisposableCommands
{
public class ApplyMetadataCommand : CommandBase, IDisposableCommand
{
private readonly string _templateKey;
private readonly string _fileId;
private readonly Dictionary<string, object> _metadata;

public ApplyMetadataCommand(string templateKey, string fileId, Dictionary<string, object> metadata,
CommandScope scope = CommandScope.Test, CommandAccessLevel accessLevel = CommandAccessLevel.User) : base(scope, accessLevel)
{
_templateKey = templateKey;
_fileId = fileId;
_metadata = metadata;
}

public async Task<string> Execute(IBoxClient client)
{
await client.MetadataManager.CreateFileMetadataAsync(_fileId, _metadata, "enterprise", _templateKey);

return _templateKey;
}

public async Task Dispose(IBoxClient client)
{
await client.MetadataManager.DeleteFileMetadataAsync(_fileId, "enterprise", _templateKey);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Box.V2.Models;

namespace Box.V2.Test.IntegrationNew.Configuration.Commands.DisposableCommands
{
public class CreateMetadataTemplateCommand : CommandBase, IDisposableCommand
{
private readonly List<BoxMetadataTemplateField> _metadataFields;

public string TemplateKey;

public CreateMetadataTemplateCommand(string templateKey, List<BoxMetadataTemplateField> metadataFields,
CommandScope scope = CommandScope.Test, CommandAccessLevel accessLevel = CommandAccessLevel.Admin) : base(scope, accessLevel)
{
TemplateKey = templateKey;
_metadataFields = metadataFields;
}

public async Task<string> Execute(IBoxClient client)
{
var metadataTemplate = new BoxMetadataTemplate
{
DisplayName = TemplateKey,
TemplateKey = TemplateKey,
Scope = "enterprise",
Fields = _metadataFields
};

var response = await client.MetadataManager.CreateMetadataTemplate(metadataTemplate);

return response.Id;
}

public async Task Dispose(IBoxClient client)
{
await client.MetadataManager.DeleteMetadataTemplate("enterprise", TemplateKey);
}
}
}
48 changes: 46 additions & 2 deletions Box.V2.Test.IntegrationNew/Configuration/IntegrationTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Box.V2.Config;
using Box.V2.JWTAuth;
Expand All @@ -22,6 +23,7 @@ public abstract class IntegrationTestBase
protected static string UserId;
protected static bool ClassInit = false;
protected static bool UserCreated = false;
protected static string EnterpriseId;

protected static Stack<IDisposableCommand> ClassCommands;
protected static Stack<IDisposableCommand> TestCommands;
Expand Down Expand Up @@ -57,6 +59,8 @@ public static async Task AssemblyInitialize(TestContext testContext)
}
var userToken = await session.UserTokenAsync(UserId);
UserClient = session.UserClient(userToken, UserId);

EnterpriseId = config.EnterpriseId;
}

[AssemblyCleanup]
Expand Down Expand Up @@ -131,9 +135,16 @@ protected static string GetUniqueName(TestContext testContext)
return string.Format("{0} - {1}", testContext.TestName, Guid.NewGuid().ToString());
}

protected static string GetUniqueName(string resourceName)
protected static string GetUniqueName(string resourceName, bool includeSpecialCharacters = true)
{
return string.Format("{0} - {1}", resourceName, Guid.NewGuid().ToString());
var uniqueName = string.Format("{0} - {1}", resourceName, Guid.NewGuid().ToString());
if (!includeSpecialCharacters)
{
var rgx = new Regex("[^a-zA-Z0-9]");
uniqueName = rgx.Replace(uniqueName, "");
}

return uniqueName;
}

public static async Task ExecuteCommand(ICleanupCommand command)
Expand Down Expand Up @@ -230,5 +241,38 @@ public static async Task<BoxRetentionPolicy> CreateRetentionPolicy(string folder
await ExecuteCommand(createRetentionPolicyCommand);
return createRetentionPolicyCommand.Policy;
}

public static async Task<Tuple<BoxFile, string>> CreateSmallFileWithMetadata
(string parentId = "0", Dictionary<string, object> metadata = null,
CommandScope commandScope = CommandScope.Test, CommandAccessLevel accessLevel = CommandAccessLevel.Admin)
{
var createFileCommand = new CreateFileCommand(GetUniqueName("file"), GetSmallFilePath(), parentId, commandScope, accessLevel);
await ExecuteCommand(createFileCommand);

var createMetadataTemplateCommand = new CreateMetadataTemplateCommand(GetUniqueName("template_key", false), ToStringMetadataFields(metadata), commandScope, accessLevel);
await ExecuteCommand(createMetadataTemplateCommand);

var applyMetadataCommand = new ApplyMetadataCommand(createMetadataTemplateCommand.TemplateKey, createFileCommand.FileId, metadata, commandScope, accessLevel);
await ExecuteCommand(applyMetadataCommand);

return Tuple.Create(createFileCommand.File, createMetadataTemplateCommand.TemplateKey);
}

private static List<BoxMetadataTemplateField> ToStringMetadataFields(Dictionary<string, object> metadataFields)
{
var mappedFields = new List<BoxMetadataTemplateField>();

foreach (var field in metadataFields)
{
mappedFields.Add(new BoxMetadataTemplateField()
{
Type = "string",
Key = field.Key,
DisplayName = field.Key
});
}

return mappedFields;
}
}
}
6 changes: 6 additions & 0 deletions Box.V2.Test/Box.V2.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@
<None Update="Fixtures\BoxFileRequest\GetFileRequest200.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Fixtures\BoxMetadata\ExecuteMetadataQuery200.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Fixtures\BoxMetadata\ExecuteMetadataWithFieldsQuery200.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Fixtures\BoxSignRequest\CancelSignRequest200.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
Expand Down
90 changes: 85 additions & 5 deletions Box.V2.Test/BoxMetadataManagerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Box.V2.Exceptions;
using Box.V2.Managers;
using Box.V2.Models;
using Box.V2.Models.Request;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Newtonsoft.Json;
Expand Down Expand Up @@ -568,13 +569,12 @@ public async Task SetFolderMetadataAsync_Create_Error()
public async Task ExecuteMetadataQuery_ValidResponse()
{
/*** Arrange ***/
var responseString = "{\"entries\":[{\"item\":{\"type\":\"file\",\"id\":\"1617554169109\",\"file_version\":{\"type\":\"file_version\",\"id\":\"1451884469385\",\"sha1\":\"69888bb1bff455d1b2f8afea75ed1ff0b4879bf6\"},\"sequence_id\":\"0\",\"etag\":\"0\",\"sha1\":\"69888bb1bff455d1b2f8afea75ed1ff0b4879bf6\",\"name\":\"My Contract.docx\",\"description\":\"\",\"size\":25600,\"path_collection\":{\"total_count\":4,\"entries\":[{\"type\":\"folder\",\"id\":\"0\",\"sequence_id\":null,\"etag\":null,\"name\":\"All Files\"},{\"type\":\"folder\",\"id\":\"15017998644\",\"sequence_id\":\"0\",\"etag\":\"0\",\"name\":\"Contracts\"},{\"type\":\"folder\",\"id\":\"15286891196\",\"sequence_id\":\"1\",\"etag\":\"1\",\"name\":\"North America\"},{\"type\":\"folder\",\"id\":\"16125613433\",\"sequence_id\":\"0\",\"etag\":\"0\",\"name\":\"2017\"}]},\"created_at\":\"2017-04-20T12:55:27-07:00\",\"modified_at\":\"2017-04-20T12:55:27-07:00\",\"trashed_at\":null,\"purged_at\":null,\"content_created_at\":\"2017-01-06T17:59:01-08:00\",\"content_modified_at\":\"2017-01-06T17:59:01-08:00\",\"created_by\":{\"type\":\"user\",\"id\":\"193973366\",\"name\":\"Box Admin\",\"login\":\"[email protected]\"},\"modified_by\":{\"type\":\"user\",\"id\":\"193973366\",\"name\":\"Box Admin\",\"login\":\"[email protected]\"},\"owned_by\":{\"type\":\"user\",\"id\":\"193973366\",\"name\":\"Box Admin\",\"login\":\"[email protected]\"},\"shared_link\":null,\"parent\":{\"type\":\"folder\",\"id\":\"16125613433\",\"sequence_id\":\"0\",\"etag\":\"0\",\"name\":\"2017\"},\"item_status\":\"active\"},\"metadata\":{\"enterprise_123456\":{\"someTemplate\":{\"$parent\":\"file_161753469109\",\"$version\":0,\"customerName\":\"Phoenix Corp\",\"$type\":\"someTemplate-3d5fcaca-f496-4bb6-9046-d25c37bc5594\",\"$typeVersion\":0,\"$id\":\"ba52e2cc-371d-4659-8d53-50f1ac642e35\",\"amount\":100,\"claimDate\":\"2016-04-10T00:00:00Z\",\"region\":\"West\",\"$typeScope\":\"enterprise_123456\"}}}}],\"next_marker\":\"AAAAAmVYB1FWec8GH6yWu2nwmanfMh07IyYInaa7DZDYjgO1H4KoLW29vPlLY173OKsci6h6xGh61gG73gnaxoS+o0BbI1/h6le6cikjlupVhASwJ2Cj0tOD9wlnrUMHHw3/ISf+uuACzrOMhN6d5fYrbidPzS6MdhJOejuYlvsg4tcBYzjauP3+VU51p77HFAIuObnJT0ff\"}";
IBoxRequest boxRequest = null;
Handler.Setup(h => h.ExecuteAsync<BoxCollectionMarkerBased<BoxMetadataQueryItem>>(It.IsAny<IBoxRequest>()))
.Returns(Task.FromResult<IBoxResponse<BoxCollectionMarkerBased<BoxMetadataQueryItem>>>(new BoxResponse<BoxCollectionMarkerBased<BoxMetadataQueryItem>>()
{
Status = ResponseStatus.Success,
ContentString = responseString
ContentString = LoadFixtureFromJson("Fixtures/BoxMetadata/ExecuteMetadataQuery200.json")
}))
.Callback<IBoxRequest>(r => boxRequest = r);

Expand Down Expand Up @@ -603,7 +603,6 @@ public async Task ExecuteMetadataQuery_ValidResponse()
Assert.AreEqual("amount >= :arg", payload["query"]);
Assert.AreEqual(100, payload["query_params"]["arg"]);
Assert.AreEqual("5555", payload["ancestor_folder_id"]);
Assert.AreEqual("amountAsc", payload["use_index"]);
var payloadOrderBy = JArray.Parse(payload["order_by"].ToString());
Assert.AreEqual("amount", payloadOrderBy[0]["field_key"]);
Assert.AreEqual("ASC", payloadOrderBy[0]["direction"]);
Expand All @@ -630,13 +629,12 @@ public async Task ExecuteMetadataQuery_ValidResponse()
public async Task ExecuteMetadataQueryWithFields_ValidResponse()
{
/*** Arrange ***/
var responseString = "{\"entries\":[{\"type\":\"file\",\"id\":\"1244738582\",\"etag\":\"1\",\"sha1\":\"012b5jdunwkfu438991344044\",\"name\":\"Very Important.docx\",\"metadata\":{\"enterprise_67890\":{\"catalogImages\":{\"$parent\":\"file_50347290\",\"$version\":2,\"$template\":\"catalogImages\",\"$scope\":\"enterprise_67890\",\"photographer\":\"Bob Dylan\"}}}},{\"type\":\"folder\",\"id\":\"124242482\",\"etag\":\"1\",\"sha1\":\"012b5ir8391344044\",\"name\":\"Also Important.docx\",\"metadata\":{\"enterprise_67890\":{\"catalogImages\":{\"$parent\":\"file_50427290\",\"$version\":2,\"$template\":\"catalogImages\",\"$scope\":\"enterprise_67890\",\"photographer\":\"Bob Dylan\"}}}}],\"limit\":2,\"next_marker\":\"0!WkeoDQ3mm5cI_RzSN--UOG1ICuw0gz3729kfhwuoagt54nbvqmgfhsygreh98nfu94344PpctrcgVa8AMIe7gRwSNBNloVR-XuGmfqTw\"}";
IBoxRequest boxRequest = null;
Handler.Setup(h => h.ExecuteAsync<BoxCollectionMarkerBased<BoxItem>>(It.IsAny<IBoxRequest>()))
.Returns(Task.FromResult<IBoxResponse<BoxCollectionMarkerBased<BoxItem>>>(new BoxResponse<BoxCollectionMarkerBased<BoxItem>>()
{
Status = ResponseStatus.Success,
ContentString = responseString
ContentString = LoadFixtureFromJson("Fixtures/BoxMetadata/ExecuteMetadataWithFieldsQuery200.json")
}))
.Callback<IBoxRequest>(r => boxRequest = r);

Expand Down Expand Up @@ -681,5 +679,87 @@ public async Task ExecuteMetadataQueryWithFields_ValidResponse()
var file = (BoxFile)items.Entries[0];
Assert.AreEqual(file.Metadata["enterprise_67890"]["catalogImages"]["photographer"].Value, "Bob Dylan");
}

[TestMethod]
[TestCategory("CI-UNIT-TEST")]
public async Task ExecuteMetadataQueryWithoutUseIndexWithFields_ValidResponse()
{
/*** Arrange ***/
IBoxRequest boxRequest = null;
Handler.Setup(h => h.ExecuteAsync<BoxCollectionMarkerBased<BoxItem>>(It.IsAny<IBoxRequest>()))
.Returns(Task.FromResult<IBoxResponse<BoxCollectionMarkerBased<BoxItem>>>(new BoxResponse<BoxCollectionMarkerBased<BoxItem>>()
{
Status = ResponseStatus.Success,
ContentString = LoadFixtureFromJson("Fixtures/BoxMetadata/ExecuteMetadataWithFieldsQuery200.json")
}))
.Callback<IBoxRequest>(r => boxRequest = r);

/*** Act ***/
var queryParams = new Dictionary<string, object>
{
{ "arg", 100 }
};
var orderByList = new List<BoxMetadataQueryOrderBy>();
var orderBy = new BoxMetadataQueryOrderBy()
{
FieldKey = "amount",
Direction = BoxSortDirection.ASC
};
orderByList.Add(orderBy);
var marker = "q3f87oqf3qygou5t478g9gwrbul";

var metadataRequest = new BoxMetadataQueryRequest
{
From = "enterprise_67890.catalogImages",
Query = "photographer = :arg",
QueryParameters = new Dictionary<string, object>
{
{ "arg", "Bob Dylan" }
},
AncestorFolderId = "5555",
OrderBy = orderByList,
Marker = marker,
AutoPaginate = false,
Fields = new List<string>
{
"id",
"name",
"sha1",
"metadata.enterprise_240748.catalogImages.photographer"
}
};

BoxCollectionMarkerBased<BoxItem> items = await _metadataManager.ExecuteMetadataQueryAsync(metadataRequest);
/*** Assert ***/

// Request check
Assert.IsNotNull(boxRequest);
Assert.AreEqual(RequestMethod.Post, boxRequest.Method);
Assert.AreEqual(MetadataQueryUri, boxRequest.AbsoluteUri.AbsoluteUri);
var payload = JObject.Parse(boxRequest.Payload);
Assert.AreEqual("enterprise_67890.catalogImages", payload["from"]);
Assert.AreEqual("photographer = :arg", payload["query"]);
Assert.AreEqual("5555", payload["ancestor_folder_id"]);
var payloadFields = JArray.Parse(payload["fields"].ToString());
Assert.AreEqual("id", payloadFields[0]);
Assert.AreEqual("name", payloadFields[1]);
Assert.AreEqual("sha1", payloadFields[2]);
Assert.AreEqual("metadata.enterprise_240748.catalogImages.photographer", payloadFields[3]);
Assert.AreEqual(marker, payload["marker"]);
Assert.AreEqual("Bob Dylan", payload["query_params"]["arg"]);
var payloadOrderBy = JArray.Parse(payload["order_by"].ToString());
Assert.AreEqual("amount", payloadOrderBy[0]["field_key"]);
Assert.AreEqual("ASC", payloadOrderBy[0]["direction"]);

// Response check
Assert.AreEqual(items.Entries[0].Type, "file");
Assert.AreEqual(items.Entries[0].Id, "1244738582");
Assert.AreEqual(items.Entries[0].Name, "Very Important.docx");
Assert.AreEqual(items.Entries[1].Type, "folder");
Assert.AreEqual(items.Entries[1].Id, "124242482");
Assert.AreEqual(items.Entries[1].Name, "Also Important.docx");
var file = (BoxFile)items.Entries[0];
Assert.AreEqual(file.Metadata["enterprise_67890"]["catalogImages"]["photographer"].Value, "Bob Dylan");
}
}
}
Loading