Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TestUtils.cs « UnitTest « Duplicati - github.com/duplicati/duplicati.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 36d7beaf1d3e655a36a490b1eb4a77fcc5a8c93c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
//  Copyright (C) 2015, The Duplicati Team
//  http://www.duplicati.com, info@duplicati.com
//
//  This library is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as
//  published by the Free Software Foundation; either version 2.1 of the
//  License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful, but
//  WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.IO;
using System.Collections.Generic;
using Duplicati.Library.Utility;
using System.Linq;
using Duplicati.Library.Logging;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Duplicati.Library.Common.IO;
using NUnit.Framework;

namespace Duplicati.UnitTest
{
    public static class TestUtils
    {
        /// <summary>
        /// The log tag
        /// </summary>
        private static readonly string LOGTAG = Library.Logging.Log.LogTagFromType(typeof(TestUtils));

        public static Dictionary<string, string> DefaultOptions
        {
            get
            {
                var opts = new Dictionary<string, string>();

                string auth_password = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "unittest_authpassword.txt");
                if (System.IO.File.Exists(auth_password))
                    opts["auth-password"] = File.ReadAllText(auth_password).Trim();
                
                return opts;
            }
        }

        public static async Task GrowingFile(string testFile, CancellationToken token)
        {
            try
            {
                var str = new string('*', 50);
                while (true)
                {
                    if (token.IsCancellationRequested)
                    {
                        continue;
                    }
                    File.AppendAllText(testFile, str);
                    await Task.Delay(18, token).ConfigureAwait(false);
                }
            }
            finally
            {
                if (File.Exists(testFile))
                {
                    File.Delete(testFile);
                }
            }
        }

        public static string GetDefaultTarget(string other = null)
        {
            string alttarget = System.IO.Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "unittest_target.txt");

