Skip to content

Commit

Permalink
Add some tests for Bot
Browse files Browse the repository at this point in the history
  • Loading branch information
ktos committed Oct 27, 2019
1 parent 010f956 commit b847b71
Show file tree
Hide file tree
Showing 4 changed files with 208 additions and 13 deletions.
26 changes: 13 additions & 13 deletions src/Bot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,11 @@ public class Bot
private readonly PostAnalyzer postAnalyzer;
private readonly Blacklist blacklist;
private readonly ILogger logger;
private HashSet<int> analyzed;

/// <summary>
/// Database with already analyzed post ids
/// </summary>
public HashSet<int> AlreadyAnalyzedDatabase { get; set; }

/// <summary>
/// Gets or sets if the database of already analyzed posts should be used
Expand Down Expand Up @@ -103,27 +107,27 @@ public void LoadAlreadyAnalyzed()
{
if (IgnoreAlreadyAnalyzed)
{
analyzed = new HashSet<int>();
AlreadyAnalyzedDatabase = new HashSet<int>();
return;
}

if (!File.Exists(AnalyzedDatabasePath))
{
analyzed = new HashSet<int>();
AlreadyAnalyzedDatabase = new HashSet<int>();
}
else
{
logger.LogDebug("Loading already analyzed posts database.");
using var fs = new FileStream(AnalyzedDatabasePath, FileMode.Open, FileAccess.Read);
if (fs.Length == 0)
{
analyzed = new HashSet<int>();
AlreadyAnalyzedDatabase = new HashSet<int>();
return;
}
else
{
var formatter = new BinaryFormatter();
analyzed = formatter.Deserialize(fs) as HashSet<int>;
AlreadyAnalyzedDatabase = formatter.Deserialize(fs) as HashSet<int>;
}
}
}
Expand All @@ -139,7 +143,7 @@ public void SaveAlreadyAnalyzed()
using var fs = new FileStream(AnalyzedDatabasePath, FileMode.Create, FileAccess.Write);
logger.LogDebug("Saving already analyzed ids database.");
var formatter = new BinaryFormatter();
formatter.Serialize(fs, analyzed);
formatter.Serialize(fs, AlreadyAnalyzedDatabase);
}

