|
| 1 | +# typed: true |
| 2 | + |
| 3 | +require "test_helper" |
| 4 | +require "open3" |
| 5 | +require "timeout" |
| 6 | +require "fileutils" |
| 7 | + |
| 8 | +class TestLoggingIntegrationTest < ActiveSupport::TestCase |
| 9 | + def test_test_logs_go_to_file_not_stdout |
| 10 | + # Clean up log file before test |
| 11 | + log_file = Rails.root.join("log/test.log") |
| 12 | + FileUtils.rm_f(log_file) |
| 13 | + FileUtils.touch(log_file) |
| 14 | + |
| 15 | + env = { |
| 16 | + "LOGSTRUCT_ENABLED" => "true", |
| 17 | + "RAILS_ENV" => "test" |
| 18 | + } |
| 19 | + |
| 20 | + # Run a simple test that will generate logs |
| 21 | + cmd = ["bundle", "exec", "rails", "test", "test/models/user_test.rb"] |
| 22 | + |
| 23 | + Open3.popen3(env, *cmd, chdir: Rails.root.to_s) do |_stdin, stdout, stderr, wait_thr| |
| 24 | + begin |
| 25 | + Timeout.timeout(30) do |
| 26 | + wait_thr.value # Wait for process to complete |
| 27 | + end |
| 28 | + rescue Timeout::Error |
| 29 | + begin |
| 30 | + Process.kill("TERM", wait_thr.pid) |
| 31 | + rescue |
| 32 | + nil |
| 33 | + end |
| 34 | + |
| 35 | + flunk "Test process timed out" |
| 36 | + end |
| 37 | + |
| 38 | + stdout_output = stdout.read |
| 39 | + stderr.read |
| 40 | + |
| 41 | + # Check that stdout doesn't contain JSON logs |
| 42 | + json_lines_in_stdout = stdout_output.lines.select { |line| |
| 43 | + line.strip.start_with?("{") && begin |
| 44 | + JSON.parse(line) |
| 45 | + rescue |
| 46 | + nil |
| 47 | + end |
| 48 | + } |
| 49 | + |
| 50 | + assert_equal 0, |
| 51 | + json_lines_in_stdout.length, |
| 52 | + "Expected no JSON logs in stdout, but found #{json_lines_in_stdout.length} lines. First few:\n#{json_lines_in_stdout.first(3).join}" |
| 53 | + |
| 54 | + # Check that log/test.log contains JSON logs |
| 55 | + assert_path_exists log_file, "Expected log/test.log to exist" |
| 56 | + log_contents = File.read(log_file) |
| 57 | + |
| 58 | + json_lines_in_file = log_contents.lines.select { |line| |
| 59 | + line.strip.start_with?("{") && begin |
| 60 | + JSON.parse(line) |
| 61 | + rescue |
| 62 | + nil |
| 63 | + end |
| 64 | + } |
| 65 | + |
| 66 | + assert_operator json_lines_in_file.length, :>, 0, "Expected JSON logs in log/test.log, but found none. File size: #{log_contents.bytesize} bytes" |
| 67 | + |
| 68 | + # Verify at least one structured log exists |
| 69 | + parsed_logs = json_lines_in_file.map { |line| JSON.parse(line) } |
| 70 | + |
| 71 | + assert parsed_logs.any? { |log| log["src"] && log["evt"] && log["lvl"] }, |
| 72 | + "Expected at least one properly structured log in log/test.log" |
| 73 | + end |
| 74 | + ensure |
| 75 | + # Clean up |
| 76 | + FileUtils.rm_f(log_file) if log_file |
| 77 | + end |
| 78 | +end |
0 commit comments