            if (File.Exists(alttarget))
                return File.ReadAllText(alttarget).Trim();
            else if (other != null)
                return other;
            else
                using(var tf = new Library.Utility.TempFolder())
                {
                    tf.Protected = true;
                    return "file://" + tf;
                }
        }

        /// <summary>
        /// Recursively copy a directory to another location.
        /// </summary>
        /// <param name="sourcefolder">Source directory path</param>
        /// <param name="targetfolder">Destination directory path</param>
        public static void CopyDirectoryRecursive(string sourcefolder, string targetfolder)
        {
            sourcefolder = Util.AppendDirSeparator(sourcefolder);

            var work = new Queue<string>();
            work.Enqueue(sourcefolder);

            var timestampfailures = 0;

            while (work.Count > 0)
            {
                var c = work.Dequeue();

                var t = Path.Combine(targetfolder, c.Substring(sourcefolder.Length));

                if (!Directory.Exists(t))
                    Directory.CreateDirectory(t);
                
                try { Directory.SetCreationTimeUtc(t, Directory.GetCreationTimeUtc(c)); }
                catch(Exception ex) 
                { 
                    if (timestampfailures++ < 20)
                        Console.WriteLine("Failed to set creation time on dir {0}: {1}", t, ex.Message); 
                }

                try { Directory.SetLastWriteTimeUtc(t, Directory.GetLastWriteTimeUtc(c)); }
                catch(Exception ex) 
                { 
                    if (timestampfailures++ < 20)
                        Console.WriteLine("Failed to set write time on dir {0}: {1}", t, ex.Message); 
                }

                
                foreach(var n in Directory.EnumerateFiles(c))
                {
                    var tf = Path.Combine(t, Path.GetFileName(n));
                    File.Copy(n, tf, true);
                    try { File.SetCreationTimeUtc(tf, System.IO.File.GetCreationTimeUtc(n)); }
                    catch(Exception ex)
                    {
                        if (timestampfailures++ < 20)
                            Console.WriteLine("Failed to set creation time on file {0}: {1}", n, ex.Message); 
                    }
                    try { File.SetLastWriteTimeUtc(tf, System.IO.File.GetLastWriteTimeUtc(n)); }
                    catch(Exception ex)
                    {
                        if (timestampfailures++ < 20)
                            Console.WriteLine("Failed to set write time on file {0}: {1}", n, ex.Message); 
                    }
                }

                foreach(var n in Directory.EnumerateDirectories(c))
                    work.Enqueue(n);
            }

            if (timestampfailures > 20)
                Console.WriteLine("Encountered additional {0} timestamp errors!", timestampfailures);
        }

        /// <summary>
        /// Returns the index of a given string, using the file system case sensitivity
        /// </summary>
        /// <returns>The index of the entry or -1 if no entry was found</returns>
        /// <param name='lst'>The list to search</param>
        /// <param name='m'>The string to find</param>
        private static int IndexOf(List<string> lst, string m)
        {
            StringComparison sc = Duplicati.Library.Utility.Utility.ClientFilenameStringComparison;
            for(int i = 0; i < lst.Count; i++)
                if (lst[i].Equals(m, sc))
                    return i;

            return -1;
        }

        /// <summary>
        /// Asserts that the two directory trees are equivalent; i.e.,
        /// that they they contain the same directories and files, recursively.
        /// </summary>
        /// <param name="expectedDir">The expected directory tree.</param>
        /// <param name="actualDir">The actual directory tree.</param>
        /// <param name="verifymetadata">True to also compare file metadata.</param>
        /// <param name="contextMessage">Context information to include in an assert message.</param>
        public static void AssertDirectoryTreesAreEquivalent(string expectedDir, string actualDir, bool verifymetadata, string contextMessage)
        {
            var localMessage = $"{contextMessage}, in directories {expectedDir} and {actualDir}";
            // Assert that expectedDir and actualDir contain the same directories
            var expectedSubdirs = SystemIO.IO_OS.EnumerateDirectories(expectedDir).OrderBy(SystemIO.IO_OS.PathGetFileName);
            var actualSubdirs = SystemIO.IO_OS.EnumerateDirectories(actualDir).OrderBy(SystemIO.IO_OS.PathGetFileName);
            Assert.That(expectedSubdirs.Select(SystemIO.IO_OS.PathGetFileName), Is.EquivalentTo(actualSubdirs.Select(SystemIO.IO_OS.PathGetFileName)), localMessage);
            // Recursively compare the contained directories
            var expectedSubdirsEnumerator = expectedSubdirs.GetEnumerator();
            var actualSubdirsEnumerator = actualSubdirs.GetEnumerator();
            while (expectedSubdirsEnumerator.MoveNext() && actualSubdirsEnumerator.MoveNext())
            {
                AssertDirectoryTreesAreEquivalent(expectedSubdirsEnumerator.Current, actualSubdirsEnumerator.Current, verifymetadata, contextMessage);
            }
            // Assert that expectedDir and actualDir contain the same files
            var expectedFiles = SystemIO.IO_OS.EnumerateFiles(expectedDir).OrderBy(SystemIO.IO_OS.PathGetFileName);
            var actualFiles = SystemIO.IO_OS.EnumerateFiles(actualDir).OrderBy(SystemIO.IO_OS.PathGetFileName);
            Assert.That(expectedFiles.Select(SystemIO.IO_OS.PathGetFileName), Is.EquivalentTo(actualFiles.Select(SystemIO.IO_OS.PathGetFileName)), localMessage);
            // Assert that the files are equal
            var expectedFilesEnumerator = expectedFiles.GetEnumerator();
            var actualFilesEnumerator = actualFiles.GetEnumerator();
            while (expectedFilesEnumerator.MoveNext() && actualFilesEnumerator.MoveNext())
            {
                AssertFilesAreEqual(expectedFilesEnumerator.Current, actualFilesEnumerator.Current, verifymetadata, contextMessage);
            }
        }

        /// <summary>
        /// Asserts that two files are equal by comparing their length, contents, and, optionally, their metadata.
        /// </summary>
        /// <param name="expectedFile">The expected file.</param>
        /// <param name="actualFile">The actual file.</param>
        /// <param name="verifymetadata">True to also compare file metadata.</param>
        /// <param name="contextMessage">Context information to include in an assert message.</param>
        public static void AssertFilesAreEqual(string expectedFile, string actualFile, bool verifymetadata, string contextMessage)
        {
            using (var expectedFileStream = SystemIO.IO_OS.FileOpenRead(expectedFile))
            using (var actualFileStream = SystemIO.IO_OS.FileOpenRead(actualFile))
            {
                // Compare file lengths
                var expectedFileStreamLength = expectedFileStream.Length;
                var actualFileStreamLength = actualFileStream.Length;
                Assert.That(actualFileStreamLength, Is.EqualTo(expectedFileStreamLength), $"{contextMessage}, file size mismatch for {expectedFile} and {actualFile}");
                // Compare file contents
                // The byte-by-byte compare is dog-slow, so we use a fast(-er) check, and then report the first byte diff if required
                if (!Utility.CompareStreams(expectedFileStream, actualFileStream, true))
                {
                    // Reset stream positions
                    expectedFileStream.Position = 0;
                    actualFileStream.Position = 0;
                    for (long i = 0; i < expectedFileStreamLength; i++)
                    {
                        var expectedByte = expectedFileStream.ReadByte();
                        var actualByte = actualFileStream.ReadByte();
                        // For performance reasons, only exercise Assert mechanism and generate message if byte comparison fails
                        if (expectedByte != actualByte)
                        {
                            var message = $"{contextMessage}, file contents mismatch at position {i} for {expectedFile} and {actualFile}";
                            Assert.That(actualByte, Is.EqualTo(expectedByte), message);
                        }
                    }
                }
            }
            // Compare file metadata
            if (verifymetadata)
            {
                Assert.That(
                    SystemIO.IO_OS.GetLastWriteTimeUtc(actualFile),
                    Is.EqualTo(SystemIO.IO_OS.GetLastWriteTimeUtc(expectedFile)).Within(1).Milliseconds,
                    $"{contextMessage}, last write time mismatch for {expectedFile} and {actualFile}");
                Assert.That(
                    SystemIO.IO_OS.GetCreationTimeUtc(actualFile),
                    Is.EqualTo(SystemIO.IO_OS.GetCreationTimeUtc(expectedFile)).Within(1).Milliseconds,
                    $"{contextMessage}, creation time mismatch for {expectedFile} and {actualFile}");
            }
        }

        public static Dictionary<string, string> Expand(this Dictionary<string, string> self, object extra)
        {
            var res = new Dictionary<string, string>(self);
            foreach(var n in extra.GetType().GetFields())
            {
                var name = n.Name.Replace('_', '-');
                var value = n.GetValue(extra);
                res[name] = value == null ? "" : value.ToString();
            }

            foreach(var n in extra.GetType().GetProperties())
            {
                var name = n.Name.Replace('_', '-');
                var value = n.GetValue(extra);
                res[name] = value == null ? "" : value.ToString();
            }

            return res;
        }

        /// <summary>
        /// Write file <paramref name="path"/> with <paramref name="contents"/>.
        /// </summary>
        public static void WriteFile(string path, byte[] contents)
        {
            using (FileStream fileStream = SystemIO.IO_OS.FileOpenWrite(path))
            {
                Utility.CopyStream(new MemoryStream(contents), fileStream);
            }
        }
    }
}