summaryrefslogtreecommitdiff
path: root/std/log/handlers_test.ts
blob: 693d2a48554dde635734ae931b40d8d5a29d78e0 (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
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import { LogLevel, getLevelName, getLevelByName } from "./levels.ts";
import { BaseHandler } from "./handlers.ts";

class TestHandler extends BaseHandler {
  public messages: string[] = [];

  public log(str: string): void {
    this.messages.push(str);
  }
}

test(function simpleHandler(): void {
  const cases = new Map<number, string[]>([
    [
      LogLevel.DEBUG,
      [
        "DEBUG debug-test",
        "INFO info-test",
        "WARNING warning-test",
        "ERROR error-test",
        "CRITICAL critical-test"
      ]
    ],
    [
      LogLevel.INFO,
      [
        "INFO info-test",
        "WARNING warning-test",
        "ERROR error-test",
        "CRITICAL critical-test"
      ]
    ],
    [
      LogLevel.WARNING,
      ["WARNING warning-test", "ERROR error-test", "CRITICAL critical-test"]
    ],
    [LogLevel.ERROR, ["ERROR error-test", "CRITICAL critical-test"]],
    [LogLevel.CRITICAL, ["CRITICAL critical-test"]]
  ]);

  for (const [testCase, messages] of cases.entries()) {
    const testLevel = getLevelName(testCase);
    const handler = new TestHandler(testLevel);

    for (const levelName in LogLevel) {
      const level = getLevelByName(levelName);
      handler.handle({
        msg: `${levelName.toLowerCase()}-test`,
        args: [],
        datetime: new Date(),
        level: level,
        levelName: levelName
      });
    }

    assertEquals(handler.level, testCase);
    assertEquals(handler.levelName, testLevel);
    assertEquals(handler.messages, messages);
  }
});

test(function testFormatterAsString(): void {
  const handler = new TestHandler("DEBUG", {
    formatter: "test {levelName} {msg}"
  });

  handler.handle({
    msg: "Hello, world!",
    args: [],
    datetime: new Date(),
    level: LogLevel.DEBUG,
    levelName: "DEBUG"
  });

  assertEquals(handler.messages, ["test DEBUG Hello, world!"]);
});

test(function testFormatterAsFunction(): void {
  const handler = new TestHandler("DEBUG", {
    formatter: (logRecord): string =>
      `fn formmatter ${logRecord.levelName} ${logRecord.msg}`
  });

  handler.handle({
    msg: "Hello, world!",
    args: [],
    datetime: new Date(),
    level: LogLevel.ERROR,
    levelName: "ERROR"
  });

  assertEquals(handler.messages, ["fn formmatter ERROR Hello, world!"]);
});