更改unittest中的日志级别

时间:2016-05-19 06:13:29

标签: python logging python-unittest

我有一个印象(但没有找到相关文档),unittest将所有记录器的日志记录级别设置为WARNING 。我想:

  • 能够从命令行(运行测试时)或测试模块本身指定所有记录器的日志记录级别
  • 避免单元测试乱用应用程序日志记录级别:运行测试时,我希望获得与运行应用程序时相同的日志记录输出(相同级别)

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:9)

除非您使用它定义的unittest类,否则我不相信_CapturingHandler本身对日志记录没有任何作用。这个简单的程序演示:

import logging
import unittest

logger = logging.getLogger(__name__)

class MyTestCase(unittest.TestCase):
    def test_something(self):
        logger.debug('logged from test_something')


if __name__ == '__main__':
    # DEBUG for demonstration purposes, but you could set the level from
    # cmdline args to whatever you like
    logging.basicConfig(level=logging.DEBUG, format='%(name)s %(levelname)s %(message)s')
    unittest.main()

运行时,它会打印

__main__ DEBUG logged from test_something
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

表明它正按预期记录DEBUG级别的事件。因此,问题很可能与其他问题有关,例如测试中的代码,或其他一些更改日志记录配置或重定向sys.stdoutsys.stderr的测试运行程序。您可能需要提供有关您的测试环境的更多信息,或者提供一个更好的演示问题的最小程序(如上例所示,unittest本身不会引起您所描述的问题)。 / p>

答案 1 :(得分:6)

请参阅以下有关使用Python登录的示例。您也可以使用'setLevel'方法更改LOG_LEVEL。

import os
import logging

logging.basicConfig()
logger = logging.getLogger(__name__)

# Change logging level here.
logger.setLevel(os.environ.get('LOG_LEVEL', logging.INFO))

logger.info('For INFO message')
logger.debug('For DEBUG message')
logger.warn('For WARNING message')
logger.error('For ERROR message')
logger.fatal('For CRITICAL message')

答案 2 :(得分:0)

这是上述@Vinay回答的补充。它没有回答原始问题。我想包括用于修改日志级别的命令行选项。目的是仅当我从命令行传递某个参数时才获取详细的登录信息。这是我解决的方法:

package com.example.notekeeper

import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

import android.support.test.espresso.Espresso.*
import android.support.test.espresso.matcher.ViewMatchers.*
import android.support.test.espresso.action.ViewActions.*
import android.support.test.espresso.assertion.ViewAssertions.*
import android.util.Log

import org.hamcrest.CoreMatchers.*

@RunWith(AndroidJUnit4::class)
class NextThroughNotesTest {

    private val tag = this::class.simpleName

    @Rule @JvmField
    var noteListActivity = ActivityTestRule(NoteListActivity::class.java)

    @Test
    fun nextThroughNotes() {

        Log.i(tag, "entered the nextThroughNotes function")
        val firstNote = allOf(instanceOf(NoteInfo::class.java), equalTo(DataManager.notes[0]))
        onData(firstNote).perform(click())

        for (index in 0..DataManager.notes.lastIndex) {
            val note = DataManager.notes[index]

            //Ivan, 5/21/2020: separate out onView spinner courses matching in order to debug
            //the issue with the spinner view not being found

            Log.i(tag, "before withId() function")
            val viewMatchedById = withId(R.id.spinnerCourses)
            Log.i(tag, "before matches() function")
            val courseMatchedByTitle = matches(withSpinnerText(note.course?.title))
            Log.i(tag, "before onView for spinner")
            onView(viewMatchedById).check(courseMatchedByTitle)
            Log.i(tag, "after onView for spinner")

            Log.i(tag, "before onView for textNoteTitle")
            onView(withId(R.id.textNoteTitle)).check(
                    matches(withText(note.title)))
            Log.i(tag, "after onView for textNoteTitle")
            Log.i(tag, "before onView for textNoteText")
            onView(withId(R.id.textNoteText)).check(
                    matches(withText(note.text)))
            Log.i(tag, "after onView for textNoteText")

            Log.i(tag, "index check against the DataManager notes collection")
            if (index != DataManager.notes.lastIndex)
                onView(allOf(withId(R.id.action_next), isEnabled())).perform(click())
            Log.i(tag, "end of index check agaonst DataManager collection")

        }
        onView(withId(R.id.action_next)).check(matches(not(isEnabled())))
        Log.i(tag, "Exiting the nextThroughNotes function. Last statement in it...")
    }

}

目的是获取更多详细的日志记录。我知道它不能回答问题,但是如果有人寻求类似的要求,我会把它留在这里。