Запуск unittest с типичной тестовой структурой каталогов

Если вы передадите аргумент String, он посчитает повторение каждого слова

/**
 * @param string
 * @return map which contain the word and value as the no of repatation
 */
public Map findDuplicateString(String str) {
    String[] stringArrays = str.split(" ");
    Map<String, Integer> map = new HashMap<String, Integer>();
    Set<String> words = new HashSet<String>(Arrays.asList(stringArrays));
    int count = 0;
    for (String word : words) {
        for (String temp : stringArrays) {
            if (word.equals(temp)) {
                ++count;
            }
        }
        map.put(word, count);
        count = 0;
    }

    return map;

}

:

 Word1=2, word2=4, word2=1,. . .
610
задан Scott Griffiths 29 September 2010 в 23:18
поделиться

5 ответов

The simplest solution for your users is to provide an executable script (runtests.py or some such) which bootstraps the necessary test environment, including, if needed, adding your root project directory to sys.path temporarily. This doesn't require users to set environment variables, something like this works fine in a bootstrap script:

import sys, os

sys.path.insert(0, os.path.dirname(__file__))

Then your instructions to your users can be as simple as "python runtests.py".

Of course, if the path you need really is os.path.dirname(__file__), then you don't need to add it to sys.path at all; Python always puts the directory of the currently running script at the beginning of sys.path, so depending on your directory structure, just locating your runtests.py at the right place might be all that's needed.

Also, the unittest module in Python 2.7+ (which is backported as unittest2 for Python 2.6 and earlier) now has test discovery built-in, so nose is no longer necessary if you want automated test discovery: your user instructions can be as simple as python -m unittest discover.

47
ответ дан 22 November 2019 в 21:51
поделиться

Используйте setup.py develop , чтобы сделать ваш рабочий каталог частью установленной среды Python, затем запустите тесты.

5
ответ дан 22 November 2019 в 21:51
поделиться

Из статьи, на которую вы ссылаетесь:

Создайте файл test_modulename.py и поместите в него свои модульные тесты. поскольку тестовые модули находятся в отдельной каталог из вашего кода, вам может понадобиться чтобы добавить родительский каталог вашего модуля в ваш PYTHONPATH, чтобы запустить их:

 $ cd / path / to / googlemaps

$ export PYTHONPATH = $ PYTHONPATH: / путь / к / googlemaps / googlemaps

$ python test / test_googlemaps.py

Наконец, есть еще один популярный фреймворк модульного тестирования для Python (это так важно!), нос. нос помогает упростить и расширить встроенный фреймворк unittest (может, для например, автоматически найти свой тест код и настройте PYTHONPATH для вы), но он не входит в стандартный дистрибутив Python.

Может, вам стоит взглянуть на нос , как он предлагает?

18
ответ дан 22 November 2019 в 21:51
поделиться

если вы запустите "python setup.py develop", то пакет будет в пути. Но вы можете не захотеть этого делать, потому что вы можете заразить вашу системную установку Python, поэтому существуют такие инструменты, как virtualenv и buildout .

9
ответ дан 22 November 2019 в 21:51
поделиться

Обычно я создаю сценарий «запустить тесты» в каталоге проекта (тот, который является общим как для исходного каталога, так и для test ), который загружает мой набор «Все тесты». Обычно это шаблонный код, поэтому я могу повторно использовать его от проекта к проекту.

run_tests.py:

import unittest
import test.all_tests
testSuite = test.all_tests.create_test_suite()
text_runner = unittest.TextTestRunner().run(testSuite)

test / all_tests.py (из Как мне запустить все модульные тесты Python в каталоге? )

import glob
import unittest

def create_test_suite():
    test_file_strings = glob.glob('test/test_*.py')
    module_strings = ['test.'+str[5:len(str)-3] for str in test_file_strings]
    suites = [unittest.defaultTestLoader.loadTestsFromName(name) \
              for name in module_strings]
    testSuite = unittest.TestSuite(suites)
    return testSuite

При такой настройке вы действительно можете просто включить антигравитацию в ваши тестовые модули. Обратной стороной является то, что вам понадобится больше кода поддержки для выполнения определенного теста ... Я просто запускаю их все каждый раз.

22
ответ дан 22 November 2019 в 21:51
поделиться
Другие вопросы по тегам:

Похожие вопросы: