|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the MIT License. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using System.Diagnostics; |
| 5 | +using System.IO; |
| 6 | +using System.Linq; |
| 7 | +using System.Threading; |
| 8 | +using System.Threading.Tasks; |
| 9 | +using Microsoft.Azure.WebJobs.Script; |
| 10 | +using Xunit; |
| 11 | + |
| 12 | +namespace WebJobs.Script.Tests |
| 13 | +{ |
| 14 | + public class FileTraceWriterTests |
| 15 | + { |
| 16 | + private string _logFilePath; |
| 17 | + |
| 18 | + public FileTraceWriterTests() |
| 19 | + { |
| 20 | + _logFilePath = Path.Combine(Path.GetTempPath(), "WebJobs.Script.Tests", "FileTraceWriterTests"); |
| 21 | + |
| 22 | + if (Directory.Exists(_logFilePath)) |
| 23 | + { |
| 24 | + Directory.Delete(_logFilePath, recursive: true); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + [Fact] |
| 29 | + public async Task MultipleConcurrentInstances_WritesAreSerialized() |
| 30 | + { |
| 31 | + int numLines = 100; |
| 32 | + |
| 33 | + // first ensure the file exists by writing a single entry |
| 34 | + // this ensures all the instances below will be operating on |
| 35 | + // the same file |
| 36 | + WriteLogs(_logFilePath, 1); |
| 37 | + |
| 38 | + // start 3 concurrent instances |
| 39 | + await Task.WhenAll( |
| 40 | + Task.Run(() => WriteLogs(_logFilePath, numLines)), |
| 41 | + Task.Run(() => WriteLogs(_logFilePath, numLines)), |
| 42 | + Task.Run(() => WriteLogs(_logFilePath, numLines)) |
| 43 | + ); |
| 44 | + |
| 45 | + string logFile = Directory.EnumerateFiles(_logFilePath).Single(); |
| 46 | + string[] fileLines = File.ReadAllLines(logFile); |
| 47 | + Assert.Equal(3 * numLines + 1, fileLines.Length); |
| 48 | + } |
| 49 | + |
| 50 | + private void WriteLogs(string logFilePath, int numLogs) |
| 51 | + { |
| 52 | + FileTraceWriter traceWriter = new FileTraceWriter(logFilePath, TraceLevel.Verbose); |
| 53 | + |
| 54 | + for (int i = 0; i < numLogs; i++) |
| 55 | + { |
| 56 | + traceWriter.Verbose(string.Format("Test message {0} {1}", Thread.CurrentThread.ManagedThreadId, i)); |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments