//
// Copyright (c) James Jackson-South and contributors.
// Licensed under the Apache License, Version 2.0.
//
namespace ImageSharp.Tests
{
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using ImageSharp.Formats;
///
/// Utility class to provide information about the test image & the test case for the test code,
/// and help managing IO.
///
public class ImagingTestCaseUtility : TestBase
{
///
/// Name of the TColor in the owner
///
public string PixelTypeName { get; set; } = string.Empty;
///
/// The name of the file which is provided by
/// Or a short string describing the image in the case of a non-file based image provider.
///
public string SourceFileOrDescription { get; set; } = string.Empty;
///
/// By default this is the name of the test class, but it's possible to change it
///
public string TestGroupName { get; set; } = string.Empty;
///
/// The name of the test case (by default)
///
public string TestName { get; set; } = string.Empty;
///
/// Gets the recommended file name for the output of the test
///
///
/// The required extension
public string GetTestOutputFileName(string extension = null)
{
string fn = string.Empty;
fn = Path.GetFileNameWithoutExtension(this.SourceFileOrDescription);
extension = extension ?? Path.GetExtension(this.SourceFileOrDescription);
extension = extension ?? ".bmp";
if (extension[0] != '.')
{
extension = '.' + extension;
}
if (fn != string.Empty) fn = '_' + fn;
string pixName = this.PixelTypeName;
if (pixName != string.Empty)
{
pixName = '_' + pixName;
}
return $"{this.GetTestOutputDir()}/{this.TestName}{pixName}{fn}{extension}";
}
///
/// Encodes image by the format matching the required extension, than saves it to the recommended output file.
///
/// The pixel format of the image
/// The image instance
/// The requested extension
/// Optional encoder
public void SaveTestOutputFile(Image image, string extension = null, IImageEncoder encoder = null)
where TColor : struct, IPackedPixel, IEquatable
{
string path = this.GetTestOutputFileName(extension);
var format = GetImageFormatByExtension(extension);
encoder = encoder ?? format.Encoder;
using (var stream = File.OpenWrite(path))
{
image.Save(stream, encoder);
}
}
internal void Init(MethodInfo method)
{
this.TestGroupName = method.DeclaringType.Name;
this.TestName = method.Name;
}
private static IImageFormat GetImageFormatByExtension(string extension)
{
extension = extension.ToLower();
return Configuration.Default.ImageFormats.First(f => f.SupportedExtensions.Contains(extension));
}
private string GetTestOutputDir()
{
string testGroupName = Path.GetFileNameWithoutExtension(this.TestGroupName);
return CreateOutputDirectory(testGroupName);
}
}
}