/// <summary>
Expand All @@ -160,13 +164,13 @@ public async Task AnalyzePostsByIdsAsync(int[] postIds)
/// <param name="post">Post to be analyzed</param>
public async Task AnalyzePostAsync(Post post)
{
if (analyzed.Contains(post.id))
if (AlreadyAnalyzedDatabase.Contains(post.id))
{
logger.LogDebug("Ignoring post {0} because already analyzed", post.id);
return;
}

analyzed.Add(post.id);
AlreadyAnalyzedDatabase.Add(post.id);
SaveAlreadyAnalyzed();

if (IgnorePost(post))
Expand Down Expand Up @@ -206,16 +210,12 @@ public async Task LoginAsync(string username, string password)

private bool IgnorePost(Post post)
{
if (blacklist == null)
return false;
else
return blacklist.IsDisallowed(post);
return blacklist.IsDisallowed(post);
}

/// <summary>
/// Get new posts from the last first page of posts set and analyze them
/// </summary>
/// <returns></returns>
public async Task AnalyzeNewPostsAsync()
{
logger.LogDebug("Getting posts...");
Expand Down
131 changes: 131 additions & 0 deletions test/BotTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
using Eleia;
using Eleia.CoyoteApi;
using Eleia.Test.Helpers;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;

namespace Eleia.Test
{
public class BotTests
{
private FakeLoggerFactory fakeLoggerFactory;

private Bot CreateBot()
{
fakeLoggerFactory = new FakeLoggerFactory();
return new Bot(new CoyoteHandler(fakeLoggerFactory), new PostAnalyzer(null), new Blacklist(), fakeLoggerFactory);
}

private List<string> GetFakeLogs()
{
return (fakeLoggerFactory.CreateLogger("") as FakeLogger).Logs;
}

[Fact]
public void LoadAlreadyAnalyzed_WhenIgnoreAlreadyAnalyzed_ShouldBeEmpty()
{
var bot = CreateBot();
bot.IgnoreAlreadyAnalyzed = true;

bot.LoadAlreadyAnalyzed();

Assert.Empty(bot.AlreadyAnalyzedDatabase);
}

[Fact]
public void SaveAlreadyAnalyzed_WhenIgnoreAlreadyAnalyzed_ShouldDoNothing()
{
var bot = CreateBot();
bot.IgnoreAlreadyAnalyzed = true;

bot.SaveAlreadyAnalyzed();

var logs = GetFakeLogs();

Assert.DoesNotContain(logs, x => x == "Saving already analyzed ids database.");
}

[Fact]
public void BlacklistUpdateDefinition_ShouldUpdateDefinition()
{
var bot = CreateBot();
bot.IgnoreAlreadyAnalyzed = true;

var old = bot.BlacklistDefinition;
bot.BlacklistDefinition = "1,2,3,4";

Assert.NotEqual(bot.BlacklistDefinition, old);
Assert.Equal("1,2,3,4", bot.BlacklistDefinition);
}

[Fact]
public async void AnalyzePostAsync_Post_ShouldUpdateAlreadyAnalyzed()
{
var bot = CreateBot();
bot.IgnoreAlreadyAnalyzed = true;
bot.LoadAlreadyAnalyzed();

await bot.AnalyzePostAsync(new Post() { id = 1, text = "" });

Assert.Single(bot.AlreadyAnalyzedDatabase);
Assert.Equal(1, bot.AlreadyAnalyzedDatabase.First());
}

[Fact]
public async void AnalyzePostAsync_SamePostIdTestedForSecondTime_ShouldBeIgnored()
{
var bot = CreateBot();
bot.IgnoreAlreadyAnalyzed = true;
bot.LoadAlreadyAnalyzed();

await bot.AnalyzePostAsync(new Post() { id = 1, text = "one text" });
await bot.AnalyzePostAsync(new Post() { id = 1, text = "different text" });

var logs = GetFakeLogs();

Assert.Contains(logs, x => x == "[Debug] Ignoring post 1 because already analyzed");
}

[Fact]
public async void AnalyzePostAsync_PostFromBlacklist_ShouldBeIgnored()
{
var bot = CreateBot();
bot.IgnoreAlreadyAnalyzed = true;
bot.LoadAlreadyAnalyzed();
bot.BlacklistDefinition = "1";

await bot.AnalyzePostAsync(new Post() { id = 1, text = "", forum_id = 1 });
var logs = GetFakeLogs();

Assert.Equal("[Debug] Ignoring post 1 because of blacklist", logs.Last());
}

[Fact]
public void Endpoints_WhenNotDebug_ShouldBeBasedOn4pnet()
{
Endpoints.IsDebug = false;

Assert.Contains("4programmers.net", Endpoints.CommentPage);
Assert.Contains("4programmers.net", Endpoints.LoginPage);
Assert.Contains("4programmers.net", Endpoints.MainPage);
Assert.Contains("4programmers.net", Endpoints.LogoutPage);
Assert.Contains("4programmers.net", Endpoints.PostsApi);
}

[Fact]
public void Endpoints_WhenDebug_ShouldBeBasedOn4pinfo()
{
Endpoints.IsDebug = true;

Assert.Contains("dev.4programmers.info", Endpoints.CommentPage);
Assert.Contains("dev.4programmers.info", Endpoints.LoginPage);
Assert.Contains("dev.4programmers.info", Endpoints.MainPage);
Assert.Contains("dev.4programmers.info", Endpoints.LogoutPage);
Assert.Contains("dev.4programmers.info", Endpoints.PostsApi);
}
}
}
56 changes: 56 additions & 0 deletions test/Helpers/FakeLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

namespace Eleia.Test.Helpers
{
public sealed class FakeLoggerFactory : ILoggerFactory, IDisposable
{
private static FakeLogger instance;

public void AddProvider(ILoggerProvider provider)
{
throw new NotImplementedException();
}

public ILogger CreateLogger(string categoryName)
{
if (instance == null)
{
instance = new FakeLogger();
}

return instance;
}

public void Dispose()
{
}
}

public class FakeLogger : ILogger
{
public List<string> Logs { get; }

public FakeLogger()
{
Logs = new List<string>();
}

public IDisposable BeginScope<TState>(TState state)
{
throw new NotImplementedException();
}

public bool IsEnabled(LogLevel logLevel)
{
return true;
}

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
Logs.Add(string.Format("[{0}] {1}", logLevel, formatter.Invoke(state, exception)));
}
}
}
8 changes: 8 additions & 0 deletions test/PostAnalyzerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,5 +115,13 @@ public void Analyze_PostWithUnformattedCodeThreshold098_UnformattedCodeFound()
Assert.Single(result);
Assert.IsType<NotFormattedCodeFound>(result[0]);
}

[Fact]
public void NotFormattedCodeFoundToString_WithValue_ShouldReturnProbabilityInText()
{
var pp = new NotFormattedCodeFound { Probability = 0.123f };

Assert.Contains("123", pp.ToString());
}
}
}

0 comments on commit b847b71

Please sign in to comment.