logo
down
shadow

Capture Ruby Logger output for testing


Capture Ruby Logger output for testing

By : user2956232
Date : November 22 2020, 10:54 AM
this one helps. I have a ruby class like this: , The magic is to use capture_subprocess_io
code :
 out, err = capture_subprocess_io do
     do_stuff
 end


Share : facebook icon twitter icon
Change Ruby Logger output dynamically

Change Ruby Logger output dynamically


By : Mona
Date : March 29 2020, 07:55 AM
wish help you to fix your issue As I know you can't do this with standart Logger, but you can find this in Log4r logger
How can I have ruby logger log output to stdout as well as file?

How can I have ruby logger log output to stdout as well as file?


By : user3205233
Date : March 29 2020, 07:55 AM
it should still fix some issue You can write a pseudo IO class that will write to multiple IO objects. Something like:
code :
class MultiIO
  def initialize(*targets)
     @targets = targets
  end

  def write(*args)
    @targets.each {|t| t.write(*args)}
  end

  def close
    @targets.each(&:close)
  end
end
log_file = File.open("log/debug.log", "a")
Logger.new MultiIO.new(STDOUT, log_file)
PyDev unittesting: How to capture text logged to a logging.Logger in "Captured Output"

PyDev unittesting: How to capture text logged to a logging.Logger in "Captured Output"


By : user3549417
Date : March 29 2020, 07:55 AM
should help you out The issue is that the unittest runner replaces sys.stdout/sys.stderr before the testing starts, and the StreamHandler is still writing to the original sys.stdout.
If you assign the 'current' sys.stdout to the handler, it should work (see the code below).
code :
import sys
import unittest
import logging

logger = logging.getLogger()
logger.level = logging.DEBUG
stream_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)

class TestCase(unittest.TestCase):
    def testSimpleMsg(self):
        stream_handler.stream = sys.stdout
        print("AA")
        logging.getLogger().info("BB")
import sys
import unittest
import logging

logger = logging.getLogger()
logger.level = logging.DEBUG

class TestCase(unittest.TestCase):
    def testSimpleMsg(self):
        stream_handler = logging.StreamHandler(sys.stdout)
        logger.addHandler(stream_handler)
        try:
            print("AA")
            logging.getLogger().info("BB")
        finally:
            logger.removeHandler(stream_handler)
How to capture the output on stderr of a logger using a StreamHandler?

How to capture the output on stderr of a logger using a StreamHandler?


By : RestrepoAramburo
Date : March 29 2020, 07:55 AM
this one helps. You'll have to pull the logging configuration into the with statement-body so StreamHandler already gets initialized with the altered stderr:
code :
import contextlib
import io
import logging

std_out_capture = io.StringIO()
with contextlib.redirect_stderr(std_out_capture):
    log_format = '[%(threadName)s] [%(levelname)s] %(message)s'
    logging.basicConfig(format=log_format)
    logging.error('Hi.')

output = std_out_capture.getvalue()
print(f'output: {output}')
# output: [MainThread] [ERROR] Hi.
How to test boost logger output in unit testing?

How to test boost logger output in unit testing?


By : Dorel Gabor
Date : March 29 2020, 07:55 AM
I hope this helps . In your googletest suite, you can use the boost::log facilities in each test case to redirect the BOOST_LOG_TRIVIAL messages to a file. After writing the BOOST_LOG_TRIVIAL message(s) you want you can then flush the file, open it, and check that it has the contents you expect. For example:
gtester.cpp
code :
#include <gtest/gtest.h>
#include <boost/shared_ptr.hpp>
#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/text_file_backend.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/trivial.hpp>
#include <string>
#include <fstream>

using sink_t = boost::log::sinks::synchronous_sink<boost::log::sinks::text_file_backend>;

struct boost_log_tester : ::testing::Test {
    void SetUp() {
        file_sink = boost::log::add_file_log("boost.log");
    }
    void TearDown() {
        boost::log::core::get()->remove_sink(file_sink);
        file_sink.reset();
    }
protected:
    boost::shared_ptr<sink_t> file_sink;
};

