Bot Framework와 DirectLine을 이용한 통합 테스트 (2)
이 부분에서는 DirectLine 인증을 수행하고 봇의 응답에서 값을 가져옵니다.
이제 역직렬화를 완료했으므로 인증을 받고 API를 호출하고 결과를 확인하는 데 사용할 컬렉션과 전체에서 정보를 가져올 차례입니다.
다음 설명에서는 Bot Framework 작동 방식에 대한 모든 기본 정보를 다루지 않습니다. 이해가 되지 않는 경우 공식 문서를 확인하세요.
WebClient를 사용하여 API 호출하기
API를 더 쉽게 호출할 수 있도록 utils 클래스를 만들었습니다. 여기에 몇 번 사용할 함수를 저장합니다. 이 클래스에는 POST용 uploadString과 GET용 downloadString가 포함되어 있습니다.
public class Utils
{
/// <summary>
/// Uploads to an URL and gets result
/// </summary>
/// <typeparam name="T">Type of object you are receiving</typeparam>
/// <param name="bearer">Token</param>
/// <param name="url">Url</param>
/// <param name="serializedJson">Serialized JSON to send</param>
/// <returns></returns>
public static T uploadString<T>(string bearer, string url, string serializedJson)
{
string serializedResult = "";
/// Webclient
using (var client = new WebClient())
{
/// Add headers
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("Authorization", $"Bearer {bearer}");
/// Upload string
serializedResult = client.UploadString(url, serializedJson);
}
/// Get result and return it as an object
return JsonConvert.DeserializeObject<T>(serializedResult);
}
/// <summary>
/// Downloads from URL
/// </summary>
/// <typeparam name="T">Type of object you are receiving</typeparam>
/// <param name="bearer">Token</param>
/// <param name="url">Url</param>
/// <returns></returns>
public static T downloadString<T>(string bearer, string url)
{
string serializedResult = "";
/// Webclient
using (var client = new WebClient())
{
/// Add headers
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("Authorization", $"Bearer {bearer}");
/// Download string
serializedResult = client.DownloadString(url);
}
/// Get result and return it as an object
return JsonConvert.DeserializeObject<T>(serializedResult);
}
}
DirectLine 인증
공식 문서를 읽으면 이를 수행하는 방법을 찾을 수 있으며 매우 쉽습니다. 우리 기능을 사용하면 훨씬 더 쉽습니다. 우선 우리가 foreach 문 안에 있다는 점을 기억하세요. 시간이 부족할 경우를 대비해 각 사례에 대해 인증을 수행하고 있기 때문에 테스트가 실패한다는 의미입니다.
/// Arrange with current requested values
string token, newToken, conversationId;
/// Act
/// 1 - Get token using secret from DirectLine in BotFramework panel
token = Utils.uploadString<DirectLineAuth>(data.Secret, data.DirectLineGenerateTokenEndpoint, "").token;
이제 대화 끝점에 대한 다음 호출을 모두 수행하는 데 사용되는 토큰이 있습니다.
대화를 만드는 중입니다.
봇과 대화하려면 먼저 대화를 만들어야 합니다. 이 대화는 대화 ID가 포함된 새 토큰을 반환합니다.
/// 2 -Create a new conversation
var createdConversation = Utils.uploadString<DirectLineAuth>(token, data.DirectLineConversationEndpoint, "");
// This returns a new token and a conversationId
newToken = createdConversation.token;
conversationId = createdConversation.conversationId;
또한 newToken 및 conversationId를 저장합니다. 둘 다 사용자가 봇에 메시지를 보내는 데 필요합니다.
활동을 대화로 보내기
이제 conversationId 및 conversationEndpoint를 사용하여 json 파일에서 request인 Activity를 보내는 최종 엔드포인트를 생성할 수 있습니다.
/// 3 - Send an activity to the conversation with new token and conversationId
string directlineConversationActivitiesEndpoint = data.DirectLineConversationEndpoint + conversationId + "/activities";
Utils.uploadString<DirectLineAuth>(newToken, directlineConversationActivitiesEndpoint, JsonConvert.SerializeObject(entry.Request));
최신 메시지 받기
메시지 기록에서 활동을 보낸 후 봇이 이미 응답했어야 하므로 워터마크가 있는 모든 메시지를 가져온 다음 해당 워터마크를 사용하여 최신 메시지/활동을 필터링해야 합니다.
/// 4 - Get all activities, we get a List<activity> and a watermark
var getLastActivity = Utils.downloadString<ActivityResponse>(newToken, directlineConversationActivitiesEndpoint);
/// 5 - Get the latest activity which is the response we should be expecting
var latestResponse = getLastActivity.activities[Int32.Parse(getLastActivity.watermark)];
이것이 이 부분의 전부입니다. 다음 부분에는 json의 assert에서 텍스트를 가져와서 Javascript에서는 eval()를 사용하고 C#에서는 Assert.isTrue()를 사용하여 최종 테스트 결과를 얻는 것과 같은 코드로 변환하는 부분이 포함됩니다.
모든 코드는 내 github의 this 저장소에 저장되어 있습니다.