instruction
stringclasses
7 values
inputs
dict
outputs
stringclasses
10 values
meta
dict
Напиши тест для этого кода на языке {language} из файла '{focal_file_path}'. Тебе необходимо написать {test_func_type} на языке {language}. Тест будет помещен в файл '{test_file_path}'. Тебе можно использовать следующие сущности, импортированные или объявленные в тестовом файле: {test_func_context} Обращай внимание на следующий код при написании теста: {focal_func_context} Код для тестирования: {focal_func} Напиши только {test_func_type} без каких-либо пояснений или комментариев. Твой ответ должен быть оформлен с помощью markdown следующим образом: ```{language} <your code> ```
{ "focal_func": "\"\"\"\npublic AntiforgeryTokenSet GetAndStoreTokens(HttpContext httpContext)\n {\n if (httpContext == null)\n {\n throw new ArgumentNullException(nameof(httpContext));\n }\n\n CheckSSLConfig(httpContext);\n\n var antiforgeryFeature = GetTokensInternal(httpContext);\n var tokenSet = Serialize(antiforgeryFeature);\n\n if (!antiforgeryFeature.HaveStoredNewCookieToken)\n {\n if (antiforgeryFeature.NewCookieToken != null)\n {\n // Serialize handles the new cookie token string.\n Debug.Assert(antiforgeryFeature.NewCookieTokenString != null);\n\n SaveCookieTokenAndHeader(httpContext, antiforgeryFeature.NewCookieTokenString);\n antiforgeryFeature.HaveStoredNewCookieToken = true;\n _logger.NewCookieToken();\n }\n else\n {\n _logger.ReusedCookieToken();\n }\n }\n\n if (!httpContext.Response.HasStarted)\n {\n // Explicitly set the cache headers to 'no-cache'. This could override any user set value but this is fine\n // as a response with antiforgery token must never be cached.\n SetDoNotCacheHeaders(httpContext);\n }\n\n return tokenSet;\n }\n\"\"\"", "focal_func_context": "\"\"\"\n#src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs\n// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics;\nusing System.Threading.Tasks;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing Microsoft.Net.Http.Headers;\n\nnamespace Microsoft.AspNetCore.Antiforgery.Internal\n{\n /// <summary>\n /// Provides access to the antiforgery system, which provides protection against\n /// Cross-site Request Forgery (XSRF, also called CSRF) attacks.\n /// </summary>\n public class DefaultAntiforgery : IAntiforgery\n {\n private readonly AntiforgeryOptions _options;\n private readonly IAntiforgeryTokenGenerator _tokenGenerator;\n private readonly IAntiforgeryTokenSerializer _tokenSerializer;\n private readonly IAntiforgeryTokenStore _tokenStore;\n private readonly ILogger<DefaultAntiforgery> _logger;\n\n public DefaultAntiforgery(\n IOptions<AntiforgeryOptions> antiforgeryOptionsAccessor,\n IAntiforgeryTokenGenerator tokenGenerator,\n IAntiforgeryTokenSerializer tokenSerializer,\n IAntiforgeryTokenStore tokenStore,\n ILoggerFactory loggerFactory)\n {\n _options = antiforgeryOptionsAccessor.Value;\n _tokenGenerator = tokenGenerator;\n _tokenSerializer = tokenSerializer;\n _tokenStore = tokenStore;\n _logger = loggerFactory.CreateLogger<DefaultAntiforgery>();\n }\n\n /// <inheritdoc />\n public AntiforgeryTokenSet GetAndStoreTokens(HttpContext httpContext)\n {\n if (httpContext == null)\n {\n throw new ArgumentNullException(nameof(httpContext));\n }\n\n CheckSSLConfig(httpContext);\n\n var antiforgeryFeature = GetTokensInternal(httpContext);\n var tokenSet = Serialize(antiforgeryFeature);\n\n if (!antiforgeryFeature.HaveStoredNewCookieToken)\n {\n if (antiforgeryFeature.NewCookieToken != null)\n {\n // Serialize handles the new cookie token string.\n Debug.Assert(antiforgeryFeature.NewCookieTokenString != null);\n\n SaveCookieTokenAndHeader(httpContext, antiforgeryFeature.NewCookieTokenString);\n antiforgeryFeature.HaveStoredNewCookieToken = true;\n _logger.NewCookieToken();\n }\n else\n {\n _logger.ReusedCookieToken();\n }\n }\n\n if (!httpContext.Response.HasStarted)\n {\n // Explicitly set the cache headers to 'no-cache'. This could override any user set value but this is fine\n // as a response with antiforgery token must never be cached.\n SetDoNotCacheHeaders(httpContext);\n }\n\n return tokenSet;\n }\n\n /// <inheritdoc />\n public AntiforgeryTokenSet GetTokens(HttpContext httpContext)\n {\n if (httpContext == null)\n {\n throw new ArgumentNullException(nameof(httpContext));\n }\n\n CheckSSLConfig(httpContext);\n\n var antiforgeryFeature = GetTokensInternal(httpContext);\n return Serialize(antiforgeryFeature);\n }\n\n /// <inheritdoc />\n public async Task<bool> IsRequestValidAsync(HttpContext httpContext)\n {\n if (httpContext == null)\n {\n throw new ArgumentNullException(nameof(httpContext));\n }\n\n CheckSSLConfig(httpContext);\n\n var method = httpContext.Request.Method;\n if (string.Equals(method, \"GET\", StringComparison.OrdinalIgnoreCase) ||\n string.Equals(method, \"HEAD\", StringComparison.OrdinalIgnoreCase) ||\n string.Equals(method, \"OPTIONS\", StringComparison.OrdinalIgnoreCase) ||\n string.Equals(method, \"TRACE\", StringComparison.OrdinalIgnoreCase))\n {\n // Validation not needed for these request types.\n return true;\n }\n\n var tokens = await _tokenStore.GetRequestTokensAsync(httpContext);\n if (tokens.CookieToken == null)\n {\n _logger.MissingCookieToken(_options.Cookie.Name);\n return false;\n }\n\n if (tokens.RequestToken == null)\n {\n _logger.MissingRequestToken(_options.FormFieldName, _options.HeaderName);\n return false;\n }\n\n // Extract cookie & request tokens\n AntiforgeryToken deserializedCookieToken;\n AntiforgeryToken deserializedRequestToken;\n if (!TryDeserializeTokens(httpContext, tokens, out deserializedCookieToken, out deserializedRequestToken))\n {\n return false;\n }\n\n // Validate\n string message;\n var result = _tokenGenerator.TryValidateTokenSet(\n httpContext,\n deserializedCookieToken,\n deserializedRequestToken,\n out message);\n\n if (result)\n {\n _logger.ValidatedAntiforgeryToken();\n }\n else\n {\n _logger.ValidationFailed(message);\n }\n\n return result;\n }\n\n /// <inheritdoc />\n\n#focal function/method here\n\n\n private void ValidateTokens(HttpContext httpContext, AntiforgeryTokenSet antiforgeryTokenSet)\n {\n Debug.Assert(!string.IsNullOrEmpty(antiforgeryTokenSet.CookieToken));\n Debug.Assert(!string.IsNullOrEmpty(antiforgeryTokenSet.RequestToken));\n\n // Extract cookie & request tokens\n AntiforgeryToken deserializedCookieToken;\n AntiforgeryToken deserializedRequestToken;\n\n DeserializeTokens(\n httpContext,\n antiforgeryTokenSet,\n out deserializedCookieToken,\n out deserializedRequestToken);\n\n // Validate\n string message;\n if (!_tokenGenerator.TryValidateTokenSet(\n httpContext,\n deserializedCookieToken,\n deserializedRequestToken,\n out message))\n {\n throw new AntiforgeryValidationException(message);\n }\n }\n\n /// <inheritdoc />\n public void SetCookieTokenAndHeader(HttpContext httpContext)\n {\n if (httpContext == null)\n {\n throw new ArgumentNullException(nameof(httpContext));\n }\n\n CheckSSLConfig(httpContext);\n\n var antiforgeryFeature = GetCookieTokens(httpContext);\n if (!antiforgeryFeature.HaveStoredNewCookieToken && antiforgeryFeature.NewCookieToken != null)\n {\n if (antiforgeryFeature.NewCookieTokenString == null)\n {\n antiforgeryFeature.NewCookieTokenString =\n _tokenSerializer.Serialize(antiforgeryFeature.NewCookieToken);\n }\n\n SaveCookieTokenAndHeader(httpContext, antiforgeryFeature.NewCookieTokenString);\n antiforgeryFeature.HaveStoredNewCookieToken = true;\n _logger.NewCookieToken();\n }\n else\n {\n _logger.ReusedCookieToken();\n }\n\n if (!httpContext.Response.HasStarted)\n {\n SetDoNotCacheHeaders(httpContext);\n }\n }\n\n private void SaveCookieTokenAndHeader(HttpContext httpContext, string cookieToken)\n {\n if (cookieToken != null)\n {\n // Persist the new cookie if it is not null.\n _tokenStore.SaveCookieToken(httpContext, cookieToken);\n }\n\n if (!_options.SuppressXFrameOptionsHeader && !httpContext.Response.Headers.ContainsKey(\"X-Frame-Options\"))\n {\n // Adding X-Frame-Options header to prevent ClickJacking. See\n // http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-10\n // for more information.\n httpContext.Response.Headers[\"X-Frame-Options\"] = \"SAMEORIGIN\";\n }\n }\n\n private void CheckSSLConfig(HttpContext context)\n {\n if (_options.Cookie.SecurePolicy == CookieSecurePolicy.Always && !context.Request.IsHttps)\n {\n throw new InvalidOperationException(Resources.FormatAntiforgery_RequiresSSL(\n string.Join(\".\", nameof(AntiforgeryOptions), nameof(AntiforgeryOptions.Cookie), nameof(CookieBuilder.SecurePolicy)),\n nameof(CookieSecurePolicy.Always)));\n }\n }\n\n private static IAntiforgeryFeature GetAntiforgeryFeature(HttpContext httpContext)\n {\n var antiforgeryFeature = httpContext.Features.Get<IAntiforgeryFeature>();\n if (antiforgeryFeature == null)\n {\n antiforgeryFeature = new AntiforgeryFeature();\n httpContext.Features.Set(antiforgeryFeature);\n }\n\n return antiforgeryFeature;\n }\n\n private IAntiforgeryFeature GetCookieTokens(HttpContext httpContext)\n {\n var antiforgeryFeature = GetAntiforgeryFeature(httpContext);\n\n if (antiforgeryFeature.HaveGeneratedNewCookieToken)\n {\n Debug.Assert(antiforgeryFeature.HaveDeserializedCookieToken);\n\n // Have executed this method earlier in the context of this request.\n return antiforgeryFeature;\n }\n\n AntiforgeryToken cookieToken;\n if (antiforgeryFeature.HaveDeserializedCookieToken)\n {\n cookieToken = antiforgeryFeature.CookieToken;\n }\n else\n {\n cookieToken = GetCookieTokenDoesNotThrow(httpContext);\n\n antiforgeryFeature.CookieToken = cookieToken;\n antiforgeryFeature.HaveDeserializedCookieToken = true;\n }\n\n AntiforgeryToken newCookieToken;\n if (_tokenGenerator.IsCookieTokenValid(cookieToken))\n {\n // No need for the cookie token from the request after it has been verified.\n newCookieToken = null;\n }\n else\n {\n // Need to make sure we're always operating with a good cookie token.\n newCookieToken = _tokenGenerator.GenerateCookieToken();\n Debug.Assert(_tokenGenerator.IsCookieTokenValid(newCookieToken));\n }\n\n antiforgeryFeature.HaveGeneratedNewCookieToken = true;\n antiforgeryFeature.NewCookieToken = newCookieToken;\n\n return antiforgeryFeature;\n }\n\n private AntiforgeryToken GetCookieTokenDoesNotThrow(HttpContext httpContext)\n {\n try\n {\n var serializedToken = _tokenStore.GetCookieToken(httpContext);\n\n if (serializedToken != null)\n {\n var token = _tokenSerializer.Deserialize(serializedToken);\n return token;\n }\n }\n catch (Exception ex)\n {\n // ignore failures since we'll just generate a new token\n _logger.TokenDeserializeException(ex);\n }\n\n return null;\n }\n\n private IAntiforgeryFeature GetTokensInternal(HttpContext httpContext)\n {\n var antiforgeryFeature = GetCookieTokens(httpContext);\n if (antiforgeryFeature.NewRequestToken == null)\n {\n var cookieToken = antiforgeryFeature.NewCookieToken ?? antiforgeryFeature.CookieToken;\n antiforgeryFeature.NewRequestToken = _tokenGenerator.GenerateRequestToken(\n httpContext,\n cookieToken);\n }\n\n return antiforgeryFeature;\n }\n\n /// <summary>\n /// Sets the 'Cache-Control' header to 'no-cache, no-store' and 'Pragma' header to 'no-cache' overriding any user set value.\n /// </summary>\n /// <param name=\"httpContext\">The <see cref=\"HttpContext\"/>.</param>\n protected virtual void SetDoNotCacheHeaders(HttpContext httpContext)\n {\n // Since antifogery token generation is not very obvious to the end users (ex: MVC's form tag generates them\n // by default), log a warning to let users know of the change in behavior to any cache headers they might\n // have set explicitly.\n LogCacheHeaderOverrideWarning(httpContext.Response);\n\n httpContext.Response.Headers[HeaderNames.CacheControl] = \"no-cache, no-store\";\n httpContext.Response.Headers[HeaderNames.Pragma] = \"no-cache\";\n }\n\n private void LogCacheHeaderOverrideWarning(HttpResponse response)\n {\n var logWarning = false;\n CacheControlHeaderValue cacheControlHeaderValue;\n if (CacheControlHeaderValue.TryParse(response.Headers[HeaderNames.CacheControl].ToString(), out cacheControlHeaderValue))\n {\n if (!cacheControlHeaderValue.NoCache)\n {\n logWarning = true;\n }\n }\n\n var pragmaHeader = response.Headers[HeaderNames.Pragma];\n if (!logWarning\n && !string.IsNullOrEmpty(pragmaHeader)\n && string.Compare(pragmaHeader, \"no-cache\", ignoreCase: true) != 0)\n {\n logWarning = true;\n }\n\n if (logWarning)\n {\n _logger.ResponseCacheHeadersOverridenToNoCache();\n }\n }\n\n private AntiforgeryTokenSet Serialize(IAntiforgeryFeature antiforgeryFeature)\n {\n // Should only be called after new tokens have been generated.\n Debug.Assert(antiforgeryFeature.HaveGeneratedNewCookieToken);\n Debug.Assert(antiforgeryFeature.NewRequestToken != null);\n\n if (antiforgeryFeature.NewRequestTokenString == null)\n {\n antiforgeryFeature.NewRequestTokenString =\n _tokenSerializer.Serialize(antiforgeryFeature.NewRequestToken);\n }\n\n if (antiforgeryFeature.NewCookieTokenString == null && antiforgeryFeature.NewCookieToken != null)\n {\n antiforgeryFeature.NewCookieTokenString =\n _tokenSerializer.Serialize(antiforgeryFeature.NewCookieToken);\n }\n\n return new AntiforgeryTokenSet(\n antiforgeryFeature.NewRequestTokenString,\n antiforgeryFeature.NewCookieTokenString,\n _options.FormFieldName,\n _options.HeaderName);\n }\n\n private bool TryDeserializeTokens(\n HttpContext httpContext,\n AntiforgeryTokenSet antiforgeryTokenSet,\n out AntiforgeryToken cookieToken,\n out AntiforgeryToken requestToken)\n {\n try\n {\n DeserializeTokens(httpContext, antiforgeryTokenSet, out cookieToken, out requestToken);\n return true;\n }\n catch (AntiforgeryValidationException ex)\n {\n _logger.FailedToDeserialzeTokens(ex);\n\n cookieToken = null;\n requestToken = null;\n return false;\n }\n }\n\n private void DeserializeTokens(\n HttpContext httpContext,\n AntiforgeryTokenSet antiforgeryTokenSet,\n out AntiforgeryToken cookieToken,\n out AntiforgeryToken requestToken)\n {\n var antiforgeryFeature = GetAntiforgeryFeature(httpContext);\n\n if (antiforgeryFeature.HaveDeserializedCookieToken)\n {\n cookieToken = antiforgeryFeature.CookieToken;\n }\n else\n {\n cookieToken = _tokenSerializer.Deserialize(antiforgeryTokenSet.CookieToken);\n\n antiforgeryFeature.CookieToken = cookieToken;\n antiforgeryFeature.HaveDeserializedCookieToken = true;\n }\n\n if (antiforgeryFeature.HaveDeserializedRequestToken)\n {\n requestToken = antiforgeryFeature.RequestToken;\n }\n else\n {\n requestToken = _tokenSerializer.Deserialize(antiforgeryTokenSet.RequestToken);\n\n antiforgeryFeature.RequestToken = requestToken;\n antiforgeryFeature.HaveDeserializedRequestToken = true;\n }\n }\n }\n}\n\"\"\"", "test_func_type": "тестовый метод", "test_func_context": "\"\"\"\nusing System;\nusing System.Linq;\nusing System.Security.Claims;\nusing System.Threading.Tasks;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.AspNetCore.Http.Features;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Testing;\nusing Microsoft.Extensions.Options;\nusing Microsoft.Net.Http.Headers;\nusing Moq;\nusing Xunit;\n// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\npublic class DefaultAntiforgeryTest\n {\n private const string ResponseCacheHeadersOverrideWarningMessage =\n \"The 'Cache-Control' and 'Pragma' headers have been overridden and set to 'no-cache, no-store' and \" +\n \"'no-cache' respectively to prevent caching of this response. Any response that uses antiforgery \" +\n \"should not be cached.\";\n private DefaultAntiforgery GetAntiforgery(\n HttpContext httpContext,\n AntiforgeryOptions options = null,\n IAntiforgeryTokenGenerator tokenGenerator = null,\n IAntiforgeryTokenSerializer tokenSerializer = null,\n IAntiforgeryTokenStore tokenStore = null)\n {\n var optionsManager = new TestOptionsManager();\n if (options != null)\n {\n optionsManager.Value = options;\n }\n var loggerFactory = httpContext.RequestServices.GetRequiredService<ILoggerFactory>();\n return new DefaultAntiforgery(\n antiforgeryOptionsAccessor: optionsManager,\n tokenGenerator: tokenGenerator,\n tokenSerializer: tokenSerializer,\n tokenStore: tokenStore,\n loggerFactory: loggerFactory);\n }\n private IServiceProvider GetServices()\n {\n var builder = new ServiceCollection();\n builder.AddSingleton<ILoggerFactory>(new LoggerFactory());\n return builder.BuildServiceProvider();\n }\n private HttpContext GetHttpContext(IAntiforgeryFeature antiforgeryFeature = null)\n {\n var httpContext = new DefaultHttpContext();\n antiforgeryFeature = antiforgeryFeature ?? new AntiforgeryFeature();\n httpContext.Features.Set(antiforgeryFeature);\n httpContext.RequestServices = GetServices();\n httpContext.User = new ClaimsPrincipal(new ClaimsIdentity(\"some-auth\"));\n return httpContext;\n }\n private DefaultAntiforgery GetAntiforgery(AntiforgeryMockContext context)\n {\n return GetAntiforgery(\n context.HttpContext,\n context.Options,\n context.TokenGenerator?.Object,\n context.TokenSerializer?.Object,\n context.TokenStore?.Object);\n }\n private Mock<IAntiforgeryTokenStore> GetTokenStore(\n HttpContext context,\n TestTokenSet testTokenSet,\n bool saveNewCookie = true)\n {\n var oldCookieToken = testTokenSet.OldCookieTokenString;\n var formToken = testTokenSet.FormTokenString;\n var mockTokenStore = new Mock<IAntiforgeryTokenStore>(MockBehavior.Strict);\n mockTokenStore\n .Setup(o => o.GetCookieToken(context))\n .Returns(oldCookieToken);\n mockTokenStore\n .Setup(o => o.GetRequestTokensAsync(context))\n .Returns(() => Task.FromResult(new AntiforgeryTokenSet(\n formToken,\n oldCookieToken,\n \"form\",\n \"header\")));\n if (saveNewCookie)\n {\n var newCookieToken = testTokenSet.NewCookieTokenString;\n mockTokenStore\n .Setup(o => o.SaveCookieToken(context, newCookieToken))\n .Verifiable();\n }\n return mockTokenStore;\n }\n private Mock<IAntiforgeryTokenSerializer> GetTokenSerializer(TestTokenSet testTokenSet)\n {\n var oldCookieToken = testTokenSet.OldCookieToken;\n var newCookieToken = testTokenSet.NewCookieToken;\n var formToken = testTokenSet.RequestToken;\n var mockSerializer = new Mock<IAntiforgeryTokenSerializer>(MockBehavior.Strict);\n mockSerializer.Setup(o => o.Serialize(formToken))\n .Returns(testTokenSet.FormTokenString);\n mockSerializer.Setup(o => o.Deserialize(testTokenSet.FormTokenString))\n .Returns(formToken);\n mockSerializer.Setup(o => o.Deserialize(testTokenSet.OldCookieTokenString))\n .Returns(oldCookieToken);\n mockSerializer.Setup(o => o.Serialize(oldCookieToken))\n .Returns(testTokenSet.OldCookieTokenString);\n mockSerializer.Setup(o => o.Serialize(newCookieToken))\n .Returns(testTokenSet.NewCookieTokenString);\n return mockSerializer;\n }\n private AntiforgeryMockContext CreateMockContext(\n AntiforgeryOptions options,\n bool useOldCookie = false,\n bool isOldCookieValid = true,\n IAntiforgeryFeature antiforgeryFeature = null)\n {\n // Arrange\n var httpContext = GetHttpContext(antiforgeryFeature);\n var testTokenSet = GetTokenSet();\n var mockSerializer = GetTokenSerializer(testTokenSet);\n var mockTokenStore = GetTokenStore(httpContext, testTokenSet, !useOldCookie);\n var mockGenerator = new Mock<IAntiforgeryTokenGenerator>(MockBehavior.Strict);\n mockGenerator\n .Setup(o => o.GenerateRequestToken(\n httpContext,\n useOldCookie ? testTokenSet.OldCookieToken : testTokenSet.NewCookieToken))\n .Returns(testTokenSet.RequestToken);\n mockGenerator\n .Setup(o => o.GenerateCookieToken())\n .Returns(useOldCookie ? testTokenSet.OldCookieToken : testTokenSet.NewCookieToken);\n mockGenerator\n .Setup(o => o.IsCookieTokenValid(null))\n .Returns(false);\n mockGenerator\n .Setup(o => o.IsCookieTokenValid(testTokenSet.OldCookieToken))\n .Returns(isOldCookieValid);\n mockGenerator\n .Setup(o => o.IsCookieTokenValid(testTokenSet.NewCookieToken))\n .Returns(!isOldCookieValid);\n return new AntiforgeryMockContext()\n {\n Options = options,\n HttpContext = httpContext,\n TokenGenerator = mockGenerator,\n TokenSerializer = mockSerializer,\n TokenStore = mockTokenStore,\n TestTokenSet = testTokenSet\n };\n }\n private TestTokenSet GetTokenSet()\n {\n return new TestTokenSet()\n {\n RequestToken = new AntiforgeryToken() { IsCookieToken = false },\n FormTokenString = \"serialized-form-token\",\n OldCookieToken = new AntiforgeryToken() { IsCookieToken = true },\n OldCookieTokenString = \"serialized-old-cookie-token\",\n NewCookieToken = new AntiforgeryToken() { IsCookieToken = true },\n NewCookieTokenString = \"serialized-new-cookie-token\",\n };\n }\n private class TestTokenSet\n {\n public AntiforgeryToken RequestToken { get; set; }\n public string FormTokenString { get; set; }\n public AntiforgeryToken OldCookieToken { get; set; }\n public string OldCookieTokenString { get; set; }\n public AntiforgeryToken NewCookieToken { get; set; }\n public string NewCookieTokenString { get; set; }\n }\n private class AntiforgeryMockContext\n {\n public AntiforgeryOptions Options { get; set; }\n public TestTokenSet TestTokenSet { get; set; }\n public HttpContext HttpContext { get; set; }\n public Mock<IAntiforgeryTokenGenerator> TokenGenerator { get; set; }\n public Mock<IAntiforgeryTokenStore> TokenStore { get; set; }\n public Mock<IAntiforgeryTokenSerializer> TokenSerializer { get; set; }\n }\n private class TestOptionsManager : IOptions<AntiforgeryOptions>\n {\n public AntiforgeryOptions Value { get; set; } = new AntiforgeryOptions();\n }\n private class TestResponseFeature : HttpResponseFeature\n {\n private bool _hasStarted = false;\n public override bool HasStarted { get => _hasStarted; }\n public TestResponseFeature()\n {\n }\n public void StartResponse()\n {\n _hasStarted = true;\n }\n }\n }\n\"\"\"", "language": "csharp", "focal_file_path": "src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs", "test_file_path": "test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs", "test_framework": "" }
[Fact] public void GetAndStoreTokens_NoExistingCookieToken_Saved_AndSetsDoNotCacheHeaders() { // Arrange var antiforgeryFeature = new AntiforgeryFeature(); var context = CreateMockContext( new AntiforgeryOptions(), useOldCookie: false, isOldCookieValid: false, antiforgeryFeature: antiforgeryFeature); var antiforgery = GetAntiforgery(context); // Act var tokenSet = antiforgery.GetAndStoreTokens(context.HttpContext); // Assert context.TokenStore.Verify( t => t.SaveCookieToken(It.IsAny<HttpContext>(), context.TestTokenSet.NewCookieTokenString), Times.Once); Assert.Equal(context.TestTokenSet.NewCookieTokenString, tokenSet.CookieToken); Assert.Equal(context.TestTokenSet.FormTokenString, tokenSet.RequestToken); Assert.NotNull(antiforgeryFeature); Assert.True(antiforgeryFeature.HaveDeserializedCookieToken); Assert.Equal(context.TestTokenSet.OldCookieToken, antiforgeryFeature.CookieToken); Assert.Equal("no-cache, no-store", context.HttpContext.Response.Headers[HeaderNames.CacheControl]); Assert.Equal("no-cache", context.HttpContext.Response.Headers[HeaderNames.Pragma]); }
{ "id": 0, "repo_id": "36972072", "focal_func_type": "method" }
Ваша задача: лаконично и строго написать {test_func_type} на {language} для следующего кода из файла '{focal_file_path}': {focal_func} Вы можете использовать только эти сущности, уже определённые в тестовом файле ('{test_file_path}'): {test_func_context} Изучите остальной код файла '{focal_file_path}' для понимания контекста: {focal_func_context} Запрещено включать дополнительные пояснения, любой текст вне кода, обсуждение ограничений или вариантов. Нужно написать только {test_func_type}. Оберните ваш тест в markdown, как показано в шаблоне: ```{language} <your code> ```
{ "focal_func": "```csharp\npublic static string Build(Assembly assembly, string prefix = \"api/\")\n {\n List<Controller> controllers = GetApis(assembly);\n string code = CreateCode(controllers);\n return code.ToString();\n }\n```", "focal_func_context": "```csharp\n#EasyTool.Web/DevelopmentCategory/BuildWebApiToTS.cs\nusing Microsoft.AspNetCore.Mvc;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\n\nnamespace EasyTool.Web.Development\n{\n public static class BuildWebApiToTS\n {\n\n#focal function/method here\n\n\n\n public static void BuildToFile(Assembly assembly, string path, string prefix = \"api/\")\n {\n var code = Build(assembly, prefix);\n string existsCode = \"\";\n if (System.IO.File.Exists(path) == true)\n existsCode = System.IO.File.ReadAllText(path);\n\n if (existsCode != code)\n {\n System.IO.File.WriteAllText(path, code);\n }\n }\n\n #region 构造代码\n\n public static string CreateCode(List<Controller> controllers, string prefix = \"api/\")\n {\n StringBuilder code = new StringBuilder();\n code.AppendLine(\"import { environment } from 'src/environments/environment';\");\n code.AppendLine(\"export const WebAPI = {\");\n\n foreach (var coll in controllers)\n {\n code.AppendLine($\" /** {coll.ApiComments?.Title} */\");\n code.AppendLine($\" {coll.Name}: {{\");\n code.AppendLine($\" Controller: `${{environment.host}}/{prefix}{coll.Name}`,\");\n foreach (var action in coll.Actions)\n {\n code.AppendLine($\" /** {action.Type} {action.ApiComments?.Title} */\");\n code.AppendLine($\" {action.Name}: `${{environment.host}}/{prefix}{coll.Name}/{action.Name}`,\");\n\n if ((action.Type == \"GET\" || action.Type == \"DELETE\") && action.ApiComments?.ParamNames?.Length > 0)\n {\n var pars = action.ApiComments.ParamNames.Select(x => $\"{x}: string | number\").Aggregate((a, b) => a + \",\" + b);\n var urlpars = action.ApiComments.ParamNames.Select(x => $\"{x}=${{{x}}}\").Aggregate((a, b) => a + \"&\" + b);\n\n code.AppendLine($@\" {action.Name}Url({pars}): string {{ return `${{environment.host}}/{prefix}{coll.Name}/{action.Name}?{urlpars}`; }},\");\n \n }\n }\n code.AppendLine($\" }},\");\n }\n\n code.AppendLine($\"}};\");\n return code.ToString();\n\n\n /*\nimport { environment } from \"src/environments/environment\";\n\nexport const WebAPI = {\n\n Debug: {\n Controller: `${environment.host}/api/Debug`,\n\n DeleteResultT: `${environment.host}/api/Debug/DeleteResultT`,\n\n GetResult(a:string){\n return `${environment.host}/api/Debug/GetResult?a=${a}`;\n }\n },\n * */\n }\n\n #endregion\n\n #region 获得接口清单\n\n public static List<Controller> GetApis(Assembly assembly)\n {\n List<Controller> controllers = new List<Controller>();\n\n var collTypes = assembly.GetTypes().Where(x => x.GetCustomAttributes(typeof(ApiControllerAttribute), false).Count() > 0);\n foreach (var collType in collTypes)\n {\n var controller = new Controller(collType.Name.Replace(\"Controller\", \"\"));\n controller.ApiComments = collType.GetCustomAttribute<ApiCommentsAttribute>();\n controllers.Add(controller);\n\n controller.Actions.AddRange(GetTypeMembers(collType, typeof(HttpGetAttribute), \"GET\"));\n controller.Actions.AddRange(GetTypeMembers(collType, typeof(HttpPostAttribute), \"POST\"));\n controller.Actions.AddRange(GetTypeMembers(collType, typeof(HttpPutAttribute), \"PUT\"));\n controller.Actions.AddRange(GetTypeMembers(collType, typeof(HttpDeleteAttribute), \"DELETE\"));\n }\n\n return controllers;\n }\n private static List<Action> GetTypeMembers(Type type, Type whereType, string saveType)\n {\n var actonTypes = type.GetMembers().Where(x => x.GetCustomAttributes(whereType, false).Count() > 0);\n\n List<Action> actons = new List<Action>();\n foreach (var actonType in actonTypes)\n {\n var action = new Action(saveType, actonType.Name);\n action.ApiComments = actonType.GetCustomAttribute<ApiCommentsAttribute>();\n actons.Add(action);\n }\n\n return actons;\n }\n\n public class Controller\n {\n public Controller(string name)\n {\n Name = name;\n }\n public string Name { get; set; }\n public ApiCommentsAttribute ApiComments { get; set; }\n public List<Action> Actions { get; set; } = new List<Action>();\n }\n\n public class Action\n {\n public Action(string type, string name)\n {\n Type = type;\n Name = name;\n }\n public string Type { get; set; }\n public string Name { get; set; }\n\n public ApiCommentsAttribute ApiComments { get; set; }\n }\n\n #endregion\n\n\n }\n\n public class ApiCommentsAttribute : Attribute\n {\n public string Title { get; set; }\n\n public string[] ParamNames { get; set; } = new string[0];\n public ApiCommentsAttribute(string title, params string[] paramNames)\n {\n Title = title;\n ParamNames = paramNames;\n }\n }\n}\n```", "test_func_type": "тестовый метод", "test_func_context": "```\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing EasyTool.Web.Development;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.ComponentModel;\n[TestClass()]\n public class BuildOptionToTSTests\n {\n }\n```", "language": "csharp", "focal_file_path": "EasyTool.Web/DevelopmentCategory/BuildWebApiToTS.cs", "test_file_path": "EasyTool.WebTests/DevelopmentCategory/BuildOptionToTSTests.cs", "test_framework": "" }
[TestMethod()] public void BuildTest() { var toDto = BuildOptionToTS.Build(this.GetType().Assembly); Assert.IsTrue(toDto.Contains("BuildOptionTest")); }
{ "id": 1, "repo_id": "642808011", "focal_func_type": "method" }
Ваша задача: лаконично и строго написать {test_func_type} на {language} для следующего кода из файла '{focal_file_path}': {focal_func} Код теста должен использовать {test_framework} фреймворк. Вы можете использовать только эти сущности, уже определённые в тестовом файле ('{test_file_path}'): {test_func_context} Изучите остальной код файла '{focal_file_path}' для понимания контекста: {focal_func_context} Запрещено включать дополнительные пояснения, любой текст вне кода, обсуждение ограничений или вариантов. Напиши только {test_func_type}. Оберните ваш тест в markdown, как показано в шаблоне: ```{language} <your code> ```
{ "focal_func": "```js\nResponse.prototype.clone = function() {\n return new Response(this._bodyInit, {\n status: this.status,\n statusText: this.statusText,\n headers: new Headers(this.headers),\n url: this.url\n })\n}\n```", "focal_func_context": "```js\n#fetch.js\n/* eslint-disable no-prototype-builtins */\nvar g =\n (typeof globalThis !== 'undefined' && globalThis) ||\n (typeof self !== 'undefined' && self) ||\n // eslint-disable-next-line no-undef\n (typeof global !== 'undefined' && global) ||\n {}\nvar support = {\n searchParams: 'URLSearchParams' in g,\n iterable: 'Symbol' in g && 'iterator' in Symbol,\n blob:\n 'FileReader' in g &&\n 'Blob' in g &&\n (function() {\n try {\n new Blob()\n return true\n } catch (e) {\n return false\n }\n })(),\n formData: 'FormData' in g,\n arrayBuffer: 'ArrayBuffer' in g\n}\nfunction isDataView(obj) {\n return obj && DataView.prototype.isPrototypeOf(obj)\n}\nif (support.arrayBuffer) {\n var viewClasses = [\n '[object Int8Array]',\n '[object Uint8Array]',\n '[object Uint8ClampedArray]',\n '[object Int16Array]',\n '[object Uint16Array]',\n '[object Int32Array]',\n '[object Uint32Array]',\n '[object Float32Array]',\n '[object Float64Array]'\n ]\n var isArrayBufferView =\n ArrayBuffer.isView ||\n function(obj) {\n return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1\n }\n}\nfunction normalizeName(name) {\n if (typeof name !== 'string') {\n name = String(name)\n }\n if (/[^a-z0-9\\-#$%&'*+.^_`|~!]/i.test(name) || name === '') {\n throw new TypeError('Invalid character in header field name: \"' + name + '\"')\n }\n return name.toLowerCase()\n}\nfunction normalizeValue(value) {\n if (typeof value !== 'string') {\n value = String(value)\n }\n return value\n}\n// Build a destructive iterator for the value list\nfunction iteratorFor(items) {\n var iterator = {\n next: function() {\n var value = items.shift()\n return {done: value === undefined, value: value}\n }\n }\n if (support.iterable) {\n iterator[Symbol.iterator] = function() {\n return iterator\n }\n }\n return iterator\n}\nexport function Headers(headers) {\n this.map = {}\n if (headers instanceof Headers) {\n headers.forEach(function(value, name) {\n this.append(name, value)\n }, this)\n } else if (Array.isArray(headers)) {\n headers.forEach(function(header) {\n if (header.length != 2) {\n throw new TypeError('Headers constructor: expected name/value pair to be length 2, found' + header.length)\n }\n this.append(header[0], header[1])\n }, this)\n } else if (headers) {\n Object.getOwnPropertyNames(headers).forEach(function(name) {\n this.append(name, headers[name])\n }, this)\n }\n}\nHeaders.prototype.append = function(name, value) {\n name = normalizeName(name)\n value = normalizeValue(value)\n var oldValue = this.map[name]\n this.map[name] = oldValue ? oldValue + ', ' + value : value\n}\nHeaders.prototype['delete'] = function(name) {\n delete this.map[normalizeName(name)]\n}\nHeaders.prototype.get = function(name) {\n name = normalizeName(name)\n return this.has(name) ? this.map[name] : null\n}\nHeaders.prototype.has = function(name) {\n return this.map.hasOwnProperty(normalizeName(name))\n}\nHeaders.prototype.set = function(name, value) {\n this.map[normalizeName(name)] = normalizeValue(value)\n}\nHeaders.prototype.forEach = function(callback, thisArg) {\n for (var name in this.map) {\n if (this.map.hasOwnProperty(name)) {\n callback.call(thisArg, this.map[name], name, this)\n }\n }\n}\nHeaders.prototype.keys = function() {\n var items = []\n this.forEach(function(value, name) {\n items.push(name)\n })\n return iteratorFor(items)\n}\nHeaders.prototype.values = function() {\n var items = []\n this.forEach(function(value) {\n items.push(value)\n })\n return iteratorFor(items)\n}\nHeaders.prototype.entries = function() {\n var items = []\n this.forEach(function(value, name) {\n items.push([name, value])\n })\n return iteratorFor(items)\n}\nif (support.iterable) {\n Headers.prototype[Symbol.iterator] = Headers.prototype.entries\n}\nfunction consumed(body) {\n if (body._noBody) return\n if (body.bodyUsed) {\n return Promise.reject(new TypeError('Already read'))\n }\n body.bodyUsed = true\n}\nfunction fileReaderReady(reader) {\n return new Promise(function(resolve, reject) {\n reader.onload = function() {\n resolve(reader.result)\n }\n reader.onerror = function() {\n reject(reader.error)\n }\n })\n}\nfunction readBlobAsArrayBuffer(blob) {\n var reader = new FileReader()\n var promise = fileReaderReady(reader)\n reader.readAsArrayBuffer(blob)\n return promise\n}\nfunction readBlobAsText(blob) {\n var reader = new FileReader()\n var promise = fileReaderReady(reader)\n var match = /charset=([A-Za-z0-9_-]+)/.exec(blob.type)\n var encoding = match ? match[1] : 'utf-8'\n reader.readAsText(blob, encoding)\n return promise\n}\nfunction readArrayBufferAsText(buf) {\n var view = new Uint8Array(buf)\n var chars = new Array(view.length)\n for (var i = 0; i < view.length; i++) {\n chars[i] = String.fromCharCode(view[i])\n }\n return chars.join('')\n}\nfunction bufferClone(buf) {\n if (buf.slice) {\n return buf.slice(0)\n } else {\n var view = new Uint8Array(buf.byteLength)\n view.set(new Uint8Array(buf))\n return view.buffer\n }\n}\nfunction Body() {\n this.bodyUsed = false\n this._initBody = function(body) {\n /*\n fetch-mock wraps the Response object in an ES6 Proxy to\n provide useful test harness features such as flush. However, on\n ES5 browsers without fetch or Proxy support pollyfills must be used;\n the proxy-pollyfill is unable to proxy an attribute unless it exists\n on the object before the Proxy is created. This change ensures\n Response.bodyUsed exists on the instance, while maintaining the\n semantic of setting Request.bodyUsed in the constructor before\n _initBody is called.\n */\n // eslint-disable-next-line no-self-assign\n this.bodyUsed = this.bodyUsed\n this._bodyInit = body\n if (!body) {\n this._noBody = true;\n this._bodyText = ''\n } else if (typeof body === 'string') {\n this._bodyText = body\n } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {\n this._bodyBlob = body\n } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {\n this._bodyFormData = body\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this._bodyText = body.toString()\n } else if (support.arrayBuffer && support.blob && isDataView(body)) {\n this._bodyArrayBuffer = bufferClone(body.buffer)\n // IE 10-11 can't handle a DataView body.\n this._bodyInit = new Blob([this._bodyArrayBuffer])\n } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {\n this._bodyArrayBuffer = bufferClone(body)\n } else {\n this._bodyText = body = Object.prototype.toString.call(body)\n }\n if (!this.headers.get('content-type')) {\n if (typeof body === 'string') {\n this.headers.set('content-type', 'text/plain;charset=UTF-8')\n } else if (this._bodyBlob && this._bodyBlob.type) {\n this.headers.set('content-type', this._bodyBlob.type)\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')\n }\n }\n }\n if (support.blob) {\n this.blob = function() {\n var rejected = consumed(this)\n if (rejected) {\n return rejected\n }\n if (this._bodyBlob) {\n return Promise.resolve(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(new Blob([this._bodyArrayBuffer]))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as blob')\n } else {\n return Promise.resolve(new Blob([this._bodyText]))\n }\n }\n }\n this.arrayBuffer = function() {\n if (this._bodyArrayBuffer) {\n var isConsumed = consumed(this)\n if (isConsumed) {\n return isConsumed\n } else if (ArrayBuffer.isView(this._bodyArrayBuffer)) {\n return Promise.resolve(\n this._bodyArrayBuffer.buffer.slice(\n this._bodyArrayBuffer.byteOffset,\n this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength\n )\n )\n } else {\n return Promise.resolve(this._bodyArrayBuffer)\n }\n } else if (support.blob) {\n return this.blob().then(readBlobAsArrayBuffer)\n } else {\n throw new Error('could not read as ArrayBuffer')\n }\n }\n this.text = function() {\n var rejected = consumed(this)\n if (rejected) {\n return rejected\n }\n if (this._bodyBlob) {\n return readBlobAsText(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as text')\n } else {\n return Promise.resolve(this._bodyText)\n }\n }\n if (support.formData) {\n this.formData = function() {\n return this.text().then(decode)\n }\n }\n this.json = function() {\n return this.text().then(JSON.parse)\n }\n return this\n}\n// HTTP methods whose capitalization should be normalized\nvar methods = ['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'TRACE']\nfunction normalizeMethod(method) {\n var upcased = method.toUpperCase()\n return methods.indexOf(upcased) > -1 ? upcased : method\n}\nexport function Request(input, options) {\n if (!(this instanceof Request)) {\n throw new TypeError('Please use the \"new\" operator, this DOM object constructor cannot be called as a function.')\n }\n options = options || {}\n var body = options.body\n if (input instanceof Request) {\n if (input.bodyUsed) {\n throw new TypeError('Already read')\n }\n this.url = input.url\n this.credentials = input.credentials\n if (!options.headers) {\n this.headers = new Headers(input.headers)\n }\n this.method = input.method\n this.mode = input.mode\n this.signal = input.signal\n if (!body && input._bodyInit != null) {\n body = input._bodyInit\n input.bodyUsed = true\n }\n } else {\n this.url = String(input)\n }\n this.credentials = options.credentials || this.credentials || 'same-origin'\n if (options.headers || !this.headers) {\n this.headers = new Headers(options.headers)\n }\n this.method = normalizeMethod(options.method || this.method || 'GET')\n this.mode = options.mode || this.mode || null\n this.signal = options.signal || this.signal || (function () {\n if ('AbortController' in g) {\n var ctrl = new AbortController();\n return ctrl.signal;\n }\n }());\n this.referrer = null\n if ((this.method === 'GET' || this.method === 'HEAD') && body) {\n throw new TypeError('Body not allowed for GET or HEAD requests')\n }\n this._initBody(body)\n if (this.method === 'GET' || this.method === 'HEAD') {\n if (options.cache === 'no-store' || options.cache === 'no-cache') {\n // Search for a '_' parameter in the query string\n var reParamSearch = /([?&])_=[^&]*/\n if (reParamSearch.test(this.url)) {\n // If it already exists then set the value with the current time\n this.url = this.url.replace(reParamSearch, '$1_=' + new Date().getTime())\n } else {\n // Otherwise add a new '_' parameter to the end with the current time\n var reQueryString = /\\?/\n this.url += (reQueryString.test(this.url) ? '&' : '?') + '_=' + new Date().getTime()\n }\n }\n }\n}\nRequest.prototype.clone = function() {\n return new Request(this, {body: this._bodyInit})\n}\nfunction decode(body) {\n var form = new FormData()\n body\n .trim()\n .split('&')\n .forEach(function(bytes) {\n if (bytes) {\n var split = bytes.split('=')\n var name = split.shift().replace(/\\+/g, ' ')\n var value = split.join('=').replace(/\\+/g, ' ')\n form.append(decodeURIComponent(name), decodeURIComponent(value))\n }\n })\n return form\n}\nfunction parseHeaders(rawHeaders) {\n var headers = new Headers()\n // Replace instances of \\r\\n and \\n followed by at least one space or horizontal tab with a space\n // https://tools.ietf.org/html/rfc7230#section-3.2\n var preProcessedHeaders = rawHeaders.replace(/\\r?\\n[\\t ]+/g, ' ')\n // Avoiding split via regex to work around a common IE11 bug with the core-js 3.6.0 regex polyfill\n // https://github.com/github/fetch/issues/748\n // https://github.com/zloirock/core-js/issues/751\n preProcessedHeaders\n .split('\\r')\n .map(function(header) {\n return header.indexOf('\\n') === 0 ? header.substr(1, header.length) : header\n })\n .forEach(function(line) {\n var parts = line.split(':')\n var key = parts.shift().trim()\n if (key) {\n var value = parts.join(':').trim()\n try {\n headers.append(key, value)\n } catch (error) {\n console.warn('Response ' + error.message)\n }\n }\n })\n return headers\n}\nBody.call(Request.prototype)\nexport function Response(bodyInit, options) {\n if (!(this instanceof Response)) {\n throw new TypeError('Please use the \"new\" operator, this DOM object constructor cannot be called as a function.')\n }\n if (!options) {\n options = {}\n }\n this.type = 'default'\n this.status = options.status === undefined ? 200 : options.status\n if (this.status < 200 || this.status > 599) {\n throw new RangeError(\"Failed to construct 'Response': The status provided (0) is outside the range [200, 599].\")\n }\n this.ok = this.status >= 200 && this.status < 300\n this.statusText = options.statusText === undefined ? '' : '' + options.statusText\n this.headers = new Headers(options.headers)\n this.url = options.url || ''\n this._initBody(bodyInit)\n}\nBody.call(Response.prototype)\n\n#focal function/method here\n\nResponse.error = function() {\n var response = new Response(null, {status: 200, statusText: ''})\n response.ok = false\n response.status = 0\n response.type = 'error'\n return response\n}\nvar redirectStatuses = [301, 302, 303, 307, 308]\nResponse.redirect = function(url, status) {\n if (redirectStatuses.indexOf(status) === -1) {\n throw new RangeError('Invalid status code')\n }\n return new Response(null, {status: status, headers: {location: url}})\n}\nexport var DOMException = g.DOMException\ntry {\n new DOMException()\n} catch (err) {\n DOMException = function(message, name) {\n this.message = message\n this.name = name\n var error = Error(message)\n this.stack = error.stack\n }\n DOMException.prototype = Object.create(Error.prototype)\n DOMException.prototype.constructor = DOMException\n}\nexport function fetch(input, init) {\n return new Promise(function(resolve, reject) {\n var request = new Request(input, init)\n if (request.signal && request.signal.aborted) {\n return reject(new DOMException('Aborted', 'AbortError'))\n }\n var xhr = new XMLHttpRequest()\n function abortXhr() {\n xhr.abort()\n }\n xhr.onload = function() {\n var options = {\n statusText: xhr.statusText,\n headers: parseHeaders(xhr.getAllResponseHeaders() || '')\n }\n // This check if specifically for when a user fetches a file locally from the file system\n // Only if the status is out of a normal range\n if (request.url.indexOf('file://') === 0 && (xhr.status < 200 || xhr.status > 599)) {\n options.status = 200;\n } else {\n options.status = xhr.status;\n }\n options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')\n var body = 'response' in xhr ? xhr.response : xhr.responseText\n setTimeout(function() {\n resolve(new Response(body, options))\n }, 0)\n }\n xhr.onerror = function() {\n setTimeout(function() {\n reject(new TypeError('Network request failed'))\n }, 0)\n }\n xhr.ontimeout = function() {\n setTimeout(function() {\n reject(new TypeError('Network request timed out'))\n }, 0)\n }\n xhr.onabort = function() {\n setTimeout(function() {\n reject(new DOMException('Aborted', 'AbortError'))\n }, 0)\n }\n function fixUrl(url) {\n try {\n return url === '' && g.location.href ? g.location.href : url\n } catch (e) {\n return url\n }\n }\n xhr.open(request.method, fixUrl(request.url), true)\n if (request.credentials === 'include') {\n xhr.withCredentials = true\n } else if (request.credentials === 'omit') {\n xhr.withCredentials = false\n }\n if ('responseType' in xhr) {\n if (support.blob) {\n xhr.responseType = 'blob'\n } else if (\n support.arrayBuffer\n ) {\n xhr.responseType = 'arraybuffer'\n }\n }\n if (init && typeof init.headers === 'object' && !(init.headers instanceof Headers || (g.Headers && init.headers instanceof g.Headers))) {\n var names = [];\n Object.getOwnPropertyNames(init.headers).forEach(function(name) {\n names.push(normalizeName(name))\n xhr.setRequestHeader(name, normalizeValue(init.headers[name]))\n })\n request.headers.forEach(function(value, name) {\n if (names.indexOf(name) === -1) {\n xhr.setRequestHeader(name, value)\n }\n })\n } else {\n request.headers.forEach(function(value, name) {\n xhr.setRequestHeader(name, value)\n })\n }\n if (request.signal) {\n request.signal.addEventListener('abort', abortXhr)\n xhr.onreadystatechange = function() {\n // DONE (success or failure)\n if (xhr.readyState === 4) {\n request.signal.removeEventListener('abort', abortXhr)\n }\n }\n }\n xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)\n })\n}\nfetch.polyfill = true\nif (!g.fetch) {\n g.fetch = fetch\n g.Headers = Headers\n g.Request = Request\n g.Response = Response\n}\n```", "test_func_type": "тестовую функцию", "test_func_context": "```\n/* eslint-env mocha */\n/* globals chai assert FileReaderSync assert WHATWGFetch */\nvar IEorEdge = /Edge\\//.test(navigator.userAgent) || /MSIE/.test(navigator.userAgent)\nvar Chrome = /Chrome\\//.test(navigator.userAgent) && !IEorEdge\nvar Safari = /Safari\\//.test(navigator.userAgent) && !IEorEdge && !Chrome\nvar support = {\n url: (function(url) {\n try {\n return new URL(url).toString() === url\n } catch (e) {\n return false\n }\n })('http://example.com/'),\n blob:\n 'FileReader' in self &&\n 'Blob' in self &&\n (function() {\n try {\n new Blob()\n return true\n } catch (e) {\n return false\n }\n })(),\n formData: 'FormData' in self,\n arrayBuffer: 'ArrayBuffer' in self,\n aborting: 'signal' in new Request(''),\n permanentRedirect: !/Trident/.test(navigator.userAgent)\n}\nfunction readBlobAsText(blob) {\n if ('FileReader' in self) {\n return new Promise(function(resolve, reject) {\n var reader = new FileReader()\n reader.onload = function() {\n resolve(reader.result)\n }\n reader.onerror = function() {\n reject(reader.error)\n }\n reader.readAsText(blob)\n })\n } else if ('FileReaderSync' in self) {\n return new FileReaderSync().readAsText(blob)\n } else {\n throw new ReferenceError('FileReader is not defined')\n }\n}\nfunction readBlobAsBytes(blob) {\n if ('FileReader' in self) {\n return new Promise(function(resolve, reject) {\n var reader = new FileReader()\n reader.onload = function() {\n var view = new Uint8Array(reader.result)\n resolve(Array.prototype.slice.call(view))\n }\n reader.onerror = function() {\n reject(reader.error)\n }\n reader.readAsArrayBuffer(blob)\n })\n } else if ('FileReaderSync' in self) {\n return new FileReaderSync().readAsArrayBuffer(blob)\n } else {\n throw new ReferenceError('FileReader is not defined')\n }\n}\nfunction arrayBufferFromText(text) {\n var buf = new ArrayBuffer(text.length)\n var view = new Uint8Array(buf)\n for (var i = 0; i < text.length; i++) {\n view[i] = text.charCodeAt(i)\n }\n return buf\n}\nfunction readArrayBufferAsText(buf) {\n var view = new Uint8Array(buf)\n var chars = new Array(view.length)\n for (var i = 0; i < view.length; i++) {\n chars[i] = String.fromCharCode(view[i])\n }\n return chars.join('')\n}\nvar preservedGlobals = {}\nvar keepGlobals = ['fetch', 'Headers', 'Request', 'Response']\nvar exercise = ['polyfill']\n// If native fetch implementation exists, replace it with the polyfilled\n// version at first. The native implementation will be restored before the\n// additional `native` pass of the test suite.\nif (!self.fetch.polyfill) {\n keepGlobals.forEach(function(name) {\n preservedGlobals[name] = self[name]\n self[name] = WHATWGFetch[name]\n })\n exercise.push('native')\n}\nvar slice = Array.prototype.slice\nfunction featureDependent(testOrSuite, condition) {\n (condition ? testOrSuite : testOrSuite.skip).apply(this, slice.call(arguments, 2))\n}\nexercise.forEach(function(exerciseMode) {\n suite(exerciseMode, function() {\n if (exerciseMode === 'native') {\n suiteSetup(function() {\n keepGlobals.forEach(function(name) {\n self[name] = preservedGlobals[name]\n })\n })\n }\n var nativeChrome = Chrome && exerciseMode === 'native'\n var nativeSafari = Safari && exerciseMode === 'native'\n var nativeEdge = /Edge\\//.test(navigator.userAgent) && exerciseMode === 'native'\n var firefox = navigator.userAgent.match(/Firefox\\/(\\d+)/)\n var brokenFF = firefox && firefox[1] <= 56 && exerciseMode === 'native'\n var emptyDefaultStatusText =\n exerciseMode !== 'native' || (exerciseMode === 'native' && (Chrome || (firefox && firefox[1] >= 67)))\n var polyfillFirefox = firefox && exerciseMode === 'polyfill'\n var omitSafari =\n Safari && exerciseMode === 'native' && navigator.userAgent.match(/Version\\/(\\d+\\.\\d+)/)[1] <= '11.1'\n // https://fetch.spec.whatwg.org/#concept-bodyinit-extract\n function testBodyExtract(factory) {\n suite('body extract', function() {\n var expected = 'Hello World!'\n var inputs = [['type USVString', expected]]\n if (support.blob) {\n inputs.push(['type Blob', new Blob([expected])])\n }\n if (support.arrayBuffer) {\n inputs = inputs.concat([\n ['type ArrayBuffer', arrayBufferFromText(expected)],\n ['type TypedArray', new Uint8Array(arrayBufferFromText(expected))],\n ['type DataView', new DataView(arrayBufferFromText(expected))]\n ])\n }\n inputs.forEach(function(input) {\n var typeLabel = input[0],\n body = input[1]\n suite(typeLabel, function() {\n featureDependent(test, support.blob, 'consume as blob', function() {\n var r = factory(body)\n return r\n .blob()\n .then(readBlobAsText)\n .then(function(text) {\n assert.equal(text, expected)\n })\n })\n featureDependent(test, support.arrayBuffer, 'consume as array buffer', function() {\n var r = factory(body)\n return r\n .arrayBuffer()\n .then(readArrayBufferAsText)\n .then(function(text) {\n assert.equal(text, expected)\n })\n })\n })\n })\n })\n }\n // https://fetch.spec.whatwg.org/#headers-class\n suite('Headers', function() {\n featureDependent(test, !brokenFF, 'is iterable with forEach', function() {\n var headers = new Headers()\n headers.append('Accept', 'application/json')\n headers.append('Accept', 'text/plain')\n headers.append('Content-Type', 'text/html')\n var results = []\n headers.forEach(function(value, key, object) {\n results.push({value: value, key: key, object: object})\n })\n assert.equal(results.length, 2)\n assert.deepEqual({key: 'accept', value: 'application/json, text/plain', object: headers}, results[0])\n assert.deepEqual({key: 'content-type', value: 'text/html', object: headers}, results[1])\n })\n featureDependent(test, !brokenFF, 'is iterable with keys', function() {\n var headers = new Headers()\n headers.append('Accept', 'application/json')\n headers.append('Accept', 'text/plain')\n headers.append('Content-Type', 'text/html')\n var iterator = headers.keys()\n assert.deepEqual({done: false, value: 'accept'}, iterator.next())\n assert.deepEqual({done: false, value: 'content-type'}, iterator.next())\n assert.deepEqual({done: true, value: undefined}, iterator.next())\n })\n featureDependent(test, !brokenFF, 'is iterable with values', function() {\n var headers = new Headers()\n headers.append('Accept', 'application/json')\n headers.append('Accept', 'text/plain')\n headers.append('Content-Type', 'text/html')\n var iterator = headers.values()\n assert.deepEqual({done: false, value: 'application/json, text/plain'}, iterator.next())\n assert.deepEqual({done: false, value: 'text/html'}, iterator.next())\n assert.deepEqual({done: true, value: undefined}, iterator.next())\n })\n featureDependent(test, !brokenFF, 'is iterable with entries', function() {\n var headers = new Headers()\n headers.append('Accept', 'application/json')\n headers.append('Accept', 'text/plain')\n headers.append('Content-Type', 'text/html')\n var iterator = headers.entries()\n assert.deepEqual({done: false, value: ['accept', 'application/json, text/plain']}, iterator.next())\n assert.deepEqual({done: false, value: ['content-type', 'text/html']}, iterator.next())\n assert.deepEqual({done: true, value: undefined}, iterator.next())\n })\n })\n // https://fetch.spec.whatwg.org/#request-class\n suite('Request', function() {\n featureDependent(test, support.url, 'construct with URL instance', function() {\n var url = new URL('https://fetch.spec.whatwg.org/')\n url.pathname = 'cors'\n var request = new Request(url)\n assert.equal(request.url, 'https://fetch.spec.whatwg.org/cors')\n })\n featureDependent(test, !nativeChrome, 'construct with used Request body', function() {\n var request1 = new Request('https://fetch.spec.whatwg.org/', {\n method: 'post',\n body: 'I work out'\n })\n return request1.text().then(function() {\n assert.throws(function() {\n new Request(request1)\n }, TypeError)\n })\n })\n featureDependent(test, support.blob, 'construct with Blob body and type sets Content-Type header', function() {\n var req = new Request('https://fetch.spec.whatwg.org/', {\n method: 'post',\n body: new Blob(['test'], {type: 'image/png'})\n })\n assert.equal(req.headers.get('content-type'), 'image/png')\n })\n featureDependent(test, support.blob, 'construct with Blob body and explicit Content-Type header', function() {\n var req = new Request('https://fetch.spec.whatwg.org/', {\n method: 'post',\n headers: {'Content-Type': 'image/png'},\n body: new Blob(['test'], {type: 'text/plain'})\n })\n assert.equal(req.headers.get('content-type'), 'image/png')\n })\n featureDependent(test, !IEorEdge, 'construct with URLSearchParams body sets Content-Type header', function() {\n var req = new Request('https://fetch.spec.whatwg.org/', {\n method: 'post',\n body: new URLSearchParams('a=1&b=2')\n })\n assert.equal(req.headers.get('content-type'), 'application/x-www-form-urlencoded;charset=UTF-8')\n })\n featureDependent(\n test,\n !IEorEdge,\n 'construct with URLSearchParams body and explicit Content-Type header',\n function() {\n var req = new Request('https://fetch.spec.whatwg.org/', {\n method: 'post',\n headers: {'Content-Type': 'image/png'},\n body: new URLSearchParams('a=1&b=2')\n })\n assert.equal(req.headers.get('content-type'), 'image/png')\n }\n )\n featureDependent(test, !nativeChrome, 'clone with used Request body', function() {\n var req = new Request('https://fetch.spec.whatwg.org/', {\n method: 'post',\n body: 'I work out'\n })\n return req.text().then(function() {\n assert.throws(function() {\n req.clone()\n }, TypeError)\n })\n })\n testBodyExtract(function(body) {\n return new Request('', {method: 'POST', body: body})\n })\n featureDependent(test, !omitSafari, 'credentials defaults to same-origin', function() {\n var request = new Request('')\n assert.equal(request.credentials, 'same-origin')\n })\n })\n // https://fetch.spec.whatwg.org/#response-class\n suite('Response', function() {\n featureDependent(test, emptyDefaultStatusText, 'default status is 200', function() {\n var res = new Response()\n assert.equal(res.status, 200)\n assert.equal(res.statusText, '')\n assert.isTrue(res.ok)\n })\n featureDependent(\n test,\n emptyDefaultStatusText,\n 'default status is 200 when an explicit undefined status code is passed',\n function() {\n var res = new Response('', {status: undefined})\n assert.equal(res.status, 200)\n assert.equal(res.statusText, '')\n assert.isTrue(res.ok)\n }\n )\n testBodyExtract(function(body) {\n return new Response(body)\n })\n featureDependent(test, support.blob, 'clone blob response', function() {\n var req = new Request(new Blob(['test']))\n req.clone()\n assert.equal(req.bodyUsed, false)\n })\n featureDependent(test, support.blob, 'construct with Blob body and type sets Content-Type header', function() {\n var r = new Response(new Blob(['test'], {type: 'text/plain'}))\n assert.equal(r.headers.get('content-type'), 'text/plain')\n })\n })\n // https://fetch.spec.whatwg.org/#body-mixin\n suite('Body mixin', function() {\n featureDependent(suite, support.blob, 'arrayBuffer', function() {\n })\n featureDependent(suite, support.blob, 'blob', function() {\n })\n featureDependent(suite, support.formData, 'formData', function() {\n featureDependent(test, !nativeChrome && !nativeEdge, 'formData rejects after body was consumed', function() {\n return fetch('/json')\n .then(function(response) {\n assert(response.formData, 'Body does not implement formData')\n response.formData()\n return response.formData()\n })\n .catch(function(error) {\n if (error instanceof chai.AssertionError) {\n throw error\n } else {\n assert(error instanceof TypeError, 'Promise rejected after body consumed')\n }\n })\n })\n featureDependent(\n test,\n !nativeChrome && !nativeSafari && !nativeEdge,\n 'parses form encoded response',\n function() {\n return fetch('/form')\n .then(function(response) {\n return response.formData()\n })\n .then(function(form) {\n assert(form instanceof FormData, 'Parsed a FormData object')\n })\n }\n )\n })\n suite('json', function() {\n featureDependent(test, !polyfillFirefox, 'handles json parse error', function() {\n return fetch('/json-error')\n .then(function(response) {\n return response.json()\n })\n .catch(function(error) {\n if (!IEorEdge) assert(error instanceof Error, 'JSON exception is an Error instance')\n assert(error.message, 'JSON exception has an error message')\n })\n })\n })\n suite('text', function() {\n })\n })\n suite('fetch method', function() {\n suite('promise resolution', function() {\n test.skip('rejects promise for network error', function() {\n return fetch('/error')\n .then(function(response) {\n assert(false, 'HTTP status ' + response.status + ' was treated as success')\n })\n .catch(function(error) {\n assert(error instanceof TypeError, 'Rejected with Error')\n })\n })\n })\n suite('request', function() {\n featureDependent(suite, support.arrayBuffer, 'ArrayBuffer', function() {\n })\n featureDependent(test, !IEorEdge, 'sends URLSearchParams body', function() {\n return fetch('/request', {\n method: 'post',\n body: new URLSearchParams('a=1&b=2')\n })\n .then(function(response) {\n return response.json()\n })\n .then(function(request) {\n assert.equal(request.method, 'POST')\n assert.equal(request.data, 'a=1&b=2')\n })\n })\n })\n featureDependent(suite, exerciseMode !== 'native' || support.aborting, 'aborting', function() {\n })\n suite('response', function() {\n })\n // https://fetch.spec.whatwg.org/#methods\n suite('HTTP methods', function() {\n })\n // https://fetch.spec.whatwg.org/#atomic-http-redirect-handling\n suite('Atomic HTTP redirect handling', function() {\n featureDependent(test, support.permanentRedirect, 'handles 308 redirect response', function() {\n return fetch('/redirect/308')\n .then(function(response) {\n assert.equal(response.status, 200)\n assert.equal(response.ok, true)\n assert.match(response.url, /\\/hello/)\n return response.text()\n })\n .then(function(body) {\n assert.equal(body, 'hi')\n })\n })\n })\n // https://fetch.spec.whatwg.org/#concept-request-credentials-mode\n suite('credentials mode', function() {\n setup(function() {\n return fetch('/cookie?name=foo&value=reset', {credentials: 'same-origin'})\n })\n featureDependent(suite, exerciseMode === 'native', 'omit', function() {\n })\n suite('same-origin', function() {\n })\n suite('include', function() {\n })\n })\n })\n })\n})\n```", "language": "js", "focal_file_path": "fetch.js", "test_file_path": "test/test.js", "test_framework": "mocha" }
test('clone POST request', function() { var req = new Request('https://fetch.spec.whatwg.org/', { method: 'post', headers: {'content-type': 'text/plain'}, body: 'I work out' }) var clone = req.clone() assert.equal(clone.method, 'POST') assert.equal(clone.headers.get('content-type'), 'text/plain') assert.notEqual(clone.headers, req.headers) assert.equal(req.bodyUsed, false) return Promise.all([clone.text(), req.clone().text()]).then(function(bodies) { assert.deepEqual(bodies, ['I work out', 'I work out']) }) })
{ "id": 2, "repo_id": "762710560", "focal_func_type": "function" }
Напиши тест для этого кода на языке {language} из файла '{focal_file_path}'. Вот код, который надо протестировать: {focal_func} Тебе необходимо написать {test_func_type} на языке {language} с использованием {test_framework} в качестве тестового фреймворка. Тест будет помещен в файл '{test_file_path}'. Обязательно учитывай код, собранный из будущего тестового файла: {test_func_context} Для тебя собран код из репозитория, который может помочь тебе в написании теста: {focal_func_context} Напиши только {test_func_type} без пояснений и комментариев. Не забывай соблюдать синтаксис языка {language}. Оформи свой ответ с соблюдением markdown разметки для кода: ```{language} <your code> ```
{ "focal_func": "\"\"\"\nstatic get RESULT_SIMILAR() {\n return 7;\n }\n\"\"\"", "focal_func_context": "\"\"\"\n#index.js\n'use strict';\nconst assert = require('assert'),\n PNGImage = require('pngjs-image'),\n Promise = require('promise');\nfunction load(value, defaultValue) {\n return (value === undefined) ? defaultValue : value;\n}\n/**\n * Pixel-diff comparison class\n *\n * @constructor\n * @class PixelDiff\n * @param {object} options\n * @param {PNGImage|Buffer} options.imageA Image object of first image\n * @param {string} options.imageAPath Path to first image\n * @param {PNGImage|Buffer} options.imageB Image object of second image\n * @param {string} options.imageBPath Path to second image\n * @param {string} [options.imageOutputPath=undefined] Path to output image file\n * @param {int} [options.imageOutputLimit=PixelDiff.OUTPUT_ALL] Determines when an image output is created\n * @param {string} [options.thresholdType=PixelDiff.THRESHOLD_PIXEL] Defines the threshold of the comparison\n * @param {int} [options.threshold=500] Threshold limit according to the comparison limit.\n * @param {number} [options.delta=20] Distance between the color coordinates in the 4 dimensional color-space that will not trigger a difference.\n * @param {int} [options.outputMaskRed=255] Value to set for red on difference pixel. 'Undefined' will not change the value.\n * @param {int} [options.outputMaskGreen=0] Value to set for green on difference pixel. 'Undefined' will not change the value.\n * @param {int} [options.outputMaskBlue=0] Value to set for blue on difference pixel. 'Undefined' will not change the value.\n * @param {int} [options.outputMaskAlpha=255] Value to set for the alpha channel on difference pixel. 'Undefined' will not change the value.\n * @param {float} [options.outputMaskOpacity=0.7] Strength of masking the pixel. 1.0 means that the full color will be used; anything less will mix-in the original pixel.\n * @param {int} [options.outputShiftRed=255] Value to set for red on shifted pixel. 'Undefined' will not change the value.\n * @param {int} [options.outputShiftGreen=165] Value to set for green on shifted pixel. 'Undefined' will not change the value.\n * @param {int} [options.outputShiftBlue=0] Value to set for blue on shifted pixel. 'Undefined' will not change the value.\n * @param {int} [options.outputShiftAlpha=255] Value to set for the alpha channel on shifted pixel. 'Undefined' will not change the value.\n * @param {float} [options.outputShiftOpacity=0.7] Strength of masking the shifted pixel. 1.0 means that the full color will be used; anything less will mix-in the original pixel.\n * @param {int} [options.outputBackgroundRed=0] Value to set for red as background. 'Undefined' will not change the value.\n * @param {int} [options.outputBackgroundGreen=0] Value to set for green as background. 'Undefined' will not change the value.\n * @param {int} [options.outputBackgroundBlue=0] Value to set for blue as background. 'Undefined' will not change the value.\n * @param {int} [options.outputBackgroundAlpha=undefined] Value to set for the alpha channel as background. 'Undefined' will not change the value.\n * @param {float} [options.outputBackgroundOpacity=0.6] Strength of masking the pixel. 1.0 means that the full color will be used; anything less will mix-in the original pixel.\n * @param {object|object[]} [options.blockOut] Object or list of objects with coordinates of blocked-out areas.\n * @param {int} [options.blockOutRed=0] Value to set for red on blocked-out pixel. 'Undefined' will not change the value.\n * @param {int} [options.blockOutGreen=0] Value to set for green on blocked-out pixel. 'Undefined' will not change the value.\n * @param {int} [options.blockOutBlue=0] Value to set for blue on blocked-out pixel. 'Undefined' will not change the value.\n * @param {int} [options.blockOutAlpha=255] Value to set for the alpha channel on blocked-out pixel. 'Undefined' will not change the value.\n * @param {float} [options.blockOutOpacity=1.0] Strength of masking the blocked-out pixel. 1.0 means that the full color will be used; anything less will mix-in the original pixel.\n * @param {boolean} [options.copyImageAToOutput=true] Copies the first image to the output image before the comparison begins. This will make sure that the output image will highlight the differences on the first image.\n * @param {boolean} [options.copyImageBToOutput=false] Copies the second image to the output image before the comparison begins. This will make sure that the output image will highlight the differences on the second image.\n * @param {string[]} [options.filter=[]] Filters that will be applied before the comparison. Available filters are: blur, grayScale, lightness, luma, luminosity, sepia\n * @param {boolean} [options.debug=false] When set, then the applied filters will be shown on the output image.\n * @param {boolean} [options.composition=true] Should a composition be created to compare?\n * @param {boolean} [options.composeLeftToRight=false] Create composition from left to right, otherwise let it decide on its own whats best\n * @param {boolean} [options.composeTopToBottom=false] Create composition from top to bottom, otherwise let it decide on its own whats best\n * @param {boolean} [options.hideShift=false] Hides shift highlighting by using the background color instead\n * @param {int} [options.hShift=2] Horizontal shift for possible antialiasing\n * @param {int} [options.vShift=2] Vertical shift for possible antialiasing\n * @param {object} [options.cropImageA=null] Cropping for first image (default: no cropping)\n * @param {int} [options.cropImageA.x=0] Coordinate for left corner of cropping region\n * @param {int} [options.cropImageA.y=0] Coordinate for top corner of cropping region\n * @param {int} [options.cropImageA.width] Width of cropping region (default: Width that is left)\n * @param {int} [options.cropImageA.height] Height of cropping region (default: Height that is left)\n * @param {object} [options.cropImageB=null] Cropping for second image (default: no cropping)\n * @param {int} [options.cropImageB.x=0] Coordinate for left corner of cropping region\n * @param {int} [options.cropImageB.y=0] Coordinate for top corner of cropping region\n * @param {int} [options.cropImageB.width] Width of cropping region (default: Width that is left)\n * @param {int} [options.cropImageB.height] Height of cropping region (default: Height that is left)\n * @param {boolean} [options.perceptual=false] Turns perceptual comparison on\n * @param {float} [options.gamma] Gamma correction for all colors\n * @param {float} [options.gammaR] Gamma correction for red\n * @param {float} [options.gammaG] Gamma correction for green\n * @param {float} [options.gammaB] Gamma correction for blue\n *\n * @property {PNGImage} _imageA\n * @property {PNGImage} _imageACompare\n * @property {string} _imageAPath\n * @property {PNGImage} _imageB\n * @property {PNGImage} _imageBCompare\n * @property {string} _imageBPath\n * @property {PNGImage} _imageOutput\n * @property {string} _imageOutputPath\n * @property {int} _imageOutputLimit\n * @property {string} _thresholdType\n * @property {int} _threshold\n * @property {number} _delta\n * @property {int} _outputMaskRed\n * @property {int} _outputMaskGreen\n * @property {int} _outputMaskBlue\n * @property {int} _outputMaskAlpha\n * @property {float} _outputMaskOpacity\n * @property {int} _outputShiftRed\n * @property {int} _outputShiftGreen\n * @property {int} _outputShiftBlue\n * @property {int} _outputShiftAlpha\n * @property {float} _outputShiftOpacity\n * @property {int} _outputBackgroundRed\n * @property {int} _outputBackgroundGreen\n * @property {int} _outputBackgroundBlue\n * @property {int} _outputBackgroundAlpha\n * @property {float} _outputBackgroundOpacity\n * @property {object[]} _blockOut\n * @property {int} _blockOutRed\n * @property {int} _blockOutGreen\n * @property {int} _blockOutBlue\n * @property {int} _blockOutAlpha\n * @property {float} _blockOutOpacity\n * @property {boolean} _copyImageAToOutput\n * @property {boolean} _copyImageBToOutput\n * @property {string[]} _filter\n * @property {boolean} _debug\n * @property {boolean} _composition\n * @property {boolean} _composeLeftToRight\n * @property {boolean} _composeTopToBottom\n * @property {int} _hShift\n * @property {int} _vShift\n * @property {object} _cropImageA\n * @property {int} _cropImageA.x\n * @property {int} _cropImageA.y\n * @property {int} _cropImageA.width\n * @property {int} _cropImageA.height\n * @property {object} _cropImageB\n * @property {int} _cropImageB.x\n * @property {int} _cropImageB.y\n * @property {int} _cropImageB.width\n * @property {int} _cropImageB.height\n * @property {object} _refWhite\n * @property {boolean} _perceptual\n * @property {float} _gamma\n * @property {float} _gammaR\n * @property {float} _gammaG\n * @property {float} _gammaB\n */\nclass PixelDiff {\n constructor(options) {\n this._imageA = options.imageA;\n this._imageAPath = options.imageAPath;\n assert.ok(options.imageAPath || options.imageA, 'Image A not given.');\n this._imageB = options.imageB;\n this._imageBPath = options.imageBPath;\n assert.ok(options.imageBPath || options.imageB, 'Image B not given.');\n this._imageOutput = null;\n this._imageOutputPath = options.imageOutputPath;\n this._imageOutputLimit = load(options.imageOutputLimit, PixelDiff.OUTPUT_ALL);\n // Pixel or Percent\n this._thresholdType = load(options.thresholdType, PixelDiff.THRESHOLD_PIXEL);\n // How many pixels different to ignore.\n this._threshold = load(options.threshold, 500);\n this._delta = load(options.delta, 20);\n this._outputMaskRed = load(options.outputMaskRed, 255);\n this._outputMaskGreen = load(options.outputMaskGreen, 0);\n this._outputMaskBlue = load(options.outputMaskBlue, 0);\n this._outputMaskAlpha = load(options.outputMaskAlpha, 255);\n this._outputMaskOpacity = load(options.outputMaskOpacity, 0.7);\n this._outputBackgroundRed = load(options.outputBackgroundRed, 0);\n this._outputBackgroundGreen = load(options.outputBackgroundGreen, 0);\n this._outputBackgroundBlue = load(options.outputBackgroundBlue, 0);\n this._outputBackgroundAlpha = options.outputBackgroundAlpha;\n this._outputBackgroundOpacity = load(options.outputBackgroundOpacity, 0.6);\n if (options.hideShift) {\n this._outputShiftRed = this._outputBackgroundRed;\n this._outputShiftGreen = this._outputBackgroundGreen;\n this._outputShiftBlue = this._outputBackgroundBlue;\n this._outputShiftAlpha = this._outputBackgroundAlpha;\n this._outputShiftOpacity = this._outputBackgroundOpacity;\n } else {\n this._outputShiftRed = load(options.outputShiftRed, 200);\n this._outputShiftGreen = load(options.outputShiftGreen, 100);\n this._outputShiftBlue = load(options.outputShiftBlue, 0);\n this._outputShiftAlpha = load(options.outputShiftAlpha, 255);\n this._outputShiftOpacity = load(options.outputShiftOpacity, 0.7);\n }\n this._blockOut = load(options.blockOut, []);\n if (typeof this._blockOut !== 'object' && (this._blockOut.length !== undefined)) {\n this._blockOut = [this._blockOut];\n }\n this._blockOutRed = load(options.blockOutRed, 0);\n this._blockOutGreen = load(options.blockOutGreen, 0);\n this._blockOutBlue = load(options.blockOutBlue, 0);\n this._blockOutAlpha = load(options.blockOutAlpha, 255);\n this._blockOutOpacity = load(options.blockOutOpacity, 1.0);\n this._copyImageAToOutput = load(options.copyImageAToOutput, true);\n this._copyImageBToOutput = load(options.copyImageBToOutput, false);\n this._filter = load(options.filter, []);\n this._debug = load(options.debug, false);\n this._composition = load(options.composition, true);\n this._composeLeftToRight = load(options.composeLeftToRight, false);\n this._composeTopToBottom = load(options.composeTopToBottom, false);\n this._hShift = load(options.hShift, 2);\n this._vShift = load(options.vShift, 2);\n this._cropImageA = options.cropImageA;\n this._cropImageB = options.cropImageB;\n // Prepare reference white\n this._refWhite = this._convertRgbToXyz({c1: 1, c2: 1, c3: 1, c4: 1});\n this._perceptual = load(options.perceptual, false);\n this._gamma = options.gamma;\n this._gammaR = options.gammaR;\n this._gammaG = options.gammaG;\n this._gammaB = options.gammaB;\n }\n\n /**\n * Version of class\n *\n * @static\n * @property version\n * @type {string}\n */\n static get version() {\n return require('./package.json').version;\n }\n /**\n * Threshold-type for pixel\n *\n * @static\n * @property THRESHOLD_PIXEL\n * @type {string}\n */\n static get THRESHOLD_PIXEL() {\n return 'pixel';\n }\n /**\n * Threshold-type for percent of all pixels\n *\n * @static\n * @property THRESHOLD_PERCENT\n * @type {string}\n */\n static get THRESHOLD_PERCENT() {\n return 'percent';\n }\n\n /**\n * Unknown result of the comparison\n *\n * @static\n * @property RESULT_UNKNOWN\n * @type {int}\n */\n static get RESULT_UNKNOWN() {\n return 0;\n }\n /**\n * The images are too different\n *\n * @static\n * @property RESULT_DIFFERENT\n * @type {int}\n */\n static get RESULT_DIFFERENT() {\n return 1;\n }\n /**\n * The images are very similar, but still below the threshold\n *\n * @static\n * @property RESULT_SIMILAR\n * @type {int}\n */\n#focal function/method here\n\n /**\n * The images are identical (or near identical)\n *\n * @static\n * @property RESULT_IDENTICAL\n * @type {int}\n */\n static get RESULT_IDENTICAL() {\n return 5;\n }\n\n /**\n * Create output when images are different\n *\n * @static\n * @property OUTPUT_DIFFERENT\n * @type {int}\n */\n static get OUTPUT_DIFFERENT() {\n return 10;\n }\n /**\n * Create output when images are similar or different\n *\n * @static\n * @property OUTPUT_SIMILAR\n * @type {int}\n */\n static get OUTPUT_SIMILAR() {\n return 20;\n }\n /**\n * Force output of all comparisons\n *\n * @static\n * @property OUTPUT_ALL\n * @type {int}\n */\n static get OUTPUT_ALL() {\n return 100;\n }\n /**\n * Runs the comparison with a promise\n *\n * @method runWithPromise\n * @example\n * const pixelDiff = new PixelDiff(...);\n * pixelDiff.runWithPromise().then(result => {\n * ...\n * });\n * @return {Promise}\n */\n runWithPromise() {\n return Promise.denodeify(this.run).call(this);\n }\n /**\n * Runs the comparison in node-style\n *\n * @method run\n * @example\n * const pixelDiff = new PixelDiff(...);\n * pixelDiff.run((err, result) => {\n * if (err) {\n * throw err;\n * }\n * ...\n * });\n *\n * @param {function} fn\n */\n run(fn) {\n let result;\n PNGImage.log = text => {\n this.log('ERROR: ' + text);\n throw new Error('ERROR: ' + text);\n };\n Promise.resolve().then(() => {\n return this._loadImage(this._imageAPath, this._imageA);\n }).then(imageA => {\n this._imageA = imageA;\n return this._loadImage(this._imageBPath, this._imageB);\n }).then(imageB => {\n let gamma, i, len, rect, color;\n this._imageB = imageB;\n // Crop images if requested\n if (this._cropImageA) {\n this._correctDimensions(this._imageA.getWidth(), this._imageA.getHeight(), this._cropImageA);\n this._crop('Image-A', this._imageA, this._cropImageA);\n }\n if (this._cropImageB) {\n this._correctDimensions(this._imageB.getWidth(), this._imageB.getHeight(), this._cropImageB);\n this._crop('Image-B', this._imageB, this._cropImageB);\n }\n // Always clip\n this._clip(this._imageA, this._imageB);\n this._imageOutput = PNGImage.createImage(this._imageA.getWidth(), this._imageA.getHeight());\n // Make a copy when not in debug mode\n if (this._debug) {\n this._imageACompare = this._imageA;\n this._imageBCompare = this._imageB;\n } else {\n this._imageACompare = PNGImage.copyImage(this._imageA);\n this._imageBCompare = PNGImage.copyImage(this._imageB);\n }\n // Block-out\n color = {\n red: this._blockOutRed,\n green: this._blockOutGreen,\n blue: this._blockOutBlue,\n alpha: this._blockOutAlpha,\n opacity: this._blockOutOpacity\n };\n for (i = 0, len = this._blockOut.length; i < len; i++) {\n rect = this._blockOut[i];\n // Make sure the block-out parameters fit\n this._correctDimensions(this._imageACompare.getWidth(), this._imageACompare.getHeight(), rect);\n this._imageACompare.fillRect(rect.x, rect.y, rect.width, rect.height, color);\n this._imageBCompare.fillRect(rect.x, rect.y, rect.width, rect.height, color);\n }\n // Copy image to composition\n if (this._copyImageAToOutput) {\n this._copyImage(this._debug ? this._imageACompare : this._imageA, this._imageOutput);\n } else if (this._copyImageBToOutput) {\n this._copyImage(this._debug ? this._imageBCompare : this._imageB, this._imageOutput);\n }\n // Apply all filters\n this._imageACompare.applyFilters(this._filter);\n this._imageBCompare.applyFilters(this._filter);\n // Gamma correction\n if (this._gamma || this._gammaR || this._gammaG || this._gammaB) {\n gamma = {\n r: this._gammaR || this._gamma, g: this._gammaG || this._gamma, b: this._gammaB || this._gamma\n };\n }\n // Comparison\n result = this._compare(this._imageACompare, this._imageBCompare, this._imageOutput, this._delta, { // Output-Mask color\n red: this._outputMaskRed,\n green: this._outputMaskGreen,\n blue: this._outputMaskBlue,\n alpha: this._outputMaskAlpha,\n opacity: this._outputMaskOpacity\n }, { // Output-Shift color\n red: this._outputShiftRed,\n green: this._outputShiftGreen,\n blue: this._outputShiftBlue,\n alpha: this._outputShiftAlpha,\n opacity: this._outputShiftOpacity\n }, { // Background color\n red: this._outputBackgroundRed,\n green: this._outputBackgroundGreen,\n blue: this._outputBackgroundBlue,\n alpha: this._outputBackgroundAlpha,\n opacity: this._outputBackgroundOpacity\n }, this._hShift, this._vShift, this._perceptual, gamma);\n // Create composition if requested\n if (this._debug) {\n this._imageOutput = this._createComposition(this._imageACompare, this._imageBCompare, this._imageOutput);\n } else {\n this._imageOutput = this._createComposition(this._imageA, this._imageB, this._imageOutput);\n }\n // Need to write to the filesystem?\n if (this._imageOutputPath && this._withinOutputLimit(result.code, this._imageOutputLimit)) {\n this._imageOutput.writeImage(this._imageOutputPath, err => {\n if (err) {\n fn(err);\n } else {\n this.log('Wrote differences to ' + this._imageOutputPath);\n fn(undefined, result);\n }\n });\n } else {\n fn(undefined, result);\n }\n }).catch(err => {\n console.error(err.stack);\n fn(err);\n });\n }\n /**\n * Runs the comparison synchronously\n *\n * @method runSync\n * @example\n * const pixelDiff = new PixelDiff(...);\n * try {\n * let result = pixelDiff.runSync();\n * ...\n * } catch(err) {\n * throw err;\n * }\n *\n * @return {Object} Result of comparison { code, differences, dimension, width, height }\n */\n runSync() {\n let result, gamma, i, len, rect, color;\n PNGImage.log = text => {\n this.log('ERROR: ' + text);\n throw new Error('ERROR: ' + text);\n };\n try {\n this._imageA = this._loadImageSync(this._imageAPath, this._imageA);\n this._imageB = this._loadImageSync(this._imageBPath, this._imageB);\n // Crop images if requested\n if (this._cropImageA) {\n this._correctDimensions(this._imageA.getWidth(), this._imageA.getHeight(), this._cropImageA);\n this._crop('Image-A', this._imageA, this._cropImageA);\n }\n if (this._cropImageB) {\n this._correctDimensions(this._imageB.getWidth(), this._imageB.getHeight(), this._cropImageB);\n this._crop('Image-B', this._imageB, this._cropImageB);\n }\n // Always clip\n this._clip(this._imageA, this._imageB);\n this._imageOutput = PNGImage.createImage(this._imageA.getWidth(), this._imageA.getHeight());\n // Make a copy when not in debug mode\n if (this._debug) {\n this._imageACompare = this._imageA;\n this._imageBCompare = this._imageB;\n } else {\n this._imageACompare = PNGImage.copyImage(this._imageA);\n this._imageBCompare = PNGImage.copyImage(this._imageB);\n }\n // Block-out\n color = {\n red: this._blockOutRed,\n green: this._blockOutGreen,\n blue: this._blockOutBlue,\n alpha: this._blockOutAlpha,\n opacity: this._blockOutOpacity\n };\n for (i = 0, len = this._blockOut.length; i < len; i++) {\n rect = this._blockOut[i];\n // Make sure the block-out parameters fit\n this._correctDimensions(this._imageACompare.getWidth(), this._imageACompare.getHeight(), rect);\n this._imageACompare.fillRect(rect.x, rect.y, rect.width, rect.height, color);\n this._imageBCompare.fillRect(rect.x, rect.y, rect.width, rect.height, color);\n }\n // Copy image to composition\n if (this._copyImageAToOutput) {\n this._copyImage(this._debug ? this._imageACompare : this._imageA, this._imageOutput);\n } else if (this._copyImageBToOutput) {\n this._copyImage(this._debug ? this._imageBCompare : this._imageB, this._imageOutput);\n }\n // Apply all filters\n this._imageACompare.applyFilters(this._filter);\n this._imageBCompare.applyFilters(this._filter);\n // Gamma correction\n if (this._gamma || this._gammaR || this._gammaG || this._gammaB) {\n gamma = {\n r: this._gammaR || this._gamma, g: this._gammaG || this._gamma, b: this._gammaB || this._gamma\n };\n }\n // Comparison\n result = this._compare(this._imageACompare, this._imageBCompare, this._imageOutput, this._delta,\n { // Output-Mask color\n red: this._outputMaskRed,\n green: this._outputMaskGreen,\n blue: this._outputMaskBlue,\n alpha: this._outputMaskAlpha,\n opacity: this._outputMaskOpacity\n }, { // Output-Shift color\n red: this._outputShiftRed,\n green: this._outputShiftGreen,\n blue: this._outputShiftBlue,\n alpha: this._outputShiftAlpha,\n opacity: this._outputShiftOpacity\n }, { // Background color\n red: this._outputBackgroundRed,\n green: this._outputBackgroundGreen,\n blue: this._outputBackgroundBlue,\n alpha: this._outputBackgroundAlpha,\n opacity: this._outputBackgroundOpacity\n },\n this._hShift, this._vShift,\n this._perceptual,\n gamma\n );\n // Create composition if requested\n if (this._debug) {\n this._imageOutput = this._createComposition(this._imageACompare, this._imageBCompare, this._imageOutput);\n } else {\n this._imageOutput = this._createComposition(this._imageA, this._imageB, this._imageOutput);\n }\n // Need to write to the filesystem?\n if (this._imageOutputPath && this._withinOutputLimit(result.code, this._imageOutputLimit)) {\n this._imageOutput.writeImageSync(this._imageOutputPath);\n this.log('Wrote differences to ' + this._imageOutputPath);\n }\n return result;\n } catch (err) {\n console.error(err.stack);\n throw err;\n }\n }\n /**\n * Determines if result is within the output limit\n *\n * @method _withinOutputLimit\n * @param {int} resultCode\n * @param {int} outputLimit\n * @return {boolean}\n * @private\n */\n _withinOutputLimit(resultCode, outputLimit) {\n return this._convertResultCodeToRelativeValue(resultCode) <= outputLimit;\n }\n /**\n * Converts the result-code to a relative value\n *\n * @method _convertResultCodeToRelativeValue\n * @param {int} resultCode\n * @return {int}\n * @private\n */\n _convertResultCodeToRelativeValue(resultCode) {\n let valueMap = {\n 0: 0, 1: 10, 7: 20, 5: 30\n };\n return valueMap[resultCode] !== undefined ? valueMap[resultCode] : 0;\n }\n /**\n * Creates a comparison image\n *\n * @method _createComposition\n * @param {PNGImage} imageA\n * @param {PNGImage} imageB\n * @param {PNGImage} imageOutput\n * @return {PNGImage}\n * @private\n */\n _createComposition(imageA, imageB, imageOutput) {\n let width, height, image = imageOutput;\n if (this._composition) {\n width = Math.max(imageA.getWidth(), imageB.getWidth());\n height = Math.max(imageA.getHeight(), imageB.getHeight());\n if (((width > height) && !this._composeLeftToRight) || this._composeTopToBottom) {\n image = PNGImage.createImage(width, height * 3);\n imageA.getImage().bitblt(image.getImage(), 0, 0, imageA.getWidth(), imageA.getHeight(), 0, 0);\n imageOutput.getImage().bitblt(image.getImage(), 0, 0, imageOutput.getWidth(), imageOutput.getHeight(), 0, height);\n imageB.getImage().bitblt(image.getImage(), 0, 0, imageB.getWidth(), imageB.getHeight(), 0, height * 2);\n } else {\n image = PNGImage.createImage(width * 3, height);\n imageA.getImage().bitblt(image.getImage(), 0, 0, imageA.getWidth(), imageA.getHeight(), 0, 0);\n imageOutput.getImage().bitblt(image.getImage(), 0, 0, imageOutput.getWidth(), imageOutput.getHeight(), width, 0);\n imageB.getImage().bitblt(image.getImage(), 0, 0, imageB.getWidth(), imageB.getHeight(), width * 2, 0);\n }\n }\n return image;\n }\n /**\n * Loads the image or uses the already available image\n *\n * @method _loadImageSync\n * @param {string} path\n * @param {PNGImage} image\n * @return {PNGImage}\n * @private\n */\n _loadImageSync(path, image) {\n if (image instanceof Buffer) {\n return PNGImage.loadImageSync(image);\n } else if ((typeof path === 'string') && !image) {\n return PNGImage.readImageSync(path);\n } else {\n return image;\n }\n }\n /**\n * Loads the image or uses the already available image\n *\n * @method _loadImage\n * @param {string} path\n * @param {PNGImage} image\n * @return {PNGImage|Promise}\n * @private\n */\n _loadImage(path, image) {\n if (image instanceof Buffer) {\n return Promise.denodeify(PNGImage.loadImage).call(PNGImage, image);\n } else if ((typeof path === 'string') && !image) {\n return Promise.denodeify(PNGImage.readImage).call(PNGImage, path);\n } else {\n return image;\n }\n }\n /**\n * Copies one image into another image\n *\n * @method _copyImage\n * @param {PNGImage} imageSrc\n * @param {PNGImage} imageDst\n * @private\n */\n _copyImage(imageSrc, imageDst) {\n imageSrc.getImage().bitblt(imageDst.getImage(), 0, 0, imageSrc.getWidth(), imageSrc.getHeight(), 0, 0);\n }\n\n /**\n * Is the difference above the set threshold?\n *\n * @method isAboveThreshold\n * @param {int} items\n * @param {int} [total]\n * @return {boolean}\n */\n isAboveThreshold(items, total) {\n if ((this._thresholdType === PixelDiff.THRESHOLD_PIXEL) && (this._threshold <= items)) {\n return true;\n } else if (this._threshold <= (items / total)) {\n return true;\n }\n return false;\n }\n\n /**\n * Log method that can be overwritten to modify the logging behavior.\n *\n * @method log\n * @param {string} text\n */\n log(text) {\n return text;\n }\n\n /**\n * Has comparison passed?\n *\n * @method hasPassed\n * @param {int} result Comparison result-code\n * @return {boolean}\n */\n hasPassed(result) {\n return ((result !== PixelDiff.RESULT_DIFFERENT) && (result !== PixelDiff.RESULT_UNKNOWN));\n }\n\n /**\n * Clips the images to the lower resolution of both\n *\n * @private\n * @method _clip\n * @param {PNGImage} imageA Source image\n * @param {PNGImage} imageB Destination image\n */\n _clip(imageA, imageB) {\n let minWidth, minHeight;\n if ((imageA.getWidth() !== imageB.getWidth()) || (imageA.getHeight() !== imageB.getHeight())) {\n minWidth = imageA.getWidth();\n if (imageB.getWidth() < minWidth) {\n minWidth = imageB.getWidth();\n }\n minHeight = imageA.getHeight();\n if (imageB.getHeight() < minHeight) {\n minHeight = imageB.getHeight();\n }\n this.log('Clipping to ' + minWidth + ' x ' + minHeight);\n imageA.clip(0, 0, minWidth, minHeight);\n imageB.clip(0, 0, minWidth, minHeight);\n }\n }\n /**\n * Crops the source image to the bounds of rect\n *\n * @method _crop\n * @param {string} which Title of image to crop\n * @param {PNGImage} image Source image\n * @param {object} rect Values for rect\n * @param {int} rect.x X value of rect\n * @param {int} rect.y Y value of rect\n * @param {int} rect.width Width value of rect\n * @param {int} rect.height Height value of rect\n * @private\n */\n _crop(which, image, rect) {\n this.log('Cropping ' + which + ' from ' + rect.x + ',' + rect.y + ' by ' + rect.width + ' x ' + rect.height);\n image.clip(rect.x, rect.y, rect.width, rect.height);\n }\n /**\n * Correcting area dimensions if necessary\n *\n * Note:\n * Priority is on the x/y coordinates, and not on the size since the size will then be removed anyways.\n *\n * @method _correctDimensions\n * @param {int} width\n * @param {int} height\n * @param {object} rect Values for rect\n * @param {int} rect.x X value of rect\n * @param {int} rect.y Y value of rect\n * @param {int} rect.width Width value of rect\n * @param {int} rect.height Height value of rect\n * @private\n */\n _correctDimensions(width, height, rect) {\n // Set values if none given\n rect.x = rect.x || 0;\n rect.y = rect.y || 0;\n rect.width = rect.width || width;\n rect.height = rect.height || height;\n // Check negative values\n rect.x = Math.max(0, rect.x);\n rect.y = Math.max(0, rect.y);\n rect.width = Math.max(0, rect.width);\n rect.height = Math.max(0, rect.height);\n // Check dimensions\n rect.x = Math.min(rect.x, width - 1); // -1 to make sure that there is an image\n rect.y = Math.min(rect.y, height - 1);\n rect.width = Math.min(rect.width, width - rect.x);\n rect.height = Math.min(rect.height, height - rect.y);\n }\n\n /**\n * Calculates the distance of colors in the 4 dimensional color space\n *\n * @method _colorDelta\n * @param {object} color1 Values for color 1\n * @param {int} color1.c1 First value of color 1\n * @param {int} color1.c2 Second value of color 1\n * @param {int} color1.c3 Third value of color 1\n * @param {int} color1.c4 Fourth value of color 1\n * @param {object} color2 Values for color 2\n * @param {int} color2.c1 First value of color 2\n * @param {int} color2.c2 Second value of color 2\n * @param {int} color2.c3 Third value of color 2\n * @param {int} color2.c4 Fourth value of color 2\n * @return {number} Distance\n * @private\n */\n _colorDelta(color1, color2) {\n let c1, c2, c3, c4;\n c1 = Math.pow(color1.c1 - color2.c1, 2);\n c2 = Math.pow(color1.c2 - color2.c2, 2);\n c3 = Math.pow(color1.c3 - color2.c3, 2);\n c4 = Math.pow(color1.c4 - color2.c4, 2);\n return Math.sqrt(c1 + c2 + c3 + c4);\n }\n /**\n * Gets the color of an image by the index\n *\n * @method _getColor\n * @param {PNGImage} image Image\n * @param {int} idx Index of pixel in image\n * @param {boolean} [perceptual=false]\n * @param {object} [gamma]\n * @return {object} Color\n * @private\n */\n _getColor(image, idx, perceptual, gamma) {\n let color;\n color = {\n c1: image.getRed(idx), c2: image.getGreen(idx), c3: image.getBlue(idx), c4: image.getAlpha(idx)\n };\n if (perceptual || gamma) {\n color = this._correctGamma(color, gamma);\n color = this._convertRgbToXyz(color);\n color = this._convertXyzToCieLab(color);\n }\n return color;\n }\n /**\n * Correct gamma and return color in [0, 1] range\n *\n * @method _correctGamma\n * @param {object} color\n * @param {object} [gamma]\n * @return {{c1: number, c2: number, c3: number, c4: number}}\n * @private\n */\n _correctGamma(color, gamma) {\n // Convert to range [0, 1]\n let result = {\n c1: color.c1 / 255, c2: color.c2 / 255, c3: color.c3 / 255, c4: color.c4\n };\n if (gamma) {\n if (gamma.r !== undefined) {\n result.c1 = Math.pow(result.c1, gamma.r);\n }\n if (gamma.g !== undefined) {\n result.c2 = Math.pow(result.c2, gamma.g);\n }\n if (gamma.b !== undefined) {\n result.c3 = Math.pow(result.c3, gamma.b);\n }\n }\n return result;\n }\n /**\n * Converts the color from RGB to XYZ\n *\n * @method _convertRgbToXyz\n * @param {object} color\n * @return {object}\n * @private\n */\n _convertRgbToXyz(color) {\n let result = {};\n result.c1 = color.c1 * 0.4887180 + color.c2 * 0.3106803 + color.c3 * 0.2006017;\n result.c2 = color.c1 * 0.1762044 + color.c2 * 0.8129847 + color.c3 * 0.0108109;\n result.c3 = color.c2 * 0.0102048 + color.c3 * 0.9897952;\n result.c4 = color.c4;\n return result;\n }\n /**\n * Converts the color from XYZ to CieLab\n *\n * @method _convertXyzToCieLab\n * @param {object} color\n * @return {object}\n * @private\n */\n _convertXyzToCieLab(color) {\n let result = {}, c1, c2, c3;\n function f (t) {\n return (t > 0.00885645167904) ? Math.pow(t, 1 / 3) : 70.08333333333263 * t + 0.13793103448276;\n }\n c1 = f(color.c1 / this._refWhite.c1);\n c2 = f(color.c2 / this._refWhite.c2);\n c3 = f(color.c3 / this._refWhite.c3);\n result.c1 = (116 * c2) - 16;\n result.c2 = 500 * (c1 - c2);\n result.c3 = 200 * (c2 - c3);\n result.c4 = color.c4;\n return result;\n }\n /**\n * Calculates the lower limit\n *\n * @method _calculateLowerLimit\n * @param {int} value\n * @param {int} min\n * @param {int} shift\n * @return {int}\n * @private\n */\n _calculateLowerLimit(value, min, shift) {\n return (value - shift) < min ? -(shift + (value - shift)) : -shift;\n }\n /**\n * Calculates the upper limit\n *\n * @method _calculateUpperLimit\n * @param {int} value\n * @param {int} max\n * @param {int} shift\n * @return {int}\n * @private\n */\n _calculateUpperLimit(value, max, shift) {\n return (value + shift) > max ? (max - value) : shift;\n }\n /**\n * Checks if any pixel in the shift surrounding has a comparable color\n *\n * @method _shiftCompare\n * @param {int} x\n * @param {int} y\n * @param {object} color\n * @param {number} deltaThreshold\n * @param {PNGImage} imageA\n * @param {PNGImage} imageB\n * @param {int} width\n * @param {int} height\n * @param {int} hShift\n * @param {int} vShift\n * @param {boolean} [perceptual=false]\n * @param {object} [gamma]\n * @return {boolean} Is pixel within delta found in surrounding?\n * @private\n */\n _shiftCompare(x, y, color, deltaThreshold, imageA, imageB, width, height, hShift, vShift, perceptual, gamma) {\n let i, xOffset, xLow, xHigh, yOffset, yLow, yHigh, delta, color1, color2, localDeltaThreshold;\n if ((hShift > 0) || (vShift > 0)) {\n xLow = this._calculateLowerLimit(x, 0, hShift);\n xHigh = this._calculateUpperLimit(x, width - 1, hShift);\n yLow = this._calculateLowerLimit(y, 0, vShift);\n yHigh = this._calculateUpperLimit(y, height - 1, vShift);\n for (xOffset = xLow; xOffset <= xHigh; xOffset++) {\n for (yOffset = yLow; yOffset <= yHigh; yOffset++) {\n if ((xOffset !== 0) || (yOffset !== 0)) {\n i = imageB.getIndex(x + xOffset, y + yOffset);\n color1 = this._getColor(imageA, i, perceptual, gamma);\n localDeltaThreshold = this._colorDelta(color, color1);\n color2 = this._getColor(imageB, i, perceptual, gamma);\n delta = this._colorDelta(color, color2);\n if ((Math.abs(delta - localDeltaThreshold) < deltaThreshold) && (localDeltaThreshold > deltaThreshold)) {\n return true;\n }\n }\n }\n }\n }\n return false;\n }\n /**\n * Does a quick comparison between the supplied images\n *\n * @method _pixelCompare\n * @param {PNGImage} imageA\n * @param {PNGImage} imageB\n * @param {PNGImage} imageOutput\n * @param {number} deltaThreshold\n * @param {int} width Width of image\n * @param {int} height Height of image\n * @param {object} outputMaskColor\n * @param {int} [outputMaskColor.red]\n * @param {int} [outputMaskColor.green]\n * @param {int} [outputMaskColor.blue]\n * @param {int} [outputMaskColor.alpha]\n * @param {float} [outputMaskColor.opacity]\n * @param {object} outputShiftColor\n * @param {int} [outputShiftColor.red]\n * @param {int} [outputShiftColor.green]\n * @param {int} [outputShiftColor.blue]\n * @param {int} [outputShiftColor.alpha]\n * @param {float} [outputShiftColor.opacity]\n * @param {object} backgroundColor\n * @param {int} [backgroundColor.red]\n * @param {int} [backgroundColor.green]\n * @param {int} [backgroundColor.blue]\n * @param {int} [backgroundColor.alpha]\n * @param {float} [backgroundColor.opacity]\n * @param {int} [hShift=0] Horizontal shift\n * @param {int} [vShift=0] Vertical shift\n * @param {boolean} [perceptual=false]\n * @param {object} [gamma]\n * @return {int} Number of pixel differences\n * @private\n */\n _pixelCompare(imageA, imageB, imageOutput, deltaThreshold, width, height, outputMaskColor, outputShiftColor, backgroundColor, hShift, vShift, perceptual, gamma) {\n let difference = 0, i, x, y, delta, color1, color2;\n for (x = 0; x < width; x++) {\n for (y = 0; y < height; y++) {\n i = imageA.getIndex(x, y);\n color1 = this._getColor(imageA, i, perceptual, gamma);\n color2 = this._getColor(imageB, i, perceptual, gamma);\n delta = this._colorDelta(color1, color2);\n if (delta > deltaThreshold) {\n if (this._shiftCompare(x, y, color1, deltaThreshold, imageA, imageB, width, height, hShift, vShift, perceptual, gamma) &&\n this._shiftCompare(x, y, color2, deltaThreshold, imageB, imageA, width, height, hShift, vShift, perceptual, gamma)) {\n imageOutput.setAtIndex(i, outputShiftColor);\n } else {\n difference++;\n imageOutput.setAtIndex(i, outputMaskColor);\n }\n } else {\n imageOutput.setAtIndex(i, backgroundColor);\n }\n }\n }\n return difference;\n }\n /**\n * Compares the two images supplied\n *\n * @method _compare\n * @param {PNGImage} imageA\n * @param {PNGImage} imageB\n * @param {PNGImage} imageOutput\n * @param {number} deltaThreshold\n * @param {object} outputMaskColor\n * @param {int} [outputMaskColor.red]\n * @param {int} [outputMaskColor.green]\n * @param {int} [outputMaskColor.blue]\n * @param {int} [outputMaskColor.alpha]\n * @param {float} [outputMaskColor.opacity]\n * @param {object} outputShiftColor\n * @param {int} [outputShiftColor.red]\n * @param {int} [outputShiftColor.green]\n * @param {int} [outputShiftColor.blue]\n * @param {int} [outputShiftColor.alpha]\n * @param {float} [outputShiftColor.opacity]\n * @param {object} backgroundColor\n * @param {int} [backgroundColor.red]\n * @param {int} [backgroundColor.green]\n * @param {int} [backgroundColor.blue]\n * @param {int} [backgroundColor.alpha]\n * @param {float} [backgroundColor.opacity]\n * @param {int} [hShift=0] Horizontal shift\n * @param {int} [vShift=0] Vertical shift\n * @param {boolean} [perceptual=false]\n * @param {object} [gamma]\n * @return {object}\n * @private\n */\n _compare(imageA, imageB, imageOutput, deltaThreshold, outputMaskColor, outputShiftColor, backgroundColor, hShift, vShift, perceptual, gamma) {\n let result = {\n code: PixelDiff.RESULT_UNKNOWN,\n differences: undefined,\n dimension: undefined,\n width: undefined,\n height: undefined\n };\n // Get some data needed for comparison\n result.width = imageA.getWidth();\n result.height = imageA.getHeight();\n result.dimension = result.width * result.height;\n // Check if identical\n result.differences = this._pixelCompare(imageA, imageB, imageOutput, deltaThreshold, result.width, result.height, outputMaskColor, outputShiftColor, backgroundColor, hShift, vShift, perceptual, gamma);\n // Result\n if (result.differences === 0) {\n this.log('Images are identical or near identical');\n result.code = PixelDiff.RESULT_IDENTICAL;\n } else if (this.isAboveThreshold(result.differences, result.dimension)) {\n this.log('Images are visibly different');\n this.log(result.differences + ' pixels are different');\n result.code = PixelDiff.RESULT_DIFFERENT;\n } else {\n this.log('Images are similar');\n this.log(result.differences + ' pixels are different');\n result.code = PixelDiff.RESULT_SIMILAR;\n }\n return result;\n }\n}\nmodule.exports = PixelDiff;\n\"\"\"", "test_func_type": "тестовую функцию", "test_func_context": "\"\"\"\n'use strict';\nconst PixelDiff = require('../'),\n PNGImage = require('pngjs-image'),\n Promise = require('promise'),\n fs = require('fs'),\n expect = require('chai').expect;\nfunction generateImage(type) {\n let image;\n switch (type) {\n case 'small-1':\n image = PNGImage.createImage(2, 2);\n image.setAt(0, 0, {red: 10, green: 20, blue: 30, alpha: 40});\n image.setAt(0, 1, {red: 50, green: 60, blue: 70, alpha: 80});\n image.setAt(1, 0, {red: 90, green: 100, blue: 110, alpha: 120});\n image.setAt(1, 1, {red: 130, green: 140, blue: 150, alpha: 160});\n break;\n case 'small-2':\n image = PNGImage.createImage(2, 2);\n image.setAt(0, 0, {red: 210, green: 220, blue: 230, alpha: 240});\n image.setAt(0, 1, {red: 10, green: 20, blue: 30, alpha: 40});\n image.setAt(1, 0, {red: 50, green: 60, blue: 70, alpha: 80});\n image.setAt(1, 1, {red: 15, green: 25, blue: 35, alpha: 45});\n break;\n case 'small-3':\n image = PNGImage.createImage(2, 2);\n break;\n case 'medium-1':\n image = PNGImage.createImage(3, 3);\n image.setAt(0, 0, {red: 130, green: 140, blue: 150, alpha: 160});\n image.setAt(0, 1, {red: 170, green: 180, blue: 190, alpha: 200});\n image.setAt(0, 2, {red: 210, green: 220, blue: 230, alpha: 240});\n image.setAt(1, 0, {red: 15, green: 25, blue: 35, alpha: 45});\n image.setAt(1, 1, {red: 55, green: 65, blue: 75, alpha: 85});\n image.setAt(1, 2, {red: 95, green: 105, blue: 115, alpha: 125});\n image.setAt(2, 0, {red: 10, green: 20, blue: 30, alpha: 40});\n image.setAt(2, 1, {red: 50, green: 60, blue: 70, alpha: 80});\n image.setAt(2, 2, {red: 90, green: 100, blue: 110, alpha: 120});\n break;\n case 'medium-2':\n image = PNGImage.createImage(3, 3);\n image.setAt(0, 0, {red: 95, green: 15, blue: 165, alpha: 26});\n image.setAt(0, 1, {red: 15, green: 225, blue: 135, alpha: 144});\n image.setAt(0, 2, {red: 170, green: 80, blue: 210, alpha: 2});\n image.setAt(1, 0, {red: 50, green: 66, blue: 23, alpha: 188});\n image.setAt(1, 1, {red: 110, green: 120, blue: 63, alpha: 147});\n image.setAt(1, 2, {red: 30, green: 110, blue: 10, alpha: 61});\n image.setAt(2, 0, {red: 190, green: 130, blue: 180, alpha: 29});\n image.setAt(2, 1, {red: 10, green: 120, blue: 31, alpha: 143});\n image.setAt(2, 2, {red: 155, green: 165, blue: 15, alpha: 185});\n break;\n case 'slim-1':\n image = PNGImage.createImage(1, 3);\n image.setAt(0, 0, {red: 15, green: 225, blue: 135, alpha: 144});\n image.setAt(0, 1, {red: 170, green: 80, blue: 210, alpha: 2});\n image.setAt(0, 2, {red: 50, green: 66, blue: 23, alpha: 188});\n break;\n case 'slim-2':\n image = PNGImage.createImage(3, 1);\n image.setAt(0, 0, {red: 15, green: 225, blue: 135, alpha: 144});\n image.setAt(1, 0, {red: 170, green: 80, blue: 210, alpha: 2});\n image.setAt(2, 0, {red: 50, green: 66, blue: 23, alpha: 188});\n break;\n }\n return image;\n}\nfunction compareBuffer(buf1, buf2) {\n if (buf1.length !== buf2.length) {\n return false;\n }\n for (let i = 0, len = buf1.length; i < len; i++) {\n if (buf1[i] !== buf2[i]) {\n return false;\n }\n }\n return true;\n}\ndescribe('Pixel-Diff', () => {\n describe('Default values', () => {\n beforeEach(() => {\n this.instance = new PixelDiff({\n imageA: 'image-a', imageAPath: 'path to image-a', imageB: 'image-b', imageBPath: 'path to image-b',\n composition: false\n });\n this.instance.log = (text) => {\n console.log(text);\n };\n });\n describe('Special cases', () => {\n beforeEach(() => {\n this.instance = new PixelDiff({\n imageA: 'image-a', imageB: 'image-b'\n });\n });\n });\n });\n describe('Methods', () => {\n beforeEach(() => {\n this.instance = new PixelDiff({\n imageA: 'image-a', imageAPath: 'path to image-a', imageB: 'image-b', imageBPath: 'path to image-b'\n });\n });\n describe('hasPassed', () => {\n# test function/method here\n });\n describe('_colorDelta', () => {\n });\n describe('_loadImage', () => {\n beforeEach(() => {\n this.image = generateImage('medium-2');\n });\n describe('from Image', () => {\n });\n describe('from Path', () => {\n });\n describe('from Buffer', () => {\n beforeEach(() => {\n this.buffer = fs.readFileSync(__dirname + '/bufferImage.png');\n });\n });\n });\n describe('_copyImage', () => {\n });\n describe('_correctDimensions', () => {\n describe('Missing Values', () => {\n });\n describe('Negative Values', () => {\n });\n describe('Dimensions', () => {\n });\n describe('Border Dimensions', () => {\n });\n });\n describe('_crop', () => {\n beforeEach(() => {\n this.croppedImage = generateImage('medium-1');\n this.expectedImage = generateImage('medium-1');\n });\n });\n describe('_clip', () => {\n });\n describe('isAboveThreshold', () => {\n describe('Pixel threshold', () => {\n beforeEach(() => {\n this.instance._thresholdType = PixelDiff.THRESHOLD_PIXEL;\n this.instance._threshold = 50;\n });\n });\n describe('Percent threshold', () => {\n beforeEach(() => {\n this.instance._thresholdType = PixelDiff.THRESHOLD_PERCENT;\n this.instance._threshold = 0.1;\n });\n });\n });\n describe('Comparison', () => {\n beforeEach(() => {\n this.image1 = generateImage('small-1');\n this.image2 = generateImage('small-2');\n this.image3 = generateImage('small-3');\n this.image4 = generateImage('small-1');\n this.maskColor = {\n red: 123, green: 124, blue: 125, alpha: 126\n };\n this.shiftColor = {\n red: 200, green: 100, blue: 0, alpha: 113\n };\n this.backgroundMaskColor = {\n red: 31, green: 33, blue: 35, alpha: 37\n };\n });\n describe('_pixelCompare', () => {\n });\n describe('_compare', () => {\n beforeEach(() => {\n this.instance._thresholdType = PixelDiff.THRESHOLD_PIXEL;\n this.instance._threshold = 3;\n });\n });\n });\n describe('Run', () => {\n beforeEach(() => {\n this.instance._imageA = generateImage('small-1');\n this.instance._imageB = generateImage('medium-1');\n this.instance._thresholdType = PixelDiff.THRESHOLD_PIXEL;\n this.instance._threshold = 3;\n this.instance._composition = false;\n });\n });\n describe('Color-Conversion', () => {\n });\n });\n})\n\"\"\"", "language": "js", "focal_file_path": "index.js", "test_file_path": "test/unit.spec.js", "test_framework": "mocha" }
it('should pass when similar', () => { expect(this.instance.hasPassed(PixelDiff.RESULT_SIMILAR)).to.be.true; })
{ "id": 3, "repo_id": "75358362", "focal_func_type": "method" }
Ты - помощник тестировщика. Твоя задача - писать юнит-тесты для данного тебе кода на языке {language}. Напиши тест для этого кода на языке {language} из файла '{focal_file_path}': {focal_func} Тебе необходимо написать {test_func_type} на языке {language}. Тест будет помещен в файл '{test_file_path}'. Для тебя собран код из репозитория, который может помочь тебе в написании теста: {focal_func_context} Пользователь уже написал некоторый код в тестовом файле, учитывай его при написании теста: {test_func_context} В ответе пиши только {test_func_type}, не добавляя комментариев и текста. Оформи свой ответ с соблюдением markdown разметки для кода: ```{language} <your code> ```
{ "focal_func": "\"\"\"\ndef create_sqlalchemy_engine_with_retry(db_uri):\n attempts = 0\n while True:\n attempts += 1\n engine = create_sqlalchemy_engine(db_uri)\n try:\n sqlalchemy.inspect(engine)\n return engine\n except Exception as e:\n if attempts < MAX_RETRY_COUNT:\n sleep_duration = 0.1 * ((2**attempts) - 1)\n _logger.warning(\n \"SQLAlchemy engine could not be created. The following exception is caught.\\n\"\n \"%s\\nOperation will be retried in %.1f seconds\",\n e,\n sleep_duration,\n )\n time.sleep(sleep_duration)\n continue\n raise\n\"\"\"", "focal_func_context": "\"\"\"\n#mlflow/store/db/utils.py\nimport logging\nimport os\nimport time\nfrom contextlib import contextmanager\n\nimport sqlalchemy\nfrom alembic.migration import MigrationContext\nfrom alembic.script import ScriptDirectory\nfrom sqlalchemy import sql\n\n# We need to import sqlalchemy.pool to convert poolclass string to class object\nfrom sqlalchemy.pool import (\n AssertionPool,\n AsyncAdaptedQueuePool,\n FallbackAsyncAdaptedQueuePool,\n NullPool,\n QueuePool,\n SingletonThreadPool,\n StaticPool,\n)\n\nfrom mlflow.environment_variables import (\n MLFLOW_SQLALCHEMYSTORE_ECHO,\n MLFLOW_SQLALCHEMYSTORE_MAX_OVERFLOW,\n MLFLOW_SQLALCHEMYSTORE_POOL_RECYCLE,\n MLFLOW_SQLALCHEMYSTORE_POOL_SIZE,\n MLFLOW_SQLALCHEMYSTORE_POOLCLASS,\n)\nfrom mlflow.exceptions import MlflowException\nfrom mlflow.protos.databricks_pb2 import BAD_REQUEST, INTERNAL_ERROR, TEMPORARILY_UNAVAILABLE\nfrom mlflow.store.db.db_types import SQLITE\nfrom mlflow.store.model_registry.dbmodels.models import (\n SqlModelVersion,\n SqlModelVersionTag,\n SqlRegisteredModel,\n SqlRegisteredModelAlias,\n SqlRegisteredModelTag,\n)\nfrom mlflow.store.tracking.dbmodels.initial_models import Base as InitialBase\nfrom mlflow.store.tracking.dbmodels.models import (\n SqlDataset,\n SqlExperiment,\n SqlExperimentTag,\n SqlInput,\n SqlInputTag,\n SqlLatestMetric,\n SqlMetric,\n SqlParam,\n SqlRun,\n SqlTag,\n)\n\n_logger = logging.getLogger(__name__)\n\nMAX_RETRY_COUNT = 15\n\n\ndef _get_package_dir():\n \"\"\"Returns directory containing MLflow python package.\"\"\"\n current_dir = os.path.dirname(os.path.abspath(__file__))\n return os.path.normpath(os.path.join(current_dir, os.pardir, os.pardir))\n\n\ndef _all_tables_exist(engine):\n return {\n t\n for t in sqlalchemy.inspect(engine).get_table_names()\n # Filter out alembic tables\n if not t.startswith(\"alembic_\")\n } == {\n SqlExperiment.__tablename__,\n SqlRun.__tablename__,\n SqlMetric.__tablename__,\n SqlParam.__tablename__,\n SqlTag.__tablename__,\n SqlExperimentTag.__tablename__,\n SqlLatestMetric.__tablename__,\n SqlRegisteredModel.__tablename__,\n SqlModelVersion.__tablename__,\n SqlRegisteredModelTag.__tablename__,\n SqlModelVersionTag.__tablename__,\n SqlRegisteredModelAlias.__tablename__,\n SqlDataset.__tablename__,\n SqlInput.__tablename__,\n SqlInputTag.__tablename__,\n }\n\n\ndef _initialize_tables(engine):\n _logger.info(\"Creating initial MLflow database tables...\")\n InitialBase.metadata.create_all(engine)\n _upgrade_db(engine)\n\n\ndef _get_latest_schema_revision():\n \"\"\"Get latest schema revision as a string.\"\"\"\n # We aren't executing any commands against a DB, so we leave the DB URL unspecified\n config = _get_alembic_config(db_url=\"\")\n script = ScriptDirectory.from_config(config)\n heads = script.get_heads()\n if len(heads) != 1:\n raise MlflowException(\n f\"Migration script directory was in unexpected state. Got {len(heads)} head \"\n f\"database versions but expected only 1. Found versions: {heads}\"\n )\n return heads[0]\n\n\ndef _verify_schema(engine):\n head_revision = _get_latest_schema_revision()\n current_rev = _get_schema_version(engine)\n if current_rev != head_revision:\n raise MlflowException(\n f\"Detected out-of-date database schema (found version {current_rev}, \"\n f\"but expected {head_revision}). Take a backup of your database, then run \"\n \"'mlflow db upgrade <database_uri>' \"\n \"to migrate your database to the latest schema. NOTE: schema migration may \"\n \"result in database downtime - please consult your database's documentation for \"\n \"more detail.\"\n )\n\n\ndef _get_managed_session_maker(SessionMaker, db_type):\n \"\"\"\n Creates a factory for producing exception-safe SQLAlchemy sessions that are made available\n using a context manager. Any session produced by this factory is automatically committed\n if no exceptions are encountered within its associated context. If an exception is\n encountered, the session is rolled back. Finally, any session produced by this factory is\n automatically closed when the session's associated context is exited.\n \"\"\"\n\n @contextmanager\n def make_managed_session():\n \"\"\"Provide a transactional scope around a series of operations.\"\"\"\n with SessionMaker() as session:\n try:\n if db_type == SQLITE:\n session.execute(sql.text(\"PRAGMA foreign_keys = ON;\"))\n session.execute(sql.text(\"PRAGMA busy_timeout = 20000;\"))\n session.execute(sql.text(\"PRAGMA case_sensitive_like = true;\"))\n yield session\n session.commit()\n except MlflowException:\n session.rollback()\n raise\n except sqlalchemy.exc.OperationalError as e:\n session.rollback()\n _logger.exception(\n \"SQLAlchemy database error. The following exception is caught.\\n%s\",\n e,\n )\n raise MlflowException(message=e, error_code=TEMPORARILY_UNAVAILABLE)\n except sqlalchemy.exc.SQLAlchemyError as e:\n session.rollback()\n raise MlflowException(message=e, error_code=BAD_REQUEST)\n except Exception as e:\n session.rollback()\n raise MlflowException(message=e, error_code=INTERNAL_ERROR)\n\n return make_managed_session\n\n\ndef _get_alembic_config(db_url, alembic_dir=None):\n \"\"\"\n Constructs an alembic Config object referencing the specified database and migration script\n directory.\n\n Args:\n db_url: Database URL, like sqlite:///<absolute-path-to-local-db-file>. See\n https://docs.sqlalchemy.org/en/13/core/engines.html#database-urls for a full list of\n valid database URLs.\n alembic_dir: Path to migration script directory. Uses canonical migration script\n directory under mlflow/alembic if unspecified. TODO: remove this argument in MLflow 1.1,\n as it's only used to run special migrations for pre-1.0 users to remove duplicate\n constraint names.\n \"\"\"\n from alembic.config import Config\n\n final_alembic_dir = (\n os.path.join(_get_package_dir(), \"store\", \"db_migrations\")\n if alembic_dir is None\n else alembic_dir\n )\n # Escape any '%' that appears in a db_url. This could be in a password,\n # url, or anything that is part of a potentially complex database url\n db_url = db_url.replace(\"%\", \"%%\")\n config = Config(os.path.join(final_alembic_dir, \"alembic.ini\"))\n config.set_main_option(\"script_location\", final_alembic_dir)\n config.set_main_option(\"sqlalchemy.url\", db_url)\n return config\n\n\ndef _upgrade_db(engine):\n \"\"\"\n Upgrade the schema of an MLflow tracking database to the latest supported version.\n Note that schema migrations can be slow and are not guaranteed to be transactional -\n we recommend taking a backup of your database before running migrations.\n\n Args:\n url: Database URL, like sqlite:///<absolute-path-to-local-db-file>. See\n https://docs.sqlalchemy.org/en/13/core/engines.html#database-urls for a full list of\n valid database URLs.\n \"\"\"\n # alembic adds significant import time, so we import it lazily\n from alembic import command\n\n db_url = str(engine.url)\n _logger.info(\"Updating database tables\")\n config = _get_alembic_config(db_url)\n # Initialize a shared connection to be used for the database upgrade, ensuring that\n # any connection-dependent state (e.g., the state of an in-memory database) is preserved\n # for reference by the upgrade routine. For more information, see\n # https://alembic.sqlalchemy.org/en/latest/cookbook.html#sharing-a-\n # connection-with-a-series-of-migration-commands-and-environments\n with engine.begin() as connection:\n config.attributes[\"connection\"] = connection\n command.upgrade(config, \"heads\")\n\n\ndef _get_schema_version(engine):\n with engine.connect() as connection:\n mc = MigrationContext.configure(connection)\n return mc.get_current_revision()\n\n\n\n#focal function/method here\n\n\n\ndef create_sqlalchemy_engine(db_uri):\n pool_size = MLFLOW_SQLALCHEMYSTORE_POOL_SIZE.get()\n pool_max_overflow = MLFLOW_SQLALCHEMYSTORE_MAX_OVERFLOW.get()\n pool_recycle = MLFLOW_SQLALCHEMYSTORE_POOL_RECYCLE.get()\n echo = MLFLOW_SQLALCHEMYSTORE_ECHO.get()\n poolclass = MLFLOW_SQLALCHEMYSTORE_POOLCLASS.get()\n pool_kwargs = {}\n # Send argument only if they have been injected.\n # Some engine does not support them (for example sqllite)\n if pool_size:\n pool_kwargs[\"pool_size\"] = pool_size\n if pool_max_overflow:\n pool_kwargs[\"max_overflow\"] = pool_max_overflow\n if pool_recycle:\n pool_kwargs[\"pool_recycle\"] = pool_recycle\n if echo:\n pool_kwargs[\"echo\"] = echo\n if poolclass:\n pool_class_map = {\n \"AssertionPool\": AssertionPool,\n \"AsyncAdaptedQueuePool\": AsyncAdaptedQueuePool,\n \"FallbackAsyncAdaptedQueuePool\": FallbackAsyncAdaptedQueuePool,\n \"NullPool\": NullPool,\n \"QueuePool\": QueuePool,\n \"SingletonThreadPool\": SingletonThreadPool,\n \"StaticPool\": StaticPool,\n }\n if poolclass not in pool_class_map:\n list_str = \" \".join(pool_class_map.keys())\n err_str = (\n f\"Invalid poolclass parameter: {poolclass}. Set environment variable \"\n f\"poolclass to empty or one of the following values: {list_str}\"\n )\n _logger.warning(err_str)\n raise ValueError(err_str)\n pool_kwargs[\"poolclass\"] = pool_class_map[poolclass]\n if pool_kwargs:\n _logger.info(\"Create SQLAlchemy engine with pool options %s\", pool_kwargs)\n return sqlalchemy.create_engine(db_uri, pool_pre_ping=True, **pool_kwargs)\n\"\"\"", "test_func_type": "тестовую функцию", "test_func_context": "\"\"\"\nfrom unittest import mock\nimport pytest\nfrom sqlalchemy.pool import NullPool\nfrom sqlalchemy.pool.impl import QueuePool\nfrom mlflow.store.db import utils\n\"\"\"", "language": "python", "focal_file_path": "mlflow/store/db/utils.py", "test_file_path": "tests/store/db/test_utils.py", "test_framework": "" }
def test_create_sqlalchemy_engine_with_retry_success_after_third_call(): with mock.patch( "sqlalchemy.inspect", side_effect=[Exception, Exception, "Inspect"] ), mock.patch( "mlflow.store.db.utils.create_sqlalchemy_engine", return_value="Engine" ) as mock_create_sqlalchemy_engine, mock.patch("time.sleep"): engine = utils.create_sqlalchemy_engine_with_retry("mydb://host:port/") assert mock_create_sqlalchemy_engine.mock_calls == [mock.call("mydb://host:port/")] * 3 assert engine == "Engine"
{ "id": 4, "repo_id": "136202695", "focal_func_type": "function" }
Ваша задача — написать {test_func_type} на языке {language} для кода из файла'{focal_file_path}'. К тестированию предоставлен следующий фрагмент кода: {focal_func} Дополнительный контекст исходного файла: {focal_func_context} Также вот что уже объявлено или импортировано для вас в будущем тестовом файле'{test_file_path}': {test_func_context} В ответе предоставляйте исключительно {test_func_type}, никаких комментариев. Ваш ответ должен быть оформлен с помощью markdown следующим образом: ```{language} <your code> ```
{ "focal_func": "\"\"\"\ndef create_urllib3_context(\n ssl_version: int | None = None,\n cert_reqs: int | None = None,\n options: int | None = None,\n ciphers: str | None = None,\n ssl_minimum_version: int | None = None,\n ssl_maximum_version: int | None = None,\n) -> ssl.SSLContext:\n \"\"\"Creates and configures an :class:`ssl.SSLContext` instance for use with urllib3.\n\n :param ssl_version:\n The desired protocol version to use. This will default to\n PROTOCOL_SSLv23 which will negotiate the highest protocol that both\n the server and your installation of OpenSSL support.\n\n This parameter is deprecated instead use 'ssl_minimum_version'.\n :param ssl_minimum_version:\n The minimum version of TLS to be used. Use the 'ssl.TLSVersion' enum for specifying the value.\n :param ssl_maximum_version:\n The maximum version of TLS to be used. Use the 'ssl.TLSVersion' enum for specifying the value.\n Not recommended to set to anything other than 'ssl.TLSVersion.MAXIMUM_SUPPORTED' which is the\n default value.\n :param cert_reqs:\n Whether to require the certificate verification. This defaults to\n ``ssl.CERT_REQUIRED``.\n :param options:\n Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,\n ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``.\n :param ciphers:\n Which cipher suites to allow the server to select. Defaults to either system configured\n ciphers if OpenSSL 1.1.1+, otherwise uses a secure default set of ciphers.\n :returns:\n Constructed SSLContext object with specified options\n :rtype: SSLContext\n \"\"\"\n if SSLContext is None:\n raise TypeError(\"Can't create an SSLContext object without an ssl module\")\n\n # This means 'ssl_version' was specified as an exact value.\n if ssl_version not in (None, PROTOCOL_TLS, PROTOCOL_TLS_CLIENT):\n # Disallow setting 'ssl_version' and 'ssl_minimum|maximum_version'\n # to avoid conflicts.\n if ssl_minimum_version is not None or ssl_maximum_version is not None:\n raise ValueError(\n \"Can't specify both 'ssl_version' and either \"\n \"'ssl_minimum_version' or 'ssl_maximum_version'\"\n )\n\n # 'ssl_version' is deprecated and will be removed in the future.\n else:\n # Use 'ssl_minimum_version' and 'ssl_maximum_version' instead.\n ssl_minimum_version = _SSL_VERSION_TO_TLS_VERSION.get(\n ssl_version, TLSVersion.MINIMUM_SUPPORTED\n )\n ssl_maximum_version = _SSL_VERSION_TO_TLS_VERSION.get(\n ssl_version, TLSVersion.MAXIMUM_SUPPORTED\n )\n\n # This warning message is pushing users to use 'ssl_minimum_version'\n # instead of both min/max. Best practice is to only set the minimum version and\n # keep the maximum version to be it's default value: 'TLSVersion.MAXIMUM_SUPPORTED'\n warnings.warn(\n \"'ssl_version' option is deprecated and will be \"\n \"removed in urllib3 v2.1.0. Instead use 'ssl_minimum_version'\",\n category=DeprecationWarning,\n stacklevel=2,\n )\n\n # PROTOCOL_TLS is deprecated in Python 3.10 so we always use PROTOCOL_TLS_CLIENT\n context = SSLContext(PROTOCOL_TLS_CLIENT)\n\n if ssl_minimum_version is not None:\n context.minimum_version = ssl_minimum_version\n else: # Python <3.10 defaults to 'MINIMUM_SUPPORTED' so explicitly set TLSv1.2 here\n context.minimum_version = TLSVersion.TLSv1_2\n\n if ssl_maximum_version is not None:\n context.maximum_version = ssl_maximum_version\n\n # Unless we're given ciphers defer to either system ciphers in\n # the case of OpenSSL 1.1.1+ or use our own secure default ciphers.\n if ciphers:\n context.set_ciphers(ciphers)\n\n # Setting the default here, as we may have no ssl module on import\n cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs\n\n if options is None:\n options = 0\n # SSLv2 is easily broken and is considered harmful and dangerous\n options |= OP_NO_SSLv2\n # SSLv3 has several problems and is now dangerous\n options |= OP_NO_SSLv3\n # Disable compression to prevent CRIME attacks for OpenSSL 1.0+\n # (issue #309)\n options |= OP_NO_COMPRESSION\n # TLSv1.2 only. Unless set explicitly, do not request tickets.\n # This may save some bandwidth on wire, and although the ticket is encrypted,\n # there is a risk associated with it being on wire,\n # if the server is not rotating its ticketing keys properly.\n options |= OP_NO_TICKET\n\n context.options |= options\n\n # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is\n # necessary for conditional client cert authentication with TLS 1.3.\n # The attribute is None for OpenSSL <= 1.1.0 or does not exist when using\n # an SSLContext created by pyOpenSSL.\n if getattr(context, \"post_handshake_auth\", None) is not None:\n context.post_handshake_auth = True\n\n # The order of the below lines setting verify_mode and check_hostname\n # matter due to safe-guards SSLContext has to prevent an SSLContext with\n # check_hostname=True, verify_mode=NONE/OPTIONAL.\n # We always set 'check_hostname=False' for pyOpenSSL so we rely on our own\n # 'ssl.match_hostname()' implementation.\n if cert_reqs == ssl.CERT_REQUIRED and not IS_PYOPENSSL:\n context.verify_mode = cert_reqs\n context.check_hostname = True\n else:\n context.check_hostname = False\n context.verify_mode = cert_reqs\n\n try:\n context.hostname_checks_common_name = False\n except AttributeError: # Defensive: for CPython < 3.8.9 and 3.9.3; for PyPy < 7.3.8\n pass\n\n # Enable logging of TLS session keys via defacto standard environment variable\n # 'SSLKEYLOGFILE', if the feature is available (Python 3.8+). Skip empty values.\n if hasattr(context, \"keylog_filename\"):\n sslkeylogfile = os.environ.get(\"SSLKEYLOGFILE\")\n if sslkeylogfile:\n context.keylog_filename = sslkeylogfile\n\n return context\n\"\"\"", "focal_func_context": "\"\"\"\n#src/urllib3/util/ssl_.py\nfrom __future__ import annotations\n\nimport hmac\nimport os\nimport socket\nimport sys\nimport typing\nimport warnings\nfrom binascii import unhexlify\nfrom hashlib import md5, sha1, sha256\n\nfrom ..exceptions import ProxySchemeUnsupported, SSLError\nfrom .url import _BRACELESS_IPV6_ADDRZ_RE, _IPV4_RE\n\nSSLContext = None\nSSLTransport = None\nHAS_NEVER_CHECK_COMMON_NAME = False\nIS_PYOPENSSL = False\nALPN_PROTOCOLS = [\"http/1.1\"]\n\n_TYPE_VERSION_INFO = typing.Tuple[int, int, int, str, int]\n\n# Maps the length of a digest to a possible hash function producing this digest\nHASHFUNC_MAP = {32: md5, 40: sha1, 64: sha256}\n\n\ndef _is_bpo_43522_fixed(\n implementation_name: str,\n version_info: _TYPE_VERSION_INFO,\n pypy_version_info: _TYPE_VERSION_INFO | None,\n) -> bool:\n \"\"\"Return True for CPython 3.8.9+, 3.9.3+ or 3.10+ and PyPy 7.3.8+ where\n setting SSLContext.hostname_checks_common_name to False works.\n\n Outside of CPython and PyPy we don't know which implementations work\n or not so we conservatively use our hostname matching as we know that works\n on all implementations.\n\n https://github.com/urllib3/urllib3/issues/2192#issuecomment-821832963\n https://foss.heptapod.net/pypy/pypy/-/issues/3539\n \"\"\"\n if implementation_name == \"pypy\":\n # https://foss.heptapod.net/pypy/pypy/-/issues/3129\n return pypy_version_info >= (7, 3, 8) # type: ignore[operator]\n elif implementation_name == \"cpython\":\n major_minor = version_info[:2]\n micro = version_info[2]\n return (\n (major_minor == (3, 8) and micro >= 9)\n or (major_minor == (3, 9) and micro >= 3)\n or major_minor >= (3, 10)\n )\n else: # Defensive:\n return False\n\n\ndef _is_has_never_check_common_name_reliable(\n openssl_version: str,\n openssl_version_number: int,\n implementation_name: str,\n version_info: _TYPE_VERSION_INFO,\n pypy_version_info: _TYPE_VERSION_INFO | None,\n) -> bool:\n # As of May 2023, all released versions of LibreSSL fail to reject certificates with\n # only common names, see https://github.com/urllib3/urllib3/pull/3024\n is_openssl = openssl_version.startswith(\"OpenSSL \")\n # Before fixing OpenSSL issue #14579, the SSL_new() API was not copying hostflags\n # like X509_CHECK_FLAG_NEVER_CHECK_SUBJECT, which tripped up CPython.\n # https://github.com/openssl/openssl/issues/14579\n # This was released in OpenSSL 1.1.1l+ (>=0x101010cf)\n is_openssl_issue_14579_fixed = openssl_version_number >= 0x101010CF\n\n return is_openssl and (\n is_openssl_issue_14579_fixed\n or _is_bpo_43522_fixed(implementation_name, version_info, pypy_version_info)\n )\n\n\nif typing.TYPE_CHECKING:\n from ssl import VerifyMode\n from typing import TypedDict\n\n from .ssltransport import SSLTransport as SSLTransportType\n\n class _TYPE_PEER_CERT_RET_DICT(TypedDict, total=False):\n subjectAltName: tuple[tuple[str, str], ...]\n subject: tuple[tuple[tuple[str, str], ...], ...]\n serialNumber: str\n\n\n# Mapping from 'ssl.PROTOCOL_TLSX' to 'TLSVersion.X'\n_SSL_VERSION_TO_TLS_VERSION: dict[int, int] = {}\n\ntry: # Do we have ssl at all?\n import ssl\n from ssl import ( # type: ignore[assignment]\n CERT_REQUIRED,\n HAS_NEVER_CHECK_COMMON_NAME,\n OP_NO_COMPRESSION,\n OP_NO_TICKET,\n OPENSSL_VERSION,\n OPENSSL_VERSION_NUMBER,\n PROTOCOL_TLS,\n PROTOCOL_TLS_CLIENT,\n OP_NO_SSLv2,\n OP_NO_SSLv3,\n SSLContext,\n TLSVersion,\n )\n\n PROTOCOL_SSLv23 = PROTOCOL_TLS\n\n # Setting SSLContext.hostname_checks_common_name = False didn't work before CPython\n # 3.8.9, 3.9.3, and 3.10 (but OK on PyPy) or OpenSSL 1.1.1l+\n if HAS_NEVER_CHECK_COMMON_NAME and not _is_has_never_check_common_name_reliable(\n OPENSSL_VERSION,\n OPENSSL_VERSION_NUMBER,\n sys.implementation.name,\n sys.version_info,\n sys.pypy_version_info if sys.implementation.name == \"pypy\" else None, # type: ignore[attr-defined]\n ):\n HAS_NEVER_CHECK_COMMON_NAME = False\n\n # Need to be careful here in case old TLS versions get\n # removed in future 'ssl' module implementations.\n for attr in (\"TLSv1\", \"TLSv1_1\", \"TLSv1_2\"):\n try:\n _SSL_VERSION_TO_TLS_VERSION[getattr(ssl, f\"PROTOCOL_{attr}\")] = getattr(\n TLSVersion, attr\n )\n except AttributeError: # Defensive:\n continue\n\n from .ssltransport import SSLTransport # type: ignore[assignment]\nexcept ImportError:\n OP_NO_COMPRESSION = 0x20000 # type: ignore[assignment]\n OP_NO_TICKET = 0x4000 # type: ignore[assignment]\n OP_NO_SSLv2 = 0x1000000 # type: ignore[assignment]\n OP_NO_SSLv3 = 0x2000000 # type: ignore[assignment]\n PROTOCOL_SSLv23 = PROTOCOL_TLS = 2 # type: ignore[assignment]\n PROTOCOL_TLS_CLIENT = 16 # type: ignore[assignment]\n\n\n_TYPE_PEER_CERT_RET = typing.Union[\"_TYPE_PEER_CERT_RET_DICT\", bytes, None]\n\n\ndef assert_fingerprint(cert: bytes | None, fingerprint: str) -> None:\n \"\"\"\n Checks if given fingerprint matches the supplied certificate.\n\n :param cert:\n Certificate as bytes object.\n :param fingerprint:\n Fingerprint as string of hexdigits, can be interspersed by colons.\n \"\"\"\n\n if cert is None:\n raise SSLError(\"No certificate for the peer.\")\n\n fingerprint = fingerprint.replace(\":\", \"\").lower()\n digest_length = len(fingerprint)\n hashfunc = HASHFUNC_MAP.get(digest_length)\n if not hashfunc:\n raise SSLError(f\"Fingerprint of invalid length: {fingerprint}\")\n\n # We need encode() here for py32; works on py2 and p33.\n fingerprint_bytes = unhexlify(fingerprint.encode())\n\n cert_digest = hashfunc(cert).digest()\n\n if not hmac.compare_digest(cert_digest, fingerprint_bytes):\n raise SSLError(\n f'Fingerprints did not match. Expected \"{fingerprint}\", got \"{cert_digest.hex()}\"'\n )\n\n\ndef resolve_cert_reqs(candidate: None | int | str) -> VerifyMode:\n \"\"\"\n Resolves the argument to a numeric constant, which can be passed to\n the wrap_socket function/method from the ssl module.\n Defaults to :data:`ssl.CERT_REQUIRED`.\n If given a string it is assumed to be the name of the constant in the\n :mod:`ssl` module or its abbreviation.\n (So you can specify `REQUIRED` instead of `CERT_REQUIRED`.\n If it's neither `None` nor a string we assume it is already the numeric\n constant which can directly be passed to wrap_socket.\n \"\"\"\n if candidate is None:\n return CERT_REQUIRED\n\n if isinstance(candidate, str):\n res = getattr(ssl, candidate, None)\n if res is None:\n res = getattr(ssl, \"CERT_\" + candidate)\n return res # type: ignore[no-any-return]\n\n return candidate # type: ignore[return-value]\n\n\ndef resolve_ssl_version(candidate: None | int | str) -> int:\n \"\"\"\n like resolve_cert_reqs\n \"\"\"\n if candidate is None:\n return PROTOCOL_TLS\n\n if isinstance(candidate, str):\n res = getattr(ssl, candidate, None)\n if res is None:\n res = getattr(ssl, \"PROTOCOL_\" + candidate)\n return typing.cast(int, res)\n\n return candidate\n\n\n\n#focal function/method here\n\n\n\n@typing.overload\ndef ssl_wrap_socket(\n sock: socket.socket,\n keyfile: str | None = ...,\n certfile: str | None = ...,\n cert_reqs: int | None = ...,\n ca_certs: str | None = ...,\n server_hostname: str | None = ...,\n ssl_version: int | None = ...,\n ciphers: str | None = ...,\n ssl_context: ssl.SSLContext | None = ...,\n ca_cert_dir: str | None = ...,\n key_password: str | None = ...,\n ca_cert_data: None | str | bytes = ...,\n tls_in_tls: typing.Literal[False] = ...,\n) -> ssl.SSLSocket:\n ...\n\n\n@typing.overload\ndef ssl_wrap_socket(\n sock: socket.socket,\n keyfile: str | None = ...,\n certfile: str | None = ...,\n cert_reqs: int | None = ...,\n ca_certs: str | None = ...,\n server_hostname: str | None = ...,\n ssl_version: int | None = ...,\n ciphers: str | None = ...,\n ssl_context: ssl.SSLContext | None = ...,\n ca_cert_dir: str | None = ...,\n key_password: str | None = ...,\n ca_cert_data: None | str | bytes = ...,\n tls_in_tls: bool = ...,\n) -> ssl.SSLSocket | SSLTransportType:\n ...\n\n\ndef ssl_wrap_socket(\n sock: socket.socket,\n keyfile: str | None = None,\n certfile: str | None = None,\n cert_reqs: int | None = None,\n ca_certs: str | None = None,\n server_hostname: str | None = None,\n ssl_version: int | None = None,\n ciphers: str | None = None,\n ssl_context: ssl.SSLContext | None = None,\n ca_cert_dir: str | None = None,\n key_password: str | None = None,\n ca_cert_data: None | str | bytes = None,\n tls_in_tls: bool = False,\n) -> ssl.SSLSocket | SSLTransportType:\n \"\"\"\n All arguments except for server_hostname, ssl_context, tls_in_tls, ca_cert_data and\n ca_cert_dir have the same meaning as they do when using\n :func:`ssl.create_default_context`, :meth:`ssl.SSLContext.load_cert_chain`,\n :meth:`ssl.SSLContext.set_ciphers` and :meth:`ssl.SSLContext.wrap_socket`.\n\n :param server_hostname:\n When SNI is supported, the expected hostname of the certificate\n :param ssl_context:\n A pre-made :class:`SSLContext` object. If none is provided, one will\n be created using :func:`create_urllib3_context`.\n :param ciphers:\n A string of ciphers we wish the client to support.\n :param ca_cert_dir:\n A directory containing CA certificates in multiple separate files, as\n supported by OpenSSL's -CApath flag or the capath argument to\n SSLContext.load_verify_locations().\n :param key_password:\n Optional password if the keyfile is encrypted.\n :param ca_cert_data:\n Optional string containing CA certificates in PEM format suitable for\n passing as the cadata parameter to SSLContext.load_verify_locations()\n :param tls_in_tls:\n Use SSLTransport to wrap the existing socket.\n \"\"\"\n context = ssl_context\n if context is None:\n # Note: This branch of code and all the variables in it are only used in tests.\n # We should consider deprecating and removing this code.\n context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers)\n\n if ca_certs or ca_cert_dir or ca_cert_data:\n try:\n context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data)\n except OSError as e:\n raise SSLError(e) from e\n\n elif ssl_context is None and hasattr(context, \"load_default_certs\"):\n # try to load OS default certs; works well on Windows.\n context.load_default_certs()\n\n # Attempt to detect if we get the goofy behavior of the\n # keyfile being encrypted and OpenSSL asking for the\n # passphrase via the terminal and instead error out.\n if keyfile and key_password is None and _is_key_file_encrypted(keyfile):\n raise SSLError(\"Client private key is encrypted, password is required\")\n\n if certfile:\n if key_password is None:\n context.load_cert_chain(certfile, keyfile)\n else:\n context.load_cert_chain(certfile, keyfile, key_password)\n\n try:\n context.set_alpn_protocols(ALPN_PROTOCOLS)\n except NotImplementedError: # Defensive: in CI, we always have set_alpn_protocols\n pass\n\n ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls, server_hostname)\n return ssl_sock\n\n\ndef is_ipaddress(hostname: str | bytes) -> bool:\n \"\"\"Detects whether the hostname given is an IPv4 or IPv6 address.\n Also detects IPv6 addresses with Zone IDs.\n\n :param str hostname: Hostname to examine.\n :return: True if the hostname is an IP address, False otherwise.\n \"\"\"\n if isinstance(hostname, bytes):\n # IDN A-label bytes are ASCII compatible.\n hostname = hostname.decode(\"ascii\")\n return bool(_IPV4_RE.match(hostname) or _BRACELESS_IPV6_ADDRZ_RE.match(hostname))\n\n\ndef _is_key_file_encrypted(key_file: str) -> bool:\n \"\"\"Detects if a key file is encrypted or not.\"\"\"\n with open(key_file) as f:\n for line in f:\n # Look for Proc-Type: 4,ENCRYPTED\n if \"ENCRYPTED\" in line:\n return True\n\n return False\n\n\ndef _ssl_wrap_socket_impl(\n sock: socket.socket,\n ssl_context: ssl.SSLContext,\n tls_in_tls: bool,\n server_hostname: str | None = None,\n) -> ssl.SSLSocket | SSLTransportType:\n if tls_in_tls:\n if not SSLTransport:\n # Import error, ssl is not available.\n raise ProxySchemeUnsupported(\n \"TLS in TLS requires support for the 'ssl' module\"\n )\n\n SSLTransport._validate_ssl_context_for_tls_in_tls(ssl_context)\n return SSLTransport(sock, ssl_context, server_hostname)\n\n return ssl_context.wrap_socket(sock, server_hostname=server_hostname)\n\"\"\"", "test_func_type": "тестовый метод", "test_func_context": "\"\"\"\nclass TestSSL:\n#Test method here\nfrom __future__ import annotations\nimport ssl\nimport typing\nfrom unittest import mock\nimport pytest\nfrom urllib3.exceptions import ProxySchemeUnsupported, SSLError\nfrom urllib3.util import ssl_\n\"\"\"", "language": "python", "focal_file_path": "src/urllib3/util/ssl_.py", "test_file_path": "test/test_ssl.py", "test_framework": "" }
@pytest.mark.parametrize( "kwargs", [ {"ssl_version": ssl.PROTOCOL_TLSv1, "ssl_minimum_version": None}, {"ssl_version": ssl.PROTOCOL_TLSv1, "ssl_maximum_version": None}, { "ssl_version": ssl.PROTOCOL_TLSv1, "ssl_minimum_version": None, "ssl_maximum_version": None, }, ], ) def test_create_urllib3_context_ssl_version_and_ssl_min_max_version_no_error( self, kwargs: dict[str, typing.Any] ) -> None: with pytest.warns( DeprecationWarning, match=r"'ssl_version' option is deprecated and will be removed in " r"urllib3 v2\.1\.0\. Instead use 'ssl_minimum_version'", ): ssl_.create_urllib3_context(**kwargs)
{ "id": 5, "repo_id": "2410676", "focal_func_type": "function" }
Ты - помощник тестировщика. Твоя задача - писать юнит-тесты для данного тебе кода на языке {language}. Напиши тест для этого кода на языке {language} из файла '{focal_file_path}': {focal_func} Тебе необходимо написать {test_func_type} на языке {language}. Тест будет помещен в файл '{test_file_path}'. Для тебя собран код из репозитория, который может помочь тебе в написании теста: {focal_func_context} Пользователь уже написал некоторый код в тестовом файле, учитывай его при написании теста: {test_func_context} В ответе пиши только {test_func_type}, не добавляя комментариев и текста. Оформи свой ответ с соблюдением markdown разметки для кода: ```{language} <your code> ```
{ "focal_func": "\"\"\"\nfunc (db *DB) CopyFile(path string, mode os.FileMode) error {\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = db.Copy(f)\n\tif err != nil {\n\t\t_ = f.Close()\n\t\treturn err\n\t}\n\treturn f.Close()\n}\n\"\"\"", "focal_func_context": "\"\"\"\n#Godeps/_workspace/src/github.com/boltdb/bolt/db.go\npackage bolt\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"hash/fnv\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"unsafe\"\n)\n\n// The smallest size that the mmap can be.\nconst minMmapSize = 1 << 22 // 4MB\n\n// The largest step that can be taken when remapping the mmap.\nconst maxMmapStep = 1 << 30 // 1GB\n\n// The data file format version.\nconst version = 2\n\n// Represents a marker value to indicate that a file is a Bolt DB.\nconst magic uint32 = 0xED0CDAED\n\nconst (\n\tminFillPercent = 0.1\n\tmaxFillPercent = 1.0\n)\n\n// DefaultFillPercent is the percentage that split pages are filled.\n// This value can be changed by setting DB.FillPercent.\nconst DefaultFillPercent = 0.5\n\nvar (\n\t// ErrDatabaseNotOpen is returned when a DB instance is accessed before it\n\t// is opened or after it is closed.\n\tErrDatabaseNotOpen = errors.New(\"database not open\")\n\n\t// ErrDatabaseOpen is returned when opening a database that is\n\t// already open.\n\tErrDatabaseOpen = errors.New(\"database already open\")\n\n\t// ErrInvalid is returned when a data file is not a Bolt-formatted database.\n\tErrInvalid = errors.New(\"invalid database\")\n\n\t// ErrVersionMismatch is returned when the data file was created with a\n\t// different version of Bolt.\n\tErrVersionMismatch = errors.New(\"version mismatch\")\n\n\t// ErrChecksum is returned when either meta page checksum does not match.\n\tErrChecksum = errors.New(\"checksum error\")\n)\n\n// DB represents a collection of buckets persisted to a file on disk.\n// All data access is performed through transactions which can be obtained through the DB.\n// All the functions on DB will return a ErrDatabaseNotOpen if accessed before Open() is called.\ntype DB struct {\n\t// When enabled, the database will perform a Check() after every commit.\n\t// A panic is issued if the database is in an inconsistent state. This\n\t// flag has a large performance impact so it should only be used for\n\t// debugging purposes.\n\tStrictMode bool\n\n\t// Sets the threshold for filling nodes when they split. By default,\n\t// the database will fill to 50% but it can be useful to increase this\n\t// amount if you know that your write workloads are mostly append-only.\n\tFillPercent float64\n\n\tpath string\n\tfile *os.File\n\tdata []byte\n\tmeta0 *meta\n\tmeta1 *meta\n\tpageSize int\n\topened bool\n\trwtx *Tx\n\ttxs []*Tx\n\tfreelist *freelist\n\tstats Stats\n\n\trwlock sync.Mutex // Allows only one writer at a time.\n\tmetalock sync.Mutex // Protects meta page access.\n\tmmaplock sync.RWMutex // Protects mmap access during remapping.\n\tstatlock sync.RWMutex // Protects stats access.\n\n\tops struct {\n\t\twriteAt func(b []byte, off int64) (n int, err error)\n\t}\n}\n\n// Path returns the path to currently open database file.\nfunc (db *DB) Path() string {\n\treturn db.path\n}\n\n// GoString returns the Go string representation of the database.\nfunc (db *DB) GoString() string {\n\treturn fmt.Sprintf(\"bolt.DB{path:%q}\", db.path)\n}\n\n// String returns the string representation of the database.\nfunc (db *DB) String() string {\n\treturn fmt.Sprintf(\"DB<%q>\", db.path)\n}\n\n// Open creates and opens a database at the given path.\n// If the file does not exist then it will be created automatically.\nfunc Open(path string, mode os.FileMode) (*DB, error) {\n\tvar db = &DB{opened: true, FillPercent: DefaultFillPercent}\n\n\t// Open data file and separate sync handler for metadata writes.\n\tdb.path = path\n\n\tvar err error\n\tif db.file, err = os.OpenFile(db.path, os.O_RDWR|os.O_CREATE, mode); err != nil {\n\t\t_ = db.close()\n\t\treturn nil, err\n\t}\n\n\t// Lock file so that other processes using Bolt cannot use the database\n\t// at the same time. This would cause corruption since the two processes\n\t// would write meta pages and free pages separately.\n\tif err := syscall.Flock(int(db.file.Fd()), syscall.LOCK_EX); err != nil {\n\t\t_ = db.close()\n\t\treturn nil, err\n\t}\n\n\t// Default values for test hooks\n\tdb.ops.writeAt = db.file.WriteAt\n\n\t// Initialize the database if it doesn't exist.\n\tif info, err := db.file.Stat(); err != nil {\n\t\treturn nil, fmt.Errorf(\"stat error: %s\", err)\n\t} else if info.Size() == 0 {\n\t\t// Initialize new files with meta pages.\n\t\tif err := db.init(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\t// Read the first meta page to determine the page size.\n\t\tvar buf [0x1000]byte\n\t\tif _, err := db.file.ReadAt(buf[:], 0); err == nil {\n\t\t\tm := db.pageInBuffer(buf[:], 0).meta()\n\t\t\tif err := m.validate(); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"meta0 error: %s\", err)\n\t\t\t}\n\t\t\tdb.pageSize = int(m.pageSize)\n\t\t}\n\t}\n\n\t// Memory map the data file.\n\tif err := db.mmap(0); err != nil {\n\t\t_ = db.close()\n\t\treturn nil, err\n\t}\n\n\t// Read in the freelist.\n\tdb.freelist = &freelist{pending: make(map[txid][]pgid)}\n\tdb.freelist.read(db.page(db.meta().freelist))\n\n\t// Mark the database as opened and return.\n\treturn db, nil\n}\n\n// mmap opens the underlying memory-mapped file and initializes the meta references.\n// minsz is the minimum size that the new mmap can be.\nfunc (db *DB) mmap(minsz int) error {\n\tdb.mmaplock.Lock()\n\tdefer db.mmaplock.Unlock()\n\n\t// Dereference all mmap references before unmapping.\n\tif db.rwtx != nil {\n\t\tdb.rwtx.root.dereference()\n\t}\n\n\t// Unmap existing data before continuing.\n\tif err := db.munmap(); err != nil {\n\t\treturn err\n\t}\n\n\tinfo, err := db.file.Stat()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"mmap stat error: %s\", err)\n\t} else if int(info.Size()) < db.pageSize*2 {\n\t\treturn fmt.Errorf(\"file size too small\")\n\t}\n\n\t// Ensure the size is at least the minimum size.\n\tvar size = int(info.Size())\n\tif size < minsz {\n\t\tsize = minsz\n\t}\n\tsize = db.mmapSize(size)\n\n\t// Memory-map the data file as a byte slice.\n\tif db.data, err = syscall.Mmap(int(db.file.Fd()), 0, size, syscall.PROT_READ, syscall.MAP_SHARED); err != nil {\n\t\treturn err\n\t}\n\n\t// Save references to the meta pages.\n\tdb.meta0 = db.page(0).meta()\n\tdb.meta1 = db.page(1).meta()\n\n\t// Validate the meta pages.\n\tif err := db.meta0.validate(); err != nil {\n\t\treturn fmt.Errorf(\"meta0 error: %s\", err)\n\t}\n\tif err := db.meta1.validate(); err != nil {\n\t\treturn fmt.Errorf(\"meta1 error: %s\", err)\n\t}\n\n\treturn nil\n}\n\n// munmap unmaps the data file from memory.\nfunc (db *DB) munmap() error {\n\tif db.data != nil {\n\t\tif err := syscall.Munmap(db.data); err != nil {\n\t\t\treturn fmt.Errorf(\"unmap error: \" + err.Error())\n\t\t}\n\t\tdb.data = nil\n\t}\n\treturn nil\n}\n\n// mmapSize determines the appropriate size for the mmap given the current size\n// of the database. The minimum size is 4MB and doubles until it reaches 1GB.\nfunc (db *DB) mmapSize(size int) int {\n\tif size < minMmapSize {\n\t\treturn minMmapSize\n\t} else if size < maxMmapStep {\n\t\tsize *= 2\n\t} else {\n\t\tsize += maxMmapStep\n\t}\n\n\t// Ensure that the mmap size is a multiple of the page size.\n\tif (size % db.pageSize) != 0 {\n\t\tsize = ((size / db.pageSize) + 1) * db.pageSize\n\t}\n\n\treturn size\n}\n\n// init creates a new database file and initializes its meta pages.\nfunc (db *DB) init() error {\n\t// Set the page size to the OS page size.\n\tdb.pageSize = os.Getpagesize()\n\n\t// Create two meta pages on a buffer.\n\tbuf := make([]byte, db.pageSize*4)\n\tfor i := 0; i < 2; i++ {\n\t\tp := db.pageInBuffer(buf[:], pgid(i))\n\t\tp.id = pgid(i)\n\t\tp.flags = metaPageFlag\n\n\t\t// Initialize the meta page.\n\t\tm := p.meta()\n\t\tm.magic = magic\n\t\tm.version = version\n\t\tm.pageSize = uint32(db.pageSize)\n\t\tm.version = version\n\t\tm.freelist = 2\n\t\tm.root = bucket{root: 3}\n\t\tm.pgid = 4\n\t\tm.txid = txid(i)\n\t}\n\n\t// Write an empty freelist at page 3.\n\tp := db.pageInBuffer(buf[:], pgid(2))\n\tp.id = pgid(2)\n\tp.flags = freelistPageFlag\n\tp.count = 0\n\n\t// Write an empty leaf page at page 4.\n\tp = db.pageInBuffer(buf[:], pgid(3))\n\tp.id = pgid(3)\n\tp.flags = leafPageFlag\n\tp.count = 0\n\n\t// Write the buffer to our data file.\n\tif _, err := db.ops.writeAt(buf, 0); err != nil {\n\t\treturn err\n\t}\n\tif err := fdatasync(db.file); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n// Close releases all database resources.\n// All transactions must be closed before closing the database.\nfunc (db *DB) Close() error {\n\tdb.metalock.Lock()\n\tdefer db.metalock.Unlock()\n\treturn db.close()\n}\n\nfunc (db *DB) close() error {\n\tdb.opened = false\n\n\tdb.freelist = nil\n\tdb.path = \"\"\n\n\t// Clear ops.\n\tdb.ops.writeAt = nil\n\n\t// Close the mmap.\n\tif err := db.munmap(); err != nil {\n\t\treturn err\n\t}\n\n\t// Close file handles.\n\tif db.file != nil {\n\t\t// Unlock the file.\n\t\t_ = syscall.Flock(int(db.file.Fd()), syscall.LOCK_UN)\n\n\t\t// Close the file descriptor.\n\t\tif err := db.file.Close(); err != nil {\n\t\t\treturn fmt.Errorf(\"db file close: %s\", err)\n\t\t}\n\t\tdb.file = nil\n\t}\n\n\treturn nil\n}\n\n// Begin starts a new transaction.\n// Multiple read-only transactions can be used concurrently but only one\n// write transaction can be used at a time. Starting multiple write transactions\n// will cause the calls to block and be serialized until the current write\n// transaction finishes.\n//\n// IMPORTANT: You must close read-only transactions after you are finished or\n// else the database will not reclaim old pages.\nfunc (db *DB) Begin(writable bool) (*Tx, error) {\n\tif writable {\n\t\treturn db.beginRWTx()\n\t}\n\treturn db.beginTx()\n}\n\nfunc (db *DB) beginTx() (*Tx, error) {\n\t// Obtain a read-only lock on the mmap. When the mmap is remapped it will\n\t// obtain a write lock so all transactions must finish before it can be\n\t// remapped.\n\tdb.mmaplock.RLock()\n\n\t// Lock the meta pages while we initialize the transaction.\n\tdb.metalock.Lock()\n\tdefer db.metalock.Unlock()\n\n\t// Exit if the database is not open yet.\n\tif !db.opened {\n\t\tdb.mmaplock.RUnlock()\n\t\treturn nil, ErrDatabaseNotOpen\n\t}\n\n\t// Create a transaction associated with the database.\n\tt := &Tx{}\n\tt.init(db)\n\n\t// Keep track of transaction until it closes.\n\tdb.txs = append(db.txs, t)\n\n\treturn t, nil\n}\n\nfunc (db *DB) beginRWTx() (*Tx, error) {\n\t// Obtain writer lock. This is released by the transaction when it closes.\n\t// This enforces only one writer transaction at a time.\n\tdb.rwlock.Lock()\n\n\t// Once we have the writer lock then we can lock the meta pages so that\n\t// we can set up the transaction.\n\tdb.metalock.Lock()\n\tdefer db.metalock.Unlock()\n\n\t// Exit if the database is not open yet.\n\tif !db.opened {\n\t\tdb.rwlock.Unlock()\n\t\treturn nil, ErrDatabaseNotOpen\n\t}\n\n\t// Create a transaction associated with the database.\n\tt := &Tx{writable: true}\n\tt.init(db)\n\tdb.rwtx = t\n\n\t// Free any pages associated with closed read-only transactions.\n\tvar minid txid = 0xFFFFFFFFFFFFFFFF\n\tfor _, t := range db.txs {\n\t\tif t.id() < minid {\n\t\t\tminid = t.id()\n\t\t}\n\t}\n\tif minid > 0 {\n\t\tdb.freelist.release(minid - 1)\n\t}\n\n\treturn t, nil\n}\n\n// removeTx removes a transaction from the database.\nfunc (db *DB) removeTx(tx *Tx) {\n\tdb.metalock.Lock()\n\n\t// Release the read lock on the mmap.\n\tdb.mmaplock.RUnlock()\n\n\t// Remove the transaction.\n\tfor i, t := range db.txs {\n\t\tif t == tx {\n\t\t\tdb.txs = append(db.txs[:i], db.txs[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Unlock the meta pages.\n\tdb.metalock.Unlock()\n\n\t// Merge statistics.\n\tdb.statlock.Lock()\n\tdb.stats.TxStats.add(&tx.stats)\n\tdb.statlock.Unlock()\n}\n\n// Update executes a function within the context of a read-write managed transaction.\n// If no error is returned from the function then the transaction is committed.\n// If an error is returned then the entire transaction is rolled back.\n// Any error that is returned from the function or returned from the commit is\n// returned from the Update() method.\n//\n// Attempting to manually commit or rollback within the function will cause a panic.\nfunc (db *DB) Update(fn func(*Tx) error) error {\n\tt, err := db.Begin(true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Mark as a managed tx so that the inner function cannot manually commit.\n\tt.managed = true\n\n\t// If an error is returned from the function then rollback and return error.\n\terr = fn(t)\n\tt.managed = false\n\tif err != nil {\n\t\t_ = t.Rollback()\n\t\treturn err\n\t}\n\n\treturn t.Commit()\n}\n\n// View executes a function within the context of a managed read-only transaction.\n// Any error that is returned from the function is returned from the View() method.\n//\n// Attempting to manually rollback within the function will cause a panic.\nfunc (db *DB) View(fn func(*Tx) error) error {\n\tt, err := db.Begin(false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Mark as a managed tx so that the inner function cannot manually rollback.\n\tt.managed = true\n\n\t// If an error is returned from the function then pass it through.\n\terr = fn(t)\n\tt.managed = false\n\tif err != nil {\n\t\t_ = t.Rollback()\n\t\treturn err\n\t}\n\n\tif err := t.Rollback(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n// Copy writes the entire database to a writer.\n// A reader transaction is maintained during the copy so it is safe to continue\n// using the database while a copy is in progress.\nfunc (db *DB) Copy(w io.Writer) error {\n\t// Maintain a reader transaction so pages don't get reclaimed.\n\tt, err := db.Begin(false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Open reader on the database.\n\tf, err := os.Open(db.path)\n\tif err != nil {\n\t\t_ = t.Rollback()\n\t\treturn err\n\t}\n\n\t// Copy the meta pages.\n\tdb.metalock.Lock()\n\t_, err = io.CopyN(w, f, int64(db.pageSize*2))\n\tdb.metalock.Unlock()\n\tif err != nil {\n\t\t_ = t.Rollback()\n\t\t_ = f.Close()\n\t\treturn fmt.Errorf(\"meta copy: %s\", err)\n\t}\n\n\t// Copy data pages.\n\tif _, err := io.Copy(w, f); err != nil {\n\t\t_ = t.Rollback()\n\t\t_ = f.Close()\n\t\treturn err\n\t}\n\n\t// Close read transaction and exit.\n\tif err := t.Rollback(); err != nil {\n\t\t_ = f.Close()\n\t\treturn err\n\t}\n\treturn f.Close()\n}\n\n// CopyFile copies the entire database to file at the given path.\n// A reader transaction is maintained during the copy so it is safe to continue\n// using the database while a copy is in progress.\n\n#focal function/method here\n\n\n// Stats retrieves ongoing performance stats for the database.\n// This is only updated when a transaction closes.\nfunc (db *DB) Stats() Stats {\n\tdb.statlock.RLock()\n\tdefer db.statlock.RUnlock()\n\treturn db.stats\n}\n\n// Check performs several consistency checks on the database.\n// An error is returned if any inconsistency is found.\nfunc (db *DB) Check() error {\n\treturn db.Update(func(tx *Tx) error {\n\t\treturn tx.Check()\n\t})\n}\n\n// This is for internal access to the raw data bytes from the C cursor, use\n// carefully, or not at all.\nfunc (db *DB) Info() *Info {\n\treturn &Info{db.data, db.pageSize}\n}\n\n// page retrieves a page reference from the mmap based on the current page size.\nfunc (db *DB) page(id pgid) *page {\n\tpos := id * pgid(db.pageSize)\n\treturn (*page)(unsafe.Pointer(&db.data[pos]))\n}\n\n// pageInBuffer retrieves a page reference from a given byte array based on the current page size.\nfunc (db *DB) pageInBuffer(b []byte, id pgid) *page {\n\treturn (*page)(unsafe.Pointer(&b[id*pgid(db.pageSize)]))\n}\n\n// meta retrieves the current meta page reference.\nfunc (db *DB) meta() *meta {\n\tif db.meta0.txid > db.meta1.txid {\n\t\treturn db.meta0\n\t}\n\treturn db.meta1\n}\n\n// allocate returns a contiguous block of memory starting at a given page.\nfunc (db *DB) allocate(count int) (*page, error) {\n\t// Allocate a temporary buffer for the page.\n\tbuf := make([]byte, count*db.pageSize)\n\tp := (*page)(unsafe.Pointer(&buf[0]))\n\tp.overflow = uint32(count - 1)\n\n\t// Use pages from the freelist if they are available.\n\tif p.id = db.freelist.allocate(count); p.id != 0 {\n\t\treturn p, nil\n\t}\n\n\t// Resize mmap() if we're at the end.\n\tp.id = db.rwtx.meta.pgid\n\tvar minsz = int((p.id+pgid(count))+1) * db.pageSize\n\tif minsz >= len(db.data) {\n\t\tif err := db.mmap(minsz); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"mmap allocate error: %s\", err)\n\t\t}\n\t}\n\n\t// Move the page id high water mark.\n\tdb.rwtx.meta.pgid += pgid(count)\n\n\treturn p, nil\n}\n\n// Stats represents statistics about the database.\ntype Stats struct {\n\tTxStats TxStats // global, ongoing stats.\n}\n\n// Sub calculates and returns the difference between two sets of database stats.\n// This is useful when obtaining stats at two different points and time and\n// you need the performance counters that occurred within that time span.\nfunc (s *Stats) Sub(other *Stats) Stats {\n\tvar diff Stats\n\tdiff.TxStats = s.TxStats.Sub(&other.TxStats)\n\treturn diff\n}\n\nfunc (s *Stats) add(other *Stats) {\n\ts.TxStats.add(&other.TxStats)\n}\n\ntype Info struct {\n\tData []byte\n\tPageSize int\n}\n\ntype meta struct {\n\tmagic uint32\n\tversion uint32\n\tpageSize uint32\n\tflags uint32\n\troot bucket\n\tfreelist pgid\n\tpgid pgid\n\ttxid txid\n\tchecksum uint64\n}\n\n// validate checks the marker bytes and version of the meta page to ensure it matches this binary.\nfunc (m *meta) validate() error {\n\tif m.checksum != 0 && m.checksum != m.sum64() {\n\t\treturn ErrChecksum\n\t} else if m.magic != magic {\n\t\treturn ErrInvalid\n\t} else if m.version != version {\n\t\treturn ErrVersionMismatch\n\t}\n\treturn nil\n}\n\n// copy copies one meta object to another.\nfunc (m *meta) copy(dest *meta) {\n\t*dest = *m\n}\n\n// write writes the meta onto a page.\nfunc (m *meta) write(p *page) {\n\n\t_assert(m.root.root < m.pgid, \"root bucket pgid (%d) above high water mark (%d)\", m.root.root, m.pgid)\n\t_assert(m.freelist < m.pgid, \"freelist pgid (%d) above high water mark (%d)\", m.freelist, m.pgid)\n\n\t// Page id is either going to be 0 or 1 which we can determine by the transaction ID.\n\tp.id = pgid(m.txid % 2)\n\tp.flags |= metaPageFlag\n\n\t// Calculate the checksum.\n\tm.checksum = m.sum64()\n\n\tm.copy(p.meta())\n}\n\n// generates the checksum for the meta.\nfunc (m *meta) sum64() uint64 {\n\tvar h = fnv.New64a()\n\t_, _ = h.Write((*[unsafe.Offsetof(meta{}.checksum)]byte)(unsafe.Pointer(m))[:])\n\treturn h.Sum64()\n}\n\n// ErrorList represents a slice of errors.\ntype ErrorList []error\n\n// Error returns a readable count of the errors in the list.\nfunc (l ErrorList) Error() string {\n\treturn fmt.Sprintf(\"%d errors occurred\", len(l))\n}\n\n// join returns a error messages joined by a string.\nfunc (l ErrorList) join(sep string) string {\n\tvar a []string\n\tfor _, e := range l {\n\t\ta = append(a, e.Error())\n\t}\n\treturn strings.Join(a, sep)\n}\n\n// _assert will panic with a given formatted message if the given condition is false.\nfunc _assert(condition bool, msg string, v ...interface{}) {\n\tif !condition {\n\t\tpanic(fmt.Sprintf(\"assertion failed: \"+msg, v...))\n\t}\n}\n\nfunc warn(v ...interface{}) {\n\tfmt.Fprintln(os.Stderr, v...)\n}\n\nfunc warnf(msg string, v ...interface{}) {\n\tfmt.Fprintf(os.Stderr, msg+\"\\n\", v...)\n}\n\"\"\"", "test_func_type": "тестовую функцию", "test_func_context": "\"\"\"\npackage bolt\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"regexp\"\n\t\"testing\"\n\t\"time\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\nvar statsFlag = flag.Bool(\"stats\", false, \"show performance stats\")\nfunc ExampleDB_Update ()\nfunc ExampleDB_View ()\nfunc ExampleDB_Begin_ReadOnly ()\nfunc ExampleDB_CopyFile ()\n// tempfile returns a temporary file path.\nfunc tempfile () string\n// withTempPath executes a function with a database reference.\nfunc withTempPath (fn func(string))\n// withOpenDB executes a function with an already opened database.\nfunc withOpenDB (fn func(*DB, string))\n// mustCheck runs a consistency check on the database and panics if any errors are found.\nfunc mustCheck (db *DB)\nfunc trunc (b []byte, length int) []byte\n// writes the current database stats to the testing log.\nfunc logStats (db *DB)\nfunc truncDuration (d time.Duration) string\n\"\"\"", "language": "go", "focal_file_path": "Godeps/_workspace/src/github.com/boltdb/bolt/db.go", "test_file_path": "Godeps/_workspace/src/github.com/boltdb/bolt/db_test.go", "test_framework": "" }
func TestDB_CopyFile(t *testing.T) { withOpenDB(func(db *DB, path string) { var dest = tempfile() db.Update(func(tx *Tx) error { tx.CreateBucket([]byte("widgets")) tx.Bucket([]byte("widgets")).Put([]byte("foo"), []byte("bar")) tx.Bucket([]byte("widgets")).Put([]byte("baz"), []byte("bat")) return nil }) assert.NoError(t, db.CopyFile(dest, 0600)) db2, err := Open(dest, 0600) assert.NoError(t, err) defer db2.Close() db2.View(func(tx *Tx) error { assert.Equal(t, []byte("bar"), tx.Bucket([]byte("widgets")).Get([]byte("foo"))) assert.Equal(t, []byte("bat"), tx.Bucket([]byte("widgets")).Get([]byte("baz"))) return nil }) }) }
{ "id": 6, "repo_id": "19961069", "focal_func_type": "method" }
Напиши тест для этого кода на языке {language} из файла '{focal_file_path}'. Тебе необходимо написать {test_func_type} на языке {language}. Тест будет помещен в файл '{test_file_path}'. Тебе можно использовать следующие сущности, импортированные или объявленные в тестовом файле: {test_func_context} Обращай внимание на следующий код при написании теста: {focal_func_context} Код для тестирования: {focal_func} Напиши только {test_func_type} без каких-либо пояснений или комментариев. Твой ответ должен быть оформлен с помощью markdown следующим образом: ```{language} <your code> ```
{ "focal_func": "```go\nfunc (s *Session) Model(value interface{}) *Session {\n\t// nil or different model, update refTable\n\tif s.refTable == nil || reflect.TypeOf(value) != reflect.TypeOf(s.refTable.Model) {\n\t\ts.refTable = schema.Parse(value, s.dialect)\n\t}\n\treturn s\n}\n```", "focal_func_context": "```go\n#gem-orm/day3-save-query/session/table.go\npackage session\n\nimport (\n\t\"fmt\"\n\t\"geeorm/log\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"geeorm/schema\"\n)\n\n// Model assigns refTable\n\n#focal function/method here\n\n\n// RefTable returns a Schema instance that contains all parsed fields\nfunc (s *Session) RefTable() *schema.Schema {\n\tif s.refTable == nil {\n\t\tlog.Error(\"Model is not set\")\n\t}\n\treturn s.refTable\n}\n\n// CreateTable create a table in database with a model\nfunc (s *Session) CreateTable() error {\n\ttable := s.RefTable()\n\tvar columns []string\n\tfor _, field := range table.Fields {\n\t\tcolumns = append(columns, fmt.Sprintf(\"%s %s %s\", field.Name, field.Type, field.Tag))\n\t}\n\tdesc := strings.Join(columns, \",\")\n\t_, err := s.Raw(fmt.Sprintf(\"CREATE TABLE %s (%s);\", table.Name, desc)).Exec()\n\treturn err\n}\n\n// DropTable drops a table with the name of model\nfunc (s *Session) DropTable() error {\n\t_, err := s.Raw(fmt.Sprintf(\"DROP TABLE IF EXISTS %s\", s.RefTable().Name)).Exec()\n\treturn err\n}\n\n// HasTable returns true of the table exists\nfunc (s *Session) HasTable() bool {\n\tsql, values := s.dialect.TableExistSQL(s.RefTable().Name)\n\trow := s.Raw(sql, values...).QueryRow()\n\tvar tmp string\n\t_ = row.Scan(&tmp)\n\treturn tmp == s.RefTable().Name\n}\n```", "test_func_type": "тестовую функцию", "test_func_context": "```\npackage session\nimport (\n\t\"testing\"\n)\ntype User struct {\n\tName string `geeorm:\"PRIMARY KEY\"`\n\tAge int\n}\n```", "language": "go", "focal_file_path": "gem-orm/day3-save-query/session/table.go", "test_file_path": "gem-orm/day3-save-query/session/table_test.go", "test_framework": "" }
func TestSession_Model(t *testing.T) { s := NewSession().Model(&User{}) table := s.RefTable() s.Model(&Session{}) if table.Name != "User" || s.RefTable().Name != "Session" { t.Fatal("Failed to change model") } }
{ "id": 7, "repo_id": "312956606", "focal_func_type": "method" }
Вы — специалист по unit-тестам. Вам нужно реализовать {test_func_type} на языке {language} для кода ниже: Тестируется код из '{focal_file_path}': {focal_func} Вы можете использовать только эти сущности, уже определённые в тестовом файле ('{test_file_path}'): {test_func_context} Также вам доступен контекст функции: {focal_func_context} Требование: предоставить только {test_func_type}, не включать комментарии, объяснения или формат личного обращения. Не разъясняйте свой выбор. Ваше решение должно быть оформлено с помощью markdown по шаблону: ```{language} <your code> ```
{ "focal_func": "```java\npublic void execute(String filterType,\n Boolean deleteBody,\n Boolean deleteUri,\n Boolean headers,\n List<String> ignoredHeaders) {\n\n RequestResponseParser requestResponseParser = null;\n\n switch (filterType) {\n case PRE_TYPE:\n requestResponseParser = TraceContextHolder.getInstance().getActualTrace().getRequest();\n break;\n\n case POST_TYPE:\n requestResponseParser = TraceContextHolder.getInstance().getActualTrace().getResponse();\n break;\n\n default:\n break;\n }\n\n if (requestResponseParser != null) {\n\n // Should delete body\n if (deleteBody) requestResponseParser.setBody(null);\n\n // Should delete URI\n if (deleteUri) requestResponseParser.setUri(null);\n\n // Should delete headers\n if (headers) {\n if (ignoredHeaders.isEmpty()) {\n requestResponseParser.setHeaders(null);\n } else {\n final Map<String, String> requestResponseHeaders = requestResponseParser.getHeaders();\n ignoredHeaders.forEach(requestResponseHeaders::remove);\n }\n }\n }\n }\n```", "focal_func_context": "```java\n#heimdall-gateway/src/main/java/br/com/conductor/heimdall/gateway/service/LogMaskerService.java\n/*-\n * =========================LICENSE_START==================================\n * heimdall-gateway\n * ========================================================================\n * Copyright (C) 2018 Conductor Tecnologia SA\n * ========================================================================\n * Licensed under the Apache License, Version 2.0 (the \"License\")\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ==========================LICENSE_END===================================\n */\npackage br.com.conductor.heimdall.gateway.service;\n\nimport br.com.conductor.heimdall.core.trace.RequestResponseParser;\nimport br.com.conductor.heimdall.core.trace.TraceContextHolder;\nimport org.springframework.stereotype.Service;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.POST_TYPE;\nimport static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;\n\n/**\n * Log Mask Service provides a method to mask the information from the {@link br.com.conductor.heimdall.core.trace.Trace}.\n *\n * @author Marcelo Aguiar Rodrigues\n */\n@Service\npublic class LogMaskerService {\n\n /**\n * Given the filter type it removes the information passed from the {@link br.com.conductor.heimdall.core.trace.Trace}.\n *\n * @param filterType {@link org.springframework.cloud.netflix.zuul.filters.support.FilterConstants}\n * @param deleteBody should delete the request body\n * @param deleteUri should delete the request uri\n * @param headers should delete the request headers\n * @param ignoredHeaders headers that should be deleted, if empty all will be deleted\n */\n\n#focal function/method here\n\n}\n```", "test_func_type": "тестовый метод", "test_func_context": "```\nimport br.com.conductor.heimdall.core.trace.RequestResponseParser;\nimport br.com.conductor.heimdall.core.trace.TraceContextHolder;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.InjectMocks;\nimport org.mockito.MockitoAnnotations;\nimport org.mockito.runners.MockitoJUnitRunner;\nimport org.springframework.mock.web.MockHttpServletRequest;\nimport java.util.*;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertNull;\nimport static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.POST_TYPE;\nimport static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;\n// Class signature\nLogMaskerServiceTest\n// Class fields\n @InjectMocks\n private LogMaskerService logMaskerService;\n// Class methods\n @Before\n public void setUp() {\n MockitoAnnotations.initMocks(this);\n TraceContextHolder.getInstance().init(true, \"developer\", new MockHttpServletRequest(), false, false, \"\", true);\n\n Map<String, String> headers = new HashMap<>();\n headers.put(\"connection\", \"Keep-alive\");\n headers.put(\"host\", \"http://another-host.com\");\n headers.put(\"Content-Type\", \"application/json;utf-8\");\n headers.put(\"simpleHeader\", \"someInformation\");\n\n String body = \"{\\\"body\\\":\\\"this is a simple body\\\"}\";\n String uri = \"http://simpleUri.com\";\n\n RequestResponseParser request = new RequestResponseParser();\n RequestResponseParser response = new RequestResponseParser();\n\n request.setHeaders(headers);\n request.setUri(uri);\n request.setBody(body);\n\n response.setHeaders(headers);\n response.setUri(uri);\n response.setBody(body);\n\n TraceContextHolder.getInstance().getActualTrace().setRequest(request);\n TraceContextHolder.getInstance().getActualTrace().setResponse(response);\n }\n @After\n public void after() {\n TraceContextHolder.getInstance().unset();\n }\n```", "language": "java", "focal_file_path": "heimdall-gateway/src/main/java/br/com/conductor/heimdall/gateway/service/LogMaskerService.java", "test_file_path": "heimdall-gateway/src/test/java/br/com/conductor/heimdall/gateway/service/LogMaskerServiceTest.java", "test_framework": "" }
@Test public void requestDeleteAllHeaders() { logMaskerService.execute(PRE_TYPE, false, false, true, new ArrayList<>()); RequestResponseParser request = TraceContextHolder.getInstance().getActualTrace().getRequest(); assertNotNull(request.getBody()); assertNotNull(request.getUri()); assertNull(request.getHeaders()); }
{ "id": 8, "repo_id": "132375056", "focal_func_type": "method" }
Ваша задача — написать {test_func_type} на языке {language} для кода из файла'{focal_file_path}'. К тестированию предоставлен следующий фрагмент кода: {focal_func} Дополнительный контекст исходного файла: {focal_func_context} Также вот что уже объявлено или импортировано для вас в будущем тестовом файле'{test_file_path}': {test_func_context} В ответе предоставляйте исключительно {test_func_type}, никаких комментариев. Ваш ответ должен быть оформлен с помощью markdown следующим образом: ```{language} <your code> ```
{ "focal_func": "```java\n@Nullable\n public static Object fromValue(ValueOrBuilder value) {\n switch (value.getKindCase()) {\n case NULL_VALUE:\n return null;\n case BOOL_VALUE:\n return value.getBoolValue();\n case STRING_VALUE:\n return value.getStringValue();\n case NUMBER_VALUE: {\n double v = value.getNumberValue();\n if (v >= Long.MIN_VALUE && v <= Long.MAX_VALUE && DoubleMath.isMathematicalInteger(v)) {\n if (v >= Integer.MIN_VALUE && v <= Integer.MAX_VALUE) {\n return (int) v;\n } else {\n return (long) v;\n }\n } else {\n return v;\n }\n }\n case LIST_VALUE:\n return asList(value.getListValue());\n case STRUCT_VALUE:\n return MoreStructs.asMap(value.getStructValue());\n default:\n throw new AssertionError(\"Unsupported value: \" + value);\n }\n }\n```", "focal_func_context": "```java\n#mug-protobuf/src/main/java/com/google/mu/protobuf/util/MoreValues.java\n/*****************************************************************************\n * ------------------------------------------------------------------------- *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); *\n * you may not use this file except in compliance with the License. *\n * You may obtain a copy of the License at *\n * *\n * http://www.apache.org/licenses/LICENSE-2.0 *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n *****************************************************************************/\npackage com.google.mu.protobuf.util;\n\nimport static java.util.Arrays.stream;\n\nimport java.util.List;\nimport java.util.stream.Collector;\n\nimport org.checkerframework.checker.nullness.qual.Nullable;\n\nimport com.google.common.collect.Lists;\nimport com.google.common.math.DoubleMath;\nimport com.google.errorprone.annotations.CheckReturnValue;\nimport com.google.mu.annotations.RequiresProtobuf;\nimport com.google.protobuf.ListValue;\nimport com.google.protobuf.ListValueOrBuilder;\nimport com.google.protobuf.NullValue;\nimport com.google.protobuf.Struct;\nimport com.google.protobuf.Value;\nimport com.google.protobuf.ValueOrBuilder;\n\n/**\n * Additional utilities to help create {@link Value} and {@link ListValue} messages.\n *\n * @since 5.8\n */\n@CheckReturnValue\n@RequiresProtobuf\npublic final class MoreValues {\n /** The {@link Value} for null. */\n public static final Value NULL =\n Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build();\n\n /** The {@link Value} for boolean {@code true}. */\n public static final Value TRUE = Value.newBuilder().setBoolValue(true).build();\n\n /** The {@link Value} for boolean {@code false}. */\n public static final Value FALSE = Value.newBuilder().setBoolValue(false).build();\n\n /** Returns {@link Value} wrapper for {@code string} if not null, or else returns {@link #NULL}. */\n public static Value nullableValueOf(@Nullable String string) {\n return string == null ? NULL : valueOf(string);\n }\n\n /** Returns {@link ListValue} wrapping {@code values}. */\n public static ListValue listValueOf(double... values) {\n return stream(values).mapToObj(MoreValues::valueOf).collect(toListValue());\n }\n\n /**\n * Returns {@link ListValue} wrapping {@code values}.\n * Null strings are converted to {@link NULL}.\n */\n public static ListValue listValueOf(@Nullable String... values) {\n return stream(values).map(MoreValues::nullableValueOf).collect(toListValue());\n }\n\n /**\n * Returns {@link ListValue} wrapping {@code values}.\n * Null structs are converted to {@link NULL}.\n */\n public static ListValue listValueOf(@Nullable Struct... values) {\n return stream(values).map(MoreValues::nullableValueOf).collect(toListValue());\n }\n\n /** Returns a {@link Collector} that collects the input values into {@link ListValue}. */\n public static Collector<Value, ?, ListValue> toListValue() {\n return Collector.of(\n ListValue::newBuilder,\n ListValue.Builder::addValues,\n (a, b) -> a.addAllValues(b.getValuesList()),\n ListValue.Builder::build);\n }\n\n /**\n * Unwraps {@code value}.\n *\n * <p>For example, {@code Values.of(1)} is unwrapped to {@code 1}; {@link ListValue} is\n * unwrapped as {@code List<Object>}; {@link Struct} is unwrapped as {@code Map<String, Object>};\n * and {@link NullValue} is unwrapped as {@code null}, etc.\n *\n * <p>Note that integral numbers in the range of {@code int} will be unwrapped as {@code Integer};\n * while integral numbers otherwise in the range of {@code long} will be unwrapped as {@code Long}.\n * All other numbers are unwrapped as {@code Double}. If you need to handle all number cases\n * unconditionally, consider to use {@link Number#doubleValue}.\n *\n * <p>The returned object is immutable. Even if {@code value} is an instance of {@link\n * Value.Builder}, and the underlying state is changed after this method returns,\n * the returned object remains unchanged.\n *\n * @see MoreStructs#asMap\n * @see #asList\n * @since 5.9\n */\n\n#focal function/method here\n\n\n /**\n * Returns a {@code List<Object>} <em>view</em> over {@code listValue}.\n *\n * <p>For example, {@code Values.of(1)} is unwrapped to {@code 1L};\n * {@link Struct} is unwrapped as {@code Map<String, Object>};\n * and {@link NullValue} is unwrapped as {@code null}, etc.\n *\n * @see MoreStructs#asMap\n * @see #fromValue\n * @since 5.9\n */\n public static List<Object> asList(ListValueOrBuilder listValue) {\n return Lists.transform(listValue.getValuesList(), MoreValues::fromValue);\n }\n\n static Value valueOf(double n) {\n return Value.newBuilder().setNumberValue(n).build();\n }\n\n static Value valueOf(boolean b) {\n return b ? TRUE : FALSE;\n }\n\n static Value valueOf(String s) {\n return Value.newBuilder().setStringValue(s).build();\n }\n\n static Value valueOf(Struct v) {\n return Value.newBuilder().setStructValue(v).build();\n }\n\n static Value valueOf(ListValue v) {\n return Value.newBuilder().setListValue(v).build();\n }\n\n /** Returns {@link Value} wrapper for {@code struct} if not null, or else returns {@link #NULL}. */\n private static Value nullableValueOf(@Nullable Struct struct) {\n return struct == null ? NULL : valueOf(struct);\n }\n\n private MoreValues() {}\n}\n```", "test_func_type": "тестовый метод", "test_func_context": "```\nimport static com.google.common.truth.Truth.assertThat;\nimport static com.google.mu.collect.Immutables.list;\nimport static com.google.mu.collect.Immutables.map;\nimport static com.google.mu.protobuf.util.MoreStructs.struct;\nimport static com.google.mu.protobuf.util.MoreValues.FALSE;\nimport static com.google.mu.protobuf.util.MoreValues.NULL;\nimport static com.google.mu.protobuf.util.MoreValues.TRUE;\nimport static com.google.mu.protobuf.util.MoreValues.listValueOf;\nimport static com.google.mu.protobuf.util.MoreValues.toListValue;\nimport static org.junit.Assert.assertThrows;\nimport java.util.List;\nimport java.util.stream.Stream;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.JUnit4;\nimport com.google.common.testing.NullPointerTester;\nimport com.google.protobuf.ListValue;\nimport com.google.protobuf.Value;\nimport com.google.protobuf.util.Structs;\nimport com.google.protobuf.util.Values;\n// Class signature\nMoreValuesTest\n```", "language": "java", "focal_file_path": "mug-protobuf/src/main/java/com/google/mu/protobuf/util/MoreValues.java", "test_file_path": "mug-protobuf/src/test/java/com/google/mu/protobuf/util/MoreValuesTest.java", "test_framework": "" }
@Test public void testFromValue_double_maxValue() { assertThat(Values.of(Double.MAX_VALUE).getNumberValue()).isEqualTo(Double.MAX_VALUE); assertThat(MoreValues.fromValue(Values.of(Double.MAX_VALUE))).isInstanceOf(Double.class); assertThat(MoreValues.fromValue(Values.of(Double.MAX_VALUE))).isEqualTo(Double.MAX_VALUE); assertThat(MoreValues.fromValue(Values.of(Double.MAX_VALUE / 2))).isEqualTo(Double.MAX_VALUE / 2); assertThat(MoreValues.fromValue(Values.of(((double) Long.MAX_VALUE) * 2))) .isEqualTo(((double) Long.MAX_VALUE) * 2); }
{ "id": 9, "repo_id": "81968413", "focal_func_type": "method" }