TEST_F(boost_log_tester,info_msg)
{
    std::string msg = "An informational severity message";
    BOOST_LOG_TRIVIAL(info) << msg;
    file_sink->flush();
    std::ifstream captured_cout("boost.log");
    ASSERT_TRUE(captured_cout.good()) << "Failure executing test: Could not open `boost.log` for reading";
    std::string cout_str;
    std::getline(captured_cout,cout_str);
    EXPECT_NE(cout_str.find(msg),std::string::npos);
}

TEST_F(boost_log_tester,error_msg)
{
    std::string msg = "An error severity message";
    BOOST_LOG_TRIVIAL(error) << msg;
    file_sink->flush();
    std::ifstream captured_cerr("boost.log");
    ASSERT_TRUE(captured_cerr.good()) << "Failure executing test: Could not open `boost.log` for reading";
    std::string cerr_str;
    std::getline(captured_cerr,cerr_str);
    EXPECT_NE(cerr_str.find(msg),std::string::npos);
}

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
$ g++ -Wall -Wextra -DBOOST_LOG_DYN_LINK -c gtester.cpp
$ g++ -o gtester gtester.o -lboost_log -lboost_thread -lboost_system -lgtest -pthread
$ ./gtester 
[==========] Running 2 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 2 tests from boost_log_tester
[ RUN      ] boost_log_tester.info_msg
[       OK ] boost_log_tester.info_msg (0 ms)
[ RUN      ] boost_log_tester.error_msg
[       OK ] boost_log_tester.error_msg (2 ms)
[----------] 2 tests from boost_log_tester (2 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 1 test case ran. (2 ms total)
[  PASSED  ] 2 tests.
Related Posts Related Posts :
  • how to call method in one application from another application in ruby on rails
  • LoadError on line ["51"] when trying compass watch command
  • Why does `Dir[directory_path].empty?` return `false` all the time?
  • ruby conjunction and union operators
  • Ruby - watch for file with extension being updated
  • How do I have Ruby YAML dump a Hash subclass as a simple Hash?
  • How do I get ruby-prof to ignore Ruby core / standard library / gem methods?
  • How do I give my instance variable a getter?
  • syntax error, unexpected '=', expecting keyword_end
  • Symbol literal or a method
  • Singleton logger usage in ruby
  • Difficult code packaging design
  • Passing absent parameters
  • Is there a more efficient way of ensuring my database gets closed?
  • Take in escaped input in Ruby command line app
  • String with comma-separated values and newlines: split values and create arrays for each newline
  • Instance variables on Ruby main class
  • How do I cache user specific objects
  • How to specify the location of the chromedriver binary
  • How to setup "application/ld+json" schema.org meta data in rails 4 app
  • How to use String split[]
  • Regex group match if present
  • Unusual use of module namespacing
  • Why doesn't this loop stop?
  • How do I run Rails/Rake from another directory?
  • Ruby Tempfile doesn't Create File on Disk
  • Consecutive letter frequency
  • Calling second-level function from the second level in Ruby
  • How do I use a Chef Resource in a Library
  • Ruby Method Name Interpolation
  • Weird behavior of #upcase! in Ruby
  • Ruby array access position in array
  • Ruby NameError: Undefined local variable
  • Using Nokogiri to validate XML: finding the line-nr of validation errors?
  • How to calling a function with arguments in one .rb script to another .rb script
  • Get and clear cookie using rest-client
  • invalid argument creating a ruby dev env with docker & fig
  • How can I better test equality for decorated objects?
  • Replace text in brackets gsub
  • Ruby's Array Combination Method
  • Don't have access to Heroku app
  • Take any hash keys and flatten into mixed array
  • Ruby On Rails Relationship Between Model, View, And Controller
  • Quitting method chain execution early
  • Data scrapping with Nokokiri and Pismo
  • Date format ends before converting entire input string
  • Rails 4: display values for lookups
  • Search for uppercased substring
  • Check params presence in Grape
  • How to create a method that checks if string1 can be rearranged to equal string2?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org